date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/16
| 2,033 | 3,676 |
<issue_start>username_0: This question is more to help me with constructing an efficient pipeline for my code.
### data
```
df <- data.frame(stringsAsFactors=FALSE,
Date = c("2015-10-26", "2015-10-26", "2015-10-26", "2015-10-26",
"2015-10-27", "2015-10-27", "2015-10-27"),
Ticker = c("ANZ", "CBA", "NAB", "WBC", "ANZ", "CBA", "WBC"),
Open = c(29.11, 77.89, 32.69, 31.87, 29.05, 77.61, 31.84),
High = c(29.17, 77.93, 32.76, 31.92, 29.08, 78.1, 31.95),
Low = c(28.89, 77.37, 32.42, 31.71, 28.9, 77.54, 31.65),
Close = c(28.9, 77.5, 32.42, 31.84, 28.94, 77.74, 31.77),
Volume = c(6350170L, 2251288L, 3804239L, 5597684L, 5925519L, 2424679L,
5448863L)
)
```
### This is what I'd like my workflow to look like
```
df %>%
mutate(new column = some_function(Open, 1)) # "Open" is column name, "1" is for row no.
```
Which should out put the following:
```
Date Ticker Open High Low Close Volume new_column
1 2015-10-26 ANZ 29.11 29.17 28.89 28.90 6350170 29.11
2 2015-10-26 CBA 77.89 77.93 77.37 77.50 2251288 29.11
3 2015-10-26 NAB 32.69 32.76 32.42 32.42 3804239 29.11
4 2015-10-26 WBC 31.87 31.92 31.71 31.84 5597684 29.11
5 2015-10-27 ANZ 29.05 29.08 28.90 28.94 5925519 29.11
6 2015-10-27 CBA 77.61 78.10 77.54 77.74 2424679 29.11
7 2015-10-27 WBC 31.84 31.95 31.65 31.77 5448863 29.11
```
Any ideas what the `some_function` would be within `tidyverse`<issue_comment>username_1: looking for `head`?
```
df %>%
mutate(newcolumn = head(Open, 1))
```
Upvotes: 2 <issue_comment>username_2: Another option could be to use just `first` function itself. If OP is looking for a function from `dplyr` which can provide value from a row then that function should be `nth`.
```
df %>%
mutate(newcolumn = first(Open))
```
OR for value from a particular row
```
df %>%
mutate(newcolumn = nth(Open, 5))
```
`nth` is a `dplyr` function.
Upvotes: 1 <issue_comment>username_3: I think OP wants to specify *any* row number, not just the first element. But you can simply do this using the standard `[` subset operator:
```r
df <- data.frame(stringsAsFactors=FALSE,
Date = c("2015-10-26", "2015-10-26", "2015-10-26", "2015-10-26",
"2015-10-27", "2015-10-27", "2015-10-27"),
Ticker = c("ANZ", "CBA", "NAB", "WBC", "ANZ", "CBA", "WBC"),
Open = c(29.11, 77.89, 32.69, 31.87, 29.05, 77.61, 31.84),
High = c(29.17, 77.93, 32.76, 31.92, 29.08, 78.1, 31.95),
Low = c(28.89, 77.37, 32.42, 31.71, 28.9, 77.54, 31.65),
Close = c(28.9, 77.5, 32.42, 31.84, 28.94, 77.74, 31.77),
Volume = c(6350170L, 2251288L, 3804239L, 5597684L, 5925519L, 2424679L,
5448863L)
)
library(dplyr)
df %>%
mutate(new_column = Open[5])
#> Date Ticker Open High Low Close Volume new_column
#> 1 2015-10-26 ANZ 29.11 29.17 28.89 28.90 6350170 29.05
#> 2 2015-10-26 CBA 77.89 77.93 77.37 77.50 2251288 29.05
#> 3 2015-10-26 NAB 32.69 32.76 32.42 32.42 3804239 29.05
#> 4 2015-10-26 WBC 31.87 31.92 31.71 31.84 5597684 29.05
#> 5 2015-10-27 ANZ 29.05 29.08 28.90 28.94 5925519 29.05
#> 6 2015-10-27 CBA 77.61 78.10 77.54 77.74 2424679 29.05
#> 7 2015-10-27 WBC 31.84 31.95 31.65 31.77 5448863 29.05
```
Created on 2018-03-16 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0).
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,257 | 6,190 |
<issue_start>username_0: I've inherited some code that interfaces with GP. While reviewing the code prior to debugging an issue I found a function that undoes updates to a set of tables.
The code contains a number of SQL commands and I was wondering if I would get better performance from a single stored procedure with an input parameter that is the table **ds** than running all these commands on each row of the table separately.
```
private void revertSave()
{
try
{
SqlConnection conn = GetConnectionToGP();
if (conn != null)
{
using (SqlCommand cmd = new SqlCommand())
{
//records from InventoryTransaction Master, Detail, and Serial tables when window is opened.
foreach (DataRow dr in _ds.Tables[0].Rows)
{
cmd.Connection = conn;
//TRANSACTION tables
cmd.CommandText = "UPDATE InventoryTransaction_Master " +
"SET Completed = 0 WHERE DocumentNumber = " + SqlString(dr["DocumentNumber"].ToString().Trim());
cmd.ExecuteNonQuery();
cmd.CommandText = "UPDATE InventoryTransaction_Serial " +
"SET BIN = '' " +
"WHERE DocumentNumber = " + SqlString(dr["DocumentNumber"].ToString().Trim()) +
" and DocumentType = 1 and ItemNumber = " + SqlString(dr["PrefixedItemNumber"].ToString().Trim()) +
" and LineSequenceNumber = " + SqlString(dr["LineSequenceNumber"].ToString().Trim()) +
" and SerialNumber = " + SqlString(dr["SerialNumber"].ToString().Trim());
cmd.ExecuteNonQuery();
//TRANSFER tables
cmd.CommandText = "SELECT DISTINCT detail.DocumentNumber " +
"FROM InventoryTransfer_Detail detail " +
"INNER JOIN InventoryTransfer_Serial serial ON detail.DocumentNumber = serial.DocumentNumber " +
"and detail.ItemNumber = serial.ItemNumber " +
"and detail.LineSequenceNumber = serial.LineSequenceNumber " +
"WHERE SessionID = " + SqlString(dr["SessionID"].ToString().Trim()) +
" and SerialNumber = " + SqlString(dr["SerialNumber"].ToString().Trim());
object obj = cmd.ExecuteScalar();
if (obj != null)
{
cmd.CommandText = "UPDATE InventoryTransfer_Master " +
"SET Completed = 0 WHERE DocumentNumber = " + SqlString(obj.ToString());
cmd.ExecuteNonQuery();
cmd.CommandText = "UPDATE InventoryTransfer_Serial " +
"SET OriginalBin = '', NewBin = '' " +
"WHERE DocumentNumber = " + SqlString(obj.ToString()) + " and SerialNumber = " + SqlString(dr["SerialNumber"].ToString().Trim());
cmd.ExecuteNonQuery();
}
}
}
if (conn.State == ConnectionState.Open)
conn.Close();
}
//this.Close();
}
catch (Exception ex)
{
ELog el = new ELog(ex, CLASS_NAME + " revertSave");
}
}
```<issue_comment>username_1: It is hard to predict performance of complex systems without actually trying it out, but it is highly likely that a stored procedure would improve the speed of execution, especially if your dataset is large.
With your current method you have
* Four SQL commands per row. So for 1,000 rows, there will be 4,000 commands.
* 4,000 network hops
* 4,000 instances of single-row locks
* 4,000 SQL compilation events
With a stored procedure, you could theoretically have
* Three SQL commands, total, that correlate all the rows necessary for fetching the necessary values. While these would be very complicated statements (with lots of joins), 3 is much less than 4,000.
* One network hop
* One transaction, containing all of the necessary row, page, or potentially table locks.
* No compilation events at all, if the stored procedure is compiled ahead of time.
Everything looks much better with the stored procedure, except the potential for greater locking. Depending on your overall solution, that lock could be a deal-breaker, as it could block other processes for other users who are trying to do the same thing at the same time.
There's also some devilish details-- for example, updating one row at a time could potentially be more efficient than doing a mass update, if the table is massive and has many rows that you are not updating, and the bulk update triggers table scans instead of index seeks. However, a good SQL developer can tailor the SQL queries and commands to nudge SQL Server in the right direction.
TLDR: In most cases, the stored procedure will give you better performance.
Upvotes: 3 [selected_answer]<issue_comment>username_2: As others have said, SQL injection and transactions are issues. Other potential issues with this code are maintainability (ease of typing AND ease of finding AND ease of debugging). Any of these issues may well be more important than the performance. It looks like it could be doing more row-based logic than set-based logic, which is usually a performance problem. If it is customary in the company to build SQL in the code, and this runs in an amount of time which is not burdensome to the systems or to the people running it, it is possibly the best place for it (leaving aside the threat of SQL injection).
If this is causing actual performance problems, it should be optimized, and the best way to optimize is to test. Does it run in 5 minutes this way? When you convert it to a stored proc, does it the take 1 minute? How about when you remove the loop, and make it entirely set-based logic?
Upvotes: 2
|
2018/03/16
| 897 | 3,620 |
<issue_start>username_0: ```php
function post_like(){
global $wpdb;
$c = $_POST['next'];
echo $c;
$d = get_the_ID();
$wpdb->insert('wp_likes',
array(
'article_id' => $d,
'user_id' => '1'
)
);
die();
}
```
and my ajax.js file:
```php
function Click_Me() {
var className = jQuery('#flag').attr('class');
if (className == "like") {
var temp = "unlike";
} else {
var temp = "like";
}
jQuery.ajax({
url: like.ajax_url,
dataType: 'html',
data: {
action: 'post_like',
next: temp
},
success: function() {
jQuery('#flag').attr('class', temp);
jQuery('#sonuc').html(temp);
}
});
}
```
If I want to get id with this method
```php
$a = get_the_ID();
$a variable's value == 0
```
Why? I tried other tricks for getting id, but methods do not works. I think the problem is ajax but I don't understand why...
Thanks for answers.<issue_comment>username_1: It is hard to predict performance of complex systems without actually trying it out, but it is highly likely that a stored procedure would improve the speed of execution, especially if your dataset is large.
With your current method you have
* Four SQL commands per row. So for 1,000 rows, there will be 4,000 commands.
* 4,000 network hops
* 4,000 instances of single-row locks
* 4,000 SQL compilation events
With a stored procedure, you could theoretically have
* Three SQL commands, total, that correlate all the rows necessary for fetching the necessary values. While these would be very complicated statements (with lots of joins), 3 is much less than 4,000.
* One network hop
* One transaction, containing all of the necessary row, page, or potentially table locks.
* No compilation events at all, if the stored procedure is compiled ahead of time.
Everything looks much better with the stored procedure, except the potential for greater locking. Depending on your overall solution, that lock could be a deal-breaker, as it could block other processes for other users who are trying to do the same thing at the same time.
There's also some devilish details-- for example, updating one row at a time could potentially be more efficient than doing a mass update, if the table is massive and has many rows that you are not updating, and the bulk update triggers table scans instead of index seeks. However, a good SQL developer can tailor the SQL queries and commands to nudge SQL Server in the right direction.
TLDR: In most cases, the stored procedure will give you better performance.
Upvotes: 3 [selected_answer]<issue_comment>username_2: As others have said, SQL injection and transactions are issues. Other potential issues with this code are maintainability (ease of typing AND ease of finding AND ease of debugging). Any of these issues may well be more important than the performance. It looks like it could be doing more row-based logic than set-based logic, which is usually a performance problem. If it is customary in the company to build SQL in the code, and this runs in an amount of time which is not burdensome to the systems or to the people running it, it is possibly the best place for it (leaving aside the threat of SQL injection).
If this is causing actual performance problems, it should be optimized, and the best way to optimize is to test. Does it run in 5 minutes this way? When you convert it to a stored proc, does it the take 1 minute? How about when you remove the loop, and make it entirely set-based logic?
Upvotes: 2
|
2018/03/16
| 849 | 2,759 |
<issue_start>username_0: How can I create a template class that can understand if type `T` is hashable or not, and if it is then use `std::unodered_set` to collect elements of type T?. Otherwise, I want it to use `std::set`.
This class have the same simple methods as above `sets` such as `insert(), find()` and so on.
```
template
class MySet {
public:
MySet() {}
bool find() {
//some code here
```
I check if type has `operator()` to get information about its "hashability". For this purpose I use the following construction, which I found on this site:
```
template
class HasHash {
typedef char one;
typedef long two;
template
static one test(decltype(&C::operator()));
template
static two test(...);
public:
enum {
value = sizeof(test(0)) == sizeof(size\_t)
};
};
```
And get is hashable or not (true or false) by typing:
```
HasHash::value
```
There is no way for me to use boost library.<issue_comment>username_1: If you have a `is_hashable` type trait (e.g. your `HasHash`), then you can use [`std::conditional`](http://en.cppreference.com/w/cpp/types/conditional), like so:
```
template
std::conditional::value, std::unordered\_set, std::set>::type
```
or if you're using C++17, it could be simplified to:
```
template
inline constexpr bool is\_hashable\_v = is\_hashable::value;
template
std::conditional\_t, std::unordered\_set, std::set>;
```
(assuming you've also implemented the `_v` version of the trait).
For some additional discussion regarding determining hashability, this is also interesting:
[Check if type is hashable](https://stackoverflow.com/questions/12753997/check-if-type-is-hashable)
here on the site.
Upvotes: 3 <issue_comment>username_2: Here's a full working example, assuming you are using `std::hash`.
```
#include
#include
#include
#include
#include
using std::cout;
using std::endl;
template using void\_t = void;
template
struct is\_hashable : std::false\_type { };
template
struct is\_hashable{})>> : std::true\_type { };
template
using set = typename std::conditional<
is\_hashable::value, std::unordered\_set, std::set
>::type;
template void test() { cout << \_\_PRETTY\_FUNCTION\_\_ << endl; }
struct dummy\_type { };
int main(int argc, char\* argv[]) {
cout << std::boolalpha;
cout << is\_hashable::value << endl;
cout << is\_hashable::value << endl;
test>();
test>();
}
```
The output should be similar to
```
true
false
void test() [with T = std::unordered_set, std::equal\_to, std::allocator >]
void test() [with T = std::set, std::allocator >]
```
**Edit**:
`is_hashable` specialization can also be done without the use of `void_t`, like this:
```
template
struct is\_hashable{},void())> : std::true\_type { };
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 932 | 3,342 |
<issue_start>username_0: My situation is as follows: In C, I launch a `pthread` that eventually blocks waiting for input by calling a receive function. The data it expects to receive will be basically a response.
Back on my original thread of execution I want to wait until the launched thread is ready to handle the response before I do anything that might cause such a response to arrive. I don't want to cause a response to arrive before the launched thread is capable of receiving it.
Edit: the original thread sends a UDP packet. It doesn't know if the other end exists or not -- it's trying to learn about the other end. It draws its own conclusion depending on whether the launched thread receives a response by a certain timeout.
One problem I have is the launched thread is only truly ready when it's blocked. Any signal it gives before it calls the blocking receive function could end up being a "long" time before it's actually ready. How do you signal when you're ready, given that you're only ready when you're blocked?
Right now I `sleep()` after receiving the ready signal, which I know is no guarantee and has disadvantages.
Another question I have is can the signal be as simple as changing an int from `0` to `1` without any mutex protection? I read that [ints are not atomic](http://www.alexonlinux.com/do-you-need-mutex-to-protect-int). But I only want to know when an int stops being `0`, and this int is only ever going to change once from `0` to something other than `0`.<issue_comment>username_1: If you have a `is_hashable` type trait (e.g. your `HasHash`), then you can use [`std::conditional`](http://en.cppreference.com/w/cpp/types/conditional), like so:
```
template
std::conditional::value, std::unordered\_set, std::set>::type
```
or if you're using C++17, it could be simplified to:
```
template
inline constexpr bool is\_hashable\_v = is\_hashable::value;
template
std::conditional\_t, std::unordered\_set, std::set>;
```
(assuming you've also implemented the `_v` version of the trait).
For some additional discussion regarding determining hashability, this is also interesting:
[Check if type is hashable](https://stackoverflow.com/questions/12753997/check-if-type-is-hashable)
here on the site.
Upvotes: 3 <issue_comment>username_2: Here's a full working example, assuming you are using `std::hash`.
```
#include
#include
#include
#include
#include
using std::cout;
using std::endl;
template using void\_t = void;
template
struct is\_hashable : std::false\_type { };
template
struct is\_hashable{})>> : std::true\_type { };
template
using set = typename std::conditional<
is\_hashable::value, std::unordered\_set, std::set
>::type;
template void test() { cout << \_\_PRETTY\_FUNCTION\_\_ << endl; }
struct dummy\_type { };
int main(int argc, char\* argv[]) {
cout << std::boolalpha;
cout << is\_hashable::value << endl;
cout << is\_hashable::value << endl;
test>();
test>();
}
```
The output should be similar to
```
true
false
void test() [with T = std::unordered_set, std::equal\_to, std::allocator >]
void test() [with T = std::set, std::allocator >]
```
**Edit**:
`is_hashable` specialization can also be done without the use of `void_t`, like this:
```
template
struct is\_hashable{},void())> : std::true\_type { };
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,030 | 3,458 |
<issue_start>username_0: I have the string
```
{"quests ":
[{
"title ":"Phite Club",
"status": "COMPLETED",
"difficulty": 3,
"members": True,
"questPoints": 1,
"userEligible": True
},{
"title": "All Fired Up",
"status": "COMPLETED",
"difficulty": 1,
"members": True,
"questPoints": 1,
"userEligible": True
}]
}
```
I want to search for `All Fired Up` and have the output be:
```
{"title": "All Fired Up",
"status": "COMPLETED",
"difficulty": 1,
"members": True,
"questPoints": 1,
"userEligible": True}
```
I don't necessarily need the quotes or { } in the output but either way I need the data.
My formatting is poor but any help is appreciated, thanks!<issue_comment>username_1: Answer for revised question
===========================
Let's define your dictionary:
```
>>> d = {"quests ":
... [{
... "title ":"Phite Club",
... "status": "COMPLETED",
... "difficulty": 3,
... "members": True,
... "questPoints": 1,
... "userEligible": True
... },{
... "title": "All Fired Up",
... "status": "COMPLETED",
... "difficulty": 1,
... "members": True,
... "questPoints": 1,
... "userEligible": True
... }]
... }
```
To retrieve the sections of interest to you:
```
>>> [y for dd in d.values() for y in dd if y.get('title') == 'All Fired Up']
[{'questPoints': 1, 'title': 'All Fired Up', 'status': 'COMPLETED', 'userEligible': True, 'members': True, 'difficulty': 1}]
```
Or, if you know ahead of time that what you are looking for is under `quests`:
```
>>> [y for y in d['quests '] if y.get('title') == 'All Fired Up']
[{'questPoints': 1, 'title': 'All Fired Up', 'status': 'COMPLETED', 'userEligible': True, 'members': True, 'difficulty': 1}]
```
Answer for original version of the question
===========================================
Let's define your string:
```
>>> s = '"{"quests":[{"title":"Phite Club","status":"COMPLETED","difficulty":3,"members":true,"questPoints":1,"userEligible":true},{"title":"All Fired Up","status":"COMPLETED","difficulty":1,"members":true,"questPoints":1,"userEligible":true},"'
```
Let's extract the parts that you want:
```
>>> import re
>>> re.findall(r'\{[^}]*All Fired Up[^}]*\}', s)
['{"title":"All Fired Up","status":"COMPLETED","difficulty":1,"members":true,"questPoints":1,"userEligible":true}']
```
The regex `\{[^}]*All Fired Up[^}]*\}` matches `All Fired Up` and all characters around it up to and including the nearest `{` on the front and `}` on the back.
[Notice that, in the current version of the question, the dictionary has key `quests` with a space after `quests`. The code above
### The JSON Question
As I wrote this answer, the string in the question was *not* valid JSON. If, in later updates, that is replaced with a valid JSON string, then [username_2's answer](https://stackoverflow.com/a/49331124/3030305) becomes appropriate.
Upvotes: 1 <issue_comment>username_2: You have a JSON string. You should parse it to python and then search for your match.
```
data = json.loads(mystring)
target = next(item for item in data if item["title"] == "All Fired Up")
```
Upvotes: -1 <issue_comment>username_3: ```
string = ".... your string ..."
data = [ s.split("}")[0] for s in string.split("{") if "All Fired Up" in s ]
```
Upvotes: 0
|
2018/03/16
| 947 | 3,218 |
<issue_start>username_0: I couldn't wrap my head around this:
```
def expr(a):
return ~(a ^ 0xFFFFFFFF), a ^ 0xFFFFFFFF, ~a, a
print(expr(0xFFFFFFFF))
print(expr(1))
print(expr(0))
print(expr(-1))
```
I understand `~a` means two's complement of `a`, but `a ^ 0xFFFFFFFF` also flips all the bits, but python will interpret it as a large number. I know Python3 is using unbound integer size, how does that work? Can someone ELI5 (Explain Like I'm Five)?
Results:
```none
( -1, 0, -4294967296, 4294967295)
(-4294967295, 4294967294, -2, 1)
(-4294967296, 4294967295, -1, 0)
( 4294967295, -4294967296, 0, -1)
```
**UPDATE:**
I guess my question can be reduced to this: in C, 111...1 can represent -1, I got this, because it's 32 bits. In Python, the integer size is unlimited, how do you represent -1 in binary? 111...1 is a large positive integer, no?<issue_comment>username_1: `0xFFFFFFFF` is a large number; it's the hexadecimal representation of 232-1. Python's ints are represented internally as a linked list of C longs, allowing theoretically unbounded size. Bitwise XOR (`^`) in Python uses zero values for the bits more significant than those you've given, so the net result is that only the lower 32 bits are flipped, resulting in behavior that diverges from what you get in C, where there are only 32 bits and the net result is that 'all' the bits are flipped.
Upvotes: 1 <issue_comment>username_2: >
> In Python, the integer size is unlimited, how do you represent -1 in binary? 111...1 is a large positive integer, no?
>
>
>
Positive numbers have an infinite sequence of leading zeros. That is, if we need to represent the number 100101 (equal to 37), that's equal to ...000100101, with as many zeros as you like in front. No computer system tries to store all of those leading zeros, because there are infinitely many, but some leading zeros might get stored in order to pad the number out to a "reasonable" size, such as 32 or 64 bits.
Python extends this concept to negative numbers by saying that they have an infinite number of leading *ones*. So if you need to represent -37, that would be ...111011011, with as many ones as you need in front. Similarly, -1 is just ...1111. So if you XOR -1 with another Python integer, it will flip *all* of that number's bits, including its leading zeros or ones (as if you had used the tilde operator). Unfortunately, Python does not have a convenient binary notation for "infinite leading ones," so you cannot write (for instance) `0b...111` as an integer literal; you must use `-1` instead, or invert it and write `~0b0`.
While this may sound ridiculous, it is actually quite mathematically sound. Under the [2-adic numbers](https://en.wikipedia.org/wiki/P-adic_number), these sequences with infinite leading ones are formally equivalent to the corresponding negative integers. If you prefer an approach more grounded in computer engineering, you might imagine that the Python integers automatically [sign-extend](https://en.wikipedia.org/wiki/Sign_extension) to however wide they need to be (which is more or less the actual implementation).
Upvotes: 3 [selected_answer]
|
2018/03/16
| 984 | 3,327 |
<issue_start>username_0: Can I get some help to fix it? I already did the code myself but I’m not sure how to fix this error.
>
> error: invalid operand to binary \* (have 'int' and 'int \*')
>
>
>
```
#include
void pay\_amount (int dollars, int \*twenties, int \*tens, int \*fives, int \*ones);
int main(void)
{
int amount, twenties, tens, fives, ones, reduced\_amount;
pay\_amount( amount, &twenties, &tens, &fives, &ones);
printf("\n"); /\* blank line \*/
printf("$20 bills: %d\n", twenties);
printf("$10 bills: %d\n", tens);
printf(" $5 bills: %d\n", fives);
printf(" $1 bills: %d\n", ones);
return 0;
}
void pay\_amount (int dollars, int \*twenties, int \*tens, int \*fives, int \*ones)
{
int reduced\_amount;
printf("Enter a dollar amount: ");
scanf("%d", &dollars);
\*twenties = dollars / 20;
reduced\_amount = dollars - (20 \* twenties);
\*tens = reduced\_amount / 10;
reduced\_amount = reduced\_amount - (10 \* tens);
\*fives = reduced\_amount / 5;
\*ones = reduced\_amount - (5 \* fives);
}
```<issue_comment>username_1: `0xFFFFFFFF` is a large number; it's the hexadecimal representation of 232-1. Python's ints are represented internally as a linked list of C longs, allowing theoretically unbounded size. Bitwise XOR (`^`) in Python uses zero values for the bits more significant than those you've given, so the net result is that only the lower 32 bits are flipped, resulting in behavior that diverges from what you get in C, where there are only 32 bits and the net result is that 'all' the bits are flipped.
Upvotes: 1 <issue_comment>username_2: >
> In Python, the integer size is unlimited, how do you represent -1 in binary? 111...1 is a large positive integer, no?
>
>
>
Positive numbers have an infinite sequence of leading zeros. That is, if we need to represent the number 100101 (equal to 37), that's equal to ...000100101, with as many zeros as you like in front. No computer system tries to store all of those leading zeros, because there are infinitely many, but some leading zeros might get stored in order to pad the number out to a "reasonable" size, such as 32 or 64 bits.
Python extends this concept to negative numbers by saying that they have an infinite number of leading *ones*. So if you need to represent -37, that would be ...111011011, with as many ones as you need in front. Similarly, -1 is just ...1111. So if you XOR -1 with another Python integer, it will flip *all* of that number's bits, including its leading zeros or ones (as if you had used the tilde operator). Unfortunately, Python does not have a convenient binary notation for "infinite leading ones," so you cannot write (for instance) `0b...111` as an integer literal; you must use `-1` instead, or invert it and write `~0b0`.
While this may sound ridiculous, it is actually quite mathematically sound. Under the [2-adic numbers](https://en.wikipedia.org/wiki/P-adic_number), these sequences with infinite leading ones are formally equivalent to the corresponding negative integers. If you prefer an approach more grounded in computer engineering, you might imagine that the Python integers automatically [sign-extend](https://en.wikipedia.org/wiki/Sign_extension) to however wide they need to be (which is more or less the actual implementation).
Upvotes: 3 [selected_answer]
|
2018/03/16
| 730 | 2,779 |
<issue_start>username_0: I'm trying to get CSS `width` property of a flexible element, but for some reason it doesn't work:
Codepen: <https://codepen.io/anon/pen/pLEwdp?editors=1010>
---
### Code:
```html
non-flex
--------
current width is: {{flexibleAreaWidth}}
---------------------------------------
non-flex
--------
...
computed: {
flexibleAreaWidth () {
let elem = this.$refs.flexibleArea
return window.getComputedStyle(elem,null).getPropertyValue("width")
}
}
```<issue_comment>username_1: `0xFFFFFFFF` is a large number; it's the hexadecimal representation of 232-1. Python's ints are represented internally as a linked list of C longs, allowing theoretically unbounded size. Bitwise XOR (`^`) in Python uses zero values for the bits more significant than those you've given, so the net result is that only the lower 32 bits are flipped, resulting in behavior that diverges from what you get in C, where there are only 32 bits and the net result is that 'all' the bits are flipped.
Upvotes: 1 <issue_comment>username_2: >
> In Python, the integer size is unlimited, how do you represent -1 in binary? 111...1 is a large positive integer, no?
>
>
>
Positive numbers have an infinite sequence of leading zeros. That is, if we need to represent the number 100101 (equal to 37), that's equal to ...000100101, with as many zeros as you like in front. No computer system tries to store all of those leading zeros, because there are infinitely many, but some leading zeros might get stored in order to pad the number out to a "reasonable" size, such as 32 or 64 bits.
Python extends this concept to negative numbers by saying that they have an infinite number of leading *ones*. So if you need to represent -37, that would be ...111011011, with as many ones as you need in front. Similarly, -1 is just ...1111. So if you XOR -1 with another Python integer, it will flip *all* of that number's bits, including its leading zeros or ones (as if you had used the tilde operator). Unfortunately, Python does not have a convenient binary notation for "infinite leading ones," so you cannot write (for instance) `0b...111` as an integer literal; you must use `-1` instead, or invert it and write `~0b0`.
While this may sound ridiculous, it is actually quite mathematically sound. Under the [2-adic numbers](https://en.wikipedia.org/wiki/P-adic_number), these sequences with infinite leading ones are formally equivalent to the corresponding negative integers. If you prefer an approach more grounded in computer engineering, you might imagine that the Python integers automatically [sign-extend](https://en.wikipedia.org/wiki/Sign_extension) to however wide they need to be (which is more or less the actual implementation).
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,131 | 3,635 |
<issue_start>username_0: In an effort to learn OpenMP, I am running a simple C++ program with OpenMP to compute the value of pi, based on this video: <https://www.youtube.com/watch?v=OuzYICZUthM>
Unfortunately, my program seems to be running faster with fewer threads, and I am not sure why. My laptop has 4 cores, so it should at least run a little faster with more than one thread.
Here is the code:
```
#include
#include
#define NUM\_THREADS 1
#define PAD 8
using namespace std;
static long num\_steps = 100000000;
double step;
int main(){
omp\_set\_num\_threads(NUM\_THREADS);
double pi;
static double sum[NUM\_THREADS][PAD];
step = 1.0/(double) num\_steps;
double x;
double start\_time = omp\_get\_wtime();
int nthreads;
#pragma omp parallel
{
double partial\_sum = 0.0;
int ID = omp\_get\_thread\_num();
int nthrds = omp\_get\_num\_threads();
if (ID == 0) nthreads = nthrds;
sum[ID][0] = 0.0;
for (int i = ID; i < num\_steps; i = i+ nthrds){
x = (i + 0.5)\*step;
sum[ID][0] += 4.0/(1.0 + x\*x);
}
}
double time = omp\_get\_wtime() - start\_time;
for (int i = 0; i < nthreads; i++){
pi += sum[i][0]\*step;
}
cout << pi << endl;
cout << time\*1000 << endl;
}
```
Can someone edify me as to why the multiple threads are taking longer than a single thread? Looking at similar posts on this issue, it appears there are problems with people's code that caused them to run slower with multiple threads. However, this code is based pretty much vertabim off the dude from the video, so I shouldn't be having this issue while running this code.
Note: The program uses numerical integration to compute the value of pi. The integral is of the function 4.0/(1+x\*x) from 0 to 1, which evaluates exactly to pi.<issue_comment>username_1: Guessing here, but my guess is that you're blowing your cache like crazy. Your threading code has two variables (`x` and `sum`) that are going to be written by all threads, meaning each one of those writes will cause a cache miss for every *other* thread that's trying to access those variables. Of the two, `sum` seems more problematic.
This is based on a [talk by <NAME>ers](https://www.youtube.com/watch?v=WDIkqP4JbkE) where he covers a similar problem (it's early in the talk if you're curious). His example shows crippling performance because of CPU cache issues.
Upvotes: 0 <issue_comment>username_2: First, I'll note that I'm unable to duplicate your results. For me, your code runs in about 500 ms with NUM\_THREADS set to 1, and about 130-140 ms with NUM\_THREADS set to 4, so it's scaling about as we'd expect for a 4-core machine.
However, that's not how I'd write the code. I'd start by simplifying the code (quite a lot). The primary use-case for OpenMP is code that doesn't currently do anything explicitly related to threads at all, then inserting a directive, and having it run substantially faster.
I'd write the code to depend more on OpenMP to handle the reduction and such, ending up with something like this:
```
#include
#include
using namespace std;
static long num\_steps = 100000000;
double step;
int main() {
double pi = 0.0;
step = 1.0 / (double)num\_steps;
double start\_time = omp\_get\_wtime();
#pragma omp parallel for reduction(+:pi)
for (int i = 0; i < num\_steps; ++i) {
double x = i \* step;
pi += 4.0 / (1.0 + x \* x);
}
pi \*= step;
double time = omp\_get\_wtime() - start\_time;
cout << pi << endl;
cout << time \* 1000 << endl;
}
```
At least for me, this runs about the same speed as your code--around 500 ms without enabling OpenMP, and around 130-140ms with OpenMP enabled.
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,823 | 5,755 |
<issue_start>username_0: I have a SVG I am trying to animate with animejs.
Basically its a selection path drawing.
I managed to animate but the result is wrong.
I want this:
[](https://i.stack.imgur.com/5bp5L.gif)
```js
var lineDrawing = anime({
targets: 'path',
strokeDashoffset: [anime.setDashoffset, 0],
easing: 'easeInOutCubic',
duration: 4000,
begin: function(anim) {
document.querySelector('path').setAttribute("stroke", "#4a56f2");
document.querySelector('path').setAttribute("fill", "none");
},
complete: function(anim) {
},
autoplay: false
});
document.querySelector('.play-drawing').onclick = lineDrawing.restart;
```
```css
body {
margin: 20px;
font-family: 'Lato';
font-weight: 300;
font-size: 1.2em;
}
#anime-demo {
position: relative;
}
svg {
padding: 10px;
}
button {
background: orange;
color: white;
margin: 5px;
padding: 10px;
border-radius: 4px;
font-family: 'Lato';
cursor: pointer;
border: none;
outline: none;
}
button:hover {
background: blue;
}
```
```html
Draw the Anchor
```<issue_comment>username_1: Unfortunately, the way you have it setup - with a single path element containing all the blocks will not work. The animation library uses stroke dash width to simulate drawing blocks. Having them all defined in a single path element can only lead to all blocks being animated at the same time.
After breaking them into separate path elements for each block, the other issue is the order to draw them in - by default it will traverse the path elements from top to bottom in the order they are in the HTML. However, the path elements are added in right-left order from top to bottom meaning the animation will start at the top middle block then alternate each one on the left side, right side, left side, etc. Instead, to get them to animate in a clockwise wrap-around order I wrote a function to initially loop through all the elements, calculate the degrees (0-360) in relation to the SVG's center point (remember your high school trigonometry?), then sort the elements based on that degree value.
Since SO requires code (but it is too long to add all of it in an answer), here is the JavaScript, the complete code in in the JSFiddle at the bottom:
```js
// Sort paths via degrees (clockwise)
document.querySelectorAll("svg").forEach(function(svgE){
var centerCoords = [ svgE.getBoundingClientRect().width / 2,
svgE.getBoundingClientRect().height / 2
];
var pathsByDeg = [];
svgE.querySelectorAll("path").forEach(function(pE){
var coords = (/^M([0-9\.]+)\s+([0-9\.]+)+/.exec(pE.getAttribute("d"))).splice(1,2).map(parseFloat);
var rad = -Math.atan2(coords[1]-centerCoords[1], coords[0]-centerCoords[0]);
var deg = ((rad / Math.PI * 180) + (rad > 0 ? 0 : 360)) - 90;
deg = deg < 0 ? deg + 360 : deg;
pathsByDeg.push([deg, pE]);
});
pathsByDeg.sort(function(a, b){
return a[0] - b[0];
});
pathsByDeg.reduce(function(c,n){
c[1].parentNode.insertBefore(n[1],c[1]);
return n;
}, pathsByDeg[0]);
});
// Setup path animation
var lineDrawing = anime({
targets: 'svg path',
easing: 'easeInOutCubic',
strokeDashoffset: [anime.setDashoffset, 0],
duration: 1000,
delay: function(el, i) { return i * 20 },
autoplay: false,
begin: function(anim) {
anim.animatables.forEach(function(elem){
var t = elem.target;
t.setAttribute("stroke", "#4a56f2");
t.setAttribute("fill", "none");
});
}
});
document.querySelector('.play-drawing').onclick = lineDrawing.restart;
```
The full result is available in the JSFiddle: <https://jsfiddle.net/jimbo2150/d8gc96em/>
Upvotes: 3 <issue_comment>username_2: **Updated Answer:** For what OP is trying to achieve. Still in pure css.
Explanation:
1. Look 'Previous Answer' on how to make it work like in the gif.
2. Now how to make each dash line like square. In blue line our `length` of each dashes is `10`. We can make the `stroke-width = 10` so they look like square. Now each square should only have `outline` and no `fill`. We will create another `mask` which blocks out the inner portion in each square.
```css
path {
fill: none
}
.path {
stroke-dasharray: 10;
stroke: blue;
stroke-width: 10;
}
/* Let the outline width of each square be 1 */
.maskSquare {
stroke: black;
/* To block or remove inner blue portion */
stroke-width: 8;
/* blue-dash-length minus 2*sqaure-length = 10 - 2 */
stroke-dasharray: 8 12;
/* 8+12 == 20 as in blue-dash-line 10+10 == 20 */
stroke-dashoffset: -1;
/* To sync */
}
.maskLineLength {
stroke: white;
stroke-width: 11;
animation: array 3s linear infinite;
}
@keyframes array {
from {
stroke-dasharray: 0 2000;
}
to {
stroke-dasharray: 1000 2000;
}
}
```
```html
```
**Previous Answer:** for the gif you provided
It can be done in pure css.
First, Blue dash path.
```css
.path {
stroke-dasharray: 10;
stroke: blue;
}
```
```html
```
Next a Masking path, using same path 1px greater stroke width.
```css
.maskPath {
animation: array 3s linear infinite;
}
@keyframes array {
from {
stroke-dasharray: 0 2000;
}
to {
stroke-dasharray: 1000 2000;
}
}
```
```html
```
When mask is applied on blue dash line result follows.
```css
.path {
stroke-dasharray: 10;
stroke: blue;
}
.maskPath {
animation: array 3s linear infinite;
}
@keyframes array {
from {
stroke-dasharray: 0 2000;
}
to {
stroke-dasharray: 1000 2000;
}
}
```
```html
```
(I may not be able help further as I am beginner in svg)
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,433 | 2,392 |
<issue_start>username_0: Sample Data:
```
id,action_datetime,value_id,
770940,03/15/2018 23:00:04,??,
801816,03/15/2018 22:45:49,??,
,,,
id,start_datetime,end_datetime,value_id
801816,03/15/2018 21:30:07,03/15/2018 21:55:29,595774419
774137,03/15/2018 22:38:35,03/15/2018 23:05:24,595777227
801816,03/15/2018 22:54:57,03/15/2018 23:02:16,595777156
647428,03/15/2018 22:53:48,03/15/2018 23:01:23,595777127
813437,03/15/2018 22:47:06,03/15/2018 23:01:04,595777115
801816,03/15/2018 22:42:03,03/15/2018 22:49:46,595776712
799132,03/15/2018 22:51:48,03/15/2018 23:00:30,595777071
813433,03/15/2018 22:48:10,03/15/2018 23:00:25,595777088
770940,03/15/2018 21:11:02,03/15/2018 22:10:45,595775340
792244,03/15/2018 22:56:44,03/15/2018 23:00:12,595777081
770940,03/15/2018 22:53:38,03/15/2018 23:00:32,595777094
647428,03/15/2018 22:40:46,03/15/2018 22:49:28,595776789
780946,03/15/2018 22:52:37,03/15/2018 23:00:48,595777105
800197,03/15/2018 22:48:26,03/15/2018 23:04:36,595777209
```
[](https://i.stack.imgur.com/rF6zd.jpg)
I need a **formula** that will return the **value\_id** (Col J) where the **action\_datetime** from Col B is between the **start\_datetime** (Col H) and **end\_datetime** (Col I) and the id from Col A matches the id from Col G.
I'd prefer a formula, but I could work with a VBA option too.
Any help would be great. I don't know how to be more specific, but if you have questions, let me know.
Thank you,<issue_comment>username_1: You can adjust the rages on this formula based on your data sets:
```
{=INDEX(H$2:H$15,MATCH(1,IF(B2>=F$2:F$15,IF(B2<=G$2:G$15,IF(A2=$E$2:$E$15,1))),0))}
```
Use `Ctrl`+`Shift`+`Enter` to activate the formula.
[](https://i.stack.imgur.com/zgRmr.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: In cell H2: =LOOKUP(G2,$B$2:$C$16,$D$2:$D$16)
[](https://i.stack.imgur.com/tJ2sZ.jpg)
This was created before the question was revised so the setup may not match yours exactly.
Credit: <https://www.mrexcel.com/forum/excel-questions/621562-vlookup-if-date-between-2-dates-table.html>
P.S. after looking at revised question, this may work better for you. In Cell C2: =vlookup(A2,$G$2:$J$15, 4,FALSE) and in Cell C3: =vlookup(A3,$G$2:$J$15
Upvotes: 0
|
2018/03/17
| 449 | 1,686 |
<issue_start>username_0: I have a code igniter project folder. Everything works fine.
But when i placed the project folder in another folder as a sub-folder, i get 404 Page Not Found for the Controller URLS i called.
For instance the CI url is <http://localhost/library>
Then i place it in another folder like : <http://localhost/school/library>
How do i solve this problem? I know its a directory problem.
Thank you.
.htaccess file :
```
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
```
Structure of folder
```
school/
students/
teachers/
library/
application/
system/
assets/
index.php
.htaccess
```
The library folder is using code igniter frame work but the school folder which is the main folder is using no frame work.<issue_comment>username_1: create a file named `.htaccess` and put this code in
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
```
Upvotes: 1 <issue_comment>username_2: The problem is you are pointing to an `index.php` that is in your root folder, change that by using `./index.php` instead.
Create a `.htaccess` file in your project folder with the following content:
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L]
```
You see the `./` part means **Add the path to where .htaccess exists**
Upvotes: 0
|
2018/03/17
| 567 | 1,964 |
<issue_start>username_0: Basically, everything *appears* to work fine and start up, but for some reason I can't call any of the commands. I've been looking around for easily an hour now and looking at examples/watching videos and I can't for the life of me figure out what is wrong. Code below:
```
import discord
import asyncio
from discord.ext import commands
bot = commands.Bot(command_prefix = '-')
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.event
async def on_message(message):
if message.content.startswith('-debug'):
await message.channel.send('d')
@bot.command(pass_context=True)
async def ping(ctx):
await ctx.channel.send('Pong!')
@bot.command(pass_context=True)
async def add(ctx, *, arg):
await ctx.send(arg)
```
The debug output I have in on\_message actually does work and responds, and the whole bot runs wihout any exceptions, but it just won't call the commands.<issue_comment>username_1: [From the documentation:](https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working)
>
> Overriding the default provided `on_message` forbids any extra commands from running. To fix this, add a `bot.process_commands(message)` line at the end of your `on_message`. For example:
>
>
>
> ```
> @bot.event
> async def on_message(message):
> # do some extra stuff here
>
> await bot.process_commands(message)
>
> ```
>
>
The default `on_message` contains a call to this coroutine, but when you override it with your own `on_message`, you need to call it yourself.
Upvotes: 8 [selected_answer]<issue_comment>username_2: Ascertained that the problem stems from your definition of `on_message`, you could actually just implement `debug` as a command, since it appears to have the same prefix as your bot:
```
@bot.command()
async def debug(ctx):
await ctx.send("d")
```
Upvotes: -1
|
2018/03/17
| 703 | 3,089 |
<issue_start>username_0: Fairly generic question because I'm afraid I don't have the best Java academic/theoretical fundamentals:
I work in a bank and we store/process lots of data. This takes the shape of account id, deal id, portfolio values, etc.
The goal is to take a request from an API or as a library, query a DB, perform some business transforms, and store to another DB.
1. Should the data types match the destination DB? I.e. use date objects when persisted as date. Long for IDs, double for decimals, string when varchar, etc..?
2. Do whatever is easier (often changing everything to strings) because of how the objects are handled in Java will have minimal performance ?
Thanks in advance for your time!<issue_comment>username_1: As Floegipoky has pointed out, use `final` so you make primitives and most simple objects immutable de facto.
Note that doesn't work for Collections, because even when an Collection object may be declared final, that only means that you can change the Collection reference, but still you can change its items with the methods their provide.
For example:
```
final List integers = new List();
// Do whatever operations you want with the list
integers.add(1); // <- No error. The list content is mutable.
integers = new List(); // <- Compiler error. The `final` means we cannot change the reference variable to point to a different list object.
```
Will add an integer to that integers list despite being final, although you cannot change the reference itself.
What you can do in these cases is to convert the list to an unmodifiable one:
```
final List integers = new List();
// Do whatever operations you want with the list
final List integersInmutable = Collections.unmodifiableList(integers);
integers = null; // Better safe than sorry…
integersInmutable.add(1); // <- runtime exception
integersInmutable = new List(); // <- compiler error
```
Probably there are other caveats, but remember that Java is an OOP language, so you can always create your own unmodifiable classes based on the ones that already exists. For example, if you want to restrict the operations you can do with a List, you can create your own list derivated from List or from AbstractList and override those methods you don't want to be used so they throw an exception for example.
Upvotes: 2 <issue_comment>username_2: Converting everything into String (e.g. converting numeric data to String) before storing into the database and converting it back to the native Java types (e.g. converting String back to numeric type) will impact performance along with the potential of being a lossy conversion.
You should take a look at the documentation and recommended best practices of the database driver you plan to use in choosing the datatypes. For example, if you are using the JDBC driver, you will find the database vendor documenting a mapping table between the Java/JDBC datatypes and the corresponding database type. Such a mapping table would have factored in choices that give the best performance without conversion loss.
Hope this helps!
Upvotes: 1
|
2018/03/17
| 611 | 2,153 |
<issue_start>username_0: Below is an excerpt of the html code:
```
Category1
"Text1 I want"
Category2
"Text2 I want"
```
I know I can extract Text1 and Text2 by using:
```
find_element = browser.find_elements_by_xpath("//div[@class='Class2']")
element = [x.text for x in find_element]
text1 = element[0]
text2 = element[1]
```
But if the structure of the html is changed, elements will be changed accordingly. Is there any way for me to extract Text1 and Text2 by referring to Category1 and Category2, respectively?
Thank you.<issue_comment>username_1: I suggest using BeautifulSoup. Find the Category1 tag, then its `next_sibling`:
```
import bs4
your_html = browser.page_source
soup = bs4.BeautifulSoup(your_html, 'lxml')
class1tag = soup.find('div', text='Category1')
tag = class1tag.next_sibling.next_sibling
print(tag)
#"Text1 I want"
print(tag.text)
#"Text1 I want"
```
Upvotes: 0 <issue_comment>username_2: If the `Text I want` always inside the next sibling `div` of `Category div`, you can try as following:
**Case 1**
```
Category1
"Text1 I want"
```
`//div[.='Category1']/following-sibling::div[1]`
**Case 2**
```
Category1
"Text1 I want"
```
`//div[.='Category1']/following-sibling::div[1]//span`
There can be many possible structure, the key part in the xpath is `//div[.='Category1']/following-sibling::div[1]`
Upvotes: 2 [selected_answer]<issue_comment>username_3: I guess that your concern regarding changes to the structure of the html are based on the fact that the semantics of the data is of key- value paid (the keys being the categories and the values are the text), while the structure is simply a list of divs where the odd ones are the keys and the following even ones are their corresponding values.
The problem though isn't with your Selenium locators, but rather in the structure of the html itself (which consequently affects your ability to use more robust locators). I would suggest that you ask the developers to improve the structure of the html to reflect it's appropriate semantics. Discuss *together* the best structure that fits all the needs, including those of the test automation.
Upvotes: 0
|
2018/03/17
| 1,232 | 4,459 |
<issue_start>username_0: ```
import React from 'react';
import {FirstCustomComponent} from './somewhere';
import {SecondCustomComponent} from './somewhere-else';
const ThirdCustomComponent = ({componentTitle, apple, banana}) => (
componentTitle === 'FirstCustomComponent'
?
:
);
export default ThirdCustomComponent;
```
What is a good way to avoid the repetition in the code sample above? I've tried dynamically generating a component by setting `const DynamicComponent = props.componentTitle` and then returning but no luck.<issue_comment>username_1: You can pass a Component as a prop. The component must be a valid react component; i.e. either a function that returns JSX or an implementation of `React.Component`
```
const ThirdCustomComponent = ({component: Component, apple, banana}) => (
);
// Using ThirdCustomComponent
import FirstCustomComponent from './FirstCustomComponent';
const apple = {...};
const banana = {...};
const Container = () => (
);
```
Upvotes: 0 <issue_comment>username_2: they're multiple ways to do this, if you don't want to import all elements into your pages, you could have a "middle" file create an object with all your elements, you could do something like this:
first.js
```
class First extends Component {
render(){
return (
first
{this.props.title}
)
}
}
```
second.js
```
class Second extends Component {
render(){
return (
second
{this.props.title}
)
}
}
```
objects.js
```
import First from './first.js'
import Second from './second.js'
const objects = {
"First": First,
"Second": Second,
}
import objects from './objects'
class Third extends Component {
render(){
const Type = objects[this.props.type];
return (
)
}
}
```
Main.js
```
class App extends Component {
render() {
return (
);
}
}
```
Upvotes: 1 <issue_comment>username_3: Probably you can achieve this using code similar to below (suppose you want to pass component names instead of component references)
```js
const First = ({a, b}) => 1-{a}-{b}
=========
const Second = ({a, b}) => 2-{a}-{b}
=========
const Comp = {
First,
Second,
} // we have Babel, ES6 object notation okay
const App = ({title, a, b}) => React.createElement(Comp[title], {a, b}) // just for one-liner, if you know React w/o JSX
/* Same as
const App = ({title, a, b}) => {
const Tag = Comp[title]
return
}
*/
ReactDOM.render(, document.getElementById('app'))
```
```html
```
Upvotes: -1 <issue_comment>username_4: You might like this approach if you are utilizing ES6 arrow functions in your React application. It utilizes the concept of an immediately invoked function. Its just generic JavaScript. Isn't that why we all write React in the first place? Well, and because we are smarter than the people that use Angular and Vue... =)
```
class Dynamic extends React.Component {
render() {
return (
{
(() => {
switch(this.props.title) {
case 'one':
return
case 'two':
return
default:
return null
}
})()
}
)
}
}
const One = () => Component One
const Two = () => Component Two
ReactDOM.render(
,
document.querySelector('#app')
)
```
I have included a working [example](https://codepen.io/DZuz14/pen/bvwrRK?editors=1010) on Codepen as well.
Upvotes: 0 <issue_comment>username_5: ```
const ThirdCustomComponent = ({componentTitle, apple, banana}) => {
const DynamicComponent =
componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return React.cloneElement(DynamicComponent, {
{ apple, banana }
}
};
```
Please try above code snippet.
Basically, `React.cloneElement(Component, props)` is the Solution.
Upvotes: 0 <issue_comment>username_6: You're close; the problem is that props.componentTitle is still a string but JSX is expects an actual Component. Specifically, (as explained in [this SO answer](https://stackoverflow.com/a/29876284/1810460)), compiles to `React.createElement(DynamicComponent , {})`, so you can do something like this
```js
const FirstCustomComponent = () => (
First
)
const SecondCustomComponent = () => (
Second
)
const ThirdCustomComponent = ({componentTitle}) => {
const DynamicComponent = componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return ;
}
ReactDOM.render(
, document.getElementById("container"));
```
```html
```
Upvotes: 0
|
2018/03/17
| 1,516 | 5,099 |
<issue_start>username_0: I trying to use navbar component from Twitter Bootstrap 4 with nested sub menu, but the arrow in the menu item that has sub menu is not appear at all, i do not no why.
here the arrow appears:
[](https://i.stack.imgur.com/J6xI4.jpg)
but not appear in my side:
[](https://i.stack.imgur.com/bQbSA.jpg)
Here's the basic outline of my html code:
```
Right Way
* Home (current)
* [Dropdown](#)
+ [Action](#)
+ [Another action](#)
+ [Submenu](#)
- [Submenu](#)
- [Submenu0](#)
- [Submenu 1](#)
* [Subsubmenu1](#)
* [Subsubmenu1](#)
- [Submenu 2](#)
* [Subsubmenu2](#)
* [Subsubmenu2](#)
```
that is my CSS code:
```
.navbar-nav li:hover > ul.dropdown-menu {
display: block;
}
.dropdown-submenu {
position: relative;
}
.dropdown-submenu > .dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
}
/* rotate caret on hover */
.dropdown-menu > li > a:hover:after {
text-decoration: underline;
transform: rotate(-90deg);
}
```
I do not know what the wrong i tried all my best.<issue_comment>username_1: You can pass a Component as a prop. The component must be a valid react component; i.e. either a function that returns JSX or an implementation of `React.Component`
```
const ThirdCustomComponent = ({component: Component, apple, banana}) => (
);
// Using ThirdCustomComponent
import FirstCustomComponent from './FirstCustomComponent';
const apple = {...};
const banana = {...};
const Container = () => (
);
```
Upvotes: 0 <issue_comment>username_2: they're multiple ways to do this, if you don't want to import all elements into your pages, you could have a "middle" file create an object with all your elements, you could do something like this:
first.js
```
class First extends Component {
render(){
return (
first
{this.props.title}
)
}
}
```
second.js
```
class Second extends Component {
render(){
return (
second
{this.props.title}
)
}
}
```
objects.js
```
import First from './first.js'
import Second from './second.js'
const objects = {
"First": First,
"Second": Second,
}
import objects from './objects'
class Third extends Component {
render(){
const Type = objects[this.props.type];
return (
)
}
}
```
Main.js
```
class App extends Component {
render() {
return (
);
}
}
```
Upvotes: 1 <issue_comment>username_3: Probably you can achieve this using code similar to below (suppose you want to pass component names instead of component references)
```js
const First = ({a, b}) => 1-{a}-{b}
=========
const Second = ({a, b}) => 2-{a}-{b}
=========
const Comp = {
First,
Second,
} // we have Babel, ES6 object notation okay
const App = ({title, a, b}) => React.createElement(Comp[title], {a, b}) // just for one-liner, if you know React w/o JSX
/* Same as
const App = ({title, a, b}) => {
const Tag = Comp[title]
return
}
*/
ReactDOM.render(, document.getElementById('app'))
```
```html
```
Upvotes: -1 <issue_comment>username_4: You might like this approach if you are utilizing ES6 arrow functions in your React application. It utilizes the concept of an immediately invoked function. Its just generic JavaScript. Isn't that why we all write React in the first place? Well, and because we are smarter than the people that use Angular and Vue... =)
```
class Dynamic extends React.Component {
render() {
return (
{
(() => {
switch(this.props.title) {
case 'one':
return
case 'two':
return
default:
return null
}
})()
}
)
}
}
const One = () => Component One
const Two = () => Component Two
ReactDOM.render(
,
document.querySelector('#app')
)
```
I have included a working [example](https://codepen.io/DZuz14/pen/bvwrRK?editors=1010) on Codepen as well.
Upvotes: 0 <issue_comment>username_5: ```
const ThirdCustomComponent = ({componentTitle, apple, banana}) => {
const DynamicComponent =
componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return React.cloneElement(DynamicComponent, {
{ apple, banana }
}
};
```
Please try above code snippet.
Basically, `React.cloneElement(Component, props)` is the Solution.
Upvotes: 0 <issue_comment>username_6: You're close; the problem is that props.componentTitle is still a string but JSX is expects an actual Component. Specifically, (as explained in [this SO answer](https://stackoverflow.com/a/29876284/1810460)), compiles to `React.createElement(DynamicComponent , {})`, so you can do something like this
```js
const FirstCustomComponent = () => (
First
)
const SecondCustomComponent = () => (
Second
)
const ThirdCustomComponent = ({componentTitle}) => {
const DynamicComponent = componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return ;
}
ReactDOM.render(
, document.getElementById("container"));
```
```html
```
Upvotes: 0
|
2018/03/17
| 1,277 | 4,565 |
<issue_start>username_0: I'm trying to create saved search of saved searches in order to see which saved search is sending which e-mail. Now once i have like 100 auto e-mails from saved searches in netsuite i would like to organize them.
For example i would like to have all active saved search with results :
1. Search name
2. Search ID
3. Email Subject
4. Email Body
5. Receipts
All i could find for now is 1(Name),2(Internal ID) and 5 (SearchSchedule : Recipient).
And just to mention this saved searches that i'm looking for are scheduled with an daily or weekly event which will trigger e-mail to go out.
Is there a way of getting 3 and 4?<issue_comment>username_1: You can pass a Component as a prop. The component must be a valid react component; i.e. either a function that returns JSX or an implementation of `React.Component`
```
const ThirdCustomComponent = ({component: Component, apple, banana}) => (
);
// Using ThirdCustomComponent
import FirstCustomComponent from './FirstCustomComponent';
const apple = {...};
const banana = {...};
const Container = () => (
);
```
Upvotes: 0 <issue_comment>username_2: they're multiple ways to do this, if you don't want to import all elements into your pages, you could have a "middle" file create an object with all your elements, you could do something like this:
first.js
```
class First extends Component {
render(){
return (
first
{this.props.title}
)
}
}
```
second.js
```
class Second extends Component {
render(){
return (
second
{this.props.title}
)
}
}
```
objects.js
```
import First from './first.js'
import Second from './second.js'
const objects = {
"First": First,
"Second": Second,
}
import objects from './objects'
class Third extends Component {
render(){
const Type = objects[this.props.type];
return (
)
}
}
```
Main.js
```
class App extends Component {
render() {
return (
);
}
}
```
Upvotes: 1 <issue_comment>username_3: Probably you can achieve this using code similar to below (suppose you want to pass component names instead of component references)
```js
const First = ({a, b}) => 1-{a}-{b}
=========
const Second = ({a, b}) => 2-{a}-{b}
=========
const Comp = {
First,
Second,
} // we have Babel, ES6 object notation okay
const App = ({title, a, b}) => React.createElement(Comp[title], {a, b}) // just for one-liner, if you know React w/o JSX
/* Same as
const App = ({title, a, b}) => {
const Tag = Comp[title]
return
}
*/
ReactDOM.render(, document.getElementById('app'))
```
```html
```
Upvotes: -1 <issue_comment>username_4: You might like this approach if you are utilizing ES6 arrow functions in your React application. It utilizes the concept of an immediately invoked function. Its just generic JavaScript. Isn't that why we all write React in the first place? Well, and because we are smarter than the people that use Angular and Vue... =)
```
class Dynamic extends React.Component {
render() {
return (
{
(() => {
switch(this.props.title) {
case 'one':
return
case 'two':
return
default:
return null
}
})()
}
)
}
}
const One = () => Component One
const Two = () => Component Two
ReactDOM.render(
,
document.querySelector('#app')
)
```
I have included a working [example](https://codepen.io/DZuz14/pen/bvwrRK?editors=1010) on Codepen as well.
Upvotes: 0 <issue_comment>username_5: ```
const ThirdCustomComponent = ({componentTitle, apple, banana}) => {
const DynamicComponent =
componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return React.cloneElement(DynamicComponent, {
{ apple, banana }
}
};
```
Please try above code snippet.
Basically, `React.cloneElement(Component, props)` is the Solution.
Upvotes: 0 <issue_comment>username_6: You're close; the problem is that props.componentTitle is still a string but JSX is expects an actual Component. Specifically, (as explained in [this SO answer](https://stackoverflow.com/a/29876284/1810460)), compiles to `React.createElement(DynamicComponent , {})`, so you can do something like this
```js
const FirstCustomComponent = () => (
First
)
const SecondCustomComponent = () => (
Second
)
const ThirdCustomComponent = ({componentTitle}) => {
const DynamicComponent = componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return ;
}
ReactDOM.render(
, document.getElementById("container"));
```
```html
```
Upvotes: 0
|
2018/03/17
| 1,338 | 4,491 |
<issue_start>username_0: For example having this:
```
Col1 | Col2 | NUMBER1
Fruit | Pear | 2
Fruit | Pear | 3
Fruit | Pear | 4
Fruit | Kiwi | 7
Fruit | Kiwi | 9
Car | Honda| 4
Car | Honda| 5
```
A fourth column would have the smallest number for each row that matches the first two columns:
```
Col1 | Col2 | NUMBER1 | COMPARED NUMBER
Fruit | Pear | 2 | 2
Fruit | Pear | 3 | 2
Fruit | Pear | 4 | 2
Fruit | Kiwi | 7 | 7
Fruit | Kiwi | 9 | 7
Car | Honda| 4 | 4
Car | Honda| 5 | 4
```
Is it possible too make a function for this?<issue_comment>username_1: You can pass a Component as a prop. The component must be a valid react component; i.e. either a function that returns JSX or an implementation of `React.Component`
```
const ThirdCustomComponent = ({component: Component, apple, banana}) => (
);
// Using ThirdCustomComponent
import FirstCustomComponent from './FirstCustomComponent';
const apple = {...};
const banana = {...};
const Container = () => (
);
```
Upvotes: 0 <issue_comment>username_2: they're multiple ways to do this, if you don't want to import all elements into your pages, you could have a "middle" file create an object with all your elements, you could do something like this:
first.js
```
class First extends Component {
render(){
return (
first
{this.props.title}
)
}
}
```
second.js
```
class Second extends Component {
render(){
return (
second
{this.props.title}
)
}
}
```
objects.js
```
import First from './first.js'
import Second from './second.js'
const objects = {
"First": First,
"Second": Second,
}
import objects from './objects'
class Third extends Component {
render(){
const Type = objects[this.props.type];
return (
)
}
}
```
Main.js
```
class App extends Component {
render() {
return (
);
}
}
```
Upvotes: 1 <issue_comment>username_3: Probably you can achieve this using code similar to below (suppose you want to pass component names instead of component references)
```js
const First = ({a, b}) => 1-{a}-{b}
=========
const Second = ({a, b}) => 2-{a}-{b}
=========
const Comp = {
First,
Second,
} // we have Babel, ES6 object notation okay
const App = ({title, a, b}) => React.createElement(Comp[title], {a, b}) // just for one-liner, if you know React w/o JSX
/* Same as
const App = ({title, a, b}) => {
const Tag = Comp[title]
return
}
*/
ReactDOM.render(, document.getElementById('app'))
```
```html
```
Upvotes: -1 <issue_comment>username_4: You might like this approach if you are utilizing ES6 arrow functions in your React application. It utilizes the concept of an immediately invoked function. Its just generic JavaScript. Isn't that why we all write React in the first place? Well, and because we are smarter than the people that use Angular and Vue... =)
```
class Dynamic extends React.Component {
render() {
return (
{
(() => {
switch(this.props.title) {
case 'one':
return
case 'two':
return
default:
return null
}
})()
}
)
}
}
const One = () => Component One
const Two = () => Component Two
ReactDOM.render(
,
document.querySelector('#app')
)
```
I have included a working [example](https://codepen.io/DZuz14/pen/bvwrRK?editors=1010) on Codepen as well.
Upvotes: 0 <issue_comment>username_5: ```
const ThirdCustomComponent = ({componentTitle, apple, banana}) => {
const DynamicComponent =
componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return React.cloneElement(DynamicComponent, {
{ apple, banana }
}
};
```
Please try above code snippet.
Basically, `React.cloneElement(Component, props)` is the Solution.
Upvotes: 0 <issue_comment>username_6: You're close; the problem is that props.componentTitle is still a string but JSX is expects an actual Component. Specifically, (as explained in [this SO answer](https://stackoverflow.com/a/29876284/1810460)), compiles to `React.createElement(DynamicComponent , {})`, so you can do something like this
```js
const FirstCustomComponent = () => (
First
)
const SecondCustomComponent = () => (
Second
)
const ThirdCustomComponent = ({componentTitle}) => {
const DynamicComponent = componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return ;
}
ReactDOM.render(
, document.getElementById("container"));
```
```html
```
Upvotes: 0
|
2018/03/17
| 1,208 | 4,356 |
<issue_start>username_0: I want to share HTML being a file and not in text form. First, would I need to generate a saved file on the phone to send later?
```
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(meuHtml));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
```<issue_comment>username_1: You can pass a Component as a prop. The component must be a valid react component; i.e. either a function that returns JSX or an implementation of `React.Component`
```
const ThirdCustomComponent = ({component: Component, apple, banana}) => (
);
// Using ThirdCustomComponent
import FirstCustomComponent from './FirstCustomComponent';
const apple = {...};
const banana = {...};
const Container = () => (
);
```
Upvotes: 0 <issue_comment>username_2: they're multiple ways to do this, if you don't want to import all elements into your pages, you could have a "middle" file create an object with all your elements, you could do something like this:
first.js
```
class First extends Component {
render(){
return (
first
{this.props.title}
)
}
}
```
second.js
```
class Second extends Component {
render(){
return (
second
{this.props.title}
)
}
}
```
objects.js
```
import First from './first.js'
import Second from './second.js'
const objects = {
"First": First,
"Second": Second,
}
import objects from './objects'
class Third extends Component {
render(){
const Type = objects[this.props.type];
return (
)
}
}
```
Main.js
```
class App extends Component {
render() {
return (
);
}
}
```
Upvotes: 1 <issue_comment>username_3: Probably you can achieve this using code similar to below (suppose you want to pass component names instead of component references)
```js
const First = ({a, b}) => 1-{a}-{b}
=========
const Second = ({a, b}) => 2-{a}-{b}
=========
const Comp = {
First,
Second,
} // we have Babel, ES6 object notation okay
const App = ({title, a, b}) => React.createElement(Comp[title], {a, b}) // just for one-liner, if you know React w/o JSX
/* Same as
const App = ({title, a, b}) => {
const Tag = Comp[title]
return
}
*/
ReactDOM.render(, document.getElementById('app'))
```
```html
```
Upvotes: -1 <issue_comment>username_4: You might like this approach if you are utilizing ES6 arrow functions in your React application. It utilizes the concept of an immediately invoked function. Its just generic JavaScript. Isn't that why we all write React in the first place? Well, and because we are smarter than the people that use Angular and Vue... =)
```
class Dynamic extends React.Component {
render() {
return (
{
(() => {
switch(this.props.title) {
case 'one':
return
case 'two':
return
default:
return null
}
})()
}
)
}
}
const One = () => Component One
const Two = () => Component Two
ReactDOM.render(
,
document.querySelector('#app')
)
```
I have included a working [example](https://codepen.io/DZuz14/pen/bvwrRK?editors=1010) on Codepen as well.
Upvotes: 0 <issue_comment>username_5: ```
const ThirdCustomComponent = ({componentTitle, apple, banana}) => {
const DynamicComponent =
componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return React.cloneElement(DynamicComponent, {
{ apple, banana }
}
};
```
Please try above code snippet.
Basically, `React.cloneElement(Component, props)` is the Solution.
Upvotes: 0 <issue_comment>username_6: You're close; the problem is that props.componentTitle is still a string but JSX is expects an actual Component. Specifically, (as explained in [this SO answer](https://stackoverflow.com/a/29876284/1810460)), compiles to `React.createElement(DynamicComponent , {})`, so you can do something like this
```js
const FirstCustomComponent = () => (
First
)
const SecondCustomComponent = () => (
Second
)
const ThirdCustomComponent = ({componentTitle}) => {
const DynamicComponent = componentTitle === 'FirstCustomComponent'
? FirstCustomComponent
: SecondCustomComponent;
return ;
}
ReactDOM.render(
, document.getElementById("container"));
```
```html
```
Upvotes: 0
|
2018/03/17
| 338 | 1,143 |
<issue_start>username_0: I have a string:
```
'<NAME>'
```
How can I get the first letter of each word in the string? For example, the first letter of each word in the above string would be:
```
P
i
g
```<issue_comment>username_1: How about you just slice the string when printing (or assign a new variable) and remove `start = word[0:][0]`:
```
trans = input("enter a sentence ")
trans = trans.lower()
t_list = trans.split()
for word in t_list:
print(word[0])
```
This works because you get a list containing all the values of the string (by default `split()` splits white-space), next you initerate through that list (this returns a single character) and then get the value of the first character of the string.
You could also use `trans = input("enter a sentence ").lower().split()` rather than redefine `trans` into a new variable each time.
Upvotes: 2 <issue_comment>username_2: ```
[ s[0] for s in '<NAME> good'.split() ]
```
Alternatively you could use zip on the unpacked result of split:
```
s = '<NAME>'
fl = next(zip(*s.split()))
print(fl) # ('P', 'i', 'g')
```
Upvotes: 4 [selected_answer]
|
2018/03/17
| 1,491 | 5,302 |
<issue_start>username_0: I just installed **Genymotion**, when I started and tried to register via Genymotion app this error appeared:
>
> Network Error
>
>
>
[](https://i.stack.imgur.com/r8y1R.png)
Seems like Genymotion can't figure out a way to connect to Internet!<issue_comment>username_1: In your, Genymotion goes to:
1. Settings -> Network
2. Check Use HTTP Proxy
3. Insert HTTP Proxy and Port
4. Click "OK"
5. Now try to login Genymotion.
I Hope to solve your problem.
Upvotes: -1 <issue_comment>username_2: I tried everything but nothing worked.
Try uninstalling Genymotion, create new account and then try to log in.
That is the only thing that worked for me.
Upvotes: 0 <issue_comment>username_3: The Genymotion website has an FAQ section where they lay out an answer that worked for me:
<https://www.genymotion.com/help/desktop/faq/#windows-ten-start-impossible>
---
Why doesn't Genymotion run on Windows 10?
To date, VirtualBox is not yet fully compatible with Windows 10. As Genymotion relies on the use of VirtualBox in the background, some problems may arise. If you have any troubles running Genymotion on Windows 10, we first recommend that you put VirtualBox in a clean state.
To do so:
```
-Uninstall VirtualBox.
-Reboot your computer if prompted by the installer.
-Install the version of VirtualBox recommended for Windows 10
-Reboot your computer if prompted by the installer.
-Open VirtualBox and go to File > Preferences > Network.
-Remove all existing host-only networks by clicking Description 1.
```
Start Genymotion a first time.
In the event of a failure, start Genymotion a second time.
If Genymotion still doesn’t run, you can manually configure a host-only network:
```
-Open VirtualBox and go to File > Preferences > Network.
-Add a new host-only network by clicking Description 1.
-Edit its configuration by clicking Description 1.
-In the Adapter tab, set the following values:
-IPv4 Address: 192.168.56.1
-IPv4 Network Mask: 255.255.255.0
-In the DHCP Server tab, set the following values:
-Check Enable Server.
-Server Address: 192.168.56.100
-Server Mask: 255.255.255.0
-Lower Address Bound: 192.168.56.101
-Upper Address Bound: 192.168.56.254
```
---
The problem appears to be the VM default settings (I suspect they get cached after first run and a manual setup doesn't always take, hence the re-install procedure)
I never had to create a new Genymotion account, my original worked after I reinstalled the Oracle VM & applied the settings they give above. (You can download an update and it should uninstall the old version and fresh install the new)
Cheers!
Upvotes: 2 <issue_comment>username_4: In Genymotion go to Settings-> Network and try to uncheck `Use HTTP Proxy`. This helped for me and hope helps others. I use Windows 7 Genymotion for personal use version 2.12.1.
Upvotes: 2 <issue_comment>username_5: Have the same problem. This helps me:
* Login to site.
* Press 'Send confirmation email'
* Click on the link in the confirmation email.
Upvotes: 1 <issue_comment>username_6: In my case (Ubuntu BB) the problem was caused by Virtualbox not having a network setting for guests. Apparently the Genymotion tool is itself (apart from the generated devices) running on a virtual device, and if no network is available for guests in Virtualbox, it would fail to connect to the internet and hence this message at login.
To resolve, just add a Nat network in the Virtualbox tool at File/Preferences/Network.
(Would be nice if a search at the maker's site /Genymotion/ for the error message generated by their software actually returned a hit! And nothing wrong with having an error message bit more informative.)
Upvotes: 0 <issue_comment>username_7: For those still having this issue, its a gateway issue.
**For Ubuntu**
type `netstat -r` to check network interfaces, now check the interface thats connected to the internet(wlan0 usually, you might see vboxnet0, ignore it).
1.copy the IP address and mask
2.open Virtual box(Latest Version->5.12)
3.click global tools,
4.click on Add(it will create vboxnet1)
5. now at IP column, paste the IP address, at mask column paste mask.
6. go to genymotion directory, open genymotion.ini
change `host.only.???? = vboxnet0` to `host.only.??? = vboxnet1(or the name of the new interface you created)`.
restart genymotion
Upvotes: 0 <issue_comment>username_8: In my case I tried few things to get it working without following the FAC as described in one of the answers above ( didn't remove VBox 5.2.16 and reinstall 5.2.6 .. didn't add a network adapter .. nothing of that)
Followed following steps:
* Remove HTTP proxy settings (or add one for testing and remove it)
* Go to Genymotion [reset login password](https://www.genymotion.com/account/password-reset/)
* Start VBox without starting any virtual devices
I guess starting VBox for first time does the job due to something in networking has bug in Genymotion.
Hope that helps.
Upvotes: 0 <issue_comment>username_9: 1- Try to uninstall *Genymotion* and reinstall it.
2- If you are using an old version then install a new version.
The above steps worked for me:)
Upvotes: 0 <issue_comment>username_10: Uninstall and Reinstall Genymotion just works for me.
Upvotes: 0
|
2018/03/17
| 812 | 2,840 |
<issue_start>username_0: i hope you can give me a hand with this one, I'm trying to put a div within a div but one keeps pulling the other down.
i'll paste some images:
This is what i'm trying to acomplish...
[enter image description here](https://i.stack.imgur.com/ABQZC.jpg)
And this is what I get...
[enter image description here](https://i.stack.imgur.com/a4LAZ.jpg)
An a brief explanation:
I need this "faded" box to be in the center on the page, then, I need this "NEW WAVE" text to be within said box, one problem I have is that if I put them in the same div, the text inherit the "faded" condition, but if I put them in different divs, the "faded" box pushes the div of the text down. I think I've tried the usual ways to fix this but nothing happens, yet, I'm just starting with HTML and CSS so clearly I'm missing something.
Now i'll leave the HTML and the CSS:
HTML:
```
NEW WAVE
--------
```
CSS (for this one i'll post an image):
[enter image description here](https://i.stack.imgur.com/GbcCI.jpg)
Thank you.<issue_comment>username_1: Here is the solution. What you have to do now is to change background colors, dimensions and other basic css to style is as you want. I suppose this is what you tried to achieve - box within a box with a title in the middle.
```css
.dimmed{width:500px;height:300px;background:blue;
display:flex;
align-items:center;
justify-content:center}
.dim-back{width:300px;height:150px;background:red;
border:5px white solid;
display:flex;
align-items:center;
justify-content:center}
```
```html
NEW WAVE
--------
```
Instead of background:blue use background:rgba(0,0,0,.3) and the last value (.3) is opacity (called alpha). You don't need a background for red box. This way it will look exactly as you want.
**UPDATE:**
Same result can be achieved after removing some . Check this solution. there is nothing easiest.
```css
.dimmed{width:500px;height:300px;
background:rgba(0,0,0,.3);
display:flex;
align-items:center;
justify-content:center}
h2{width:300px;height:150px;
border:5px white solid;
display:flex;
align-items:center;
justify-content:center}
```
```html
NEW WAVE
--------
```
You can use padding for tags instead of dimensions. In that case padding and border is the only thing you need. It depends on what you put in h2 tags (block image or text).
Upvotes: 1 [selected_answer]<issue_comment>username_2: Okay, Since you haven't shown your CSS yet.
The primary mistakes which I usually end up doing when using Bootstrap was with my starting and closing of div tags
You current structure happens to be like this.
```
NEW WAVE
--------
```
Try Nesting your div tags like this
```
NEW WAVE
--------
```
Upvotes: 1
|
2018/03/17
| 544 | 2,096 |
<issue_start>username_0: I suppose this should be straightforward, but I'm stuck to get that "cpsc" value. I tried to google this, and almost all of the search results told me to use ".value". But this particular class "control term" doesn't seem to work, and only returned "undefined".
```html
```
My code:
document.getElementsByClassName("control term")[0].value;<issue_comment>username_1: You are reading from the `div`. You should read from `input` instead.
`document.getElementsBYId("inputTag").value;`
Upvotes: 2 <issue_comment>username_2: The problem is that the class "control term" is on the div element and not your input. Also as a note, a class should be only one word (ie. controlTerm), having a space between them assigns two different classes to the div: control, and, term.
You have two options:
1. Add a class to your input
2. Get the child of document.getElementsByClassName("control term") and then extract its value.
Hope this helps
```
document.getElementsByClassName("term")[0].value;
```
Upvotes: 0 <issue_comment>username_3: ```
Try it
function myFunction() {
alert(document.getElementsByClassName("control term")[0].value);
}
```
You have to put class attribute in input tag
Upvotes: 0 <issue_comment>username_4: You need to add class to your input and then you can get the value of input using the following code.
```
Click me
function myFunction(){
alert(document.getElementsByClassName("test")[0].value);
}
```
If you have multiple input box with same class name inside "control term" div, you can access their values using following code.
```
Click me
function myFunction(){
alert(document.getElementsByClassName("test")[0].value);
alert(document.getElementsByClassName("test")[1].value);
}
```
Or if you want to get all values of input box inside "control term" div, you can do something like this.
```
Click me
function myFunction(){
var x = document.getElementsByClassName("control term");
for(var i = 0;i<=x.length;i++){
alert(x[0].getElementsByClassName("test")[i].value);
}
```
Hope this will help you.
Upvotes: 0
|
2018/03/17
| 623 | 2,299 |
<issue_start>username_0: I have a class:
```
const helper = function(val){
console.log(this.a);
console.log(this.b);
this.bar();
};
export class Foo {
public b = '45'
private a = 15;
bar(){
}
myMethod(){
return helper.apply(this,arguments);
}
}
```
the problem is, in the helper function, it doesn't know what the context is (what the value of 'this' is).
Is there a way for me to tell typescript that the value for this in the helper function is an instance of `Foo`?
(the reason I use the helper function is to create true private methods).<issue_comment>username_1: You are reading from the `div`. You should read from `input` instead.
`document.getElementsBYId("inputTag").value;`
Upvotes: 2 <issue_comment>username_2: The problem is that the class "control term" is on the div element and not your input. Also as a note, a class should be only one word (ie. controlTerm), having a space between them assigns two different classes to the div: control, and, term.
You have two options:
1. Add a class to your input
2. Get the child of document.getElementsByClassName("control term") and then extract its value.
Hope this helps
```
document.getElementsByClassName("term")[0].value;
```
Upvotes: 0 <issue_comment>username_3: ```
Try it
function myFunction() {
alert(document.getElementsByClassName("control term")[0].value);
}
```
You have to put class attribute in input tag
Upvotes: 0 <issue_comment>username_4: You need to add class to your input and then you can get the value of input using the following code.
```
Click me
function myFunction(){
alert(document.getElementsByClassName("test")[0].value);
}
```
If you have multiple input box with same class name inside "control term" div, you can access their values using following code.
```
Click me
function myFunction(){
alert(document.getElementsByClassName("test")[0].value);
alert(document.getElementsByClassName("test")[1].value);
}
```
Or if you want to get all values of input box inside "control term" div, you can do something like this.
```
Click me
function myFunction(){
var x = document.getElementsByClassName("control term");
for(var i = 0;i<=x.length;i++){
alert(x[0].getElementsByClassName("test")[i].value);
}
```
Hope this will help you.
Upvotes: 0
|
2018/03/17
| 615 | 2,041 |
<issue_start>username_0: When I want to deploy my Django App on Heroku, I met an error as below:
`DisallowedHost at /
Invalid HTTP_HOST header: 'ecommerceyy.herokuapp.com'. You may need to add 'ecommerceyy.herokuapp.com' to ALLOWED_HOSTS.`
However, I have code in production.py like:
```
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com']
```
And my wsgi.py is like:
```
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings")
application = get_wsgi_application()
```
And encrypt ssl/tls https like:
```
CORS_REPLACE_HTTPS_REFERER = True
HOST_SCHEME = "https://"
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_SECONDS = 1000000
SECURE_FRAME_DENY = True
```
I modify my setting.py into a settings folder
[](https://i.stack.imgur.com/sOgjb.png)
the BASE\_DIR is like `os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))`
In the **init**.py in the settings folder, the code is like from
```
from .base import *
from .production import *
try:
from .local import *
except:
pass
```
So what's wrong with my app?<issue_comment>username_1: I commit out from .base & from .local, only push .production to heroku, it works.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Heroku has added the django\_heroku package which handles this along with several other nice pieces of functionality.
<https://devcenter.heroku.com/articles/django-app-configuration>
Upvotes: 2 <issue_comment>username_3: What you can do:
* Open `settings.py`.
* On top add: `import django_heroku`.
* Add: `django_heroku.settings(locals())`.
Then push code with all `requirements.txt`, `procfiles` and `runtime.txt`.
Upvotes: -1
|
2018/03/17
| 428 | 1,929 |
<issue_start>username_0: I'm trying to create a shell using C that can take multiple commands separated by a semicolon(;). Currently I'm trying to use strtok to separate the commands but I don't think I'm using it correctly. I'll post all the info I can without posting the entire code. Is strtok being used correctly?
```
char *semi=";";
else
{
char *token=strtok(str,semi);
if(token != NULL)
{
token=strtok(NULL,semi);
if((childpid = fork()) == 0)
{
if ((execvp(args[0], args))<0)//prints error message when unknown command is used
{
printf("Error! Command not recognized.\n");
}
execvp(args[0],args);
free(args);//deallocate args
exit(0);
}
```
Edit: As per instructed I removed a large chunk of the code originally posted to focus solely on the use of strtok. When compiled the makeshift shell will accept one command at a time. I'm trying to use ";" to separate and run two commands simultaneously. Am I using strtok correctly? If not, is there an alternative?<issue_comment>username_1: I commit out from .base & from .local, only push .production to heroku, it works.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Heroku has added the django\_heroku package which handles this along with several other nice pieces of functionality.
<https://devcenter.heroku.com/articles/django-app-configuration>
Upvotes: 2 <issue_comment>username_3: What you can do:
* Open `settings.py`.
* On top add: `import django_heroku`.
* Add: `django_heroku.settings(locals())`.
Then push code with all `requirements.txt`, `procfiles` and `runtime.txt`.
Upvotes: -1
|
2018/03/17
| 659 | 2,274 |
<issue_start>username_0: I have the following code running on Xcode Playground. However, even though I specify that the label is centered at the center of the view, it doesn't appear there.
```
import UIKit
import PlaygroundSupport
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
label.center = CGPoint(x: view.frame.width / 2, y: view.frame.height / 2)
label.text = "<NAME>!"
label.textColor = UIColor.black
view.addSubview(label)
}
}
PlaygroundPage.current.liveView = TestViewController()
```
[](https://i.stack.imgur.com/jZShO.png)<issue_comment>username_1: `view` frame is not finalized when `viewDidLoad` is triggered, you need to set the frame of the label inside the method `viewDidLayoutSubviews` as this method is being invoked when view bound was finalized.
**Try**
```
class TestViewController: UIViewController {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
label.text = "<NAME>!"
label.textColor = UIColor.black
self.view.addSubview(label)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.label.center = self.view.center
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: The view controller's view's frame is not final in `viewDidLoad`.
You either need to set the label's autoresizingMask or apply constraints to keep it in the center.
And since you made the label wider than the text, you also need to set the label's `textAlignment` to `center`.
```
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
label.center = view.center
label.text = "Hello World!"
label.textColor = .black
label.textAlignment = .center // or call label.sizeToFit()
label.autoresizingMask = [ .flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, ]
view.addSubview(label)
```
Upvotes: 2
|
2018/03/17
| 529 | 1,943 |
<issue_start>username_0: I want to create a blob storage trigger that takes any files put into blob storage (a fast process) and transfers them to Data Lake storage (NOT to another Blob Storage location).
Can this be done?
Can it be done using JavaScript, or does it require C#?
Does sample code exist showing how to do this? If so, would you be so kind as to point me to it?
Note: we've created a pipeline that will go from Blob Storage to Data lake storage. That's not what I'm asking about here.<issue_comment>username_1: You could potentially use an Azure Function or Azure Logic App to detect new files on Blob Storage and either call your webhook to trigger the pipeline or do the move itself.
Upvotes: 1 <issue_comment>username_2: >
> Can this be done?
>
>
>
As username_1 mentioned that we could use Azure function to do that.
>
> Can it be done using JavaScript, or does it require C#?
>
>
>
It can be done with javascript or C#.
>
> Does sample code exist showing how to do this? If so, would you be so kind as to point me to it?
>
>
>
How to create a Blob storage triggered function, please refer to [this document](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-storage-blob-triggered-function#create-a-blob-storage-triggered-function). We also could get the C#/javascript demo code from [this document](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob#trigger---example).
**JavaScript code**
```
module.exports = function(context) {
context.log('Node.js Blob trigger function processed', context.bindings.myBlob);
context.done();
};
```
**C# code**
```
[FunctionName("BlobTriggerCSharp")]
public static void Run([BlobTrigger("samples-workitems/{name}")] Stream myBlob, string name, TraceWriter log)
{
log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}
```
Upvotes: 0
|
2018/03/17
| 749 | 2,560 |
<issue_start>username_0: The code below is supposed to create a directory for the country (two letter code) if it doesn't exist and a directory based on the age group if it doesn't exist however whenever someone uploads an image it comes in as a broken image and isn't shown unless I precreate the directories. I checked the error log and it gives me the following warning:
>
> PHP Warning: mkdir(): No such file or directory in /home/wppspeacepals/public\_html/insertParentStudent.php on line 64
>
>
> PHP Warning: mkdir(): No such file or directory in /home/wppspeacepals/public\_html/insertParentStudent.php on line 70
>
>
>
```
$user_path = $_SERVER['DOCUMENT_ROOT']."/wp-content/themes/wellness-
pro/artis-images/".$get_Country->country."/".$age_group_label;
if(!is_dir($user_path)){
mkdir($user_path, 0777);
}
$user_id = $get_Country->prefix_char.$get_Country->registration_number;
$user_path = $_SERVER['DOCUMENT_ROOT']."/wp-content/themes/wellness-pro/artis-images/".$get_Country->country."/".$age_group_label."/".$user_id;
if(!is_dir($user_path)){
mkdir($user_path, 0777);
}
```<issue_comment>username_1: You could potentially use an Azure Function or Azure Logic App to detect new files on Blob Storage and either call your webhook to trigger the pipeline or do the move itself.
Upvotes: 1 <issue_comment>username_2: >
> Can this be done?
>
>
>
As username_1 mentioned that we could use Azure function to do that.
>
> Can it be done using JavaScript, or does it require C#?
>
>
>
It can be done with javascript or C#.
>
> Does sample code exist showing how to do this? If so, would you be so kind as to point me to it?
>
>
>
How to create a Blob storage triggered function, please refer to [this document](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-storage-blob-triggered-function#create-a-blob-storage-triggered-function). We also could get the C#/javascript demo code from [this document](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob#trigger---example).
**JavaScript code**
```
module.exports = function(context) {
context.log('Node.js Blob trigger function processed', context.bindings.myBlob);
context.done();
};
```
**C# code**
```
[FunctionName("BlobTriggerCSharp")]
public static void Run([BlobTrigger("samples-workitems/{name}")] Stream myBlob, string name, TraceWriter log)
{
log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}
```
Upvotes: 0
|
2018/03/17
| 562 | 1,968 |
<issue_start>username_0: ```
import json
import requests
import sys
exampleURL = 'https://apps.runescape.com/runemetrics/quests?user=Marebelle'
questName = 'All Fired Up'
response = requests.get(exampleURL)
if response.status_code==200:
questData = response.content.decode('utf-8')
```
how can I search for questName and have it print this only `{"title":"All Fired Up","status":"COMPLETED","difficulty":1,"members":true,"questPoints":1,"userEligible":true}`
sorry for bad formatting, any help is appreciated, thanks!<issue_comment>username_1: You could potentially use an Azure Function or Azure Logic App to detect new files on Blob Storage and either call your webhook to trigger the pipeline or do the move itself.
Upvotes: 1 <issue_comment>username_2: >
> Can this be done?
>
>
>
As username_1 mentioned that we could use Azure function to do that.
>
> Can it be done using JavaScript, or does it require C#?
>
>
>
It can be done with javascript or C#.
>
> Does sample code exist showing how to do this? If so, would you be so kind as to point me to it?
>
>
>
How to create a Blob storage triggered function, please refer to [this document](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-storage-blob-triggered-function#create-a-blob-storage-triggered-function). We also could get the C#/javascript demo code from [this document](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob#trigger---example).
**JavaScript code**
```
module.exports = function(context) {
context.log('Node.js Blob trigger function processed', context.bindings.myBlob);
context.done();
};
```
**C# code**
```
[FunctionName("BlobTriggerCSharp")]
public static void Run([BlobTrigger("samples-workitems/{name}")] Stream myBlob, string name, TraceWriter log)
{
log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}
```
Upvotes: 0
|
2018/03/17
| 545 | 2,147 |
<issue_start>username_0: Assume RDS A has the following tables: table1, table2, table3;
And RDS B has the above tables and then more: table1, table2, table3, table4, table5.
Can I do a one-way copy from RDS A to RDS B?
That is, the data in the three tables (table1, table2, table3) in RDS A is copied to the corresponding three tables (table1, table2, table3) in RDS B simultaneously.
Moreover, can I modify the other two table i.e. table4 and table5 of RDS B, afterwards?
If this is possible, what will be the proper steps to achieve that?<issue_comment>username_1: Yes! You can do it using Aws Database Migration Service. Please take a look at <https://aws.amazon.com/dms/>
You can use AWS console to create and map the source and destination or install the schema something from amazon to do it.
Upvotes: 0 <issue_comment>username_2: There are multiple ways to achieve this. Each approach has its tradeoffs interms of staleness of data, efficiency, cost & etc.
* Using AWS Glue you can do timely data migrations in the form so of ETL. Few advantages of this approach is that you can select idividual tables for migration as well as do any transformation before data puts in to RDS B. If you are familiar with Python this will be a great choice since its serverless and less moving parts to manage.
* Using AWS Data Migration Service. Suits both for timely migrations as well as continuous migrations.
* Using AWS Data Pipeline. More suitable for very large databases and if you also have plans to do any computational heavy transformatins. For small databases this can be a overkill.
* For timely migrations, you can create a Snapshot of RDS A and Restore it to RDS B or promote a Read Replica to RDS B.
More details in comparing AWS Glue and other Services refer the [AWS FAQ](https://aws.amazon.com/glue/faqs/#gluefaq-positioning).
Note: All of these approaches are one way trasfer so you can edit the tables on the RDS B.
Upvotes: 2 <issue_comment>username_3: Using the AWS Data Migration Service you can perform a one-time move or continuous replication of specific tables and even specific columns within those tables.
Upvotes: 0
|
2018/03/17
| 682 | 1,943 |
<issue_start>username_0: I'd like to know how to default a nested defaultdict to a list `[0,0,0]`. For example, I'd like to make this hierarchical defaultdict.
```
dic01 = {'year2017': {'jul_to_sep_temperature':[25, 20, 17],
'oct_to_dec_temperature':[10, 8, 7]},
'year2018': {'jan_to_mar_temperature':[ 8, 9, 10].
'apr_to_jun_temperature':[ 0, 0, 0]}
}
```
To make this nested dictioanry, I did `dic01 = defaultdict(dict)` and added a dictionary as `dic01['year2018']['jan_temperature'] = [8, 9, 10]`. My question is if it's possible to update each element of a list without previously binding [0, 0, 0]. In other works, if I make a defaultdict as `defaultdict(dict)`, I have to bind a list [0,0,0] before using it, and I'd like to skip this binding process.
```
# The way I do this
dic01['year2018']['jul_to_sep_temperature'] = [0,0,0] # -> how to omit this procedure?
dic01['year2018']['jul_to_sep_temperature'][0] = 25
# The way I want to do this
dic01['year2018']['jul_to_sep_temperature'][0] = 25 # by the end of July
```<issue_comment>username_1: You can specify that you want a default value of a `defaultdict` that has a default value of `[0, 0, 0]`
```
from collections import defaultdict
dic01 = defaultdict(lambda: defaultdict(lambda: [0, 0, 0]))
dic01['year2018']['jul_to_sep_temperature'][0] = 25
print(dic01)
```
prints
```
defaultdict( at 0x7f4dc28ac598>, {'year2018': defaultdict(.. at 0x7f4dc28ac510>, {'jul\_to\_sep\_temperature': [25, 0, 0]})})
```
Which you can treat as a regular nested dictionary
Upvotes: 4 [selected_answer]<issue_comment>username_2: Not sure if this is more elegant than what you are trying to avoid, but:
```
dic01 = defaultdict(lambda: defaultdict(lambda: [0,0,0]))
dic01['year2018']['jul_to_sep_temperature'][0] = 25
```
you can nest `defaultdicts` however you want by passing lambda functions
Upvotes: 2
|
2018/03/17
| 1,315 | 3,358 |
<issue_start>username_0: I want to format the float numbers in my Python app according to the current locale. The [Format Specification Mini-Language](https://docs.python.org/3/library/string.html#formatspec) states that one of the "available presentation types for floating point and decimal values" is:
>
> 'n' Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
>
>
>
But I can't make it work. This is how I tried:
```
$ unset LC_ALL
$ unset LANG
$ export LANG=de_DE.UTF-8
$ python3 -c "import locale; print (locale.getdefaultlocale())"
('de_DE', 'UTF-8')
$ python3 -c "print ('{0:.3n}'.format(3.14))"
3.14
```
I also tried with:
```
$ python3 -c "import locale; print (locale.str(3.14))"
3.14
$ python3 -c "import locale; print (locale.format_string('%.2f', 3.14))"
3.14
```
I would expect all of these to print `3,14`, not `3.14`. Any idea what's wrong?<issue_comment>username_1: [`format_string()`](https://docs.python.org/3/library/locale.html#locale.format_string) says "Formats a number val according to the current `LC_NUMERIC` setting."
If you are wanting to test numbers in different locales this is how you change the locale:
```py
import locale
# Change to German locale
locale.setlocale(locale.LC_NUMERIC, 'de_DE')
```
Using some of your examples, we have:
```py
number = 3.14
print(r'Expecting 3,14 Using %g')
print(locale.format_string('%g', number))
print(r'Expecting 3,14 Using %.2f')
print(locale.format_string('%.2f', number))
print(r'Expecting 3,14 Using locale.str()')
print(locale.str(number))
```
Output:
```bash
Expecting 3,14 Using %g
3,14
Expecting 3,14 Using %.2f
3,14
Expecting 3,14 Using locale.str()
3,14
```
Changing locale (back) to US
```py
locale.setlocale(locale.LC_NUMERIC, 'en_US')
```
Now I get the following output:
```bash
Expecting 3.14 Using %g
3.14
Expecting 3.14 Using %.2f
3.14
Expecting 3.14 Using locale.str()
3.14
```
Upvotes: 1 <issue_comment>username_2: Only setting the environment variables is not enough:
```bash
$ unset LC_ALL
$ unset LANG
$ export LANG=de_DE.UTF-8
```
You need to set LC\_NUMERIC or LC\_ALL explicitly with [locale.setlocale](https://docs.python.org/3/library/locale.html#locale.setlocale) at the start of your Python script:
```bash
$ python3 -c "import locale; locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3.14 3.14 3.14 3.14 3.14
$ python3 -c "import locale; locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3,14 3,14 3,14 3.14 3,14
$ python3 -c "import locale; locale.setlocale(locale.LC_ALL, 'en_US.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3.14 3.14 3.14 3.14 3.14
$ python3 -c "import locale; locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3,14 3,14 3,14 3.14 3,14
```
Upvotes: 2
|
2018/03/17
| 605 | 2,158 |
<issue_start>username_0: When I typed in my answer i got this:
```
The given method does not accept the given parameter types.
no suitable method found for min(int,int,int)
Math.min(species, Q13, shadow);
^
method Math.min(double,double) is not applicable
(actual and formal argument lists differ in length)
method Math.min(float,float) is not applicable
(actual and formal argument lists differ in length)
method Math.min(int,int) is not applicable
(actual and formal argument lists differ in length)
method Math.min(long,long) is not applicable
(actual and formal argument lists differ in length)
```
Any idea how I can fix the aforementioned error? I'm new to this site and the Java programming language and I'm very confused on how to fix this error.
Thank you for your help!<issue_comment>username_1: [`Math.min(int, int)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#min-int-int-) does not take three (or more) arguments. It only takes two. Change
```
int variable = Math.min(species, Q13, shadow);
```
to
```
int variable = Math.min(species, Math.min(Q13, shadow));
```
Upvotes: 0 <issue_comment>username_2: `Math.min` is only limited to two arguments, you can either pass the result of one `Math.min` into another `Math.min` call just as Elliott has shown in his answer or you can do:
```
int min = IntStream.of(species, Q13, shadow).min().getAsInt();
```
Upvotes: 0 <issue_comment>username_3: Alternatively, you could create your own min function, something like:
```
public static int min(int... params) {
int min = Integer.MAX_VALUE;
for (int param : params) {
if (param < min)
min = param;
}
return min;
}
```
This is not as fancy as functional programming, but it's still compatible to Java7 for those that for one reason or another cannot still use Java8 in some projects.
Or you could just use Apache Commons ObjectUtils.min generic function:
```
@SafeVarargs
public static > T min(T... values)
```
<https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#min-T...->
Upvotes: 1
|
2018/03/17
| 1,540 | 5,503 |
<issue_start>username_0: am trying to Fetch the movies data from Mysql DB and show it to Recycler view
but when i run the app nothing shows
here is code i am using Retrofite Library
but i can't parse the Data to the Recycler view
i've made Adapter and Model Class normally like the Json
>
> MainActivity.class
>
>
>
```
public class MainActivity extends AppCompatActivity {
private static final String url="http://192.168.1.109/stu/";
RecyclerView recyclerViewMovies;
List movies;
MoviesAdapter adapter;
TextView Errortxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\_main);
Errortxt = (TextView)findViewById(R.id.txterror);
recyclerViewMovies = (RecyclerView)findViewById(R.id.recyclerview);
recyclerViewMovies.setHasFixedSize(true);
recyclerViewMovies.setLayoutManager(new LinearLayoutManager(this));
movies = new ArrayList<>();
loadDatafromServer();
}
private void loadDatafromServer() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call call = api.ShowMoviesData();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
MovieListsModels movie = response.body();
adapter = new MoviesAdapter(MainActivity.this, (List) movie);
recyclerViewMovies.setAdapter(adapter);
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call call, Throwable t) {
Errortxt.setText(t.getMessage().toString());
}
});
}
```
this is the interface of the methods
>
> Api.class Interface
>
>
>
```
public interface Api {
@GET("config.php")
Call ShowMoviesData();
}
```
>
> MovieLists.class
>
>
>
```
public class MovieListsModels {
public MovieListsModels() {
}
int id;
String movie_name;
String movie_image;
String movie_genre;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMovie_name() {
return movie_name;
}
public void setMovie_name(String movie_name) {
this.movie_name = movie_name;
}
public String getMovie_image() {
return movie_image;
}
public void setMovie_image(String movie_image) {
this.movie_image = movie_image;
}
public String getMovie_genre() {
return movie_genre;
}
public void setMovie_genre(String movie_genre) {
this.movie_genre = movie_genre;
}
public MovieListsModels(int id, String movie_name, String movie_image, String movie_genre) {
this.id = id;
this.movie_name = movie_name;
this.movie_image = movie_image;
this.movie_genre = movie_genre;
}
}
```
>
> MovieAdapter.class
>
>
>
```
public class MoviesAdapter extends RecyclerView.Adapter {
private Context mContext;
private List MovieList = new ArrayList<>();
public MoviesAdapter(Context mContext, List movieList) {
this.mContext = mContext;
MovieList = movieList;
}
@NonNull
@Override
public MovieHolderView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row\_item,parent,false);
MovieHolderView holder = new MovieHolderView(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MovieHolderView holder, int position) {
MovieListsModels list = MovieList.get(position);
holder.txtName.setText(list.getMovie\_name());
holder.txtGenre.setText(list.getMovie\_genre());
Picasso.get()
.load(list.getMovie\_image())
.into(holder.imgMovie);
}
@Override
public int getItemCount() {
return MovieList.size();
}
public class MovieHolderView extends RecyclerView.ViewHolder {
TextView txtName,txtGenre;
ImageView imgMovie;
public MovieHolderView(View itemView) {
super(itemView);
txtName =(TextView)itemView.findViewById(R.id.movieName);
txtGenre =(TextView)itemView.findViewById(R.id.movieGenre);
imgMovie =(ImageView)itemView.findViewById(R.id.movieImg);
}
}
}
```<issue_comment>username_1: [`Math.min(int, int)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#min-int-int-) does not take three (or more) arguments. It only takes two. Change
```
int variable = Math.min(species, Q13, shadow);
```
to
```
int variable = Math.min(species, Math.min(Q13, shadow));
```
Upvotes: 0 <issue_comment>username_2: `Math.min` is only limited to two arguments, you can either pass the result of one `Math.min` into another `Math.min` call just as Elliott has shown in his answer or you can do:
```
int min = IntStream.of(species, Q13, shadow).min().getAsInt();
```
Upvotes: 0 <issue_comment>username_3: Alternatively, you could create your own min function, something like:
```
public static int min(int... params) {
int min = Integer.MAX_VALUE;
for (int param : params) {
if (param < min)
min = param;
}
return min;
}
```
This is not as fancy as functional programming, but it's still compatible to Java7 for those that for one reason or another cannot still use Java8 in some projects.
Or you could just use Apache Commons ObjectUtils.min generic function:
```
@SafeVarargs
public static > T min(T... values)
```
<https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#min-T...->
Upvotes: 1
|
2018/03/17
| 567 | 2,029 |
<issue_start>username_0: I'm using Redux-Saga to return data to state. I'd like to take that state and set it to a Field value within Redux-Form. I would think I could use something like
```
dispatch(change('form', 'field', 'value'));
```
The complication is handling this after the saga returns the value. Thus preventing a race event. I have the value I need in mapStateToProps in an HOC. Is there anyway to watch for a change to that prop and set the Redux-form value upon change?
Things I've looked into thus far include include setting a new Initial Value. Happy to provide any code necessary, but figured I'd start here to see what would actually help getting this solved vs making a text wall.<issue_comment>username_1: [`Math.min(int, int)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#min-int-int-) does not take three (or more) arguments. It only takes two. Change
```
int variable = Math.min(species, Q13, shadow);
```
to
```
int variable = Math.min(species, Math.min(Q13, shadow));
```
Upvotes: 0 <issue_comment>username_2: `Math.min` is only limited to two arguments, you can either pass the result of one `Math.min` into another `Math.min` call just as Elliott has shown in his answer or you can do:
```
int min = IntStream.of(species, Q13, shadow).min().getAsInt();
```
Upvotes: 0 <issue_comment>username_3: Alternatively, you could create your own min function, something like:
```
public static int min(int... params) {
int min = Integer.MAX_VALUE;
for (int param : params) {
if (param < min)
min = param;
}
return min;
}
```
This is not as fancy as functional programming, but it's still compatible to Java7 for those that for one reason or another cannot still use Java8 in some projects.
Or you could just use Apache Commons ObjectUtils.min generic function:
```
@SafeVarargs
public static > T min(T... values)
```
<https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#min-T...->
Upvotes: 1
|
2018/03/17
| 1,780 | 5,270 |
<issue_start>username_0: I have a table where users get to set a reaction/vote to a given event and I want to be able to create a summary view to see which reaction was voted on most times, divided by group per event.
The sample data is as follows:
```
DECLARE @voteTable AS TABLE (
id INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
eventId VARCHAR(255) NOT NULL
, isGroupA INT NOT NULL
, isGroupB INT NOT NULL
, userVote VARCHAR(255) NOT NULL
);
INSERT INTO @voteTable (eventId, isGroupA, isGroupB, userVote)
VALUES
('event1','0','0','fantastic'),
('event1','0','0','fantastic'),
('event1','0','0','fantastic'),
('event1','0','0','fantastic'),
('event1','0','0','fantastic'),
('event1','0','0','fantastic'),
('event1','0','0','meh'),
('event1','0','0','meh'),
('event1','1','0','fine'),
('event1','1','0','fine'),
('event1','1','0','great'),
('event1','1','0','ok'),
('event1','1','0','ok'),
('event1','1','0','ok'),
('event1','0','1','fine'),
('event1','0','1','great'),
('event1','0','1','great'),
('event1','0','1','ok'),
('event1','1','1','bad'),
('event1','1','1','bad'),
('event1','1','1','horrible'),
('event1','1','1','horrible'),
('event1','1','1','horrible'),
('event1','1','1','horrible'),
('event1','1','1','horrible'),
('event1','1','1','ok'),
('event2','0','0','fantastic'),
('event2','0','0','fantastic'),
('event2','0','0','fantastic'),
('event2','0','0','horrible'),
('event2','0','0','fantastic'),
('event2','0','0','fantastic'),
('event2','0','0','fine'),
('event2','0','0','great'),
('event2','1','0','meh'),
('event2','1','0','meh'),
('event2','1','0','ok'),
('event2','1','0','ok'),
('event2','1','0','ok'),
('event2','1','0','ok'),
('event2','0','1','bad'),
('event2','0','1','bad'),
('event2','0','1','bad'),
('event2','0','1','bad'),
('event2','1','1','fine'),
('event2','1','1','fine'),
('event2','1','1','great'),
('event2','1','1','great'),
('event2','1','1','ok'),
('event2','1','1','bad'),
('event2','1','1','ok'),
('event2','1','1','ok')
```
The output I want to get should be like:
```
eventId | groupA | groupB | everyone
----------------------------------------
event1 | horrible | horrible | fantastic
event2 | ok | bad | ok
```
The reason being that for event1:
* Those with a 1 for isGroupA voted "horrible" 5 times, more than any
other vote type.
* Those with a 1 for isGroupB also voted "horrible" 5 times, more than
any other vote.
* The most votes regardless of group for event1
was "fantastic."
Similarly for event2:
* Those in groupA voted "ok" 7 times, more than any other vote.
* Those in groupB voted "bad" 5 times, more than any other vote.
* Vote type with the highest frequency regardless of group was "ok"
I hope I was clear in my problem. Let me know if I was unclear or if I need to clarify anything.
I was thinking of doing something with a `COUNT(isGroupA) as aVotes`, grouping by eventId and userVote and using the `RANK()` function, but I can't seem to wrap my head around how to structure the whole query.
Thanks in advance for the help!<issue_comment>username_1: You are looking for the mode. One method for getting this uses aggregation and window functions:
```
select eventid,
max(case when grp = 'A' then uservote end) as groupA,
max(case when grp = 'B' then uservote end) as groupB,
max(case when grp = 'Both' then uservote end) as both
from (select eventid, uservote, grp, count(*) as cnt,
row_number() over (partition by eventid, grp order by count(*) desc) as seqnum
from votetable vt cross apply
(values (case when isGroupA = '1' then 'A' end),
(case when isGroupB = '1' then 'b' end),
('Both')
) v(grp)
where grp is not null
group by eventid, uservote, grp
) eg
where seqnum = 1
group by eventId;
```
[Here](http://www.sqlfiddle.com/#!18/71b52/9) is a SQL Fiddle.
Upvotes: 2 <issue_comment>username_2: using Cte table
```
;
with CteCount as(
Select eventId, isGroupA, null as isGroupB,
ROW_NUMBER() over (Partition by eventId, isGroupA, UserVote Order by eventId, isGroupA, UserVote) as isGroupACount,
null as isGroupBCount,
null as isAllCount,
uservote
from @voteTable
where isGroupA = 1
UNION ALL
Select eventId, null as isGroupA, isGroupB,
null,
ROW_NUMBER() over (Partition by eventId, isGroupB, UserVote Order by eventId, isGroupB, UserVote) as isGroupBCount,
null,
uservote
from @voteTable
where isGroupB = 1
UNION ALL
Select eventId, null as isGroupA, null as isGroupB,
null,
null,
ROW_NUMBER() over (Partition by eventId, UserVote Order by eventId, UserVote) as isAllCount,
uservote
from @voteTable
),
CteSummary as(
Select eventId,
max(isGroupACount) as GroupA,
max(isGroupBCount) as GroupB,
max(isAllCount) as isAll
from CteCount
Group by eventId
)
Select
*,
(Select a.userVote from CteCount a where a.isGroupA = 1 and isGroupACount = GroupA and a.eventId = CteSummary.eventId) as GroupAvote,
(Select a.userVote from CteCount a where a.isGroupB = 1 and isGroupBCount = GroupB and a.eventId = CteSummary.eventId) as GroupBvote,
(Select a.userVote from CteCount a where a.isAllCount = isAll and a.eventId = CteSummary.eventId) as Allvote
from CteSummary
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 1,769 | 6,142 |
<issue_start>username_0: I'm trying to declare a function template that should accept and return a non-const reference when passed an lvalue, but return an RVO-compatible local copy when passed an rvalue:
```
? StringReplace(? str, ? from, ? to);
```
I want template to generate the following signatures:
1. for non-const lvalues
```
std::string& StringReplace(std::string& str, const std::string& from, const std::string& to);
```
2. for const lvalues
```
std::string StringReplace(const std::string& str, const std::string& from, const std::string& to);
```
3. for non-const rvalues
```
std::string StringReplace(std::string&&, const std::string&, const std::string&)
```
4. for const rvalues
```
std::string StringReplace(const std::string&&, const std::string&, const std::string&)
```
5. for string literal
```
std::string StringReplace(std::string&&, const std::string&, const std::string&)
```
---
Is it possible to specify one using single template?
Perhaps there is a function or method in the standard library that achieves the same result by using one or multiple templates I should use as a reference?
---
See [my answer](https://stackoverflow.com/a/49346191/188530) for the version I ended up with.<issue_comment>username_1: I believe this basic idea meets your requirements:
```
template
Str foo(Str&& str)
{
return std::forward(str);
}
```
If the argument is a non-const lvalue, then `Str` is deducted to `S&` and the forward resolves to `S&` also.
If the argument is an rvalue then `Str` is deduced to `S`, and the return value is copy/move-constructed from the argument.
If you explicitly give the template argument, then forwarding reference deduction is suppressed and you would have to make sure to give `S&` if the function argument is an lvalue that `S&` can bind directly to; or `S` otherwise.
There is never RVO for a function parameter passed by reference; e.g. suppose the calling context were `std::string s = StringReplace( std::string("foo"), x, Y);` , the compiler cannot know at this point to use the same memory space for `s` as the temporary string. The best you can do is to move-construct the return value.
---
*Note:* Your original code tries to deduce `Str` for all 3 arguments, this causes deduction conflicts. You should deduce the forwarding reference and for the other two, either use a non-deduced context or a different template parameter. For example:
```
template
Str StringReplace(Str&& str, T const& from, T const& to)
```
or use the `CRef` as shown in username_2's answer (deduction is disabled if the parameter appears to the left of `::`).
Upvotes: 3 [selected_answer]<issue_comment>username_2: With some aggressive molding of parameters and return value, this seems to do almost what you specified.
Case 2 need to be specified with or the forwarding reference will not work.
```
#include
#include
template
using CRef = typename std::remove\_reference::type const&;
template
Str StringReplace(Str&& str, CRef from, CRef to)
{
std::cout << \_\_PRETTY\_FUNCTION\_\_ << std::endl;
if (std::is\_same::value)
std::cout << "rvalue-ref\n\n";
else if (std::is\_same::value)
std::cout << "lvalue-ref\n\n";
return std::forward(str);
}
int main() {
std::string s1;
StringReplace(s1, "", "");
// Forwarding reference will deduce Str to std::string& when passing an lvalue
StringReplace(s1, "", "");
StringReplace(std::move(s1), "", "");
StringReplace(std::move(s1), "", "");
StringReplace("", "", "");
const std::string& test = s1;
StringReplace(test, "", "");
}
```
A question mark remains for how to deal with `const &` being passed in. As you can see if you run this, it will also return a `const &` as it stands now.
[Live example](https://ideone.com/tfSfT1)
Upvotes: 2 <issue_comment>username_3: Based on the commentaries and answers I ended up with two templates:
```
// true only if T is const
template
using StringReplaceIsConst = std::conditional\_t>::value, std::true\_type, std::false\_type>;
// lvalue, lvalue reference, rvalue, rvalue reference, string literal
template::value>>
Str StringReplace(
Str&& str,
const std::remove\_reference\_t& from,
const std::remove\_reference\_t& to
) {
return std::forward(str);
}
// const lvalue, const lvalue reference, const rvalue, const rvalue reference
template::value>>
std::decay\_t StringReplace(
Str&& str,
const std::remove\_reference\_t& from,
const std::remove\_reference\_t& to
) {
std::decay\_t mutableStr{std::forward(str)};
StringReplace(mutableStr, from, to);
return mutableStr;
}
```
[Live example](https://ideone.com/d2Tpkf)
---
While the version above works I find it impractical. The user is actually interested in whether modification is done **in place** or **in a copy**:
* Simpler debugging: user can add logging to verify which version is called
* Static analysis: user can annotate the definition to make compiler automatically issue warnings
With these points in mind:
```
// true only if T is a non-const lvalue reference
template
using StringReplaceIsInPlace = std::conditional\_t::value && !std::is\_const>::value, std::true\_type, std::false\_type>;
// lvalue, lvalue reference, rvalue reference,
template::value>>
Str StringReplace(
Str&& str,
const std::remove\_reference\_t& from,
const std::remove\_reference\_t& to
) {
return std::forward(str); // forward might be redundant, as Str is always an lvalue reference.
}
// const lvalue, const lvalue reference, rvalue, const rvalue, const rvalue reference, string literal
// std::decay ensures that return is by-value and compiler can use RVO
template::value>>
std::decay\_t StringReplace(
Str&& str,
const std::remove\_reference\_t& from,
const std::remove\_reference\_t& to
) {
std::decay\_t mutableStr{std::forward(str)}; // move construct for non-const rvalues, otherwise copy-construct
StringReplace(mutableStr, from, to);
return mutableStr; // RVO-compatible
}
```
The second declaration can be annotated with `[[nodiscard]]` (C++17), `[[gnu::warn_unused_result]]` (clang and gcc) or `_Check_return_` (msvs).
[Live example](https://ideone.com/TulRXJ)
Upvotes: 1
|
2018/03/17
| 1,784 | 6,088 |
<issue_start>username_0: I am trying to build a project that has compileSdkVersion 25 and targetSdkVersion 25 but I need to change both to 23 so after changing compileSdkVersion 23 and targetSdkVersion 23 I am getting an error
>
> Error:resource
> android:style/TextAppearance.Material.Widget.Button.Borderless.Colored
> not found. Error:resource
> android:style/TextAppearance.Material.Widget.Button.Colored not found.
> Error:failed linking references.
> Error:java.util.concurrent.ExecutionException:
> java.util.concurrent.ExecutionException:
> com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
> details Error:java.util.concurrent.ExecutionException:
> com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
> details Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error:
> check logs for details Error:Execution failed for task
> ':app:processDebugResources'.
>
>
>
> >
> > Failed to execute aapt
> >
> >
> >
>
>
>
[](https://i.stack.imgur.com/YkdbV.png)
I am an iOS developer and doesn't have much experience in Android, I am unable to find where this error point in code and how to fix.
**Edit: 1**
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '26.0.2'
defaultConfig {
applicationId 'com.abc.app'
minSdkVersion 21
targetSdkVersion 23
versionCode 4
versionName '1.3'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
buildConfigField("String", "API_KEY", "\"empty\"")
//buildConfigField("String", "API_KEY", API_KEY)
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
exclude 'META-INF/services/com.fasterxml.jackson.core.ObjectCodec'
exclude 'META-INF/services/com.fasterxml.jackson.core.JsonFactory'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.wang.avi:library:2.1.3'
implementation 'com.android.support:appcompat-v7:25.4.0'
implementation 'com.android.support:customtabs:25.4.0'
implementation 'com.android.support:cardview-v7:25.4.0'
implementation 'com.nex3z:toggle-button-group:1.1.2'
implementation 'com.github.ivbaranov:materialfavoritebutton:0.1.4'
implementation 'com.android.support:design:25.4.0'
implementation 'com.android.volley:volley:1.0.0'
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.2'
implementation 'com.yqritc:recyclerview-flexibledivider:1.2.9'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.google.code.gson:gson:2.8.1'
implementation 'com.github.bumptech.glide:glide:4.3.1'
implementation 'com.google.android.gms:play-services-ads:11.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
implementation('com.github.fcopardo:easyrest:v1.4.2@aar') {
transitive = true
}
// compile 'com.github.wrdlbrnft:sorted-list-adapter:0.3.0.27'
testImplementation 'junit:junit:4.12'
}
```<issue_comment>username_1: android:style/TextAppearance.Material.Widget.Button.Borderless.Colored was added in API 24 so you can't use it with version 23. You can use a style that was added before version 23. You can also apply new styles to newer-versioned devices and apply an old style as a default: <https://developer.android.com/guide/topics/ui/look-and-feel/themes.html#Versions>
**Added** 03/20/'18 12:32
As you're not familiar with Android, a simple solution is to just use an older text appearance. This at least makes the app working on your Android 5 device. Afterwards you can learn about how to further customize the TextView, but for now let's just make it work.
1. The appearance of text may be set for a certain TextView within a layout file, located at [something]/res/layout/xxx.xml, which the "layout" could also be "layout-xxx".
2. It may be set within a style file, located at [something]/res/values/styles.xml, "values" may also be "values-xxx".
folder "res" can be easily found from the project tree in Android Studio.
You can also use **Ctrl+Shift+F** to search in whole project.
When you find it, just delete or comment the line.
Upvotes: 4 <issue_comment>username_2: Check "style.xml" file & you see errors are highlighted. Change App theme color in following:
Upvotes: 1 <issue_comment>username_3: **Issue:**
The colorError is supported in android 26 or higher and this package is on 23, However the package might be in the lower version.
**Solution:**
Add the following code in build.gradle.
place this inside allprojects {
```
// force libs to use recent buildtools
// https://github.com/luggit/react-native-config/issues/299
subprojects {
afterEvaluate {
project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion = 27
buildToolsVersion = "27.0.3"
}
}
}
}
```
Upvotes: 3 <issue_comment>username_4: just replace this:
```
@android:style/TextAppearance.Material.Widget.Button.Borderless.Colored
```
for this:
```
@android:style/Widget.Material.Button.Borderless.Colored
```
Upvotes: -1
|
2018/03/17
| 656 | 2,105 |
<issue_start>username_0: I am trying to make a single page poetry page that flips between poems by replacing the content inside of the elements. The problem that I have is with replacing the image link because Javascript marks the double slash "//" as comment so it makes the link break. Is there a way to set any variables to be the entire img tag along with the link inside?
```
function loadDreams() {
$("h2").html("Dreams");
$("h3").html("by <NAME>");
$("p").html("Hold fast to dreams
For if dreams die
Life is a broken-winged bird
That cannot fly.
Hold fast to dreams
For When dreams go
Life is a barren field
Frozen with snow.
");
$("div").html("");
}
```<issue_comment>username_1: ```
$("div").html("");
```
Singular quote things inside the html("") should do it. At the moment you're actually breaking out after "< img src="
Upvotes: 0 <issue_comment>username_2: The issue is that you're opening your JavaScript string literal with double-quotes, then inadvertently closing the string with the src attribute double-quotes. It's fine to have `//` as long as it's inside a string literal.
It's best to use something like single quotes for your JS strings so that the HTML double quotes can peacefully coexist inside. (or use double quotes for the JS and single quotes for HTML... just don't mix).
Upvotes: 2 [selected_answer]<issue_comment>username_3: Instead of wrapping your in double quotes, use single quotes:
```
function loadDreams() {
$("h2").html("Dreams");
$("h3").html("by <NAME>");
$("p").html("Hold fast to dreams
For if dreams die
Life is a broken-winged bird
That cannot fly.
Hold fast to dreams
For When dreams go
Life is a barren field
Frozen with snow.
");
$("div").html('');
}
```
Upvotes: 0
|
2018/03/17
| 461 | 1,255 |
<issue_start>username_0: Im trying to create a list of a sliding window from a pandas dataframe but instead of giving me the specific values it only returns the header. Why is this happening and what can I do to get around this?
```
import pandas as pd
batch_size = 3
data = pd.DataFrame([1,2,3,4,5,6,7,8,9])
def process(data):
batches = []
for i in range(len(data) - batch_size + 1):
batches.append(list(data.iloc[i:i + batch_size]))
return batches
process(data)
```<issue_comment>username_1: Use `pd.Series.iloc` instead of `pd.DataFrame.iloc` to produce rolling values for a series:
```
data[0].iloc[i:(i+batch_size)]
# [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]
```
Your result is because you are effectively calculating `list` of a dataframe for specified index range, which is not clear. `list(data)`, for example, returns `[0]`, and it's not obvious what you should *expect* from such code.
Upvotes: 1 <issue_comment>username_2: Consider using a list comprehension instead of a for loop:
```
[data.iloc[i:i + batch_size, 0].tolist()
for i in range(data.shape[0] - batch_size + 1)]
#[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]
```
Upvotes: 2
|
2018/03/17
| 2,709 | 9,050 |
<issue_start>username_0: Wikipedia says:
>
> 32-bit CPU and ALU architectures are those that are based on registers, address buses, or data buses of that size.
>
>
>
So each memory address refers to 32-bits.
But what does that really mean, exactly? In Intel X86-32 assembly, which is agreed to be 32-bit, there are 32-bit registers, 16-bit registers, and 8-bit registers.
Consider the following assembly
```
mov ax, bx ; move 16-bit bx into 16-bit ax
mov ah, bh ; move 8-bit bh into 8-bit ah
movzx eax, ax ; move 16-bit ax into 32-bit eax (zero-extending ax)
```
Are all these lines acceptable? If so, why do we insist that this is a 32-bit system? Inexorably, the assembly manages smaller address sizes.<issue_comment>username_1: Wikipedia's explanation is a bit fuzzy, but then again this is a subject which is difficult to receive a precise definition. Take for example the term "passenger car". Can you define it precisely? No.
It used to be that a 32-bit architecture was one that had a 32-bit data bus, but things are quite a bit more complicated nowadays.
A working definition today would be that the bitness of the architecture tends to coincide with the size in bits of the largest available general-purpose registers.
So, a 32-bit system can be expected to have 8-bit, 16-bit, and 32-bit registers but (usually) no larger registers. Similarly, a 16-bit system can be expected to have 8-bit and 16-bit registers, but (usually) no larger registers.
Upvotes: 2 <issue_comment>username_2: x86-32 (aka IA-32) is a 32-bit extension to 16-bit 8086, which was designed for easy porting of asm source from 8-bit 8080 to 8086. ([Why are first four x86 GPRs named in such unintuitive order?](https://retrocomputing.stackexchange.com/questions/5121/why-are-first-four-x86-gprs-named-in-such-unintuitive-order) on retrocomputing).
This history is why modern x86 has so much partial-register stuff, with direct support for 8 and 16-bit operand-size.
Most other architectures with 32-bit registers only allow narrow loads/stores, with ALU operations being only full register width. (But that's as much because they're RISC architectures (MIPS, SPARC, and even the slightly less-RISCy ARM), while x86 is definitely a CISC architecture.)
The 64-bit extensions to RISC architectures like MIPS still support 32-bit operations, usually implicitly zero-extending 32-bit results into the "full" registers [the same way x86-64 does](https://stackoverflow.com/questions/11177137/why-do-x86-64-instructions-on-32-bit-registers-zero-the-upper-part-of-the-full-6). (Especially if 64-bit isn't a new mode, but rather just new opcodes within the same mode, with semantics designed so that existing machine code will run the same way when addressing modes use the full registers but all the legacy opcodes still only write the low 32 bits.)
So the situation you observe on x86-32 (with narrow operations on partial registers being supported) is present in all architectures that exist as a wider extension to an older architecture, whether it runs in a new mode (where machine code decodes differently) or not. It's just that x86 ancestry goes back to 16-bit within x86, and back to 8-bit as an influence on 8086.
---
[Motorola 68000](https://en.wikipedia.org/wiki/Motorola_68000) has 32-bit registers, according to Wikipedia "the main ALU" is only 16-bit. (Maybe 32-bit operations are slower or some are not supported, but definitely 32-bit add/and instructions are supported. I don't know the details behind why Wikipedia says that).
Originally 68000 was designed to work with a 16-bit external bus, so 16-bit loads/stores were more efficient on those early CPUs. I think later 68k CPUs widened the data buses, making 32-bit load/store as fast as 16-bit. Anyway, **I think m68k is another example of a 32-bit architecture that supports a lot of 16-bit operations.** Wikipedia describes it as "a 16/32-bit CISC microprocessor".
---
With the addition of caches, twice as many 16-bit integers fit in a cache line as 32-bit integers, so for *sequential* access 16-bit only costs half as much average / sustained memory bandwidth. **Talking about "bus width" gets more complicated when there's cache**, so there's a bus or internal data path between the load/store units and cache, and between cache and memory. (And in a multi-level cache, between different levels of cache).
---
Deciding whether to call an architecture (or a specific implementation of that architecture) 8 / 16 / 32 / 64-bit is pretty arbitrary. **The marketing department is likely to pick the widest thing they can justify, and use that in descriptions of the CPU**. That might be a data bus or a register width, or address space or anything else. (Many 8-bit CPUs use 16-bit addresses in a concatenation of two 8-bit registers, although most of them don't try to claim to be 16-bit. They might be advertized as 8/16-bit though.)
---
**32-bit x86 is considered 32-bit because that's the maximum width of a pointer, or a "general purpose" integer register.** 386 added several major new things: 32-bit integer registers / operand size (accessible with prefixes from real mode), and 32-bit protected mode with virtual memory paging, where the default address and operand sizes are 32 bits.
---
**The *physical* CPUs that can run IA-32 machine code today** have vastly wider buses and better memory bandwidth than the first generation 386SX CPUs, but they still support the same IA-32 architecture (plus extensions).
These days, essentially all new x86 CPUs can also run in x86-64 mode. When running in IA-32 mode, a modern x86 CPU will only be using the low 32 bits of its 64-bit physical integer registers (like for instructions that use 32-bit operand-size in 32-bit or 16-bit mode).
But besides the integer registers, there are the 80-bit x87 registers (which can be used as 64-bit integer-SIMD MMX registers), and also the XMM / YMM / ZMM registers (SSE / AVX / AVX512).
SSE2 is baseline for x86-64, and can be assumed in most 32-bit code these days, so at least 128-bit registers are available, and can be used for 64-bit integer add/sub/shift even in 32-bit mode with instructions like [`paddq`](https://github.com/HJLebbink/asm-dude/wiki/PADDB_PADDW_PADDD_PADDQ).
Modern CPUs also have at least 128-bit connections between the vector load/store units and cache, so load/store/copy bandwidth when data fits in L1d cache is not limited by the external dual/triple/quad-channel DDR3/DDR4 DRAM controllers (which do burst transfers of 8x 64-bits = one 64-byte cache line over 64-bit external buses).
Instead, CPUs have large fast caches, including a shared L3 cache so data written by one core and read by another doesn't usually have to go through memory if it's still hot in L3. See [some details on how cache can be that fast for Intel IvyBridge](https://electronics.stackexchange.com/questions/329789/how-can-cache-be-that-fast/329955#329955), which has only 128-bit load/store paths even though it supports 256-bit AVX instructions. Haswell widened the load/store paths to 256-bit as well. Skylake-AVX512 widened the registers and data paths to 512-bit for L1d cache, and the connection between L1d and L2.
But on paper, x86 (since P5 Pentium and later) only guarantees that [aligned loads/stores up to 64 bits are atomic](https://stackoverflow.com/questions/36624881/why-is-integer-assignment-on-a-naturally-aligned-variable-atomic-on-x86), so implementations with SSE are allowed to split 128-bit XMM loads/stores into two 64-bit halves. Pentium III and Pentium M actual did this. But note that i586 Pentium predated x86-64 by a decade, and the only way it could load/store 64 bits was with x87 `fld` or `fild`. Pentium MMX could do 64-bit MMX `movq` loads/stores. Anyway, this atomicity guarantee includes uncached stores (e.g. for MMIO), which was possible (cheaply, without a bus-lock) because **the P5 microarchitecture has a 64-bit external bus, even though it's strictly 32-bit other than the FPU**.
Even pure integer code benefits from the wide data paths because it increases bandwidth for integer code with loads/stores that hit in L3 or especially L2 cache, but not L1d cache.
---
All these SIMD extensions to x86 make it vastly more powerful than a purely 32-bit integer architecture. But when running in 32-bit mode, it's still the same mode introduced by 386, and we call it 32-bit mode. It's as good a name as any, but don't try to read too much into it.
In fact, don't read *anything* into it except for integer / pointer register widths. The hardware it runs on typically has 64-bit integer registers, and 48-bit virtual address space. And data buses + caches of various huge widths, and complex out-of-order machinery to give the illusion of running in-order while [actually looking at a window of up to 224 uops to find instruction-level parallelism](https://softwareengineering.stackexchange.com/questions/349972/how-does-a-single-thread-run-on-multiple-cores/350024#350024). (Skylake / Kaby Lake / Coffee Lake ROB size).
Upvotes: 2
|
2018/03/17
| 259 | 933 |
<issue_start>username_0: I don't have much knowledge about xml file. I am trying to execute the TestNG through xml file.. Its shows following error before adding the suggested line at top of the program..
eroor:
[TestNGContentHandler] [WARN] It is strongly recommended to add "" at the top of your file, otherwise TestNG may fail or not work as expected.
After adding the recommended line its shows the following error:
org.testng.TestNGException: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 6; The processing instruction target matching "[xX][mM][lL]" is not allowed.
following is the xml file..
```
xml version="1.0" encoding="UTF-8"? (shows error at this line)
```<issue_comment>username_1: This line should be the first line
```
xml version="1.0" encoding="UTF-8"?
```
Upvotes: -1 <issue_comment>username_2: ```
xml version="1.0" encoding="UTF-8"?
```
The second line should be removed.
Upvotes: 0
|
2018/03/17
| 1,314 | 4,733 |
<issue_start>username_0: I have the route below to show a specific post details page: "<http://proj.test/>{slug}" for example "<http://proj.test/test-post>" if the name of the post introduced was "test post".
The issue is that, can exist posts with the same name, so the url like "<http://proj.test/test-post>" will not work properly. Because can exist more posts with the same "test post" name.
So it should be necessary to besides the slug add in the url the id of the post.
So, I have a post controller to create a new post, so I was trying to insert in the slug column of the post the slug with the id of the post: (I dont know if this is a good approach to handle this issue)
```
$post = Post::create([
'name' => $request->name,
...
'slug' => str_slug($request->name."-".Post::id)
]);
```
But it appears "Undefined class constant 'id'". Do you know how to fix the issue?
show method of FrontController to show the post details view:
```
public function show($slug){
$post = Post::where('slug', $slug)->first();
return view('post.show')->with('post',$post);
}
```
Route:
```
Route::get('/{slug}', [
'uses' => 'FrontController@show',
'as' =>'show'
]);
```<issue_comment>username_1: Jon,
The 'Laravel' way to do this, or at least the most efficient way, would be to just use the Post's id in the route rather than the slug. So if AJAX, just put the $post->id in a data field and pull it from javascript when submitting.
The route might be something like
```
Route::get("test/{post}", 'Testing\TestController@showTest');
```
Then on your controller, you could either pull the Post object by
```
$post = Post::find($post);
```
or use Route Model Binding and just typehint the controller function:
```
public function showTest(Post $post){ etc }
```
For your other question above about setting the id into the slug, this is probably not a good way to go... However, if you need to, I would recommend a two step process $post = create(); then $post->slug = 'slug'.$post->id. Again, not the best way to go, but it would work...
And of course you can always pass a slug through the route, but I would first look at the purpose for which you are looking to do this - is it purely cosmetic, or are you looking for a way to identify the post? You can always add a loop into the controller to look up all the posts with that slug... but it is a lot easier to send the id, which you will always have access to, and then sort as above.
Hope this helps
Upvotes: -1 <issue_comment>username_2: ```
$post = Post::create([
'name' => $request->name,
...
'slug' => str_slug($request->name."-".Post::id)
]);
```
This doesn't work because a) there is no static method `id` on a model, b) you can't get an id of the model before actually saving it to the database.
The simple (and still more elegant) solution would be to check if a post with that slug already exists and only append a number to the post if it does. That way the majority (probably) of the posts will have a url without a number appended to them.
Something like this:
```
// Create a slug
$slug = str_slug($request->name);
if (Post::where('slug', $slug)->first() !== null) {
$n = 0;
do {
// Increase n and append it to the slug
$newName = $slug . '-' . ++$n;
// Iterate until the slug is NOT found in the database,
// which means it's unique
} while (Post::where('slug', $newName)->first() !== null);
}
$post = Post::create([
'name' => $request->name,
...
'slug' => isset($newName) ? $newName : $slug
]);
```
But probably a nicer way of doing it would be to prefix the slug with either user's name (still not necessarily unique) or timestamp or something else.
Upvotes: 0 <issue_comment>username_3: In the case where posts might not have unique slugs, you should follow the Stackoverflow approach - which is `/id/slug` where slug doesn't do anything except provide a friendly view.
The following is a link to this actual question - note how the slug doesn't in-fact matter. Sure it redirects onto your question with the right slug, but initially the slug doesn't do anything (the id does):
`stackoverflow.com/questions/49331496/this-can-actually-be-anything`
So your code might end up looking like:
```
public function show($id, $slug){
$post = Post::find($id)->first();
// if you want to redirect if the slug doesn't match, like SO
if($post->slug !== $slug) {
return redirect()->route('post.show', ['id' => $post->id, 'slug' => $post->slug]);
}
return view('post.show')->with('post', $post);
}
Route::get('/{id}/{slug?}', [
'uses' => 'FrontController@show',
'as' =>'post.show'
]);
```
Upvotes: 1 [selected_answer]
|
2018/03/17
| 627 | 1,779 |
<issue_start>username_0: The oplog has a field called ts, which looks like this:
```
{"ts":"6533707677506207745","t":2,"h":"-7325657776689654694", ...}
```
I want to query the oplog, like so:
```
db.oplog.rs.find({ts:{$gt:x}});
```
how can I generate a Timestamp, that represents now? How about 30 seconds before now?
if I do:
```
const x = new Timestamp();
```
I get a error saying:
[](https://i.stack.imgur.com/H6Yta.png)
**What is the correct way to generate a Timestamp? How can I query the oplog with the right ts value?**
Here are the docs for Timestamp:
<http://mongodb.github.io/node-mongodb-native/core/api/Timestamp.html>
but I cannot figure out what low number/high number is about.<issue_comment>username_1: this seems to yield the current time, but I frankly do not know why:
```
import {Timestamp} from 'bson';
const t = new Timestamp(1, Math.ceil(Date.now()/1000));
```
this value can be used to query a field in the db, that has a timestamp field, like so:
```
query.ts = {$gt: t};
const q = coll.find(query);
```
Upvotes: 0 <issue_comment>username_2: That timestamp is seconds from the UNIX epoch and Date() is milliseconds. So...
```
db.oplog.rs.find({ts:{$gt:Timestamp((new Date().getTime()-30000)/1000,0)}})
```
What we do here is get current time 30000 milliseconds ago, divide that with 1000 to get seconds and then add (needed) second parameter to Timestamp -function.
Edit:
Of course, if you need exact Timestamp() value, you fill that decimal part of (new Date().getTime()-30000)/1000 as second parameter.
```
var x=(new Date().getTime()-30000)/1000;
var y=Math.floor(x);
var z=Math.round((x-y)*1000);
db.oplog.rs.find({ts:{$gt:Timestamp(y,z)}})
```
Upvotes: 1
|
2018/03/17
| 494 | 1,912 |
<issue_start>username_0: I have this Function
```
[FunctionName("json")]
public static JsonResult json
(
[HttpTrigger(AuthorizationLevel.Anonymous, new string[] { "POST", "GET", "DELETE", "PATCH", "PUT" })]
HttpRequest req,
TraceWriter log
)
{
return new JsonResult(new
{
Nome = "TONY",
Metodo = req.Method.ToString()
});
}
```
the problem is that it is returning
```
{"nome":"TONY","metodo":"GET"}
```
I want it to return
```
{"Nome":"TONY","Metodo":"GET"}
```
In ASP.Net Core 2 I used this:
```
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
// Keep the Case as is
```
**How to configure Azure Functions to do that way?**<issue_comment>username_1: you could do something like this:
```
[FunctionName("json")]
public static HttpResponseMessage Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = req,
Content = new StringContent(
content: JsonConvert.SerializeObject(new
{
Nome = "TONY",
Metodo = req.Method.ToString()
}),
encoding: System.Text.Encoding.UTF8,
mediaType: "application/json")
};
}
```
Upvotes: 3 <issue_comment>username_2: Add the JsonPropertyAttribute to the properties and include Json.NET via #r "Newtonsoft.Json" at the top of the file.
```
#r "Newtonsoft.Json"
using Newtonsoft.Json;
```
And decorate the properties
```
[JsonProperty(PropertyName = "nome" )]
public string Nome { get; set; }
[JsonProperty(PropertyName = "metodo" )]
public string Metodo { get; set; }
```
Upvotes: 0
|
2018/03/17
| 356 | 1,474 |
<issue_start>username_0: I am working on a Xamarin.Forms PCL app. I am trying to make it so users can comment on posts which displays as the post then scrolling down shows comments with a docked entry at the bottom of the page at all times
I tried
```
```
but when I click the entry it is covered by the keyboard, is it possible to make it sit above the keyboard?<issue_comment>username_1: you could do something like this:
```
[FunctionName("json")]
public static HttpResponseMessage Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = req,
Content = new StringContent(
content: JsonConvert.SerializeObject(new
{
Nome = "TONY",
Metodo = req.Method.ToString()
}),
encoding: System.Text.Encoding.UTF8,
mediaType: "application/json")
};
}
```
Upvotes: 3 <issue_comment>username_2: Add the JsonPropertyAttribute to the properties and include Json.NET via #r "Newtonsoft.Json" at the top of the file.
```
#r "Newtonsoft.Json"
using Newtonsoft.Json;
```
And decorate the properties
```
[JsonProperty(PropertyName = "nome" )]
public string Nome { get; set; }
[JsonProperty(PropertyName = "metodo" )]
public string Metodo { get; set; }
```
Upvotes: 0
|
2018/03/17
| 2,044 | 6,932 |
<issue_start>username_0: I've been racking my brain for two days trying to figure out why the program is behaving this way. For a class project, I'm trying to write a program that parses an address and outputs it a certain way. Before I actually get to the output portion of the program, I just wanted to make sure my Bison-fu was actually correct and outputting some debugging information correctly.
It looks as if Flex and Bison are cooperating with each other nicely, as expected, but for some reason, when I get to the parsing of the third line of the address, yytext just skips over the zip code and goes straight to the new line.
Below is a stripped down version of my Flex and Bison files that I tested and still outputs the same thing as the full version:
```
[19:45] $ cat scan.l
%option noyywrap
%option nounput
%option noinput
%{
#include
#include "y.tab.h"
#include "program4.h"
%}
%%
[\ \t]+ { /\* Eat whitespace \*/}
[\n] { return EOLTOKEN; }
"," { return COMMATOKEN; }
[0-9]+ { return INTTOKEN; }
[A-Za-z]+ { return NAMETOKEN; }
[A-Za-z0-9]+ { return IDENTIFIERTOKEN; }
%%
/\*This area just occupies space\*/
[19:45] $ cat parse.y
%{
#include
#include
#include "program4.h"
%}
%union {int num; char id[20]; }
%start locationPart
%expect 0
%token NAMETOKEN
%token EOLTOKEN
%token INTTOKEN
%token COMMATOKEN
%type townName zipCode stateCode
%%
/\* Entire block \*/
locationPart: townName COMMATOKEN stateCode zipCode EOLTOKEN
{ printf("Rule 12: LP: TN COMMA SC ZC EOL: %s\n", yytext); }
| /\* bad location part \*/
{ printf("Rule 13: LP: Bad location part: %s\n", yytext); }
;
/\* Lil tokens \*/
townName: NAMETOKEN
{ printf("Rule 23: TN: NAMETOKEN: %s\n", yytext); }
;
stateCode: NAMETOKEN
{ printf("Rule 24: SC: NAMETOKEN: %s\n", yytext); }
;
zipCode: INTTOKEN DASHTOKEN INTTOKEN
{ printf("Rule 25: ZC: INT DASH INT: %s\n", yytext); }
| INTTOKEN
{ printf("Rule 26: ZC: INT: %s\n", yytext); }
;
%%
int yyerror (char const \*s){
extern int yylineno; //Defined in lex
fprintf(stderr, "ERROR: %s at symbol \"%s\"\n at line %d.\n", s, yytext,
yylineno);
exit(1);
}
[19:45] $ cat addresses/zip.txt
Rockford, HI 12345
[19:45] $ parser < addresses/zip.txt
Operating in parse mode.
Rule 23: TN: NAMETOKEN: Rockford
Rule 24: SC: NAMETOKEN: HI
Rule 26: ZC: INT:
Rule 12: LP: TN COMMA SC ZC EOL:
Parse successful!
[19:46] $
```
As you can see near the bottom, it prints `Rule 26: ZC: INT:` but fails to print the 5 digit zip code. It's like the program just skips the number and stores the newline instead. Any ideas why it won't store and print the zip code?
Notes:
* yytext is defined as an extern in my .h file (not posted here);
* I am using the `-vdy` flags to compile the parse.c file<issue_comment>username_1: If you want to trace the workings of your parser, you are much better off enabling bison's trace feature. It's really easy. Just add the `-t` or `--debug` flag to the `bison` command to generate the code, and then add a line to actually produce the tracing:
```
/* This assumes you have #included the parse.tab.h header */
int main(void) {
#if YYDEBUG
yydebug = 1;
#endif
```
This is explained in [the Bison manual](https://www.gnu.org/software/bison/manual/bison.html#Tracing); the `#if` lets your program compile if you leave off the `-t` flag. While on the subject of flags, I strongly suggest you do not use the `-y` flag; it is for compiling old Yacc programs which relied on certain obsolete features. If you don't use `-y`, then bison will use the basename of your `.y` file with extensions `.tab.c` and `.tab.h` for the generated files.
Now, your bison file says that some of your tokens have semantic types, but your flex actions do not set semantic values for these tokens and your bison actions don't use the semantic values. Instead, you simply print the value of `yytext`. If you think about this a bit, you should be able to see why it won't work. Bison is a *lookahead* parser; it makes its parsing decisions based on the the current parsing state and a peek at the next token (if necessary). It peeks at the next token by calling the lexer. And when you call the lexer, it changes the value of `yytext`.
Bison (unlike other yacc implementations) doesn't always peek at the next token. But in your zipcode rule, it has no alternative, since it cannot tell whether the next token is a `-` or not without looking at it. In this case, it is not a dash; it is a newline. So guess what `yytext` contains when you print it out in the zipcode action.
If your tokenizer were to save the text in the `id` semantic value member (which is what it is for) then your parser would be able to access the semantic values as `$1`, `$2`, ...
Upvotes: 2 <issue_comment>username_2: Because `yytext` is a global variable, it's overwritten and you will have to copy it in your *lex* script. In a pure parser, even though it's not global anymore it's still reused and passed as a parameter so it's incorrect to use it's value like you are attempting.
Also, don't use it in bison, instead use `$n` where `n` is the position of the token in the rule. You probably need the `%union` directive changed to something like
```
%union {
int number;
char *name;
};
```
So in the *flex* file, if you want to capture the text do something like
```
[A-Za-z]+ { yylval.name = strdup(yytext); return NAMETOKEN; }
```
and remember, do not use `yytext` in *bison*, it's an internal thing used by the lexer.
Then and since you have defined a type for the zip code
```
/* Entire block */
locationPart: townName COMMATOKEN stateCode zipCode EOLTOKEN {
printf("Rule 12: LP: TN COMMA SC ZC EOL: town:%s, stateCode:%d zip-code:%s\n", $1, $3, $4);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: The problem is here:
```
zipCode: INTTOKEN DASHTOKEN INTTOKEN { // case 25 }
| INTTOKEN { // case 26 }
;
```
The parser doesn't know which rule to take--25 or 26--until it's parsed the next token to see if it is a DASHTOKEN. By the time the code is executed, yytext has already been overwritten.
The easiest way to handle this is to have a production that takes the INTTOKENs and returns what was in yytext[] in malloc()'d memory. Something like:
```
zipCode: inttoken DASHTOKEN inttoken
{
printf("Rule 25: zip is %s-%s\n", $1, $3);
free($1);
free($3);
}
| inttoken
{
printf("Rule 26: zip is %s\n", $1);
free($1);
}
;
inttoken: INTTOKEN { $$ = strdup(yytext); }
;
```
Upvotes: 0
|
2018/03/17
| 1,506 | 5,794 |
<issue_start>username_0: I'm desperately looking for help with an issue I'm having. So I've been following [this](https://www.youtube.com/watch?v=Lg4PVqRRO2Q) tutorial series, which are absolutely great, but in comparison to using a `Bottom Navigation` like he is in the video, I'm using a `Navigation Drawer' with fragments.
When I select `HomeFragment` within the `NavigationDrawer`, the layout loads but with everything pushed down below the `Toolbar`. Now, the Toolbar is fully functional as the hamburger and more options menu icon are indeed there, but are invisible to also being white, therefore it's more a Design issue.
[](https://i.stack.imgur.com/UxSMd.png)
Also, regarding the `Toolbar's` style, yes I've made it to be transparent on purpose so that the finished UI looks like the "Expected Output" image below.
**Expected Output** - This is what the identical layout looks like in `HomeActivity` in oppose to `HomeFragment`.
[](https://i.stack.imgur.com/Rhhc4.png)
The below is my code for the `HomeActivity`, which nests the `FrameLayout` for the `Fragments`.
```
xml version="1.0" encoding="utf-8"?
```
I have declared and initiated the `Toolbar` within the `HomeActivity` class like normal, and when the `HomeActivity` is displayed the `Toolbar` is indeed there, which makes me question whether I must declare it again within the `HomeFragment` class? If so, how would you go about doing that?
If any other code is required from other layouts or classes, ask away. Any help will be much appreciated!<issue_comment>username_1: If you want to trace the workings of your parser, you are much better off enabling bison's trace feature. It's really easy. Just add the `-t` or `--debug` flag to the `bison` command to generate the code, and then add a line to actually produce the tracing:
```
/* This assumes you have #included the parse.tab.h header */
int main(void) {
#if YYDEBUG
yydebug = 1;
#endif
```
This is explained in [the Bison manual](https://www.gnu.org/software/bison/manual/bison.html#Tracing); the `#if` lets your program compile if you leave off the `-t` flag. While on the subject of flags, I strongly suggest you do not use the `-y` flag; it is for compiling old Yacc programs which relied on certain obsolete features. If you don't use `-y`, then bison will use the basename of your `.y` file with extensions `.tab.c` and `.tab.h` for the generated files.
Now, your bison file says that some of your tokens have semantic types, but your flex actions do not set semantic values for these tokens and your bison actions don't use the semantic values. Instead, you simply print the value of `yytext`. If you think about this a bit, you should be able to see why it won't work. Bison is a *lookahead* parser; it makes its parsing decisions based on the the current parsing state and a peek at the next token (if necessary). It peeks at the next token by calling the lexer. And when you call the lexer, it changes the value of `yytext`.
Bison (unlike other yacc implementations) doesn't always peek at the next token. But in your zipcode rule, it has no alternative, since it cannot tell whether the next token is a `-` or not without looking at it. In this case, it is not a dash; it is a newline. So guess what `yytext` contains when you print it out in the zipcode action.
If your tokenizer were to save the text in the `id` semantic value member (which is what it is for) then your parser would be able to access the semantic values as `$1`, `$2`, ...
Upvotes: 2 <issue_comment>username_2: Because `yytext` is a global variable, it's overwritten and you will have to copy it in your *lex* script. In a pure parser, even though it's not global anymore it's still reused and passed as a parameter so it's incorrect to use it's value like you are attempting.
Also, don't use it in bison, instead use `$n` where `n` is the position of the token in the rule. You probably need the `%union` directive changed to something like
```
%union {
int number;
char *name;
};
```
So in the *flex* file, if you want to capture the text do something like
```
[A-Za-z]+ { yylval.name = strdup(yytext); return NAMETOKEN; }
```
and remember, do not use `yytext` in *bison*, it's an internal thing used by the lexer.
Then and since you have defined a type for the zip code
```
/* Entire block */
locationPart: townName COMMATOKEN stateCode zipCode EOLTOKEN {
printf("Rule 12: LP: TN COMMA SC ZC EOL: town:%s, stateCode:%d zip-code:%s\n", $1, $3, $4);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: The problem is here:
```
zipCode: INTTOKEN DASHTOKEN INTTOKEN { // case 25 }
| INTTOKEN { // case 26 }
;
```
The parser doesn't know which rule to take--25 or 26--until it's parsed the next token to see if it is a DASHTOKEN. By the time the code is executed, yytext has already been overwritten.
The easiest way to handle this is to have a production that takes the INTTOKENs and returns what was in yytext[] in malloc()'d memory. Something like:
```
zipCode: inttoken DASHTOKEN inttoken
{
printf("Rule 25: zip is %s-%s\n", $1, $3);
free($1);
free($3);
}
| inttoken
{
printf("Rule 26: zip is %s\n", $1);
free($1);
}
;
inttoken: INTTOKEN { $$ = strdup(yytext); }
;
```
Upvotes: 0
|
2018/03/17
| 3,048 | 9,133 |
<issue_start>username_0: I am trying to follow [this](https://spark.apache.org/docs/latest/running-on-kubernetes.html) but I am encountering an error.
In particular, when I run:
```
spark-submit.cmd --master k8s://https://192.168.1.40:8443 --deploy-mode cluster --name spark-pi --class org.apache.spark.examples.SparkPi --conf spark.executor.instances=1 --conf spark.kubernetes.container.image=spark:spark --conf spark.kubernetes.driver.pod.name=spark-pi-driver local:///opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar
```
I get:
```
2018-03-17 02:09:00 INFO LoggingPodStatusWatcherImpl:54 - State changed, new state:
pod name: spark-pi-driver
namespace: default
labels: spark-app-selector -> spark-798e78e46c5c4a11870354b4b89602c0, spark-role -> driver
pod uid: c6de9eb7-297f-11e8-b458-00155d735103
creation time: 2018-03-17T01:09:00Z
service account name: default
volumes: default-token-m4k7h
node name: minikube
start time: 2018-03-17T01:09:00Z
container images: spark:spark
phase: Failed
status: [ContainerStatus(containerID=docker://5c3a1c81333b9ee42a4e41ef5c83003cc110b37b4e0b064b0edffbfcd3d823b8, image=spark:spark, imageID=docker://sha256:92e664ebc1612a34d3b0cc7522615522805581ae10b60ebf8c144854f4207c06, lastState=ContainerState(running=null, terminated=null, waiting=null, additionalProperties={}), name=spark-kubernetes-driver, ready=false, restartCount=0, state=ContainerState(running=null, terminated=ContainerStateTerminated(containerID=docker://5c3a1c81333b9ee42a4e41ef5c83003cc110b37b4e0b064b0edffbfcd3d823b8, exitCode=1, finishedAt=Time(time=2018-03-17T01:09:01Z, additionalProperties={}), message=null, reason=Error, signal=null, startedAt=Time(time=2018-03-17T01:09:01Z, additionalProperties={}), additionalProperties={}), waiting=null, additionalProperties={}), additionalProperties={})]
```
With `kubectl logs -f spark-pi-driver` telling me that:
```
C:\spark-2.3.0-bin-hadoop2.7>kubectl logs -f spark-pi-driver
++ id -u
+ myuid=0
++ id -g
+ mygid=0
++ getent passwd 0
+ uidentry=root:x:0:0:root:/root:/bin/ash
+ '[' -z root:x:0:0:root:/root:/bin/ash ']'
+ SPARK_K8S_CMD=driver
+ '[' -z driver ']'
+ shift 1
+ SPARK_CLASSPATH=':/opt/spark/jars/*'
+ env
+ grep SPARK_JAVA_OPT_
+ sed 's/[^=]*=\(.*\)/\1/g'
+ readarray -t SPARK_JAVA_OPTS
+ '[' -n '/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar;/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar' ']'
+ SPARK_CLASSPATH=':/opt/spark/jars/*:/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar;/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar'
+ '[' -n '' ']'
+ case "$SPARK_K8S_CMD" in
+ CMD=(${JAVA_HOME}/bin/java "${SPARK_JAVA_OPTS[@]}" -cp "$SPARK_CLASSPATH" -Xms$SPARK_DRIVER_MEMORY -Xmx$SPARK_DRIVER_MEMORY -Dspark.driver.bindAddress=$SPARK_DRIVER_BIND_ADDRESS $SPARK_DRIVER_CLASS $SPARK_DRIVER_ARGS)
+ exec /sbin/tini -s -- /usr/lib/jvm/java-1.8-openjdk/bin/java -Dspark.executor.instances=1 -Dspark.driver.port=7078 -Dspark.driver.blockManager.port=7079 -Dspark.submit.deployMode=cluster -Dspark.jars=/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar,/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar -Dspark.app.id=spark-798e78e46c5c4a11870354b4b89602c0 -Dspark.kubernetes.container.image=spark:spark -Dspark.master=k8s://https://192.168.1.40:8443 -Dspark.kubernetes.executor.podNamePrefix=spark-pi-fb36460b4e853cc78f4f7ec4d9ec8d0a -Dspark.app.name=spark-pi -Dspark.driver.host=spark-pi-fb36460b4e853cc78f4f7ec4d9ec8d0a-driver-svc.default.svc -Dspark.kubernetes.driver.pod.name=spark-pi-driver -cp ':/opt/spark/jars/*:/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar;/opt/spark/examples/jars/spark-examples_2.11-2.3.0.jar' -Xms1g -Xmx1g -Dspark.driver.bindAddress=172.17.0.4 org.apache.spark.examples.SparkPi
Error: Could not find or load main class org.apache.spark.examples.SparkPi
```
It cannot find the SparkPi class. Yet, when I explore the `spark:spark` container, the JAR is inside:
```
\opt\spark\examples\jars:
spark-examples_2.11-2.3.0.jar
```
So the image was built correctly...
Any ideas what's wrong?
Help!!!
*Edit*
I have been doing some more testing. I did set up an AKS in Azure and launched the same Docker image getting the same error. I was following [this](https://learn.microsoft.com/en-us/azure/aks/spark-job) instructions but using the same Docker image as in local through ACR.
Also, the .JAR was uploaded to Blob Storage and an URL used for the case of AKS. Still I got the exact same error.
This somehow makes me think the error might be in the way I build the image itself or in the way I build the .JAR more so than in some configuration of the Cluster itself.
Yet, no cigar.
Any ideas - or even an URL to get a working Spark 2.3 image - would be welcome.
I build the image in Windows. I will try to build it in Linux shortly, maybe that is the problem all along...
Thx<issue_comment>username_1: If you want to trace the workings of your parser, you are much better off enabling bison's trace feature. It's really easy. Just add the `-t` or `--debug` flag to the `bison` command to generate the code, and then add a line to actually produce the tracing:
```
/* This assumes you have #included the parse.tab.h header */
int main(void) {
#if YYDEBUG
yydebug = 1;
#endif
```
This is explained in [the Bison manual](https://www.gnu.org/software/bison/manual/bison.html#Tracing); the `#if` lets your program compile if you leave off the `-t` flag. While on the subject of flags, I strongly suggest you do not use the `-y` flag; it is for compiling old Yacc programs which relied on certain obsolete features. If you don't use `-y`, then bison will use the basename of your `.y` file with extensions `.tab.c` and `.tab.h` for the generated files.
Now, your bison file says that some of your tokens have semantic types, but your flex actions do not set semantic values for these tokens and your bison actions don't use the semantic values. Instead, you simply print the value of `yytext`. If you think about this a bit, you should be able to see why it won't work. Bison is a *lookahead* parser; it makes its parsing decisions based on the the current parsing state and a peek at the next token (if necessary). It peeks at the next token by calling the lexer. And when you call the lexer, it changes the value of `yytext`.
Bison (unlike other yacc implementations) doesn't always peek at the next token. But in your zipcode rule, it has no alternative, since it cannot tell whether the next token is a `-` or not without looking at it. In this case, it is not a dash; it is a newline. So guess what `yytext` contains when you print it out in the zipcode action.
If your tokenizer were to save the text in the `id` semantic value member (which is what it is for) then your parser would be able to access the semantic values as `$1`, `$2`, ...
Upvotes: 2 <issue_comment>username_2: Because `yytext` is a global variable, it's overwritten and you will have to copy it in your *lex* script. In a pure parser, even though it's not global anymore it's still reused and passed as a parameter so it's incorrect to use it's value like you are attempting.
Also, don't use it in bison, instead use `$n` where `n` is the position of the token in the rule. You probably need the `%union` directive changed to something like
```
%union {
int number;
char *name;
};
```
So in the *flex* file, if you want to capture the text do something like
```
[A-Za-z]+ { yylval.name = strdup(yytext); return NAMETOKEN; }
```
and remember, do not use `yytext` in *bison*, it's an internal thing used by the lexer.
Then and since you have defined a type for the zip code
```
/* Entire block */
locationPart: townName COMMATOKEN stateCode zipCode EOLTOKEN {
printf("Rule 12: LP: TN COMMA SC ZC EOL: town:%s, stateCode:%d zip-code:%s\n", $1, $3, $4);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: The problem is here:
```
zipCode: INTTOKEN DASHTOKEN INTTOKEN { // case 25 }
| INTTOKEN { // case 26 }
;
```
The parser doesn't know which rule to take--25 or 26--until it's parsed the next token to see if it is a DASHTOKEN. By the time the code is executed, yytext has already been overwritten.
The easiest way to handle this is to have a production that takes the INTTOKENs and returns what was in yytext[] in malloc()'d memory. Something like:
```
zipCode: inttoken DASHTOKEN inttoken
{
printf("Rule 25: zip is %s-%s\n", $1, $3);
free($1);
free($3);
}
| inttoken
{
printf("Rule 26: zip is %s\n", $1);
free($1);
}
;
inttoken: INTTOKEN { $$ = strdup(yytext); }
;
```
Upvotes: 0
|
2018/03/17
| 1,239 | 3,940 |
<issue_start>username_0: So, I have this single page that consists of a few sections. Users can go to these sections by scrolling themselves or clicking in the navbar (a href with anchor). Due to the Bootstrap 4 navbar being fixed to the top, the content gets placed under it. Is there a way I could offset anchors by -54px, so that whenever I click on an anchor link, it would show the content below the navbar (X:54px) and not under the navbar (X:0px).
Made this codepen to show the problem I'm facing:
<https://codepen.io/anon/pen/XEjaKv>
Whenever you click an anchor link, it will take you to the section, however, the navbar is covering the text..
All sections are 100 viewheight.
SCSS used:
```
.container{
section{
height: 100vh;
&#section1{
margin-top: 54px; // we need to offset the first section by 54px because of the navbar..
}
&#section1, &#section3{
background-color: #ddd;
}
&#section2, &#section4{
background-color:#ccc;
}
}
}
html{
scroll-behavior:smooth;
}
</code></pre>
```<issue_comment>username_1: Usually when using a sticky header like that you’ll want to find the height of your navbar and offset the entire view accordingly. Something like
```
body {
margin-top:2rem;
}
```
Your other option would be to use JavaScript.
Upvotes: -1 <issue_comment>username_2: There are a few different ways to solve it, but I think the best way is to put a hidden pseudo element `::before` each section. This is a **CSS only solution**, no JS or jQuery...
```
section:before {
height: 54px;
content: "";
display:block;
}
```
<https://www.codeply.com/go/J7ryJWF5fr>
That will put the space needed to account for the fixed-top Navbar. You'll also want to remove the `margin-top` offset for `#section1` since this method will work consistently for *all* sections and allow the scrollspy to work.
---
**Related**
[How do I add a data-offset to a Bootstrap 4 fixed-top responsive navbar?](https://stackoverflow.com/questions/39588914/how-do-i-add-a-data-offset-to-a-bootstrap-4-fixed-top-responsive-navbar)
[Href Jump with Bootstrap Sticky Navbar](https://stackoverflow.com/questions/48593881/href-jump-with-bootstrap-sticky-navbar)
Upvotes: 5 [selected_answer]<issue_comment>username_3: you can use `jQuery` to override the default behavior so you don't have to change the layout ( margin, padding .. etc.)
```
var divId;
$('.nav-link').click(function(){
divId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(divId).offset().top - 54
}, 100);
});
```
<https://codepen.io/anon/pen/NYRvaL>
Upvotes: 4 <issue_comment>username_4: I like to dynamically offset the height header (or navbar) like this:
```
$('.nav-link').click(function(e){
let divCoords = $(e.target.hash).offset();
let height = $('header').height();
e.preventDefault();
window.scrollTo({
left: divCoords.left,
top: divCoords.top - height,
behavior: 'smooth'
});
});
```
Upvotes: -1 <issue_comment>username_5: [This](https://stackoverflow.com/a/11842865/3620572) solution adds a padding and removes the gap by a negative margin at the top. This worked best for me.
```
section {
padding-top: 56px;
margin-top: -56px;
}
```
```css
.offset {
height: 54px;
}
/* START SNIPPET */
section {
padding-top: 56px;
margin-top: -56px;
}
/* END SNIPPET */
#section1 p, #section3 p {
background-color: #ddd;
}
#section2 p, #section4 p {
background-color: #ccc;
}
p {
min-height: 15rem;
}
```
```html
[Navbar](#)
* [Section 1](#section1)
* [Section 2](#section2)
* [Section 3](#section3)
* [Section 4](#section4)
Section 1
Section 2
Section 3
Section 4
```
Upvotes: 3 <issue_comment>username_6: This elegant CSS 1-liner solution worked nicely for me:
>
> html { scroll-padding-top: 125px; }
>
>
>
My navbar height is 125px
Upvotes: 4
|
2018/03/17
| 2,923 | 11,401 |
<issue_start>username_0: I've made a `ListView` in Flutter, but now I have some `ListTiles` in this `ListView` that can be selected. Upon selection, I want the background color to change to a color of my choice. I don't know how to do that.
In [the docs](https://docs.flutter.io/flutter/material/ListTileTheme/style.html) they mention that a `ListTile` has a property `style`. However, when I try to add that (as in third last line in the code below), this `style` property gets a squiggly red line underneath and the compiler tells me that `The named parameter 'style' isn't defined`.
```
Widget _buildRow(String string){
return new ListTile(
title: new Text(string),
onTap: () => setState(() => toggleSelection(string)),
selected: selectedFriends.contains(string),
style: new ListTileTheme(selectedColor: Colors.white,),
);
}
```<issue_comment>username_1: It's not `ListTile` that has the `style` property. But `ListTileTheme`.
`ListTileTheme` is an inheritedWidget. And like others, it's used to pass *down* data (such as theme here).
To use it, you have to wrap any widget **above** your ListTile with a `ListTileTheme` containing the desired values.
`ListTile` will then theme itself depending on the closest `ListTileTheme` instance.
Upvotes: 5 [selected_answer]<issue_comment>username_2: I was able to change the background color of the ListTile using a **BoxDecoration** inside **Container**:
```
ListView (
children: [
new Container (
decoration: new BoxDecoration (
color: Colors.red
),
child: new ListTile (
leading: const Icon(Icons.euro\_symbol),
title: Text('250,00')
)
)
]
)
```
Upvotes: 5 <issue_comment>username_3: If you also need an `onTap` listener with a ripple effect, you can use `Ink`:
```
ListView(
children: [
Ink(
color: Colors.lightGreen,
child: ListTile(
title: Text('With lightGreen background'),
onTap: () { },
),
),
],
);
```
[](https://i.stack.imgur.com/67osY.gif)
Upvotes: 5 <issue_comment>username_4: I was able to change the Background Color of ListTile by making it a child of Container Widget and adding color to the Container Widget.
Here drawerItem is the model class which holds the isSelected value. Color of background depends on isSelected value.
Note: For unselected items keep the color Transparent so you will still get the ripple effect.
```
for (var i = 0; i < drawerItems.length; i++) {
var drawerItem = drawerItems[i];
drawerOptions.add(new Container(
color: drawerItem.isSelected
? Colors.orangeAccent
: Colors.transparent,
child: new ListTile(
title: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [Text(drawerItem.title), drawerItem.count],
),
leading: SvgPicture.asset(
drawerItem.icon,
width: 34,
height: 34,
),
onTap: () {
\_handleNavigation(i);
},
selected: drawerItem.isSelected,
),
));
}
```
[](https://i.stack.imgur.com/lfZHx.png)
Upvotes: 0 <issue_comment>username_5: ### Screenshot:
[](https://i.stack.imgur.com/bVdFS.gif)
---
### Short answer:
```dart
ListTile(
tileColor: isSelected ? Colors.blue : null,
)
```
---
### Full Code:
```dart
// You can also use `Map` but for the sake of simplicity I'm using two separate `List`.
final List \_list = List.generate(20, (i) => i);
final List \_selected = List.generate(20, (i) => false); // Fill it with false initially
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemBuilder: (\_, i) {
return ListTile(
tileColor: \_selected[i] ? Colors.blue : null, // If current item is selected show blue color
title: Text('Item ${\_list[i]}'),
onTap: () => setState(() => \_selected[i] = !\_selected[i]), // Reverse bool value
);
},
),
);
}
```
Upvotes: 6 <issue_comment>username_6: Wrap `ListTile` in an [`Ink`](https://api.flutter.dev/flutter/material/Ink-class.html).
```dart
Ink(
color: isSelected ? Colors.blue : Colors.transparent,
child: ListTile(title: Text('hello')),
)
```
Upvotes: 4 <issue_comment>username_7: I know that the original question has been answered, but I wanted to add **how to set the color of `ListTile` while the tile is being pressed**. The property you are looking for is called `highlight color` and it can be set by wrapping the `ListTile` in a `Theme` widget, like this:
```
Theme(
data: ThemeData(
highlightColor: Colors.red,
),
child: ListTile(...),
)
);
```
**Note:** if the `Theme` widget resets the font of text elements inside the `ListTile`, just set its `fontFamily` property to the same value You used in other places in your app.
Upvotes: 3 <issue_comment>username_8: Unfortunately, ListTile doesn't have background-color property. Hence, we have to simply wrap the ListTile widget into a Container/Card widget and then we can use its color property.
Further, We have to provide SizedBox widget with some height to separate the same colored ListTiles.
I am sharing that worked for me :)
I hope it will definitely help you.
Screenshot: [see how it works](https://i.stack.imgur.com/MrQla.jpg)
```
return
ListView(
children: snapshot.data.documents.map((doc) {
return Column(children: [
Card(
color: Colors.grey[200],
child: ListTile(
leading: Icon(Icons.person),
title: Text(doc.data['coursename'], style: TextStyle(fontSize: 22),),
subtitle: Text('Price: ${doc.data['price']}'),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () async {
await Firestore.instance
.collection('courselist')
.document(doc.documentID)
.delete();
},
),
),
),
SizedBox(height: 2,)
],);
}).toList(),[enter image description here][1]
);
```
Upvotes: 3 <issue_comment>username_9: An easy way would be to store the initial index in a variable and then change the state of that variable whenever tapped.
```
ListView.builder(
shrinkWrap: true,
itemCount: 4,
itemBuilder: (context, index) {
return Container( //I have used container for this example. [not mandatory]
color: tappedIndex == index ? Colors.blue : Colors.grey,
child: ListTile(
title: Center(
child: Text('${index + 1}'),
),onTap:(){
setState((){
tappedIndex=index;
});
}));
})
```
full code:
```
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyWidget(),
);
}
}
class MyWidget extends StatefulWidget {
@override
MyWidgetState createState() => MyWidgetState();
}
class MyWidgetState extends State {
late int tappedIndex;
@override
void initState() {
super.initState();
tappedIndex = 0;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ListView.builder(
shrinkWrap: true,
itemCount: 4,
itemBuilder: (context, index) {
return Container(
color: tappedIndex == index ? Colors.blue : Colors.grey,
child: ListTile(
title: Center(
child: Text('${index + 1}'),
),onTap:(){
setState((){
tappedIndex=index;
});
}));
})
]));
}
}
```
Dartpad link: <https://dartpad.dev/250ff453b97cc79225e8a9c657dffc8a>
Upvotes: 3 <issue_comment>username_10: This is no more pain!
Now you can use `tileColor` and `selectedTileColor` property of `ListTile` widget to achieve it.
Have a look at this [Issue #61347](https://github.com/flutter/flutter/pull/61347) which got merged into master.
Upvotes: 4 <issue_comment>username_11: Your answer has been answered in [Github](https://github.com/flutter/flutter/issues/33392#issuecomment-567103946).
```
Card(
color: Colors.white,
shape: ContinuousRectangleBorder(
borderRadius: BorderRadius.zero,
),
borderOnForeground: true,
elevation: 0,
margin: EdgeInsets.fromLTRB(0,0,0,0),
child: ListTile(
// ...
),
)
```
Upvotes: 0 <issue_comment>username_12: I have used as
```
ListTile(
title: Text('Receipts'),
leading: Icon(Icons.point_of_sale),
tileColor: Colors.blue,
),
```
Upvotes: 2 <issue_comment>username_13: There are two props: tileColor and selectedTileColor.
`tileColor` - when the tile/row is Not selected;
`selectedTileColor` - when the tile/row is selected
```
ListTile(
selected: _isSelected,
tileColor: Colors.blue,
selectedTileColor: Colors.greenAccent,
)
```
Upvotes: 1 <issue_comment>username_14: [enter image description here](https://i.stack.imgur.com/zfGRG.gif)>Make variable
```
int slectedIndex;
```
>
> on tap
>
>
>
```
onTap:(){
setState(() {
selectedIndex=index;
})
```
>
> Tile property
>
>
>
```
color:selectedIndex==index?Colors.red :Colors.white,
```
>
> Same As in List View Builder
>
>
>
```
ListView.builder(
itemCount: 10,
scrollDirection:Axis.vertical,
itemBuilder: (context,index)=>GestureDetector(
onTap:(){
setState(() {
selectedIndex=index;
});
} ,
child: Container(
margin: EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color:selectedIndex==index?Colors.red :Colors.white,
),)
```
Upvotes: 2 <issue_comment>username_15: Use the Material widget with InkWell Widget then put inside it the ListTile as shown here in this example:
```
return Material(
color: Colors.white,
child: ListTile(
hoverColor: Colors.greenAccent,
onLongPress: longPressCallback,
title: Text(
'$taskTitle',
style: TextStyle(
decoration: isChecked
? TextDecoration.lineThrough
: TextDecoration.none),
),
trailing: Checkbox(
activeColor: Colors.lightBlueAccent,
value: isChecked,
onChanged: checkboxCallback)),
);
```
Upvotes: 0
|
2018/03/17
| 1,062 | 3,741 |
<issue_start>username_0: I'm trying to make a `.request()` call using Alamofire 4 and Swift 4. Here's the code I'm using:
```
static func getPlaceData(url: String, parameters: [String: String]) {
Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
if response.result.isSuccess {
let json: JSON = JSON(response.result.value!)
print(json)
} else {
print("error")
}
}
}
```
where `headers` is:
```
let headers: HTTPHeaders = [
"Authorization": "Bearer /*PRIVATE KEY*/"
]
```
I am getting the following error:
*Extra argument 'method' in call*, at the `Alamofire.request(...` line.
I've read through quite a few SO posts about similar issues but none of their solutions have fixed my problem:
* [Alamofire Swift 3.0 Extra argument in call](https://stackoverflow.com/questions/39490839/alamofire-swift-3-0-extra-argument-in-call)
* [Swift Alamofire Request Error - Extra Argument in call](https://stackoverflow.com/questions/44704860/swift-alamofire-request-error-extra-argument-in-call)
I've also read in the [this documentation guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol) and [this issues thread on GitHub](https://github.com/Alamofire/Alamofire/issues/1508) but neither have solved the issue.
What is the proper syntax for a `.request()` call with required `parameters` and `headers`?
The code is for making an authenticated call from Swift code using the Yelp Fusion API -- maybe someone can suggest a better method than Alamofire?<issue_comment>username_1: I went through the documentations and found out two things
1. The request method signature which is
```
public func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
```
[Link to the documentation](https://github.com/Alamofire/Alamofire/blob/master/Source/Alamofire.swift#L132)
2. The `Parameter` typeAlias is a type of `[String:Any]` where as you are passing `[String:String]` which is conflicting.
[Link to the Parameter Definition in the DOC](https://github.com/Alamofire/Alamofire/blob/0456f5b501f46591a77b4bb6f2e2e2a97d095042/Source/ParameterEncoding.swift#L44)
So all you need to do it change the signature and you are good.
Upvotes: 2 <issue_comment>username_2: I figured out the issue, no thanks to any documentation or GitHub threads.
The logic in the above code snippet (from the question) referenced a constant called `headers`, which was declared outside of `getPlaceData(url:parameters:)`. This is because in order to access the Yelp Fusion API you need to include an extra field in the `HTTP` header you send to include the private API key using the format mentioned [here](https://www.yelp.com/developers/documentation/v3/authentication).
I moved the `headers` data structure inside of `getPlaceData(url:parameters:)` and it fixed the issue, so my resulting function is as follows:
```
static func getPlaceData(url: String, parameters: [String: String]) {
let headers: HTTPHeaders = [
"Authorization": "Bearer /*PRIVATE KEY*/"
]
Alamofire.request(url, method: .get, parameters: parameters, encoding:
JSONEncoding.default, headers: headers).responseJSON { (response) in
if response.result.isSuccess {
let json: JSON = JSON(response.result.value!)
print(json)
} else {
print("error")
}
}
}
```
Not sure why this fixed the issue, but the code works now.
Upvotes: 1 [selected_answer]
|
2018/03/17
| 1,038 | 3,805 |
<issue_start>username_0: I have a function that creates an array of Observables (batchOfRequests) from an array of items (myItemsArray). Each myItem pushes one Observable (http request) with two parameters from properties of myItem (propertyOne, propertyTwo, etc.) I then use Observable.concat to make the requests for each Observable in the batchOfRequests. This works fine and I can see the data returned from each request in returnedData. However, at this point, I have no idea which myItem in the myItemsArray belongs to each request. Is there a way to link or map each myItem to the Observable that was pushed into the batchOfRequests ?
```
performMultipleRequests(): void
{
let batchOfRequests: Observable[] = [];
for (let myItem of this.myItemsArray)
{
this.batchOfTrendRequests.push(this.myService.makeHTTPCall(myItem.propertyOne, myItem.propertyTwo))
}
this.batchOfRequests = this.batchOfRequests.map(obs =>
{
return obs.catch(err => Observable.of(err));
});
Observable.concat(...this.batchOfRequests)
.finally(() =>
{
return;
})
.subscribe((returnedData: any) =>
{
// do something with my returned data... but I need myItem information as well
return;
}), (error) =>
{
return;
}
}
```<issue_comment>username_1: [forkJoin](https://www.learnrxjs.io/operators/combination/forkjoin.html) will emit an array of the responses in the same order as your myItemsArray. Thereby you can match each response back to its request according to its array index:
```
performMultipleRequests(): void {
let batchOfRequests: this.myItemsArray.map(myItem =>
this.myService.makeHTTPCall(myItem.propertyOne, myItem.propertyTwo)
.catch(err => Observable.of(err))
);
Observable.forkJoin(...batchOfRequests).subscribe((myResponsesArray: any[]) => {
myResponsesArray.forEach((returnedData, index) => {
// lookup myItem corresponding to this returnedData
const myItem = this.myItemsArray[index];
...
});
});
}
```
Note that the use of `.catch()` ensures that partial failures do not cause the whole batch to fail.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could map the data you want before pushing to the array. Like so:
```
let batchOfRequests: Observable<{ myData: any, httpResponse: any }>[] = [];
for (let myItem of this.myItemsArray)
{
const httpRequest = this.myService.makeHTTPCall(myItem.propertyOne, myItem.propertyTwo);
const mappedRequest = httpRequest.map(res => {
return { myData: myItem, httpResponse: res };
});
batchOfRequests.push(mappedRequest);
}
```
instead of using map after filling the array you could also do your error-catching already in the loop:
```
let mappedRequest = httpRequest.map(res => {
return { myData: myItem, httpResponse: res };
});
mappedRequest = mappedRequest.catch(err => Observable.of(err));
```
Upvotes: 0 <issue_comment>username_3: you can make use of async/wait like as below , and
advantages are
1. of this its simple (no fancy stuff)
2. it execute request in parallel
3. it will return values in order , so 0 promise value is 0, 1 pushed promise in return 1 etc.
check here : [JavaScript Demo: Promise.all()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
[async/wait in trypscript](https://basarat.gitbooks.io/typescript/docs/async-await.html)
```
async performMultipleRequests(): void
{
let batchOfRequests: Promise[] = [];
for (let myItem of this.myItemsArray)
{
this.batchOfTrendRequests.push
(this.myService.makeHTTPCall
(myItem.propertyOne, myItem.propertyTwo).toPromise());
}
//this will return you array of all completed request
const allRetunValue = await Promise.all(batchOfTrendRequests);
allRetunValue.forEach(retval=> { console.log(retval); });
}
```
Upvotes: 0
|
2018/03/17
| 710 | 2,883 |
<issue_start>username_0: I have a main function that calls this function:
```
private void splashScreen() throws MalformedURLException {
JWindow window = new JWindow();
ImageIcon image = new ImageIcon(new URL("https://i.imgur.com/Wt9kOSU.png"));
JLabel imageLabel = new JLabel(image);
window.add(imageLabel);
window.pack();
window.setVisible(true);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
window.setVisible(false);
window.dispose();
}
```
I have added the image to the window, packed the window and then made it visible, the frame pops up but, the image does not show up in the frame. I am fairly certain that this code should work?<issue_comment>username_1: You are using Thread.sleep() so the GUI sleeps and can't repaint itself. Read the section from the Swing tutorial on [Concurrency](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information.
Don't use Thread.sleep().
Instead use a `Swing Timer` to schedule the event in 5 seconds. Read the section from the Swing tutorial on [How to Use Timers](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for more information.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Like username_1 said, a Swing Timer would be the proper way to deal with this. But since creating custom threads is something you will do a lot in the future, here's a "manual" example for how you could solve this:
```
private void showSplashScreen() {
[Create window with everything and setVisible, then do this:]
final Runnable threadCode = () -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(window::dispose); // Closes the window - but does so on the Swing thread, where it needs to happen.
// The thread has now run all its code and will die gracefully. Forget about it, it basically never existed.
// Btw., for the thread to be able to access the window like it does, the window variable either needs to be "final" (((That's what you should do. My mantra is, make EVERY variable (ESPECIALLY method parameters!) final, except if you need them changeable.))), or it needs to be on class level instead of method level.
};
final Thread winDisposerThread = new Thread(threadCode);
winDisposerThread.setDaemon(true); // Makes sure that if your application dies, the thread does not linger.
winDisposerThread.setName("splash window closer timer"); // Always set a name for debugging.
winDisposerThread.start(); // Runs the timer thread. (Don't accidentally call .run() instead!)
// Execution of your program continues here IMMEDIATELY, while the thread has now started and is sleeping for 5 seconds.
}
```
Upvotes: 1
|
2018/03/17
| 838 | 2,485 |
<issue_start>username_0: I am in the process of making a rock, paper, scissors shoot game in tkinter currently, and am trying to write a function that determines who wins. 1 = rock, 2 = paper, 3 = scissors. The script is not printing anything except when comp == 2 and choice == 1.
```
def Winning():
if (((comp == 2) and (choice == 1)) or ((comp == 3) and (choice == 2)) or
((comp == 1) and (choice == 3))):
messagebox.showinfo("Info", "YOU LOSE!!!")
if (((choice == 2) and (comp == 1)) or ((choice == 3) and (comp == 2))
or ((choice == 1) and (comp == 3))):
messagebox.showinfo("Info", "YOU WIN!!!")
else:
messagebox.showinfo("Info", "DRAW!!!")
```<issue_comment>username_1: Where does you function get `comp` and `choice` ?
Something like this would work :
```
from tkinter import messagebox
rock=1
paper=2
scissors=3
def Winning(comp, choice):
if (((comp == 2) and (choice == 1)) or ((comp == 3) and (choice == 2)) or((comp == 1) and (choice == 3))):
messagebox.showinfo("Info", "YOU LOSE!!!")
if (((choice == 2) and (comp == 1)) or ((choice == 3) and (comp == 2)) or((choice == 1) and (comp == 3))):
messagebox.showinfo("Info", "YOU WIN!!!")
else:
messagebox.showinfo("Info", "DRAW!!!")
Winning(rock, paper)
```
Is this what you want ?
Upvotes: 1 [selected_answer]<issue_comment>username_2: I think you went about this the wrong way. Assuming we have to use numeric input, I would do:
```
ROCK, PAPER, SCISSORS = range(1, 4)
roshambo = {
ROCK: SCISSORS,
PAPER: ROCK,
SCISSORS: PAPER
}
def Winning(comp, choice):
if comp == choice:
messagebox.showinfo("Info", "DRAW!!!")
elif comp == roshambo[choice]:
messagebox.showinfo("Info", "YOU WIN!!!")
else:
messagebox.showinfo("Info", "YOU LOSE!!!")
```
This makes your logic clear and simplifies the code. And, it makes it easier to extend the problem:
```
ROCK, PAPER, SCISSORS, LIZARD, SPOCK = range(1, 6)
roshambo = {
ROCK: [LIZARD, SCISSORS],
PAPER: [ROCK, SPOCK],
SCISSORS: [PAPER, LIZARD],
LIZARD: [SPOCK, PAPER],
SPOCK: [SCISSORS, ROCK]
}
def Winning(comp, choice):
if comp == choice:
messagebox.showinfo("Info", "DRAW!!!")
elif comp in roshambo[choice]:
messagebox.showinfo("Info", "YOU WIN!!!")
else:
messagebox.showinfo("Info", "YOU LOSE!!!")
```
Dictionaries are your friend, never program without them!
Upvotes: 2
|
2018/03/17
| 753 | 2,515 |
<issue_start>username_0: I've pieced together a small program designed to build random names. It is not finished, however it is currently repeating the same name if I attempt to re-run the program. Program is built on Ubuntu Linux, C++ running the emacs text editor.
Here is the full code below, I am still fairly new to C++ but haven't encountered this issue before.
```
#include
#include
#include
#include
using namespace std;
string randomName(int length) {
char consonents[] = {'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z'};
char vowels[] = {'a','e','i','o','u','y'};
string name = "";
int random = rand() % 2;
int count = 0;
for(int i = 0; i < length; i++) {
if(random < 2 && count < 2) {
name = name + consonents[rand() % 19];
count++;
}
else {
name = name + vowels[rand() % 5];
count = 0;
}
random = rand() % 2;
}
return name;
}
int main() {
cout << "Enter a name length: " << endl;
int length;
cin >> length;
cout << randomName(length) << endl;
return 0;
}
```
I have read the predictability for rand() and in the other questions that were similar to this they mention that rand() often repeats values. Surely this can't be every single time the program is run though can it?
In example:
If I run the program with a name length of 5 I may get something like: tfuvi
If I then run the program a second time with a name length of 2 I will get: tf
If I then run the program a third time with the name length of 4 I will get: tfuv
This can't be coincidence right?
Any help is greatly appreciated, if there is any documentation that explains this or if anyone knows a reason please let me know, thanks.<issue_comment>username_1: Set up the seed before calling `rand()`:
```
srand(time(NULL));
```
Then you can call `rand() % n`
Also be sure to include ctime for time();
Upvotes: 0 <issue_comment>username_2: >
> If no seed value is provided, the `rand()` function is automatically seeded with a value of 1.
>
>
>
Meaning that every time you run your program, you always get the same pseudo-random sequence. So, please seed your random number generator with `srand(time(NULL))` or in some other way: [Recommended way to initialize srand?](https://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand)
Upvotes: 3 [selected_answer]<issue_comment>username_3: you must initialize the random seed, call this before use **rand()** function in your program
```
srand (time(NULL));
```
Upvotes: 0
|
2018/03/17
| 1,751 | 3,780 |
<issue_start>username_0: I've found code that should work, I am trying to organize data in descending order, however, when I put in this code, I only get the first one in descending order, not both. I want both in descending order, how can I do that? Here is my code. The overall goal of this is to make sure that NumberOfPlays and FourthDownConversions are in descending order by Formation. Can someone help here?
```
SELECT Form, Down/Dist as AverageDistance, Play/Down AS NumberOfPlays, Gain/Down AS FourthDownConversionRate
FROM footballOffStats
WHERE Form IS NOT NULL AND Down = 4 AND Form != "" AND Gain IS NOT NULL
ORDER BY FourthDownConversionRate DESC, NumberOfPlays DESC;
```
These are the results being produced, how can I get NumberOfPlays and FourthDownConversion both in descending order?
```
Form AverageDistance NumberOfPlays FourthDownConversionRate
EARLY LT 4 109.25 1.25
DIAMOND 2 34.25 0
DBL FLEX 0.4444 24.5 4.25
SHIFT TO EMPTY 0.4 24 5
BLUE LIZ 0.8 23.75 1
BLUE RIP 0.5 23.75 1
BLUE RIP 0.5 23.5 2.25
DBL FLEX SNUG 1 23.25 0
RIP HIP 1.3333 23 5.75
Ace 0.5714 22.5 8.75
ACE RT 0.5714 22.5 3.75
ACE 0.4 22.5 1.75
Early Rip 0.6667 22.5 1.75
QUAD FLEX 0.8 22.5 1.25
ACE 0.8 22.5 1.25
BLUE RIP 0.3077 22.5 0
BLUE RIP 0.4 22.5 0
ACE 0.4 22.5 0
EARLY RIP 1.3333 22.5 0
SEATTLE 1.3333 22.5 0
BLUE RIP 0.5 22.5 0
BLUE LIZ 0.5714 22.5 -1.25
ACE 2 22 3.25
BLUE RIP 1 22 0
Blue Rex 4 22 0
BLUE RIP 0.4 21 13
BLUE RIP 0.16 21 0
EARLY RT 0.4 20.25 9.25
Rip Weak 0.25 20.25 9
Ace 0.4 20 10.75
JUMBO 2 19.5 0.5
HURRY 4 19.5 0.5
TOWERS 4 19.25 0.5
JUMBO 2 19 0.25
BIG GREEN 4 19 0
Blue Liz 0.5714 18.75 10.25
Liz Hip 0.8 18.75 4
DIAMOND 4 18.75 0
Blue LIz 0.2857 18.75 0
DIAMOND 1 18.5 3
WHACKY 4 18.25 12.25
WHACKY 4 18.25 0.75
BIG GREEN 4 18 0.5
BLUE 0.6667 17 -1
BIG GREEN 4 15 0
EMPTY LT 0.8 14 2
ACE 1.3333 14 1
TRIPS LT FLEX 1.3333 14 0
DBL FLEX 1.3333 13.75 1.5
DBL FLEX 0.4 13.25 2.75
DBL FLEX 1.3333 13 1.25
ACE 4 10.5 -0.5
BLUE LT 1 9.25 1.25
BLUE LIZ 1.3333 9.25 0.75
LEX 4 9.25 0
BLUE SEATTLE 2 9 1.5
REX 1.3333 9 0.75
EARLY RT 4 8.75 1.25
REX 4 8.75 0.5
BLUE RIP 0.2353 8.5 2.75
BLUE REX 4 8.5 0.75
BLUE REX 4 8.5 0
JUMBO WING 2 2 1.5
Ace Lt 2 0.5 0.75
JUMBO 4 0.5 0.5
LIZ WK 4 0 17.5
Blue Liz 1.3333 0 9.25
WHACKY 4 0 4.5
HURRY BG 4 0 4.25
ACE LT 4 0 2.25
TRIPS FLEX 0.5714 0 2
BROWN LT 0.8 0 1.5
ORANGE REX 4 0 1.5
BLUE RIP STACK 1.3333 0 1.5
BLUE LIZ 4 0 1.25
BUNCH LT 1 0 1.25
ACE 0.6667 0 1.25
ACE 2 0 1.25
Weak Lex 4 0 1
ACE 4 0 1
DIAMOND 4 0 0.5
Hurry 4 0 0.25
BLUE LT Flop 0.6667 0 0
BLUE BOSTON 0.4 0 0
```<issue_comment>username_1: Set up the seed before calling `rand()`:
```
srand(time(NULL));
```
Then you can call `rand() % n`
Also be sure to include ctime for time();
Upvotes: 0 <issue_comment>username_2: >
> If no seed value is provided, the `rand()` function is automatically seeded with a value of 1.
>
>
>
Meaning that every time you run your program, you always get the same pseudo-random sequence. So, please seed your random number generator with `srand(time(NULL))` or in some other way: [Recommended way to initialize srand?](https://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand)
Upvotes: 3 [selected_answer]<issue_comment>username_3: you must initialize the random seed, call this before use **rand()** function in your program
```
srand (time(NULL));
```
Upvotes: 0
|
2018/03/17
| 878 | 3,162 |
<issue_start>username_0: so I have to write a function join(a,b,c,d) that takes up to 4 strings, and joins them together with a comma. The function should still work when given less than 4 strings, including printing out just one string with no commas attached when given only one string as an argument. However, I can only make it work with 3
```
function join(a,b,c,d)
if b == nil then
print(a .. ", " .. c .. ", " .. d)
elseif c == nil then
print(a .. ", " .. b .. ", " .. d)
elseif d == nil then
print(a .. ", " .. b .. ", " .. c)
else
print(a .. ", ".. b .. ", " .. c .. ", " .. d)
end
end
```
I don't know how to make it take less than 3 arguments, please help<issue_comment>username_1: What you're looking for can be achieved by what most programming languages call "default/optional parameters." However, Lua seems to do this slightly differently - it only **actually** requires the argument if you actually use it in the function (without surrounding it with the conditional checking for nil) - so your approach was actually correct, just missing a little conditional magic. Rewrite your program as follows, you'll find that the function does what you need:
```
function join(a,b,c,d)
io.write(a)
if b ~= nil then
io.write(", " .. b)
end
if c ~= nil then
io.write(", " .. c)
end
if d ~= nil then
io.write(", " .. d)
end
end
join('test')
join('test', 'test1')
join('test', 'test1', 'test2')
join('test', 'test1', 'test2', 'test3')
```
Test-run the code here: <https://jdoodle.com/a/qoc>
Important note about the change from your version: notice how it's just if-blocks and not if-else blocks. That is primarily what enables the "flow-of-control" to check for potentially none of the last 3 params existing. You might want to do some further reading on "flow-of-control" and "conditionals."
Note: replaced `print` with `io.write` because:
1. `io.write` doesn't append a newline character to the end of its output by default, so you can print out your words on the same line, separated only by a comma and a space.
2. For future reference: as the discussions in [these answers](https://stackoverflow.com/questions/7148678/lua-print-on-the-same-line) indicate, io.write is the preferred output method anyway.
Further reference:
* Check out [this discussion about "default/optional arguments"](https://forum.defold.com/t/lua-defining-a-function-with-optional-parameters-solved/3340/2) and their lua equivalents. Since you didn't actually have any "default" values, so to speak, for your optional params, it was good enough to simply check their nil conditions. Often, you may want to use a "default" value though, and that discussion goes into details on how to do so in Lua.
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you only concatenate and print those string inputs, you don't even need to give names to arguments:
```
local function join(...)
print(table.concat({...}, ", ")
end
join("a")
join("a","b")
join("a","b","c")
join("a","b","c","d","e","f","blah-blah","as many as you want", "even more")
```
Upvotes: 3
|
2018/03/17
| 390 | 1,206 |
<issue_start>username_0: Please I NEED some one to run this code and send me the output, because i am unable to run it
package squarematrix;
public class SquareMatrix {
```
public static void main(String[] args) {
int[][] m = {
{10, 12, 11}, // {1, 2, 3},
{ 9, 8, 31}, // {4, 5, 6},
{ 2, 16, 24} // {7, 8, 9},
};
int sum = 0;
int R = m.length; // length of rows
int C = m[0].length; // length of columns
if (R == C) { // checks that matrix is square
// for m the secondary diagonal is 2, 8, 11 --> sum = 21
for (int i = 0; i < m.length; i++) { // iterates through secondsary diagonal
sum += m[i][m.length - i - 1]; // adds each diagonal element to sum
} } else {
System.out.println("This is not a square matrix.");
}
System.out.println("Diagonal sum: " + sum);
}
}
```<issue_comment>username_1: It's output is: *Diagonal sum: 21*
It's a `Java` program and I ran it on an online compiler: <https://ideone.com/6KrzGh>
Upvotes: 0 <issue_comment>username_2: this is JAVA code, not JavaScript code
and the output is:
Diagonal sum: 21
Upvotes: 1
|
2018/03/17
| 1,155 | 4,001 |
<issue_start>username_0: I have tried searching for solutions to this question but still haven't found it. The HTML is executing fine but the Javascript is not executing. I have included it in the index.html file and tried an external .js file. Still can't get my javascript to execute. Also having issues with CSS not executing. Need some new eyes. Thanx...
```
X-Ray Quiz
##### Quick Asessment
Identify this image

identify this image

normal
COPD
Choice
Identify this image

Normal
choice
Asthma
```
main.js
```
function check () {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
If (question1 == “normal”) {
correct ++;
}
if (question2 == “COPD”) {
correct ++;
}
if (question3 == “Fibrosis”) {
correct ++;
}
document.getElementById(“after_submit”).style.visibility = “visible”;
document.getElementById(“number_correct”).innerHTML = “You got “ +
correct + “correct.”;
}
var messages = [ “Great job”, “That’s just okay”, “ You really need to
do better!”];
var range;
if (correct <1) {
range =2;
if (correct > 0 && correct<3) {
range = 1;
}
if (correct>2) {
range = 0;
}
document.getElementById(“after_submit”).style.visibility = “visible”;
document.getElementById(“message”).innerHTML = messages[range];
document.getElementById(“number_correct”).innerHTML = “ You got “ +
correct + “ correct. “;
}
```<issue_comment>username_1: First of all, your JavaScript file isn't linked to your HTML. You may need to add:
Upvotes: 1 <issue_comment>username_2: There are lots of errors in the code, so even if it's wired up correctly, it's not going to run.
For example:
```
If (question1 == “normal”) {/* ...etc */ }
```
`If` should be lower case. And those quote marks are fancy quotes `“` rather than `"`. I don't know if all interpreters choke on those, but mine does.
Also you are defining `correct` in the function `check()` but then try to access it outside the function, where it is no longer in scope. This results in an error.
All these errors are easy to find if you use the browser console — they are all listed there. In Chrome it's `Ctrl+Shift+J` (Windows / Linux) or `Cmd+Opt+J` (Mac).
Upvotes: 0 <issue_comment>username_3: Alright - like the others were saying, there were a lot of errors in your code. I went and tried to correct your code as best as I could, but I also noticed that there was no `message` element. I added that, and now the program works. Of course, there's no CSS to add to this snippet, so it looks a bit bland. hope this works for you!
```js
function check () {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
if (question1 == 'normal') {
correct ++;
}
if (question2 == 'COPD') {
correct ++;
}
if (question3 == 'Fibrosis') {
correct ++;
}
document.getElementById('after_submit').style.visibility = 'visible';
document.getElementById('number_correct').innerHTML = 'You got ' + correct + 'correct.';
var messages = [ 'Great job', 'That’s just okay', ' You really need to do better!'];
var range;
if (correct <1) {
range =2;
if (correct > 0 && correct<3) {
range = 1;
}
if (correct>2) {
range = 0;
}
document.getElementById('after_submit').style.visibility = 'visible';
document.getElementById('message').innerHTML = messages[range];
document.getElementById('number_correct').innerHTML = ' You got ' + correct + ' correct. ';
}
}
```
```html
X-Ray Quiz
##### Quick Asessment
Identify this image

identify this image

normal
COPD
Choice
Identify this image

Normal
choice
Asthma
```
Upvotes: 0
|
2018/03/17
| 891 | 3,212 |
<issue_start>username_0: I'm defining the Vue.js instance like this in `app.js`:
```
const vm = new Vue({
el: '#app',
data: {
page: 'welcome'
}
});
```
and using Laravel's default webpack script:
```
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
```
Vue is loading correctly as the components are displaying and the Vue developer plugin is showing appropriate data.
However, in the developer console and in scripts on the page `vm` is not defined.
For instance on the page that is loading a Vue component
```
console.log(vm); // Error: vm is not defined.
```
How do I access the Vue instance? I want to set a one of its data properties.<issue_comment>username_1: First of all, your JavaScript file isn't linked to your HTML. You may need to add:
Upvotes: 1 <issue_comment>username_2: There are lots of errors in the code, so even if it's wired up correctly, it's not going to run.
For example:
```
If (question1 == “normal”) {/* ...etc */ }
```
`If` should be lower case. And those quote marks are fancy quotes `“` rather than `"`. I don't know if all interpreters choke on those, but mine does.
Also you are defining `correct` in the function `check()` but then try to access it outside the function, where it is no longer in scope. This results in an error.
All these errors are easy to find if you use the browser console — they are all listed there. In Chrome it's `Ctrl+Shift+J` (Windows / Linux) or `Cmd+Opt+J` (Mac).
Upvotes: 0 <issue_comment>username_3: Alright - like the others were saying, there were a lot of errors in your code. I went and tried to correct your code as best as I could, but I also noticed that there was no `message` element. I added that, and now the program works. Of course, there's no CSS to add to this snippet, so it looks a bit bland. hope this works for you!
```js
function check () {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
if (question1 == 'normal') {
correct ++;
}
if (question2 == 'COPD') {
correct ++;
}
if (question3 == 'Fibrosis') {
correct ++;
}
document.getElementById('after_submit').style.visibility = 'visible';
document.getElementById('number_correct').innerHTML = 'You got ' + correct + 'correct.';
var messages = [ 'Great job', 'That’s just okay', ' You really need to do better!'];
var range;
if (correct <1) {
range =2;
if (correct > 0 && correct<3) {
range = 1;
}
if (correct>2) {
range = 0;
}
document.getElementById('after_submit').style.visibility = 'visible';
document.getElementById('message').innerHTML = messages[range];
document.getElementById('number_correct').innerHTML = ' You got ' + correct + ' correct. ';
}
}
```
```html
X-Ray Quiz
##### Quick Asessment
Identify this image

identify this image

normal
COPD
Choice
Identify this image

Normal
choice
Asthma
```
Upvotes: 0
|
2018/03/17
| 524 | 1,434 |
<issue_start>username_0: I would like to transform a long data set with repeated observations:
```
obs code
1 A
2 B
4 G
2 D
1 H
3 K
```
Into a "shorter" data set with a comma separated, summary column:
```
obs code
1 A,H
2 B,D
3 K
4 G
```
I tried something like:
```
df <- data.frame(obs=c("1","2","4","2","1","3"), code=c("A","B","G","D","H","K"),stringsAsFactors = F)
df %>% group_by(obs) %>%
mutate(id=1:n()) %>%
spread(id,code) %>%
replace_na(list(`1` = "", `2` = "")) %>%
unite(new,2:3, remove=FALSE,sep=",")
```
However, this gives me additional "," for obs 3 and 4.
Is there a nicer was to solve my problem?<issue_comment>username_1: Instead of `spread`ing to 'wide' format and then using `replace_na`, this can be done more directly by `paste`ing the 'code' in `summarise` after the `group_by` step
```
df %>%
group_by(obs) %>%
summarise(code = toString(code))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a base R solution using `aggregate` as an alternative:
```
with(df, aggregate(code, by = list(obs = obs), toString));
# obs x
#1 1 A, H
#2 2 B, D
#3 3 K
#4 4 G
```
If you don't want the extra space between `code`s, you can `paste0` entries (instead of using `toString`):
```
with(df, aggregate(code, by = list(obs = obs), paste0, collapse = ","));
# obs x
#1 1 A,H
#2 2 B,D
#3 3 K
#4 4 G
```
Upvotes: 1
|
2018/03/17
| 360 | 1,155 |
<issue_start>username_0: I'm using large titles, in the main view I have a scrollView and a view behind the scrollView that is a background image. When I do this, large titles doesn't work (are always big while you scroll) because the scrollView is not the first element inside the main view. If I change the order, the background image covers the scroll view.
Any solutions? Thanks!!<issue_comment>username_1: Instead of `spread`ing to 'wide' format and then using `replace_na`, this can be done more directly by `paste`ing the 'code' in `summarise` after the `group_by` step
```
df %>%
group_by(obs) %>%
summarise(code = toString(code))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a base R solution using `aggregate` as an alternative:
```
with(df, aggregate(code, by = list(obs = obs), toString));
# obs x
#1 1 A, H
#2 2 B, D
#3 3 K
#4 4 G
```
If you don't want the extra space between `code`s, you can `paste0` entries (instead of using `toString`):
```
with(df, aggregate(code, by = list(obs = obs), paste0, collapse = ","));
# obs x
#1 1 A,H
#2 2 B,D
#3 3 K
#4 4 G
```
Upvotes: 1
|
2018/03/17
| 1,067 | 3,840 |
<issue_start>username_0: I'm creating a chain of responsibility pipeline using `System.Func` where each function in the pipeline holds a reference to the next.
When building the pipeline, I'm unable to pass the inner function by reference as it throws a StackOverflowException due to the reassignment of the pipeline function, for example:
```
Func, string> handler1 = (s, next) => {
s = s.ToUpper();
return next.Invoke(s);
};
Func pipeline = s => s;
pipeline = s => handler1.Invoke(s, pipeline);
pipeline.Invoke("hello"); // StackOverFlowException
```
I can work around this with a closure:
```
Func, string> handler1 = (s, next) => {
s = s.ToUpper();
return next.Invoke(s);
};
Func, Func> closure =
next => s => handler1.Invoke(s, next);
Func pipeline = s => s;
pipeline = closure.Invoke(pipeline);
pipeline.Invoke("hello");
```
However, I would like to know if there is a more efficient way to build up this chain of functions, perhaps using Expressions?<issue_comment>username_1: Using expressions, the "building" part of the process is guaranteed to be less efficient because of the cost of compiling the expressions, probably at least two orders of magnitude slower than linking up the `Func`s.
Going deep with expressions - where the elements of the pipeline are expressions themselves rather than `Func`s, can be used to create a more runtime-efficient implementation by rewriting. Slower to set up, but essentially every time you are handed an expression for an element like:
```
Expression, string>> handler1 = (s, next) =>
next.Invoke(s.ToUpper());
```
You rewrite it so that the body of whatever is supposed to be in `next` just gets inlined directly in where `next.Invoke(...)` appears in the expression tree.
This does limit you to expression-bodied elements though (effectively, you just need to make the body of any complex handlers call a helper function instead of doing whatever work they need to do inline).
Trying to dredge up an example of this out there somewhere, but can't think of a good one off the top of my head. Good luck!
Upvotes: 1 <issue_comment>username_2: Chain of responsibility is like a linked list from my point of view. Normally, it would create a class to encapsulate each handler that contains a reference to the next handler in the chain. But if you want to go with `Func` style, we could do something similar using procedural style:
Demo here: <https://dotnetfiddle.net/LrlaRm>
```
public static void Main()
{
Func handler1 = (s) => {
s = s.ToUpper();
return s;
};
Func handler2 = (s) => {
s = s.TrimStart();
return s;
};
Func chain = ChainBuilder(handler1, handler2);
Console.WriteLine(chain(" hello"));
}
static Func, Func, Func> ChainBuilder = (f1, f2) => s => {
s = f1(s);
if (f2 != null) {
s = f2(s);
}
return s;
};
```
What i'm doing is creating a higher order function to build the chain.
Another demo to chain 3 handlers using the same idea: <https://dotnetfiddle.net/ni0DKL>
However, I recommend creating a class for this: <https://dotnetfiddle.net/CsVpzh>. It's better from encapsulation & abstraction points of view and easy to extend to add specific configurations to each handler.
Upvotes: 1 <issue_comment>username_3: What about that? This way you can build chains of arbitrary length.
```
void Main()
{
Func f1 = x => x.Replace("\*", string.Empty);
Func f2 = x => x.Replace("--", string.Empty);
Func f3 = x => x.ToUpper();
//Func pipeline = x => f3(f2(f1(x)));
Func pipeline = Pipeline(f1, f2, f3);
pipeline.Invoke("te-\*-st").Dump(); // prints "TEST"
}
Func Pipeline(params Func[] functions)
{
Func resultFn = x => x;
for (int i = 0; i < functions.Length; i++)
{
Func f = functions[i];
Func fPrev = resultFn;
resultFn = x => f(fPrev(x));
}
return resultFn;
}
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,491 | 4,843 |
<issue_start>username_0: I have a string and want to check if it can be used as a valid variable without getting a syntax error. For example
```
def variableName(string):
#if string is valid variable name:
#return True
#else:
#return False
input >>> variableName("validVariable")
output >>> True
input >>> variableName("992variable")
output >>> False
```
I would not like to use the .isidentifier(). I want to make a function of my own.<issue_comment>username_1: The following answer is true only for "old-style" Python-2.7 identifiers;
```
"validVariable".isidentifier()
#True
"992variable".isidentifier()
#False
```
Since you changed your question after I posted the answer, consider writing a regular expression:
```
re.match(r"[_a-z]\w*$", yourstring,flags=re.I)
```
Upvotes: 3 <issue_comment>username_2: You could use a regular expression.
For example:
```
isValidIdentifier = re.match("[A-Za-z_](0-9A-Za-z_)*",identifier)
```
Note that his only checks for alphanumeric characters. The actual standard supports other characters. See here: <https://www.python.org/dev/peps/pep-3131/>
You may also need to exclude reserved words such as def, True, False, ... see here: <https://www.programiz.com/python-programming/keywords-identifier>
Upvotes: 0 <issue_comment>username_3: In Python 3 a valid identifier can have characters outside of ASCII range, as you don't want to use [`str.isidentifier`](https://docs.python.org/3.3/library/stdtypes.html#str.isidentifier), you can write your own version of it in Python.
Its specification can be found here: <https://www.python.org/dev/peps/pep-3131/#specification-of-language-changes>
Implementation:
---------------
```
import keyword
import re
import unicodedata
def is_other_id_start(char):
"""
Item belongs to Other_ID_Start in
http://unicode.org/Public/UNIDATA/PropList.txt
"""
return bool(re.match(r'[\u1885-\u1886\u2118\u212E\u309B-\u309C]', char))
def is_other_id_continue(char):
"""
Item belongs to Other_ID_Continue in
http://unicode.org/Public/UNIDATA/PropList.txt
"""
return bool(re.match(r'[\u00B7\u0387\u1369-\u1371\u19DA]', char))
def is_xid_start(char):
# ID_Start is defined as all characters having one of
# the general categories uppercase letters(Lu), lowercase
# letters(Ll), titlecase letters(Lt), modifier letters(Lm),
# other letters(Lo), letter numbers(Nl), the underscore, and
# characters carrying the Other_ID_Start property. XID_Start
# then closes this set under normalization, by removing all
# characters whose NFKC normalization is not of the form
# ID_Start ID_Continue * anymore.
category = unicodedata.category(char)
return (
category in {'Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl'} or
is_other_id_start(char)
)
def is_xid_continue(char):
# ID_Continue is defined as all characters in ID_Start, plus
# nonspacing marks (Mn), spacing combining marks (Mc), decimal
# number (Nd), connector punctuations (Pc), and characters
# carryig the Other_ID_Continue property. Again, XID_Continue
# closes this set under NFKC-normalization; it also adds U+00B7
# to support Catalan.
category = unicodedata.category(char)
return (
is_xid_start(char) or
category in {'Mn', 'Mc', 'Nd', 'Pc'} or
is_other_id_continue(char)
)
def is_valid_identifier(name):
# All identifiers are converted into the normal form NFKC
# while parsing; comparison of identifiers is based on NFKC.
name = unicodedata.normalize(
'NFKC', name
)
# check if it's a keyword
if keyword.iskeyword(name):
return False
# The identifier syntax is \*.
if not (is\_xid\_start(name[0]) or name[0] == '\_'):
return False
return all(is\_xid\_continue(char) for char in name[1:])
if \_\_name\_\_ == '\_\_main\_\_':
# From goo.gl/pvpYg6
assert is\_valid\_identifier("a") is True
assert is\_valid\_identifier("Z") is True
assert is\_valid\_identifier("\_") is True
assert is\_valid\_identifier("b0") is True
assert is\_valid\_identifier("bc") is True
assert is\_valid\_identifier("b\_") is True
assert is\_valid\_identifier("µ") is True
assert is\_valid\_identifier("") is True
assert is\_valid\_identifier(" ") is False
assert is\_valid\_identifier("[") is False
assert is\_valid\_identifier("©") is False
assert is\_valid\_identifier("0") is False
```
---
You can check CPython and Pypy's implmentation [here](https://github.com/python/cpython/blob/a49ac9902903a798fab4970ccf563c531199c3f8/Objects/unicodeobject.c#L12020) and [here](https://bitbucket.org/pypy/pypy/src/3f6eaa010fce78cc7973bdc1dfdb95970f08fed2/pypy/objspace/std/unicodeobject.py?at=release-pypy3.5-v5.10.1&fileviewer=file-view-default#unicodeobject.py-527) respectively.
Upvotes: 3
|
2018/03/17
| 307 | 1,217 |
<issue_start>username_0: The strangest thing happened. My froala rich text fields (Rails app) stopped working afer I committed some other work.
The symptoms were the following:
* In Firefox, I could not enter spaces, only letters would appear as I typed
* In Chrome, spaces showed, but I could not create new lines
* None of the formatting toolbar buttons worked (bold, italics, etc)
(Used for rails form fields that require rich text. Licensed version.)<issue_comment>username_1: So it turned out that some Javascript must have clobbered a Froala method?
The following code was in a javascript file in our code base:
```
var getSelection = function(){...
```
Once I renamed the method, everything worked perfectly.
```
var getHydrantSelection = function(){...
```
The code relying on the new method, and the Froala editor code were both working again!
(Shrug. Probably a better way to scope the JS?)
Upvotes: 0 <issue_comment>username_2: I am one of the makers of the Froala Editor. It looks like you're using the Froala Editor V1. The editor JS is scoped and it is strange that you're getting this conflict. Do you have any methods in your JS which override the getSelection method somehow?
Upvotes: -1
|
2018/03/17
| 1,301 | 3,875 |
<issue_start>username_0: So I am new to front-end web development and I am struggling mightily trying to arrange 3 tags in a container . Here is the code i have currently:
index.html
```



```
styles.css
```
.container {
background-color: #888;
border: 1px solid #000;
border -radius: 20px;
width: 800px;
height: 500px;
}
```
I've created a container div with width and height temporarily set to 800px and 500px. These are generally constant (they change with the window width / height, but that's it). I would like the 3 images to fit in the container div, arranged with the first image to the left, and then the 2nd and 3rd images stacked on top of each other to the right.
[](https://i.stack.imgur.com/k6If6.png)
This is a picture I made in excel describing how I'd like the pictures arranged. I've tried using auto, max-height, min-height, etc. but none of them fit the container how I'd like... any help with this is appreciated!
Edit - let me know if the image dimensions are needed and I can grab those. Also, if this is something that can be solved with flex-box, which is some css tools i am vaguely familiar with, that may be helpful too!<issue_comment>username_1: The width of all images would have to be 1/2 the width of the container.
Image one will have to have full height of the container.
The heights of Image 2, and 3 will have to total the height of container.
(I usually edit the pics outside of the code such as adobe photoshop, to the widths and heights I desire so that I don't have to use code to do it. Faster load time!) But if you must you can put it width and heights in the code.
After all that my html is:
```



```
my css is:
```
.container {
background-color: #888;
border: 1px solid #000;
border-radius: 20px;
width: 800px;
height: 500px;
float: left;
}
#image1 {
float: left;
}
#image2 {
position: absolute;
top: 1px;
left: 400px;
}
#image3 {
position: absolute;
top: 250px;
left: 400px;
}
```
The corners on your container are rounded so you will have to round the pics corners accordingly. example for image2 (border-top-right-radius: 20px). You can do the same for other pictures corners. I am also unsure of he position of your container to actual page so I just floated it left. Good Luck! I hope that helps.
Upvotes: -1 <issue_comment>username_2: If the proportions of the display blocks are fixed and the image sizes may vary, then your best option might be to put the images in the background of elements with CSS and use the `background-size` property to let the image fill the container:
```css
.container {
background-color: #888;
border: 1px solid #000;
border-radius: 20px;
width: 800px;
height: 500px;
overflow: hidden; /* this is only needed
to preserve the rounded edges
of the container */
}
#img1 {
width: 400px;
height: 500px;
}
#img2 {
width: 400px;
height: 200px;
}
#img3 {
width: 400px;
height: 300px;
}
div.container div {
width: 100px;
height: 100px;
float: left;
background-size: cover;
}
```
```html
```
Adjust the proportions as needed. You should also be able to optimize the CSS declarations by grouping them better, but this is intentionnally a very explicit example.
Upvotes: 2 [selected_answer]
|
2018/03/17
| 638 | 2,125 |
<issue_start>username_0: I have a program which is trying to set values in ImageData represented as a [Uint8ClampedArray](https://kotlinlang.org/api/latest/jvm/stdlib/org.khronos.webgl/-uint8-clamped-array/index.html) in a Kotlin program. According to [the specification for the set method](https://kotlinlang.org/api/latest/jvm/stdlib/org.khronos.webgl/set.html), I need to pass a Kotlin byte into the array, but Kotlin bytes are signed:
```
...create context...
//setup pix as a js Uint8ClampedArray
val imgd = context.createImageData(100.0, 100.0)
val pix = imgd.data //pix is now a Uint8ClampedArray
//sets pix[40] to 127
pix[40] = 127
//gives an error - Kotlin bytes are signed, so it cannot be passed as a literal
pix[40] = 200
//also doesn't work, still converts to a signed byte
pix[40] = 200.toByte()
```
My problem with this is that Javascript will read this as only 127, not 255. How can I set values of this array to be greater than 127? I can't even find a hack-y way to make the JS result read what I want, because ultimately the assignment needs a signed byte which doesn't allow for values greater than 127.<issue_comment>username_1: I figured it out! You can do an unsafe cast of the UInt8 array to a UInt16 array, then use that instead, and javascript seems to figure out what you mean:
```
//instead of val pix = imgd.data
val pix = imgd.data.unsafeCast()
// now you can assign values outside the -127..127 range
```
Upvotes: 2 <issue_comment>username_2: There is an issue in the Kotlin tracker — <https://youtrack.jetbrains.com/issue/KT-24583>
>
> org.khronos.webgl.Uint8ClampedArray getter and setter declarations use Byte. Which means assigning values over 127 to it is not trivial.
> Also the values obtained from it violate the Byte contract
>
>
> Besides one could argue that it is not a "real" array. Assigning values outside of 0..255 range is completely normal for it.
>
>
> This case is important, because it is used for the canvas manipulation: <https://developer.mozilla.org/en-US/docs/Web/API/ImageData/data>
>
>
>
Upvotes: 2
|
2018/03/17
| 553 | 2,101 |
<issue_start>username_0: I have a service.ts file passing a Observables in between my Angular Components and I have the result of a click event on one Component being passed to the component below.
My problem is that I can `console.log` the object that I *want* to store in my `selectedContact` variable (see below), but when I attempt to assign the `subscribe()` response to my `selectedContact` variable and then bind it to my HTML, it just shows as `[object Object].
Here's my code:
```
import { Component, OnInit } from '@angular/core';
import { AppComponent } from '../app.component';
import { ApiService } from '../api.service';
@Component({
selector: 'app-contact-details',
templateUrl: './contact-details.component.html',
styleUrls: ['./contact-details.component.scss']
})
export class ContactDetailsComponent implements OnInit {
selectedContact: any[] = [];
error: string;
constructor(private _apiService: ApiService) { }
ngOnInit() { this.showContact() }
showContact() {
this._apiService.newContactSubject.subscribe(
data => this.selectedContact = data)
}
}
```
When I run this:
```
showContact() {
this._apiService.newContactSubject.subscribe(
data => console.log(data))
}
```
I get the *correct* Object logging to the console (the click event from the other component).
But when I run this:
```
showContact() {
this._apiService.newContactSubject.subscribe(
data => this.selectedContact = data)
}
```
I get `[Object Object]`
What am I missing? Thanks!!!<issue_comment>username_1: I think in html, you bind `this.selectedContact` to some html component. But since `this.selectedContact` is an object, you have to bind to its property like so: `{{selectedContact.proppertyName }}`
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you did this:
```
showContact() {
this._apiService.newContactSubject.subscribe(
data => this.selectedContact = JSON.stringify(data))
}
```
...you'd see your object, but it's not going to be formatted that well. You'll have to do more work to get well-formatted output.
Upvotes: 0
|
2018/03/17
| 359 | 1,293 |
<issue_start>username_0: I am attempting to make a Batch program that copies all files from a flashdrive onto my desktop, then change all Batch files to Text files. I know of the long way to do this...
```
ren "%userprofile%\Desktop\Batch\*.bat" "*.txt"
ren "%userprofile%\Desktop\Batch\Format-Transfer\*.bat" "*.txt"
ren "%userprofile%\Desktop\Batch\Fun Files\*.bat" "*.txt"
ren "%userprofile%\Desktop\Batch\Fun Files\Local ShutDown\*.bat" "*.txt"
...And so on
```
...however, I am asking if there is a way to recursively use a similar command to the one above on every subdirectory.
[I currently have the file movement part solved with the following line.]
```
xcopy /s %dr%:\*.* "%userprofile%\Desktop\Batch"
```<issue_comment>username_1: I think in html, you bind `this.selectedContact` to some html component. But since `this.selectedContact` is an object, you have to bind to its property like so: `{{selectedContact.proppertyName }}`
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you did this:
```
showContact() {
this._apiService.newContactSubject.subscribe(
data => this.selectedContact = JSON.stringify(data))
}
```
...you'd see your object, but it's not going to be formatted that well. You'll have to do more work to get well-formatted output.
Upvotes: 0
|
2018/03/17
| 858 | 3,277 |
<issue_start>username_0: My project is: when people click a or `-` among a list of section, test, and practice etc. Each click will render a presentational component. My question is whether there is a solution to simplify my code as below.
```
createSection = () => {
this.setState({
sectionVisilibity: !this.state.sectionVisilibity
})
```
}
```
createPractice = () => {
this.setState({
practiceVisilibity: !this.state.practiceVisilibity
})
}
```
my initialstate is like this
```
sectionVisilibity:false,
practiceVisilibity:false,
```
And, the structure of state is
```
this.state={
.....,
sections:[
sec1:{name:'',description:''},
sec2:{...}
]
}
```
My button group is like this
```
const BtnGroup = ({ createSection, createPractice }) => (
* Section
* Practice
* Subsection
* Download
* Test
)
```
Are there a way I can write like
```
createComponent=()=> {
//conditionally decide the click action by click event
//The thing I confused about is I did not pass any event here, but the click is work. It can change the flag between true and false.
}
```
Therefore, could anyone know how to grab value like multiple input I can use attribute to setState. How about onClick?
Thanks in advance!!<issue_comment>username_1: You could in theory do some conditional logic on the event, but I don't think you want to do that.
Try something like:
```
- createComponent('practice')}>Practice
```
Upvotes: 1 <issue_comment>username_2: There is two another way to do that.
First is make an object of array of your state and then in same order set your li tags in which buttons are present. And on click send index also so that on the basis of index you can change state.
Second is same take your state in object array and on click send name also like the above answer. And in your function you can use seitch case or if else condition which button has beej clicked by the name.
```
this.state = {
data: [
{createSection:false},
{createBlock:false}
]
}
onClick(e,index,propertyName){
let data = this.state.data;
data[index].propertyName = true;
this.setState({data:data});
}
- this.onClick(e,index,'createSection')}> Create Section
- this.onClick(e,index,'CreateBlock')}> Create Section
```
Keep that in mind that button order must be same as states.
Upvotes: 0 <issue_comment>username_3: I have a simple solution for this kind of problem.
the basic problem here is how to pass parameters to a onClick function.
what i do in this kind of scenario is to use data attributes.
```
handleClick(ev){
const type = ev.target.dataset.clickType;
// switch on type and you got the solution
}
const BtnGroup = ({ handleClick }) => (
* Section
* Practice
* Subsection
* Download
* Test
)
```
if there is any click action that you want to map to the same handler . you just have to add the same `data-click-type ="attribute"`
in some cases you need to pass the entire object as an argument. that can
also be achieved by using JSON.stringify`(ob)
also you are not creating any dynamic functions inside `onClick` which makes it more efficient.
Upvotes: 2 [selected_answer]
|
2018/03/17
| 277 | 652 |
<issue_start>username_0: Consider below table :
```
IP Address
192.168.1.9
192.168.1.4
192.168.1.4
192.168.1.3
192.168.1.9
```
I want to write a sql query such that I get following data :
```
IP Address Count
192.168.1.3 1
192.168.1.4 2
192.168.1.4 2
192.168.1.9 3
192.168.1.9 3
```<issue_comment>username_1: Use `dense_rank()`:
```
select ip_address, dense_rank() over (order by ip_address) as cnt
from t;
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
SELECT ip_address,
ROW_NUMBER() OVER(PARTITION BY ip_address) AS count
FROM table1;
```
is what id do
Upvotes: 0
|
2018/03/17
| 1,635 | 5,710 |
<issue_start>username_0: I would like to include the versions.html in the sidebar and could not succeed.
I tried to add versions.html in \*\* for sidebars, this had no effect:
```
html_sidebars = {
'**': ['versions.html']
}
```
Also how to declare the different versions in `conf.py`.
I have looked at [sphinxcontrib-versioning](https://github.com/Robpol86/sphinxcontrib-versioning) but it is not exactly what I am looking for.<issue_comment>username_1: This can be achieved by adding a `_templates/versions.html` file to override the rtd theme's default [jinja template file](https://www.sphinx-doc.org/en/master/templating.html) and adding some variables to the `conf.py` file.
Execute the following to create a new '\_templates/' directory and 'versions.html' file:
```
mkdir _templates
cat > _templates/versions.html <<'EOF'
{% if READTHEDOCS or display_lower_left %}
{# Add rst-badge after rst-versions for small badge style. #}
Read the Docs
v: {{ current\_version }}
{% if languages|length >= 1 %}
{{ \_('Languages') }}
{% for slug, url in languages %}
{% if slug == current\_language %} **{% endif %}
[{{ slug }}]({{ url }})
{% if slug == current\_language %}** {% endif %}
{% endfor %}
{% endif %}
{% if versions|length >= 1 %}
{{ \_('Versions') }}
{% for slug, url in versions %}
{% if slug == current\_version %} **{% endif %}
[{{ slug }}]({{ url }})
{% if slug == current\_version %}** {% endif %}
{% endfor %}
{% endif %}
{% if downloads|length >= 1 %}
{{ \_('Downloads') }}
{% for type, url in downloads %}
[{{ type }}]({{ url }})
{% endfor %}
{% endif %}
{% if READTHEDOCS %}
{{ \_('On Read the Docs') }}
[{{ \_('Project Home') }}](//{{ PRODUCTION_DOMAIN }}/projects/{{ slug }}/?fromdocs={{ slug }})
[{{ \_('Builds') }}](//{{ PRODUCTION_DOMAIN }}/builds/{{ slug }}/?fromdocs={{ slug }})
{% endif %}
---
{% trans %}Free document hosting provided by [Read the Docs](http://www.readthedocs.org).{% endtrans %}
{% endif %}
EOF
```
And execute the following to append to the `conf.py` file:
```
cat >> conf.py <<'EOF'
############################
# SETUP THE RTD LOWER-LEFT #
############################
try:
html_context
except NameError:
html_context = dict()
html_context['display_lower_left'] = True
templates_path = ['_templates']
if 'REPO_NAME' in os.environ:
REPO_NAME = os.environ['REPO_NAME']
else:
REPO_NAME = ''
# SET CURRENT_LANGUAGE
if 'current_language' in os.environ:
# get the current_language env var set by buildDocs.sh
current_language = os.environ['current_language']
else:
# the user is probably doing `make html`
# set this build's current language to english
current_language = 'en'
# tell the theme which language to we're currently building
html_context['current_language'] = current_language
# SET CURRENT_VERSION
from git import Repo
repo = Repo( search_parent_directories=True )
if 'current_version' in os.environ:
# get the current_version env var set by buildDocs.sh
current_version = os.environ['current_version']
else:
# the user is probably doing `make html`
# set this build's current version by looking at the branch
current_version = repo.active_branch.name
# tell the theme which version we're currently on ('current_version' affects
# the lower-left rtd menu and 'version' affects the logo-area version)
html_context['current_version'] = current_version
html_context['version'] = current_version
# POPULATE LINKS TO OTHER LANGUAGES
html_context['languages'] = [ ('en', '/' +REPO_NAME+ '/en/' +current_version+ '/') ]
languages = [lang.name for lang in os.scandir('locales') if lang.is_dir()]
for lang in languages:
html_context['languages'].append( (lang, '/' +REPO_NAME+ '/' +lang+ '/' +current_version+ '/') )
# POPULATE LINKS TO OTHER VERSIONS
html_context['versions'] = list()
versions = [branch.name for branch in repo.branches]
for version in versions:
html_context['versions'].append( (version, '/' +REPO_NAME+ '/' +current_language+ '/' +version+ '/') )
# POPULATE LINKS TO OTHER FORMATS/DOWNLOADS
# settings for creating PDF with rinoh
rinoh_documents = [(
master_doc,
'target',
project+ ' Documentation',
'© ' +copyright,
)]
today_fmt = "%B %d, %Y"
# settings for EPUB
epub_basename = 'target'
html_context['downloads'] = list()
html_context['downloads'].append( ('pdf', '/' +REPO_NAME+ '/' +current_language+ '/' +current_version+ '/' +project+ '-docs_' +current_language+ '_' +current_version+ '.pdf') )
html_context['downloads'].append( ('epub', '/' +REPO_NAME+ '/' +current_language+ '/' +current_version+ '/' +project+ '-docs_' +current_language+ '_' +current_version+ '.epub') )
EOF
```
See this site for an example:
* <https://maltfield.github.io/rtd-github-pages/>
The whole config to create the above site can be viewed (and easily forked) from the following GitHub repo:
* <https://github.com/maltfield/rtd-github-pages/>
For more information on how I set this up, see this [article on how to setup the lower-left Read the Docs menu for navigation between languages and versions and downloads](https://tech.michaelaltfield.net/2020/07/23/sphinx-rtd-github-pages-2/).
Upvotes: 4 [selected_answer]<issue_comment>username_2: If the solution above doesn't pan out for anyone I was able to use this extension to add versioning. [sphinx-multiversion](https://holzhaus.github.io/sphinx-multiversion/master/configuration.html#configuration). My documentation set up is sphinx with the read-the-docs-theme with private repo for docs on Azure Dev Ops. Same results with this as code snippet above. Refer to the Installation, Quickstart, Configuration and Templates pages for all the working parts.
Upvotes: 1
|
2018/03/17
| 1,298 | 3,978 |
<issue_start>username_0: I'm looking to sort a table according to two different columns.
This is what I have:
```
| EAN | album_id | photo |
|-----|----------|-----------|
| 111 | 123 | 64.jpg |
| 111 | 123 | 65.jpg |
| 222 | 123 | 64.jpg |
| 222 | 123 | 65.jpg |
```
This is the desired result:
```
| EAN | album_id | photo | primary |
|-----|----------|----------------|---------|
| 111 | 123 | 64.jpg, 65.jpg | 1 |
| 222 | 123 | 64.jpg, 65.jpg | 0 |
```
This is the raw code I'm working with (I change it for my specific need), so far it only handles the album\_id and photo sorting but not the EAN or primary columns:
```
Sub merge()
Dim LR As Long, Delim As String
'Allow user to set the Delimiter
Delim = Application.InputBox("Merge column B values with what delimiter?", "Delimiter", "|", Type:=2)
If Delim = "False" Then Exit Sub
If Delim = "" Then
If MsgBox("You chose a blank delimiter, this will merge column B value into a single continuous string. Proceed?", _
vbYesNo, "Merge with no delimiter") = vbNo Then Exit Sub
End If
'Sort data
Application.ScreenUpdating = False
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("A1").CurrentRegion.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
'Concatenate column B values so last matching row in each group has all values
With Range("E2:E" & LR)
.FormulaR1C1 = "=IF(RC1=R[-1]C1, R[-1]C & " & """" & Delim & """" & " & RC2, RC2)"
.Value = .Value
.Copy Range("B2")
.FormulaR1C1 = "=IF(RC1=R[1]C1, """", 1)"
Range("E:E").AutoFilter 1, "<>1"
.EntireRow.Delete xlShiftUp
.EntireColumn.Clear
End With
ActiveSheet.AutoFilterMode = False
Columns.AutoFit
Application.ScreenUpdating = True
End Sub
```
How can I change the code (in part or completely) to achieve the end result I'm looking for?
Thank you very much for any help in solving this issue.<issue_comment>username_1: You are going to be deleting rows so sort first then work from the bottom up.
```
dim i as long, delim as string
delim = ", "
with worksheets("sheet1")
with .cells(1, 1).currentregion
.cells.sort Key1:=.Columns(1), Order1:=xlAscending, _
Key2:=.Columns(2), Order2:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlyes
for i = .rows.count -1 to 2 step -1
if .cells(i, "A").value = .cells(i+1, "A").value and _
.cells(i, "B").value = .cells(i+1, "B").value then
.cells(i, "C").value = .cells(i, "C").value & delim & .cells(i+1, "C").value
.cells(i+1, "A").entirerow.delete
.cells(i, "D").value = abs(iserror(application.match(.cells(i, "B").value, .range(.cells(1, "B"),.cells(i-1, "B")), 0)))
end if
next i
end with
end with
```
[](https://i.stack.imgur.com/UWFiy.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: you could use `Dictionary` object and `TextToColumns` method of `Range` object
```
Option Explicit
Sub main()
Dim cell As Range
Dim key As Variant
With CreateObject("Scripting.Dictionary")
For Each cell In Range("A2", Cells(Rows.Count, 1).End(xlUp))
.Item(cell.Value & "|" & cell.Offset(, 1).Value) = .Item(cell.Value & "|" & cell.Offset(, 1).Value) & cell.Offset(, 2).Value & " "
Next
Range("A1").CurrentRegion.Offset(1).Resize(Range("A1").CurrentRegion.Rows.Count - 1).Clear
For Each key In .Keys
Cells(Rows.Count, 1).End(xlUp).Offset(1).Value = key
Cells(Rows.Count, 3).End(xlUp).Offset(1).Value = Join(Split(Trim(.Item(key)), " "), ",")
Next
Range("A2", Cells(Rows.Count, 1).End(xlUp)).TextToColumns Range("A2"), xlDelimited, , , , , , , True, "|"
End With
End Sub
```
Upvotes: 1
|
2018/03/17
| 1,484 | 3,872 |
<issue_start>username_0: Let's say currently i have a list with:
```
L = [[1,'JAYCE'],[2,'AMIE'],[3,'JACK'],[4,'STEVE'],[5,'JAYCE']]
```
and i have another list which contains the names sorted in order:
```
sortedNames = ['AMIE','JACK','JAYCE','JAYCE','STEVE']
```
The output I want to get is, based on the sorted names list, i want to add the ID back to the names in the sorted order which is based off the sortedNames list.
```
finalist = [[2,'AMIE'],[3,'JACK'],[1,'JAYCE'],[5,'JAYCE'],[4,'STEVE']]
```
Note that Jayce appeared twice so even if the first occurrence of Jayce has 5, followed by 1, its totally fine too.
I've been thinking of something like:
```
L = [[1,'JAYCE'],[2,'AMIE'],[3,'JACK'],[4,'STEVE'],[5,'JAYCE']]
sortedNames = ['AMIE','JACK','JAYCE','JAYCE','STEVE']
finalist = []
for i in sortedNames:
j = 0
if i in L[j][1]:
finalist.append(L[0] + i)
j+=1
print(finalist)
```
I'm getting an error saying:
```
TypeError: can only concatenate list (not "str") to list
```
I'm definitely appending it wrong.<issue_comment>username_1: You can create a dictionary by grouping each name to a listing of all the IDs found for the name. Then, `next` can be applied.
```
import itertools
L = [[1,'JAYCE'],[2,'AMIE'],[3,'JACK'],[4,'STEVE'],[5,'JAYCE']]
new_l = {a:iter([c for c, _ in b]) for a, b in itertools.groupby(sorted(L, key=lambda x:x[-1]), key=lambda x:x[-1])}
sortedNames = ['AMIE','JACK','JAYCE','JAYCE','STEVE']
final_data = [[next(new_l[i]), i] for i in sortedNames]
```
Output:
```
[[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
```
**Edit:**
It is also possible to utilize `sorted`:
```
L = [[1,'JAYCE'],[2,'AMIE'],[3,'JACK'],[4,'STEVE'],[5,'JAYCE']]
sortedNames = ['AMIE','JACK','JAYCE','JAYCE','STEVE']
new_result = sorted(L, key=lambda x:(sortedNames.index(x[-1]), x[0]))
```
Output:
```
[[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
```
Upvotes: 0 <issue_comment>username_2: So, as long as your data is well behaved, you could group your numbers into deques using a defaultdict:
```
In [14]: from collections import defaultdict, deque
In [15]: grouper = defaultdict(deque)
In [16]: for a,b in L:
...: grouper[b].append(a)
...:
```
Then simply:
```
In [17]: grouper
Out[17]:
defaultdict(collections.deque,
{'AMIE': deque([2]),
'JACK': deque([3]),
'JAYCE': deque([1, 5]),
'STEVE': deque([4])})
In [18]: [[grouper[x].popleft(), x] for x in sortedNames]
Out[18]: [[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
```
I realize it is an ugly wart to use `pop` inside a list comprehension...
Here's an approach using only `dict` and `list`:
```
In [19]: grouper = {}
...: for a,b in L:
...: grouper.setdefault(b, []).append(a)
...:
In [20]: grouper = {k:v[::-1] for k, v in grouper.items()}
In [21]: [[grouper[x].pop(), x] for x in sortedNames]
Out[21]: [[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
```
Both approaches are O(N).
### Edit
I just realized that what you *really* want is instead of generating a list of sorted names, just sort `L` using a key directly:
```
In [26]: L
Out[26]: [[1, 'JAYCE'], [2, 'AMIE'], [3, 'JACK'], [4, 'STEVE'], [5, 'JAYCE']]
In [27]: from operator import itemgetter
In [28]: sorted(L, key=itemgetter(1))
Out[28]: [[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
```
Upvotes: 1 <issue_comment>username_3: You can use the [sorted()](https://docs.python.org/3/library/functions.html#sorted) function to do this, and lookup the position of the stored name using its `key` argument:
```
finalList = sorted(L, key=lambda x: sortedNames.index(x[1]))
```
Which results in:
```
[[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
```
Upvotes: 1
|
2018/03/17
| 683 | 2,639 |
<issue_start>username_0: I'm trying to deploy a simple Spring Boot application. `application.properties` contains the following:
```
spring.datasource.name=MyDS
spring.datasource.username=user
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.xa.data-source-class-name=com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
spring.datasource.password=<PASSWORD>
spring.jpa.database=mysql
spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect
spring.datasource.url=jdbc\:mysql\://host\:3306/mydb
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
entitymanager.packagesToScan: /
```
Upon deploying I get the following:
```
java.lang.IllegalStateException: Unable to create XADataSource instance from 'com.mysql.jdbc.jdbc2.optional.MysqlXADataSource'
at org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration.createXaDataSourceInstance(XADataSourceAutoConfiguration.java:107)
at org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration.createXaDataSource(XADataSourceAutoConfiguration.java:94)
at org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration.dataSource(XADataSourceAutoConfiguration.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 47 more
```
I've only encountered this kind of exception when the XA DataSource was set to `org.mysql.jdbc.MySQLDataSource`. In that case setting it to `com.mysql.jdbc.jdbc2.optional.MysqlXADataSource` is supposed to do the trick. Any suggestions are welcome.
UPDATE: after bringing in the older versions of Atomikos in `pom.xml` I can choose between `atomikos-util 3.8.0` in which case the `spring-boot:run` fails with `java.lang.ClassNotFoundException: com.atomikos.util.Assert`. If however I change the version to `atomikos-util 4.0.0` or higher I get `com.atomikos.diagnostics.Console`.<issue_comment>username_1: ```
spring.datasource.xa.properties.driver-class-name=com.mysql.jdbc.Driver
```
You also need to tell which driver xa datasource will use
Upvotes: 2 <issue_comment>username_2: ```
@Bean
public DataSource dataSource() {
DataSource dataSource = new DataSource();
....
return dataSource;
}
```
This might do the trick
Upvotes: 1
|
2018/03/17
| 628 | 1,994 |
<issue_start>username_0: Everytime i try to run a npm command i get a wierd error. This happened after i ran ***npm config set prefix /usr/local*** whilst trying to install react and after that i wasnt able to run a single npm command without this error. If anyone has any idea of what this means or how to fix it please help ! thanks !
```
TypeError: Cannot read property 'get' of undefined
at errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:211:17)
at C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js:83:20
at cb (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:215:22)
at C:\Program Files\nodejs\node_modules\npm\lib\npm.js:253:24
at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:81:7
at Array.forEach (native)
at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:80:13
at f (C:\Program Files\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
at afterExtras (C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:178:20)
at C:\Program Files\nodejs\node_modules\npm\node_modules\mkdirp\index.js:47:53
C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:211
if (npm.config.get('json')) {
^
TypeError: Cannot read property 'get' of undefined
```<issue_comment>username_1: if you are getting an EPERM you may need to open up a command prompt and specify 'run as administrator', ' I'm admin on my PC and still need to do this from time to time with NPM scripts
Upvotes: 3 [selected_answer]<issue_comment>username_2: 1. Run `cmd` as administrator
2. `npm config set prefix/usr/local`
(changed the prefix)
3. `npm start` in normal console
Upvotes: 2 <issue_comment>username_3: Try installing it globally first, using the command
```
npm install -g create-react-app
```
And then, you can create your app using the command,
```
npx create-react-app
```
Credits : <https://github.com/facebook/create-react-app/issues/9091>
Upvotes: 1
|
2018/03/17
| 784 | 2,578 |
<issue_start>username_0: I've know versions of this question has been discussed, and I think this is unique. Why does a delay of 0, still causes the below behavior.
```
for(var i = 0; i <3; i ++) {
console.log(i, 'started');
setTimeout(()=> {
console.log(i);
},0)
console.log(i, 'done');
}
console.log('loop over');
// 0 started
// 0 done
// 1 started
// 1 done
// 2 started
// 2 done
// loop over
// 3 3 3
```
Here is what I *think* I know so far:
Quoted from MDN in respect to setTimeouts position on the stack:
>
> This is because even though setTimeout was called with a delay of
> zero, it's placed on a queue and scheduled to run at the next
> opportunity; not immediately. Currently-executing code must complete
> before functions on the queue are executed, thus the resulting
> execution order may not be as expected.
>
>
>
Am I correct in saying the for-loop and any synchronous code is placed on the call stack *before* setTimeout, AND even if you set the delay to 0, setTimeout will always run only after the for-loop has completed? Otherwise, why would a delay of 0, still result in the above behavior?
Thanks!
EDIT:
After getting started in the right direction, I found a few videos and a nice little tool that shows you the event loop and how it relates to this example code. Here is the JS runtime simulator: [loupe](http://latentflip.com/loupe/?code=<KEY>ZyhpLCdlbmQnKTsKICB9!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D)<issue_comment>username_1: JavaScript, both in the browser and on the server, runs as an event loop. The runtime is constantly polling for events. Events consist of user actions (e.g. DOM element x was clicked), I/O (data came back from I/O or ajax call), and timer events (in this case). `setTimeout(fn, 0)` simply adds an event to be processed by the event loop at minimum when 0 milliseconds have elapsed. It will always execute after the current event has been processed.
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> Am I correct in saying the for-loop and any synchronous code is placed
> on the call stack before setTimeout
>
>
>
To be pedantic, setTimeout() itself gets called synchronously, and placed on the callstack right after `console.log(i, 'started');` . It's the settimeout *callback* (in your case `console.log(i)`) that gets queued and called asynchronously.
Upvotes: 0
|
2018/03/17
| 644 | 2,244 |
<issue_start>username_0: I am getting
```
Uncaught RangeError: Maximum call stack size exceeded
at eval (index.js?4bd6:38)
at Object.dispatch (applyMiddleware.js?6ce6:35)
at dispatchChildActions (index.js?4bd6:33)
at eval (index.js?4bd6:39)
at Object.dispatch (applyMiddleware.js?6ce6:35)
at dispatchChildActions (index.js?4bd6:33)
at eval (index.js?4bd6:39)
at Object.dispatch (applyMiddleware.js?6ce6:35)
at dispatchChildActions (index.js?4bd6:33)
```
When I try to add `redux-batched-actions` middleware into my `applyMiddleware()`
```
const store = createStore(
enableBatching(appReducer), // added enableBatching
composeWithDevTools(
applyMiddleware(
batchDispatchMiddleware, // and this
sagaMiddleware,
historyMiddleware,
)
)
)
```
Whats wrong?<issue_comment>username_1: Not sure.
Here is the code that works for me, maybe it will help:
```
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
}) : compose;
const enhancers = composeEnhancers(
applyMiddleware(ReduxThunk),
autoRehydrate()
);
const initialState = {};
const store = createStore(
reducers,
initialState,
compose(enhancers)
);
persistStore(store);
ReactDOM.render(
, document.querySelector('#app'));
```
Upvotes: 0 <issue_comment>username_2: I took the time to go through the source code for you. It was a package bug. I have submitted a [pull request](https://github.com/tshelburne/redux-batched-actions/pull/22).
A previous merge was causing an infinite recursion, where non-batched actions were repeatedly being dispatched. I also think you should only use the middleware or the higher order reducer depending on your use case, see the ReadMe for a small explanation.
Please try out the fix and let me know as I do not have a project currently set up.
Hope this solves your issue!
Upvotes: 2 <issue_comment>username_3: I had the same errror when forgit to wrap my actions in curly braces:
```
return bindActionCreators(...TaskActions, ...UserActions, dispatch)
```
instead of
```
return bindActionCreators({...TaskActions, ...UserActions}, dispatch)
```
Upvotes: 0
|
2018/03/17
| 566 | 2,157 |
<issue_start>username_0: Am retrieving a distance using distance calculator script using Google Maps etc...
Then calculating a fare cost based on that distance, but the output from that script displays dynamically from Google as x,y miles in the distance field
using `document.getElementById("distance_road").value = distance1;`
and `distance1 = response.routes[0].legs[0].distance.text;`
In the 'cost' field data accepted and entered in this format (00.00) so here the the output is resulting in a `$NAN` when trying to run the calculation.
Here is the cost script:
```
function calculatefare() { /* variable declarations*/
var subTotal=0.00;
var pricePerFifthMile=0.54;
var dropOffCharge=2.60;
var overTwoPassengerCharge=0.50;
var tripMilage=Number(document.getElementById("distance_road").value);
var passengers=Number(document.getElementById("passengers").value);
/* if there are over 2 riders, each additional passenger pays $2 if (passengers>2)*/ { subTotal=overTwoPassengerCharge*(passengers-3+1); }
/* calculate the price based on miles in*/
subTotal+=parseInt(tripMilage*5)*pricePerFifthMile; subTotal+=dropOffCharge; /* prints the price to the div. toFixed adds cents to integer calculations */
document.getElementById('price').innerHTML=" $"+subTotal.toFixed(2);
}
// JavaScript Document
```
Is there any way to make this script accepts that format(read it) (xx,x miles)
or let say to clean this output to be xx.x which means removing the ',' and 'miles'.
I tried :
`sanitizedDistance = parseFloat(distance1.replace(",","."));`<issue_comment>username_1: Simply chain the miles and comma replacements like this
```
sanitizedDistance = parseFloat(distance1.replace("miles","").replace(",","."))
```
Upvotes: 2 <issue_comment>username_2: The fix is to redefine the variable distance1, before getting outputed and called in the form. so the output will be parsed to define the desired output formatting. And that was possible only through defining the same function distance1 and not adding another function.
```
var distance1 = parseFloat(distance1.replace(",","."));
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 264 | 1,030 |
<issue_start>username_0: I want to know how to setup my **info@\*\*\*\*\*.com** account and send email from this in my c# web API application.
I configured some code like this:
```
SmtpClient client = new SmtpClient();
client.Host = "173.***.**.**";
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.EnableSsl = true;
```
Am I doing anything wrong?<issue_comment>username_1: Simply chain the miles and comma replacements like this
```
sanitizedDistance = parseFloat(distance1.replace("miles","").replace(",","."))
```
Upvotes: 2 <issue_comment>username_2: The fix is to redefine the variable distance1, before getting outputed and called in the form. so the output will be parsed to define the desired output formatting. And that was possible only through defining the same function distance1 and not adding another function.
```
var distance1 = parseFloat(distance1.replace(",","."));
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 239 | 1,009 |
<issue_start>username_0: I'm new and currently learning ASP.NET, I'm building the main page of my website, but based on the image attached, I don't understand why the "Order Now" button is not align in the center even though I have already set it text-align to center in css. Also the "bounceInUp" animation imported from Animate.css is not working for the button as well, but it works perfectly for the description under the WELCOME.<issue_comment>username_1: Simply chain the miles and comma replacements like this
```
sanitizedDistance = parseFloat(distance1.replace("miles","").replace(",","."))
```
Upvotes: 2 <issue_comment>username_2: The fix is to redefine the variable distance1, before getting outputed and called in the form. so the output will be parsed to define the desired output formatting. And that was possible only through defining the same function distance1 and not adding another function.
```
var distance1 = parseFloat(distance1.replace(",","."));
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 487 | 1,880 |
<issue_start>username_0: I've developed an Excel add-in using the Excel-DNA library. I'd like to create a guided product tour for when the user first installs the plugin. I'm looking for the traditional product tour workflow where the window is dimmed, and the plugin features are highlighted with textual description and arrows to navigate the tour.
I've found a plugin called AbleBits that has a product tour that i'm looking to build. However, I can't find what library they used to build it, or where I should start.
<issue_comment>username_1: Build a multipage form with a next button bottom right. Offer a "Do not see this again" checkbox on the initial page of the form. Simply walk them thru your add in page 1 click next to page two (which has a 'back' button bottom left) onto page 3 and so on. Final page has a finish button. That's it really.
You can store VBA values (state, such as the do not show again boolean) in the registry.
Upvotes: 1 <issue_comment>username_2: I work for Ablebits.com, so I am sharing first-hand experience:
We did not use any components (libraries) to build the tour. It was done by drawing on a layered window (<https://msdn.microsoft.com/en-us/library/ms997507.aspx>) that is placed on top of the Excel window.
The background of this window is made translucent so that the Excel window can be seen, while the pictures and captions are non-transparent.
To highlight the necessary elements on the ribbon, we find their coordinates using UIAutomation and draw a fully transparent rectangle in that place. The interaction with a user is implemented by making the images of the buttons in different states and processing the mouse and keyboard events.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 398 | 1,471 |
<issue_start>username_0: I am getting a very small issue in setting up my screen views equally on all iPhone screen sizes. Attached is the screenshot of the same. I want to keep the spacing (X) equal b/w view's top-view1-view2-bottom on all iPhone devices. What will be the best approach to do so ??
I tried to use view1 & view2 in stackView and distributed them equal vertically. But that way the logo image is also taking full width as of view's frame. I know I am missing very little thing in my code. But I am not able to get it rightly.
Any help would be appreciated. Thanks in advance.
[](https://i.stack.imgur.com/9OjZv.jpg)<issue_comment>username_1: 1. Use Stack Views to place all the elements vertically. May be you will have to use multiple stack views. i.e.
>
> `StackView1` would be the textFields and button
>
>
> `StackView2` would be logo and `stackView1` with minimum spacing, which is the consistent spacing you want.
>
>
>
2. Then make your `stackView2` centre vertically and horizontally within the container/superview.
3. Lastly, make `stackView2` top, bottom, leading, trailing anchors greater than equal to zero, so that it never goes out of the screen bounds.
Upvotes: 1 <issue_comment>username_2: Put a two UIView. First is above view1 and second in between view1 and view2. make background color clear for both views. Put equal height constraint for view1 and view2.
Upvotes: 0
|
2018/03/17
| 472 | 1,560 |
<issue_start>username_0: my input file looks like this :
S New York 25 76 49
i want to read them where S is a character and New York is either a string or a cstring and the other 3 are integers. My problem is reading in New York i cant use getline since the 3 integers come after it and not in a new line. What can i do?<issue_comment>username_1: I would suggest using Regular Expressions to parse the input. Added to the standard library in C++ 11 [C++ reference](http://www.cplusplus.com/reference/regex/)
More details on wikipedia: [Regular Expressions in C++](https://en.wikipedia.org/wiki/C%2B%2B11#Regular_expressions)
Upvotes: 1 <issue_comment>username_2: Your other option is simply to read a character at a time and as long as the character `isalpha()` or `isspace()` followed by another `isalpha()`, store the character in your string. For example:
```
#include
#include
#include
using namespace std;
int main (void) {
char c, last = 0;
string s;
while (cin.get(c)) { /\* read a character at a time \*/
/\* if last is alpha or (last is space and current is alpha) \*/
if (last && (isalpha(last) || (isspace(last) && isalpha(c))))
s.push\_back(last); /\* add char to string \*/
last = c; /\* set last to current \*/
}
cout << "'" << s << "'\n";
}
```
**Example Use/Output**
```
$ echo "S New York 25 76 49" | ./bin/cinget
'S New York'
```
It may not be as elegant as a regex, but you can always parse what you need simply by walking through each character of input and picking out what you need.
Upvotes: 1 [selected_answer]
|
2018/03/17
| 1,716 | 5,282 |
<issue_start>username_0: I have a code where it would give a dot for every 3 digit numbers lke snippet below
```js
function convertToRupiah(angka)
{
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.';
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str)
{
// var tindak_lanjut =
$('#nilai_tindak_lanjut').val().replace(".", "").replace(".", "");
var temuan = str.replace(".", "").replace(".", "");
// var total = temuan-tindak_lanjut;
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan').on('keyup focusin focusout ', (function(event)
{
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
});
})
);
```
```html
```
But the input text with id `nilai_potensi_kerugian` always error when the number digit were reached Billion (ex. 10.000.000.000). What could go wrong with my code ?<issue_comment>username_1: Your `convertToRupiah` seems fine, BUT your `showkerugian()` is feeding wrong `angka` into `convertToRupiah`.
Let's review **your code**:
```js
function convertToRupiah(angka)
{
console.log(angka) // I added this to log what is fed into the function
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.';
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str)
{
// var tindak_lanjut = $('#nilai_tindak_lanjut').val().replace(".", "").replace(".", "");
var temuan = str.replace(".", "").replace(".", "");
// var total = temuan-tindak_lanjut;
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan').on('keyup focusin focusout ', (function(event)
{
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
;
});
})
);
```
```html
```
See the problem? Your code only removes the first 2 occurrence of `.`.
To fix the problem, I changed the line
```
var temuan = str.replace(".", "").replace(".", "");
```
into
```
var temuan = str.replace(/\./g, "");
```
which will remove ALL occurrence of `.` due to `RegExp`'s `g` flag
```js
function convertToRupiah(angka) {
var rupiah = '';
console.log(angka)
var angkarev = angka.toString().split('').reverse().join('');
for (var i = 0; i < angkarev.length; i++) {
if (i%3 == 0) {
rupiah += angkarev.substr(i,3)+'.';
}
}
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str) {
var temuan = str.replace(/\./g, "");
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
}
$('input#nilai_temuan').on('keyup focusin focusout ', (function(event) {
if (event.which >= 37 && event.which <= 40) return;
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
});
})
);
```
```html
```
Upvotes: 1 <issue_comment>username_2: The problem is inside your `showkerugian` function:
>
> `var temuan = str.replace(".", "").replace(".", "");`
>
>
>
Previous statement only replace up to two `.` in your `str` variable.
Therefore, numbers which requires more than two dots are not reset correctly. Read more about [string.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace).
Check the problem and a possible solution using a `RegExp` as a pattern in the `replace` function:
```js
console.log('10.000.000.000'.replace('.', '').replace('.', ''));
// -> 10000000.000
console.log('10.000.000.000'.replace(/\./g, ''));
// -> 10000000000
```
The following includes the fix in your snippet:
```js
function convertToRupiah(angka){
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.';
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str) {
var temuan = str.replace(/\./g, ""); // update pattern to regex in order to replace all `.` occurrences
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan') .on('keyup focusin focusout ', function(event) {
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
});
});
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 2,183 | 7,086 |
<issue_start>username_0: So I have a multilayered problem. I am trying to I am trying to just print out 'input was jack' if the raw\_input was 'jack' and also subtract 'tries' by 1, and then run the function again and print out amount of 'tries' at the end of both the first 'if' statement and the 'else' statement, and if the raw\_input wasn't 'jack' it adds 1 to 'tries' and if 'tries' reaches a total of 4 the function prints stop. I have run into a couple of different problems. Either the counter seems to reset every single time so it's always just '1' or I can't just keep running the function. It just doesn't seem like it's following the 'if or else' theory I thought it would be. So I have the following code:
```
tries = 0
def usrinfo():
name = raw_input('input name ')
a = ('jill','jack',name,'meg')
for element in a:
if element == 'jack':
print('input was jack')
tries =-1
print(tries)
usrinfo()
else:
if element != 'jack':
tries =+ 1
return tries
print(tries)
usrinfo()
if tries == 4:
print('stopped')
usrinfo()
```
If I type 'jack' I get:
```
Nothing...as in a blank output
```
I want:
```
input was jack
-1
```
Then I want the function to run again...and get
```
input was jack
-2
```
And so on.
If I type anything other than 'jack' I get:
```
Nothing...as in a blank output
```
I want to get:
```
1
```
Then for the function to run again....and get
```
2
```
Then if I type anything other than 'jack'. I want with each attempt to print the increasing level of tries from 1 - 4 such as below:
```
1
2
3
4
```
Then when it reaches 4 it prints 'stopped' or runs whatever command. I want to essentially keep the code running and control the value of 'tries' according to whether or not the input is 'jack' or something else. Because even when I create an even simpler code like this:
```
def userinput():
tries = 0
username = raw_input('input username ')
if username == 'jack':
tries -=1
print(username + ' '+ str(tries) + ' success')
userinput()
else:
if username != 'jack':
tries +=1
print('tries ' + str(tries))
userinput()
userinput()
```
My results on this code with input of 'f' are:
```
input username f
tries 1
input username f
tries 1
input username f
```
Instead I want to get:
```
input username f
tries 1
input username f
tries 2
input username f
tries 3
```
And with input of 'jack' I want:
```
input username jack
jack -1 success
input username jack
jack -2 success
input username jack
jack -3 success
input username jack
jack -4 success
```
And so on. Any help is much appreciated. I'm not sure what I'm doing wrong. It just seems like 'tries' is constantly resetting itself.
Hopefully this is clear...I've spent a lot of time trying to make code just to be able to demonstrate to someone with more knowledge where my misunderstanding might be...
Thanks guys and gals.<issue_comment>username_1: Your `convertToRupiah` seems fine, BUT your `showkerugian()` is feeding wrong `angka` into `convertToRupiah`.
Let's review **your code**:
```js
function convertToRupiah(angka)
{
console.log(angka) // I added this to log what is fed into the function
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.';
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str)
{
// var tindak_lanjut = $('#nilai_tindak_lanjut').val().replace(".", "").replace(".", "");
var temuan = str.replace(".", "").replace(".", "");
// var total = temuan-tindak_lanjut;
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan').on('keyup focusin focusout ', (function(event)
{
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
;
});
})
);
```
```html
```
See the problem? Your code only removes the first 2 occurrence of `.`.
To fix the problem, I changed the line
```
var temuan = str.replace(".", "").replace(".", "");
```
into
```
var temuan = str.replace(/\./g, "");
```
which will remove ALL occurrence of `.` due to `RegExp`'s `g` flag
```js
function convertToRupiah(angka) {
var rupiah = '';
console.log(angka)
var angkarev = angka.toString().split('').reverse().join('');
for (var i = 0; i < angkarev.length; i++) {
if (i%3 == 0) {
rupiah += angkarev.substr(i,3)+'.';
}
}
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str) {
var temuan = str.replace(/\./g, "");
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
}
$('input#nilai_temuan').on('keyup focusin focusout ', (function(event) {
if (event.which >= 37 && event.which <= 40) return;
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
});
})
);
```
```html
```
Upvotes: 1 <issue_comment>username_2: The problem is inside your `showkerugian` function:
>
> `var temuan = str.replace(".", "").replace(".", "");`
>
>
>
Previous statement only replace up to two `.` in your `str` variable.
Therefore, numbers which requires more than two dots are not reset correctly. Read more about [string.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace).
Check the problem and a possible solution using a `RegExp` as a pattern in the `replace` function:
```js
console.log('10.000.000.000'.replace('.', '').replace('.', ''));
// -> 10000000.000
console.log('10.000.000.000'.replace(/\./g, ''));
// -> 10000000000
```
The following includes the fix in your snippet:
```js
function convertToRupiah(angka){
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.';
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str) {
var temuan = str.replace(/\./g, ""); // update pattern to regex in order to replace all `.` occurrences
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan') .on('keyup focusin focusout ', function(event) {
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
});
});
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 495 | 1,583 |
<issue_start>username_0: Can you help me with this problem? I have an `input-group` within *bootstrap 4*. In my `input-group` I have 2 inputs, first with prepend and second with append.
It's wrapped in a `col-12` `div` in a `form-group` and I need to set the `width` of the first input and second to some specific (but different) value. I tried to set the `width` in my custom css, but without success. Is it possible? I know, that I can set it via wrapping it in a div with another col, but than I have both input below and not side by side.
Code:
```html
Telephone
+
```<issue_comment>username_1: I found a solution. I tried set max-width instead of only width and it works.
For the above example it would be:
```css
#preselection {
max-width: 15%;
}
```
```html
Telephone
+
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I've found a solution on the internet and you can visit it at [codeply](https://www.codeply.com/go/wv5NMmTgwq/bootstrap-4-input_group-prepend-equal-width)!.
It is pretty neat and simple. To do so, you just need to add the following `CSS` to your stylesheet.
```
.input-group>.input-group-prepend {
flex: 0 0 30%;
}
.input-group .input-group-text {
width: 100%;
}
```
To set the width of the `input-group-text`, just change the value of the `flex` of the `input-group`, for instance, as seen above `30%` of the total width.
Thank the author of the link above for this simple code snippet.
Upvotes: 4 <issue_comment>username_3: You can do it with class `w-50` and `w-100`
like this
```
label
```
Upvotes: 4
|
2018/03/17
| 723 | 2,938 |
<issue_start>username_0: I am a beginner in web development. I know that the `index.php` file provides the foundation of a website. With some template design, we can re-use the headers and footers for many of the pages of the site. For the content, suppose I have the following:
```
php include 'content.php';?
```
However, each page contains unique content. Therefore, this makes me think that for every page that I have, I need to create a separate PHP file. For instance, for page one I create a `content_one.php` file and for page two I create a `content_two.php` etc. Am I correct in my assumption? Thanks in advance.<issue_comment>username_1: Yes, that's pretty much the standard pattern for those coming to PHP from a predominantly HTML background. Typically they'll start with a multiple-page HTML site, each page with its own HTML file. As the site grows, they'll realize there is a lot of duplicated markup (header, footer, etc) and it becomes tedious to keep it all consistent. The solution is to rename their pages with a `.php` extension so the files are processed before they're served to the client, then the duplicate markup is removed and placed in an include file. The files are then all updated to pull in the content from the file using either `include` or `require`.
I wouldn't say that approach is wrong. This is exactly how I came to PHP oh so many years ago! But it isn't really the best in the long run. Realize that it's a stepping stone and as you learn more you'll realize what proper architecture/design looks like.
I don't know the true level of your programming experiences. When you're comfortable, you make want to look into some web frameworks, like [Slim](https://www.slimframework.com/) and [Laravel](https://laravel.com/). In these frameworks, the `index.php` file serves as a central entry point. All requests go through index and then are dispatched to different classes/methods/functions depending on the requested path. This is when your site starts to resemble a web application more than a web site from the development standpoint.
Best of luck!
Upvotes: 1 [selected_answer]<issue_comment>username_2: The simplest way of doing this is to make your index.php the front controller for the site.
You do this with a case statement like this:
```
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
switch ($page) {
case 'faq' :
require_once('includes/faq.php');
exit;
case 'blog' :
require_once('includes/blog.php');
exit;
case 'home':
default:
require_once('includes/home.php');
}
```
Then your menus just need to use `www.test.com?page=blog` and adding new pages is as simple as putting the code and markup for that page in a new script in the includes directory and updating your menu code.
With rewrite rules, you can easily have url's like `www.test.com/page/blog`
It's a simple and effective way to handle routing.
Upvotes: 1
|
2018/03/17
| 726 | 2,832 |
<issue_start>username_0: I need help with my programming exercise and I need to go from one HTML file to another but it is not working for me.
`
```
function userSubmit(){
var choice, output;
choice = document.getElementById('colourMenu');
if (choice === 'file:///Users/missminimegs/Documents/pinkpulldown.html'){
window.location.href = "file:///Users/missminimegs/Documents/pinkpulldown.html";
}
}
body {
background: rgb(204, 204, 255);
font-family: Arial;
color: white;
text-align: center;
}
`
```<issue_comment>username_1: Yes, that's pretty much the standard pattern for those coming to PHP from a predominantly HTML background. Typically they'll start with a multiple-page HTML site, each page with its own HTML file. As the site grows, they'll realize there is a lot of duplicated markup (header, footer, etc) and it becomes tedious to keep it all consistent. The solution is to rename their pages with a `.php` extension so the files are processed before they're served to the client, then the duplicate markup is removed and placed in an include file. The files are then all updated to pull in the content from the file using either `include` or `require`.
I wouldn't say that approach is wrong. This is exactly how I came to PHP oh so many years ago! But it isn't really the best in the long run. Realize that it's a stepping stone and as you learn more you'll realize what proper architecture/design looks like.
I don't know the true level of your programming experiences. When you're comfortable, you make want to look into some web frameworks, like [Slim](https://www.slimframework.com/) and [Laravel](https://laravel.com/). In these frameworks, the `index.php` file serves as a central entry point. All requests go through index and then are dispatched to different classes/methods/functions depending on the requested path. This is when your site starts to resemble a web application more than a web site from the development standpoint.
Best of luck!
Upvotes: 1 [selected_answer]<issue_comment>username_2: The simplest way of doing this is to make your index.php the front controller for the site.
You do this with a case statement like this:
```
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
switch ($page) {
case 'faq' :
require_once('includes/faq.php');
exit;
case 'blog' :
require_once('includes/blog.php');
exit;
case 'home':
default:
require_once('includes/home.php');
}
```
Then your menus just need to use `www.test.com?page=blog` and adding new pages is as simple as putting the code and markup for that page in a new script in the includes directory and updating your menu code.
With rewrite rules, you can easily have url's like `www.test.com/page/blog`
It's a simple and effective way to handle routing.
Upvotes: 1
|
2018/03/17
| 1,093 | 4,032 |
<issue_start>username_0: I want to change a global variable in the top ajax form and use it in the bottom ajax form.
This is not working when I do like this:
```
var xGlobalTitle; //global variable that I want to use
$.ajax({
type: 'GET',
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
xGlobalTitle = data.xglobalTitle; //I want to change the value of the variable in here.
}
})
alert(window.xGlobalTitle); //And I want to use this value in here
$.post("/Home/selectRooms", { xtitle: xGlobalTitle }, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('|' +
' ' +
'' +
'...' +
'' +
' |' +
' ' + Xroom\_name + ' |' +
' ' +
'' +
'' +
' |' +
'
');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
```
How can I do this . Is there anyone in this regard who will support me?<issue_comment>username_1: This is an issue of timing, not of access to the global variable. Your `alert` executes before `xGlobalTitle = data.xglobalTitle;` executes.
Upvotes: 1 <issue_comment>username_2: This will not work because ajax being asynchronous.There is no certainty when the first ajax will be `success`
So in order to use the value in the second ajax you need to wait till the first ajax is successful. This issue can be solved chaining all the ajax or by using `Promise` & `.then`
Also `.done` method of jquery `ajax` can be helpful.Put the `$.post` inside the `.done` callback function
```
var xGlobalTitle; //global variable that I want to use
$.ajax({
type: 'GET',
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
xGlobalTitle = data.xglobalTitle; //I want to change the value of the variable in here.
}
}).done(function(data){
alert(window.xGlobalTitle)
$.post("/Home/selectRooms", { xtitle: xGlobalTitle }, function (data) {
//rest of the code
})
})
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: In your ajax you should used `async: false`
follow this link [from stockoverflow answer](https://stackoverflow.com/questions/1478295/what-does-async-false-do-in-jquery-ajax)
```
var xGlobalTitle; //global variable that I want to use
$.ajax({
type: 'GET',
async: false,
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
xGlobalTitle = data.xglobalTitle; //I want to change the value of the variable in here.
}
})
```
Upvotes: 0 <issue_comment>username_4: Your second request is happening without waiting for the data coming from the the first one(async call),so there are many ways to do this also one of that
var xGlobalTitle; //global variable that I want to use
$.ajax({
type: 'GET',
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
```
xGlobalTitle = data.xglobalTitle; //I want to change the value of the variable in here.
alert(window.xGlobalTitle); //And I want to use this value in here
$.post("/Home/selectRooms", { xtitle: xGlobalTitle }, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('|' +
' ' +
'' +
'...' +
'' +
' |' +
' ' + Xroom\_name + ' |' +
' ' +
'' +
'' +
' |' +
'
');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
}
```
})
Upvotes: 0
|
2018/03/17
| 241 | 1,028 |
<issue_start>username_0: Can we we trigger an azure function only when certain document with field values inserted into Cosmos DB ? E.G an employee document with country "USA" field value trigger azure function. I couldn't figure this one out as its always triggering the function whenever there is an item added / modified which makes too much function calls.
Thanks !
Regards,
Sowmyan<issue_comment>username_1: the trigger doesn't seem to have any way to filter based on field value, but you can always partition your data into different collections if that makes sense for your case
Upvotes: 1 [selected_answer]<issue_comment>username_2: Well based on the suggestion from one of the cosmosdb expert from microsoft
>
> "Right now we don't support filters on the Change Feed but it is in
> the roadmap :) You can apply a filter within the Function's code as a
> workaround right now on the batch of received documents."
>
>
>
You can do the above rather than partitioning which is going to cost you much.
Upvotes: 1
|
2018/03/17
| 476 | 1,558 |
<issue_start>username_0: I'm trying to convert the code below into a function, but keep getting errors. Can anyone help with the steps I need to take in order to refactor this code into a funtion?
```
n1 = int(input('Enter First Number'))
n2 = int(input('Enter Second Number'))
n3 = int(input('Enter Third Number'))
average = int(n1 + n2 + n3)/3
print('')
print('The Average Is:'),
print(average)
```<issue_comment>username_1: This is one way.
```
def calculate_average():
n1 = int(input('Enter First Number'))
n2 = int(input('Enter Second Number'))
n3 = int(input('Enter Third Number'))
return int(n1 + n2 + n3)/3
average = calculate_average()
print('')
print('The Average Is:')
print(average)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: So, one simple way is as follows:
```
def calculate_average(x, y, z):
l = [x, y, z]
return int(sum(l)/len(l))
```
If you would like the function to be agnostic to the length of the list of numbers, you can pass the list in as the function argument like so:
```
def calculate_average(l):
# pass in list of numbers
return int(sum(l)/len(l))
```
You would call this function like this: calculate\_average([n1, n2, n3])
You could also do a single line by importing statics (as suggested below) or numpy and using the mean function.
```
import numpy
numpy.mean([n1, n2, n3])
import statistics
statistics.mean([n1, n2, n3])
```
There's likely 10 other ways to do this. Thanks peanut gallery and Happy averaging/meaning!!
Upvotes: 0
|
2018/03/17
| 589 | 2,088 |
<issue_start>username_0: In a controller I am using two validation like this:
```
public function update(Request $request){
if( $request->hasFile('img1') ){
$request->validate(
[
'img1'=>'image'
]
);
}
if( $request->hasFile('img2') ){
$request->validate(
[
'img2'=>'image'
]
);
}
}
```
Now if I upload incorrect file types for both img1 & img2 Only the first validation is checked and laravel redirects user to the original form page. This way message for only first validation is displayed. Even though second file type was also incorrect. I want to make sure all validate methods are checked are executed before I get redirected to the page I came from i.e., the page containing form.
Also I can't put validate method for file in one `if statement` as `img1` and `img2` might not be present at the same time. Because user might just want to upload one file.<issue_comment>username_1: This is one way.
```
def calculate_average():
n1 = int(input('Enter First Number'))
n2 = int(input('Enter Second Number'))
n3 = int(input('Enter Third Number'))
return int(n1 + n2 + n3)/3
average = calculate_average()
print('')
print('The Average Is:')
print(average)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: So, one simple way is as follows:
```
def calculate_average(x, y, z):
l = [x, y, z]
return int(sum(l)/len(l))
```
If you would like the function to be agnostic to the length of the list of numbers, you can pass the list in as the function argument like so:
```
def calculate_average(l):
# pass in list of numbers
return int(sum(l)/len(l))
```
You would call this function like this: calculate\_average([n1, n2, n3])
You could also do a single line by importing statics (as suggested below) or numpy and using the mean function.
```
import numpy
numpy.mean([n1, n2, n3])
import statistics
statistics.mean([n1, n2, n3])
```
There's likely 10 other ways to do this. Thanks peanut gallery and Happy averaging/meaning!!
Upvotes: 0
|
2018/03/17
| 542 | 1,802 |
<issue_start>username_0: I am looking to find the total number of players by counting the unique screen names.
# Dependencies
import pandas as pd
```
# Save path to data set in a variable
df = "purchase_data.json"
# Use Pandas to read data
data_file_pd = pd.read_json(df)
data_file_pd.head()
```

```
# Find total numbers of players
player_count = len(df['SN'].unique())
TypeError Traceback (most recent call last)
in ()
1 # Find total numbers of players
----> 2 player\_count = len(df['SN'].unique())
TypeError: string indices must be integers
```<issue_comment>username_1: This is one way.
```
def calculate_average():
n1 = int(input('Enter First Number'))
n2 = int(input('Enter Second Number'))
n3 = int(input('Enter Third Number'))
return int(n1 + n2 + n3)/3
average = calculate_average()
print('')
print('The Average Is:')
print(average)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: So, one simple way is as follows:
```
def calculate_average(x, y, z):
l = [x, y, z]
return int(sum(l)/len(l))
```
If you would like the function to be agnostic to the length of the list of numbers, you can pass the list in as the function argument like so:
```
def calculate_average(l):
# pass in list of numbers
return int(sum(l)/len(l))
```
You would call this function like this: calculate\_average([n1, n2, n3])
You could also do a single line by importing statics (as suggested below) or numpy and using the mean function.
```
import numpy
numpy.mean([n1, n2, n3])
import statistics
statistics.mean([n1, n2, n3])
```
There's likely 10 other ways to do this. Thanks peanut gallery and Happy averaging/meaning!!
Upvotes: 0
|
2018/03/17
| 994 | 3,825 |
<issue_start>username_0: I try like this :
```
php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ChangePasswordRequest extends FormRequest
{
...
public function rules()
{
return [
'old_password' = '<PASSWORD>|confirmed',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>'
];
}
}
```
I have entered the old password correctly, but there is still a message :
>
> The old password confirmation does not match.
>
>
>
How can I solve this problem?<issue_comment>username_1: The ["confirmed" rule](https://laravel.com/docs/5.6/validation#rule-confirmed) doesn't do what you expect it here to do.
If you set `confirmed` rule on a field `old_password` it will look for form input `old_password_confirmation` and check that its value is equal to the value of `old_password`. It's basically an inverse of `same:field` with predefined expected name (it will add `_confirmation` to the original name).
In your case you would use it like this and it will perform same function as your current `password_confirmation => same:password` rule:
```
public function rules()
{
return [
'old_password' => '<PASSWORD>',
'password' => '<PASSWORD>',
];
}
```
For what you want to achieve you could either [create your own validation rule](https://laravel.com/docs/5.6/validation#custom-validation-rules) or (in my opinion better) check whether the entered password is correct in the controller.
Upvotes: 0 <issue_comment>username_2: According to the [documentation](https://laravel.com/docs/5.6/validation#rule-confirmed):
*`Hash::check()`* function which allows you to check whether the old password entered by a user is correct or not.
```
if (Hash::check("parameter1", "parameter2")) {
//add logic here
}
parameter1 - user password that has been entered on the form
parameter2 - old password hash stored in a database
```
It will return true if the old password has been entered correctly and you can add your logic accordingly
*`new_password`* and *`new_confirm_password`* to be same, you can add your validation in form request like this:
```
'new_password' => '<PASSWORD>',
'new_confirm_password' => '<PASSWORD>|same:<PASSWORD>'
```
Upvotes: 1 <issue_comment>username_3: what you can do is to make a rule. the following will probably solve your problem.
**CurrentPassword.php**
```
php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash;
class CurrentPassword implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return Hash::check($value,auth()-user()->password);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Current password is incorrect';
}
}
```
and in your controller, you can make something like this:
```
$this->validate($request,[
'password_current'=>['required',new CurrentPassword()],
'password'=>'required|string|min:6|confirmed',
]);
$request->user()->update([
'password'=><PASSWORD>($request->password)
]);
```
Upvotes: 2 <issue_comment>username_4: (Laravel v7.x)
You are looking for rule called 'password':
```
...
'old_password' => '<PASSWORD>',
...
```
As well you could specify an authentication guard using the rule's first parameter like this:
```
...
'old_password' => '<PASSWORD>',
...
```
Here is docs:
<https://laravel.com/docs/7.x/validation#rule-password>
Upvotes: 2
|
2018/03/17
| 1,358 | 5,494 |
<issue_start>username_0: Suppose i have a structure like this:
```
items: {
id1: {
likes: 123
},
id2: {
likes: 456
},
id3: {
sourceId: 'id1',
likes: 123
},
id4: {
sourceId: 'id1',
likes: 123
}
[,...]
}
```
where any item can either be a source item or an item that references a source item. The purpose of referencing the source item is to keep counters consistent across all items that share the same sourceId.
Therefore, when i change a counter on a source item, i want to batch write that counter's value to all the items that have that item as their sourceId.
### My concern
Suppose I read in the docs referencing some sourceId, then i commit the changes in a batch to all of them. What if a very small subset of the docs in the batch were deleted in the small window of time since the documents were read in, or a rare but possible write-rate conflict occurs? Do none of the counters get updated because 1 or 2 documents failed to be updated?
Is it possible to submit a batch that writes the changes to each of its documents independently, such that if one fails, it has no impact on if the others get written?
Or maybe for this scenario it might be better to read in the documents referencing some sourceId and then write the changes to each document in parallel such that write independence is achieved. *I don't like this approach since the number of requests would be the size of the batch.*
What are your thoughts?<issue_comment>username_1: Take a careful read of the API docs for [BatchWrite](https://cloud.google.com/nodejs/docs/reference/firestore/0.12.x/WriteBatch). It will answer your questions. Since you're not showing your batch code (are you using set? update?), we have to look at the API docs to assess the failure cases:
>
> create()
>
>
> This will fail the batch if a document exists at its location.
>
>
>
It sounds like you're probably not using create(), but this is the failure case.
>
> set()
>
>
> If the document does not exist yet, it will be created.
>
>
>
So, a set will not fail if the documented was deleted before the batch got committed.
>
> update()
>
>
> If the document doesn't yet exist, the update fails and the entire
> batch will be rejected.
>
>
>
So, if you try to update a nonexistent document, the batch will fail.
If you want to decide what to do with each document, depending on its existence and contents, then control the failure cases, use a [transaction](https://firebase.google.com/docs/firestore/manage-data/transactions#transactions).
Upvotes: 2 [selected_answer]<issue_comment>username_2: If I understand your question, I had a similar scenario and here's how I did it. First, I use generated universal ID's, uid's, for all my item keys/id's. Then, what you do is on the grandchildren, simply write the uid of the parent it is associated with. Each grandchild could be associated with more than one parent.
As you create new items, you have to recursively update the parent with the uid of the item so the parent has record of all its associated child items.
```
fetchPromise = [];
fetchArray = [];
if(!selectIsEmpty("order-panel-one-series-select") || !selectIsUnselected(orderPanelOneSeriesSelect)){
orderPanelOneTitle.innerHTML = "Select " + orderPanelOneSeriesSelect.value.toString().toUpperCase() + " Option";
}
//on change we need to populate option select based on this value
//now we need to get the particular series doc and fill get array then prmise all to get all options
familyuid = getRecordFromList(doc.getElementById("order-panel-one-family-select"),orderPanelOneFamilySelect.selectedIndex);
seriesuid = getRecordFromList(doc.getElementById("order-panel-one-series-select"),orderPanelOneSeriesSelect.selectedIndex);
optionuid = getRecordFromList(doc.getElementById("order-panel-one-option-select"),orderPanelOneOptionsSelect.selectedIndex);
optionRef = db.collection("products").doc(familyuid).collection("option");
itemRef = db.collection("products").doc(familyuid).collection("item");
targetRef = db.collection("products").doc(familyuid).collection("option").doc(optionuid);
try {
targetRef.get().then(function(snap) {
if (snap.exists) {
for (var key in snap.data()) {
if (snap.data().hasOwnProperty(key)) {
fetchPromise = itemRef.doc(key).get();
fetchArray.push(fetchPromise);
}
}
Promise.all(fetchArray).then(function(values) {
populateSelectFromQueryValues(values,"order-panel-one-item-select");
if(!selectIsEmpty("order-panel-one-item-select")){
enableSelect("order-panel-one-item-select");
}
targetRef.get().then(function(snap){
if(snap.data().name){
var str = snap.data().name.toString();
orderAsideInfo.innerHTML = "Select " + capitalizeFirstLetter(str) + " item.";
}
});
});
}
}).catch(function(error) {
toast("error check console");
console.log("Error getting document:", error);
});
}
```
[](https://i.stack.imgur.com/K0gEG.jpg)
Upvotes: 0
|