date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/15
| 873 | 2,808 |
<issue_start>username_0: I am following a Laravel course on Udemy and while I followed everything the instructor did, for some weird reason I am not getting the expected result.
This is the Relationship One to One lesson and I added a function in User Model to check if it has any posts.
Then added the route to display post if user\_id equals.
app\User.php
```
public function post() {
return $this->hasOne('App\Post');
}
```
app\Http\routes.php
```
Route::get('/user/{id}/post', function($id) {
return User::find($id)->post;
});
```
Below is the screenshot from the database showing that I have a post with user\_id = 1 in the posts table. I also have a user with id=1 in the user's table.
[MySQL data](https://i.stack.imgur.com/okq3V.png)
Why do I get a blank page when visiting domain/user/1/post?
Sohel, i got a result from your function, but had to use
```
var_dump(User::with('post')->where('id',1)->first());
```
Then tried something else:
```
return User::with('post')->where('id',$id)->first();
```
And this is the result:
```
{"id":1,"name":"Nick","email":"<EMAIL>","created_at":"2018-03-15 09:49:51","updated_at":"2018-03-15 09:49:51","post":null}
```<issue_comment>username_1: I think you need `->hasMany()` relation if you want to check if user has any posts because the user can has many posts... and the code would be:
```
public function posts() {
return $this->hasMany('App\Post');
}
```
The call:
```
User::find($id)->posts;
```
Upvotes: -1 <issue_comment>username_2: Your one to one relationship should go as:
app\User.php
```
public function post() {
return $this->hasOne('App\Post');
}
```
app\Post.php
```
public function user() {
return $this->hasOne('App\User');
}
```
you can try doing this function in controller:
```
public function getPost {
$user= User::find($id);
return $user->post();
}
```
Upvotes: 0 <issue_comment>username_3: The issue was not with the functions, the issue was in the database.
Column deleted\_at was not NULL and it was marking the post as being soft deleted, therefore not being displayed.
Upvotes: 0 <issue_comment>username_4: Since the "user\_id" field is in the "posts" table, the relation in the App\User model need to be:
```
public function post() {
return $this->hasMany('App\Post');
}
```
then, call it without the parenthesis to get the result:
```
public function getPost {
$user= User::find($id);
return $user->post;
}
```
When you use the parenthesis, you get the builder and not the result. example:
```
public function getPost {
$user= User::find($id);
return $user->post()->get();
}
```
OR
```
public function getPost {
$user= User::find($id);
return $user->post()->where('name', 'like', '%hello%')->get();
}
```
Upvotes: 0
|
2018/03/15
| 258 | 787 |
<issue_start>username_0: I want to change the language of the date i get in my view from english to french
```
{{ strftime("%d %B %Y, %H:%M", strtotime($article->created_at)) }}
```<issue_comment>username_1: Set `Carbon` locale first, then access
```
Carbon::setLocale('fr');
$date_to_show_in_view = $article->created_at->diffForHumans();
```
For your second query(to get `15 Mars 2018`), use this-
```
php
setlocale(LC_TIME, 'French');
echo $base_weight_category-created_at->formatLocalized('%d %B %Y');
?>
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: we can use another method with translatedFormat
```
Carbon::setLocale('fr');
echo $base_weight_category->created_at->translatedFormat('l jS F Y');
```
we can see result jeudi 2 avril 2020
Upvotes: 3
|
2018/03/15
| 515 | 1,794 |
<issue_start>username_0: I have a function that appends the information from 2 tables, but both tables have the column "name". How can I dictate which table name is utilized?
```js
function createTableRow(customers) {
var data = JSON.parse(customers.results);
if (locations != 0) {
for (var i = 0; i < data.length; i++) {
var row = $('|
');
$('#table').append(row);
row.append($(' ' + data[i].name + ' |'));
row.append($(' ' + data[i].description + ' |'));
row.append($(' ' + data[i].name + ' |'));
}
}
}
```
Here is the database query that is used to make customers.results
```
SELECT customers.name, customers.description, orders.name FROM customers INNER JOIN orders on orders.id = customers.pid
```
Lets say the tables are named **customers** and **orders** both with the column "name"
I want the first **data[i].name** to show the Customers name and the second **data[i].name** to show the Orders name.<issue_comment>username_1: Give one of your columns a alias in your SQL query:
```
SELECT
customers.name AS cus_name,
customers.description,
orders.name
FROM customers
INNER JOIN orders on orders.id = customers.pid
```
Note that `AS` is not required but will make your query a bit more explicit
Then access the customer name with `data[i].cus_name`
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to make alias for `order.name` like
```
SELECT customers.name, customers.description, orders.name as order_name
FROM customers INNER JOIN orders on orders.id = customers.pid
```
And use `order_name` for showing order name like,
```
row.append($(' ' + data[i].name + ' |'));
row.append($(' ' + data[i].description + ' |'));
row.append($(' ' + data[i].order\_name + ' |'));
```
Upvotes: 1
|
2018/03/15
| 1,061 | 3,477 |
<issue_start>username_0: I'm using **prefetch\_related** to join three tables. **Products,** **ProductPrices** and **ProductMeta**. But besides I'm following the documentation, the debugger says that I'm using **three queries** instead of one (with joins)
Also this creates a second problem. **Some products doesn't have prices in some countries** because they are not avaliable there. But using this code, the product appears but with an empty price.
So, **I'd like to exclude the products that doesn't have prices or meta**. I'm doing something wrong?
This is my code:
```
prefetch_prices = Prefetch(
'product_prices',
queryset=ProductPrices.objects.filter(country=country_obj),
to_attr='price_info'
)
prefetch = Prefetch(
'product_meta',
queryset=ProductMeta.objects.filter(language=lang),
to_attr='meta_info'
)
products = Product.objects.prefetch_related(prefetch, prefetch_prices).all()
```
That produces these SQL Queries:
```
{ 'sql': 'SELECT DISTINCT `products`.`id`, `products`.`image`, '
'`products`.`wholesale_price`, `products`.`reference`, '
'`products`.`ean13`, `products`.`rating`, `products`.`sales`, '
'`products`.`active`, `products`.`active_in`, '
'`products`.`encilleria`, `products`.`delivery`, '
'`products`.`stock`, `products`.`ingredients`, '
'FROM `products` WHERE `products`.`active` = 1 ',
'time': '0.098'},
{ 'sql': 'SELECT `products_meta`.`id`, `products_meta`.`product_id`, '
'`products_meta`.`name`, `products_meta`.`slug`, '
'`products_meta`.`tagline`, `products_meta`.`key_ingredients`, '
'`products_meta`.`ideal_for`, `products_meta`.`description`, '
'`products_meta`.`advice`, `products_meta`.`summary`, '
'`products_meta`.`language` FROM `products_meta` WHERE '
"(`products_meta`.`language` = 'en' AND "
'`products_meta`.`product_id` IN (52001, 51972, 52038, 52039, '
'52040, 52041, 51947, 51948, 51949, 51950, 51951, 51953, 51954, '
'51832))',
'time': '0.096'},
{ 'sql': 'SELECT `products_prices`.`id`, `products_prices`.`product_id`, '
'`products_prices`.`country_id`, `products_prices`.`price` FROM '
'`products_prices` WHERE (`products_prices`.`country_id` = 1 '
'AND `products_prices`.`product_id` IN (52001, 51972, 52038, '
'52039, 52040, 52041, 51947, 51948, 51949, 51950, 51951, 51953, '
'51954, 51832))',
'time': '0.046'}
```
Thanks<issue_comment>username_1: Give one of your columns a alias in your SQL query:
```
SELECT
customers.name AS cus_name,
customers.description,
orders.name
FROM customers
INNER JOIN orders on orders.id = customers.pid
```
Note that `AS` is not required but will make your query a bit more explicit
Then access the customer name with `data[i].cus_name`
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to make alias for `order.name` like
```
SELECT customers.name, customers.description, orders.name as order_name
FROM customers INNER JOIN orders on orders.id = customers.pid
```
And use `order_name` for showing order name like,
```
row.append($(' ' + data[i].name + ' |'));
row.append($(' ' + data[i].description + ' |'));
row.append($(' ' + data[i].order\_name + ' |'));
```
Upvotes: 1
|
2018/03/15
| 1,139 | 3,148 |
<issue_start>username_0: Data:
```
0 09:30:38
1 13:40:27
2 18:05:24
3 04:58:08
4 09:00:09
```
Essentially what I'd like to do is split this into three columns [hour, minute, second]
I've tried the following code but none seem to be working:
```
train_sample.time.hour
AttributeError: 'Series' object has no attribute 'hour'
train_sample.time.dt.hour
AttributeError: Can only use .dt accessor with datetimelike values
pd.DatetimeIndex(train_sample.time).hour
TypeError: is not convertible to datetime
```
This seems so simple but I can't figure it out. Any help would be much appreciated.<issue_comment>username_1: Use list comprehension with extract attributes of `time`s:
```
import datetime as datetime
df = pd.DataFrame({'time': [datetime.time(9, 30, 38),
datetime.time(13, 40, 27),
datetime.time(18, 5, 24),
datetime.time(4, 58, 8),
datetime.time(9, 0, 9)]})
print (df)
time
0 09:30:38
1 13:40:27
2 18:05:24
3 04:58:08
4 09:00:09
df[['h','m','s']] = pd.DataFrame([(x.hour, x.minute, x.second) for x in df['time']])
```
Or convert to `string`s, split and convert to `int`:
```
df[['h','m','s']] = df['time'].astype(str).str.split(':', expand=True).astype(int)
print (df)
time h m s
0 09:30:38 9 30 38
1 13:40:27 13 40 27
2 18:05:24 18 5 24
3 04:58:08 4 58 8
4 09:00:09 9 0 9
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: One way is to convert to `timedelta` and extract via [`pd.Series.dt.components`:](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.components.html)
```
df[['hour','minute','second']] = pd.to_timedelta(df['time']).dt.components.iloc[:, 1:4]
```
**Result**
```
time hour minute second
0 09:30:38 9 30 38
1 13:40:27 13 40 27
2 18:05:24 18 5 24
3 04:58:08 4 58 8
4 09:00:09 9 0 9
```
Upvotes: 0 <issue_comment>username_3: Splitting using `:` and creating a dataframe with each of the split as separate column values.
```
import pandas as pd
d = {0: '09:30:38',
1: '13:40:27',
2: '18:05:24',
3: '04:58:08',
4: '09:00:09'}
df = pd.DataFrame([v.split(':') for v in d.values()], columns=['hour', 'minute', 'second'])
print(df)
```
**Result:**
```
hour minute second
0 09 30 38
1 13 40 27
2 18 05 24
3 04 58 08
4 09 00 09
```
Upvotes: 2 <issue_comment>username_4: Looks like your problem is really just missing the [datetime accessor](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html) Use `dt` at the end of your Series then you can extract with the .hour method
```
train_sample['hour'] = train_sample.dt.hour
train_sample['minute'] = train_sample.dt.minute
train_sample['second'] = train_sample.dt.second
```
Upvotes: 2
|
2018/03/15
| 543 | 1,836 |
<issue_start>username_0: I used this query for get the total count of Property\_SubType using GROUP BY.Now i want to get the Min and Max price for particular Property\_SubType form my database how to do it?
Below my query:
```
SELECT Matrix_Unique_ID,Property_Type,Property_SubType,Subdivision,
COUNT(*) as count
FROM ncrmls_mls_res_listings_sorted_2
WHERE `city`='ABC'
GROUP BY Property_SubType,Property_Type
```<issue_comment>username_1: There is a `MIN()` and `MAX()` function in MySQL. These return the smalles and biggest value for the selected column.
Try something like this (top of my head, not tested):
```
SELECT Matrix_Unique_ID,
Property_Type,
MIN(Property_SubType),
MAX(Property_SubType),
Subdivision,
COUNT(*) as count
FROM
ncrmls_mls_res_listings_sorted_2
WHERE
`city`='ABC'
GROUP BY
Property_SubType, Property_Type
```
Hope this helps you out!
Upvotes: -1 <issue_comment>username_2: You seem to want this query:
```
SELECT Property_Type, Property_SubType, MIN(Price), MAX(Price)
FROM ncrmls_mls_res_listings_sorted_2
WHERE city = 'ABC'
GROUP BY Property_Type, Property_SubType;
```
You appear to be using a (mis)feature of MySQL that allows extra columns in the `SELECT` in an aggregation query.
It occurs to me that you might want full data about the min and max. If so, you can use a subquery:
```
SELECT r.*
FROM ncrmls_mls_res_listings_sorted_2 rl JOIn
(SELECT Property_Type, Property_SubType,
MIN(Price) as minprice, MAX(Price) as maxprice
FROM ncrmls_mls_res_listings_sorted_2
WHERE city = 'ABC'
GROUP BY Property_Type, Property_SubType
) pts
ON pts.Property_Type = rl.Property_Type AND
pts.Property_SubType = rl.Property_SubType AND
rl.price IN (minprice, maxprice);
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 861 | 2,757 |
<issue_start>username_0: I have two datasets, one is the shape file of the french regions, and the second is a file containing points. I want to (efficiently) find the regions containing at least one point.
When I print the two datasets i see [](https://i.stack.imgur.com/CgwHr.png)
I have tried to read the shape files with geopandas as follows
```
point_data = gpd.read_file(name_file) # I read the points
regions = gpd.read_file('regions-20180101-shp/regions-20180101.shp') # I read the regions
reg.apply(lambda x: x.geometry.contains(point_data).any()) # I try to get the intersectons
```
I get an error. While if I simply try
`reg.geometry.contains(point_data)`
I get
```
0 False
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 False
...
```
And I get the same results if I use `within`. Of course I can do it with for cycles but I would like to find a more efficient way.<issue_comment>username_1: The problem seems to be given by the types being Points and not Polygons.
One way around I have found is to make the points as a polygon, and then study the intesection between polygons. In this case it works well, but this wont always give the correct answer. The code is
```
g1 = point_data.geometry
g1 = [list(g.coords)[0] for g in g1]
p1 = polygon.Polygon(g1)
reg.apply(lambda x: x.geometry.intersects(p1),axis=1)
```
Once again this will only work if the polygons with contain at least one point are neighbors.
Upvotes: 0 <issue_comment>username_2: What you tried was almost correct. When applying a function to a GeoSeries, the function receives single shapely geometries, so in this case a single polygon. For that single polygon, we want to check if at least one of the points is within that polygon:
```
regions.apply(lambda x: points.within(x).any())
```
With as small reproducible example:
```
import geopandas
from shapely.geometry import Polygon, Point
regions = geopandas.GeoSeries([Polygon([(0,0), (0,1), (1,1), (1, 0)]),
Polygon([(1,1), (1,2), (2,2), (2, 1)]),
Polygon([(1,0), (1,1), (2,1), (2, 0)])])
points = geopandas.GeoSeries([Point(0.5, 0.5), Point(0.2, 0.8), Point(1.2, 1.8)])
```
which looks like:
[](https://i.stack.imgur.com/QcTpt.png)
then applying the function looks like:
```
>>> regions.apply(lambda x: points.within(x).any())
0 True
1 True
2 False
dtype: bool
```
If `regions` and `points` would be GeoDataFrames instead of GeoSeries, you will need to add a `.geometry` in the above.
Upvotes: 3 [selected_answer]
|
2018/03/15
| 740 | 2,758 |
<issue_start>username_0: I am defining a css class, and trying to use its member from javascript. The result is undefined. Where is my mistake?
```js
function myFunction() {
var x = document.getElementById("myId").style.myMember;
document.getElementById("debug").innerHTML = x;
}
```
```css
.myClass {
myMember: 123;
}
```
```html
Click the button to get the style property of the myId element.
Try it
My content.
```
The [example](https://www.w3schools.com/code/tryit.asp?filename=FPDQGK3PR27M) at w3schools, if you want to try it.
---
Some background: I'm trying to create a very simple page with slideshow. I found out a way to create the slides in css thanks to w3schools (sorry, it's what comes out on top when I search).
Now I want to be able to set the display time separately for each slide in the html file, and this time to have a default value if it's omitted.
It seemed reasonable for display time to be part of the style of the slide, at least logical in my head. I understand now from the answers so far that the css styles can't be added to with custom attributes, is that correct?
What would be the correct way to pass a display time from this:
```

```
to this javascript function?:
```
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "block";
setTimeout(carousel, 500); // Get display time from html instead!
}
```<issue_comment>username_1: if you enter in the console "document.getElementById("myId").style", you get all the applicable styles to your given selection. the class "my123" is not recognised in there that's why you get the result as undefined.
Upvotes: 0 <issue_comment>username_2: You are trying to declare "myMember" as property and want to use it in Javascript but myMember is not a CSS property so its returning undefined.
The style property returns a CSSStyleDeclaration object, which represents an element's style attribute.
The style property is used to get or set a specific style of an element using different CSS properties.
Upvotes: 0 <issue_comment>username_3: First of all `element.style` object will give you the style values which is defined inline in that particular element...
Second `myMember` is not an valid css property so it will give you nothing...
```js
function myFunction() {
var x = document.getElementById("myId").style.display;
document.getElementById("debug").innerHTML = x;
}
```
```html
Click the button to get the style property of the myId element.
Try it
My content.
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 618 | 1,948 |
<issue_start>username_0: I have an `EditText` to enter IBAN number. I want to format this
```
TR330006100519786457841326
```
while the user typing the input I want to for mat it like
```
TR33 0006 1005 1978 6457 8413 26
```
so basically I want to **add white space after each 4 digits**
I tried using `TextWatcher`, when `char sequence length` hits 4 I'm forcing a space but it doesn't work when user put "spaces"<issue_comment>username_1: Here is a base string way of doing this:
```
String input = "TR330006100519786457841326";
input = input.replaceAll("(\\w{4})", "$1 ");
System.out.println(input);
TR33 0006 1005 1978 6457 8413 26
```
Inside your text watcher, you can replace the string with the output generated by the above regex replacement.
```
final EditText editText = (EditText) findViewById(R.id.text1);
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = editText.getText().toString();
input = input.replaceAll("(\\w{4})", "$1 ");
editText.setText(input);
}
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try using below regular expression:
```
input.replaceAll("....", "$0 ");
```
Upvotes: 2 <issue_comment>username_3: Use this method
```
public static String insertSeperator(String text, String insert, int period) {// text= data, insert= , period=
text=text.replaceAll(" ","");
StringBuilder builder = new StringBuilder(
text.length() + insert.length() \* (text.length() / period) + 1);
int index = 0;
String prefix = "";
while (index < text.length()) {
// Don't put the insert in the very first iteration.
// This is easier than appending it \*after\* each substring
builder.append(prefix);
prefix = insert;
builder.append(text.substring(index, Math.min(index + period, text.length())));
index += period;
}
return builder.toString();
}
```
Upvotes: 0
|
2018/03/15
| 849 | 2,952 |
<issue_start>username_0: I know a lot of people already had similar question, i read a few of them, but found nothing what actualy helped me so far.
I have a gitlab with private repo enabled, I also use Google Kubernetes Engine. I have a few Docker container in my private repo, and I want to deploy one of them to the Kubernetes Engine.
I have created a secret with `kubectl create secret generic db-user-pass --from-file=./username.txt --from-file=./password.txt`
I also tried `kubectl create secret docker-registry name --docker-server=registry.xy.z --docker-username=google --docker-password=xyz --docker-email=<EMAIL>`
Then I created my Deployment file:
```
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: backend-test
labels:
app: 13371337
spec:
replicas: 1
template:
metadata:
labels:
app: 13371337
spec:
containers:
- name: backend
image: registry.xy.z/group/project/backend:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
imagePullSecrets:
- name: db-user-pass or name
```
Any ideas how to get it running?<issue_comment>username_1: Using `kubectl create secret docker-registry name` is a [right way](https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod) to provide credentials of private docker registry.
`imagePullSecrets` options looking good too, if you specify there a name of your docker-registry secret.
So, from Kubernetes path everything looking good.
Try to check events of the pod which will be created by Deployment, just find you pod by `kubectl get pods` and call `kubectl describe pod $name_of_your_pod`, you will see an actual reason why it cannot pull an image.
Also, if your depository is insecure or has self-signed certificate, try to follow [that guide](https://docs.docker.com/registry/insecure/#deploy-a-plain-http-registry) to allow docker daemon pulling image from there, that is an often reason of image pull failures.
Upvotes: 5 [selected_answer]<issue_comment>username_2: In order to create a secret you can use the following command: (notice I gave it a name)
```
kubectl create secret docker-registry my_registry \
--docker-server=registry.xy.z \
--docker-username=google \
--docker-password=xyz \
--docker-email=<EMAIL>
```
or using yaml:
```
apiVersion: v1
kind: Secret
metadata:
name: my_registry
type: Opaque
data:
docker-server: registry.xy.z
docker-username: google
docker-password: xyz
docker-email: <EMAIL>
```
and your deployment need to use the secret name:
```
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: backend-test
labels:
app: 13371337
spec:
replicas: 1
template:
metadata:
labels:
app: 13371337
spec:
containers:
- name: backend
image: registry.xy.z/group/project/backend:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
imagePullSecrets:
- name: my_registry
```
Notice: you must create the secret per namespace.
Upvotes: 2
|
2018/03/15
| 749 | 2,813 |
<issue_start>username_0: Lets say that I own a repair shop and I want to add a vehicle to my database each time a new customer comes to my shop. Assuming that I have a car class that asks for all the necessary information. Is is possible to create a dynamic array of this object that is constantly adding or subtracting the amount of customer cars that come into the shop, or is this more improbable?
Ex.
```
using namespace std; //I know its not a good idea to use, prof wants us too.
class Car{
Car(){
//get user data
}
};
int main () {
int choice;
static int counter = 0;
Car *car = new Car[Counter];
cout << "Would you like to add a vehicle to the our database(yes/no): ";
cin >> choice;
if (choice == "yes") {
car[counter].Car::Car();
counter++;
}
```<issue_comment>username_1: Using `kubectl create secret docker-registry name` is a [right way](https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod) to provide credentials of private docker registry.
`imagePullSecrets` options looking good too, if you specify there a name of your docker-registry secret.
So, from Kubernetes path everything looking good.
Try to check events of the pod which will be created by Deployment, just find you pod by `kubectl get pods` and call `kubectl describe pod $name_of_your_pod`, you will see an actual reason why it cannot pull an image.
Also, if your depository is insecure or has self-signed certificate, try to follow [that guide](https://docs.docker.com/registry/insecure/#deploy-a-plain-http-registry) to allow docker daemon pulling image from there, that is an often reason of image pull failures.
Upvotes: 5 [selected_answer]<issue_comment>username_2: In order to create a secret you can use the following command: (notice I gave it a name)
```
kubectl create secret docker-registry my_registry \
--docker-server=registry.xy.z \
--docker-username=google \
--docker-password=xyz \
--docker-email=xy@z.de
```
or using yaml:
```
apiVersion: v1
kind: Secret
metadata:
name: my_registry
type: Opaque
data:
docker-server: registry.xy.z
docker-username: google
docker-password: xyz
docker-email: <EMAIL>
```
and your deployment need to use the secret name:
```
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: backend-test
labels:
app: 13371337
spec:
replicas: 1
template:
metadata:
labels:
app: 13371337
spec:
containers:
- name: backend
image: registry.xy.z/group/project/backend:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
imagePullSecrets:
- name: my_registry
```
Notice: you must create the secret per namespace.
Upvotes: 2
|
2018/03/15
| 2,325 | 9,909 |
<issue_start>username_0: I am new to android development. tried to implement android dialog in my project but the it's not showing .There are no errors in the logcat.
**This is the XML code for it :**
```
```
**This is the part where I have implemented alertdialog :**
```
FloatingActionButton add_button = findViewById(R.id.add_item);
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Create item list");
final EditText enter_item_list=new EditText(MainActivity.this);
enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
enter_item_list.setHint("Type a name");
enter_item_list.setHintTextColor(Color.RED);
builder.setView(enter_item_list);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String item_name = enter_item_list.getText().toString().trim();
add_item_to_list(item_name);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
});
itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
}
});
}
private void add_item_to_list(String item_name) {
String item_id = itemList_ref.document().getId();
InventoryModel inventoryModel = new InventoryModel(item_id,item_name ,UserName);
itemList_ref.document(item_id).set(inventoryModel).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.d("TAG","Inventory list created");
}
});
}
```
**This is the full code :**
```
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.omniheart.elloslai.storage_checker.model.InventoryModel;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private String UserEmail , UserName ;
private GoogleApiClient googleApiClient ;
private FirebaseAuth firebase_auth;
private FirebaseFirestore Firestore_ref;
private FirebaseAuth.AuthStateListener authStateListener;
private CollectionReference itemList_ref ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(googleSignInAccount!=null){
UserEmail=googleSignInAccount.getEmail();
UserName = googleSignInAccount.getDisplayName();
Toast.makeText(this,"Welcome" + UserName,Toast.LENGTH_LONG).show();
}
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
firebase_auth=FirebaseAuth.getInstance();
Firestore_ref=FirebaseFirestore.getInstance();
authStateListener=new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebase_auth.getCurrentUser();
if(firebaseUser == null) {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
};
FloatingActionButton add_button = findViewById(R.id.add_item);
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Create item list");
final EditText enter_item_list=new EditText(MainActivity.this);
enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
enter_item_list.setHint("Type a name");
enter_item_list.setHintTextColor(Color.RED);
builder.setView(enter_item_list);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String item_name = enter_item_list.getText().toString().trim();
add_item_to_list(item_name);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
});
itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
}
});
}
private void add_item_to_list(String item_name) {
String item_id = itemList_ref.document().getId();
InventoryModel inventoryModel = new InventoryModel(item_id,item_name ,UserName);
itemList_ref.document(item_id).set(inventoryModel).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.d("TAG","Inventory list created");
}
});
}
@Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
firebase\_auth.addAuthStateListener(authStateListener);
}
@Override
protected void onStop() {
super.onStop();
if(googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main\_menu, menu);
return true ;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign\_out\_button:
signOut() ;
return true ;
default:
return super.onOptionsItemSelected(item);
}
}
private void signOut() {
Map map = new HashMap<>();
map.put("tokenId", FieldValue.delete());
Firestore\_ref.collection("users").document(UserEmail).update(map).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
firebase\_auth.signOut();
if (googleApiClient.isConnected()){
Auth.GoogleSignInApi.signOut(googleApiClient);
}
}
});
}
}
```<issue_comment>username_1: You forgot to use [**`alertDialog.show();`**](https://developer.android.com/reference/android/app/Dialog.html#show()) to display your [`AlertDialog`](https://developer.android.com/reference/android/app/AlertDialog.html)
Check your code you have put **`alertDialog.show();`** inside **`builder.setNegativeButton`** that's why your `alertDialog` is not displaying
Change your code like below code
```
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Create item list");
final EditText enter_item_list=new EditText(MainActivity.this);
enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
enter_item_list.setHint("Type a name");
enter_item_list.setHintTextColor(Color.RED);
builder.setView(enter_item_list);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String item_name = enter_item_list.getText().toString().trim();
add_item_to_list(item_name);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
}
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Declare Variable globally**
```
AlertDialog alertDialog ;
```
**add this after your negative button click**
```
alertDialog = builder.create();
alertDialog.show();
```
Upvotes: 2
|
2018/03/15
| 751 | 3,120 |
<issue_start>username_0: I want to display all the images in my cloudinary gallery in to my react app. Can I call the function directly like this?
```
showImages = () =>{
cloudinary.v2.api.resources({
cloud_name: CLOUDINARY_CLOUD_NAME,
upload_preset: CLOUDINARY_UPLOAD_PRESET,
api_key: CLOUDINARY_API_KEY,
api_secret: CLOUDINARY_API_SECRET,
type: 'upload'}, function(error, result){
console.log("herrrrrrrrrreeeeeeeeeeeee",error,result);
});
```
}
---
It gives me this error.
```
Failed to load https://api.cloudinary.com/v1_1/dashboardui/resources/image/upload?: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
```<issue_comment>username_1: You forgot to use [**`alertDialog.show();`**](https://developer.android.com/reference/android/app/Dialog.html#show()) to display your [`AlertDialog`](https://developer.android.com/reference/android/app/AlertDialog.html)
Check your code you have put **`alertDialog.show();`** inside **`builder.setNegativeButton`** that's why your `alertDialog` is not displaying
Change your code like below code
```
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Create item list");
final EditText enter_item_list=new EditText(MainActivity.this);
enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
enter_item_list.setHint("Type a name");
enter_item_list.setHintTextColor(Color.RED);
builder.setView(enter_item_list);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String item_name = enter_item_list.getText().toString().trim();
add_item_to_list(item_name);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
}
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Declare Variable globally**
```
AlertDialog alertDialog ;
```
**add this after your negative button click**
```
alertDialog = builder.create();
alertDialog.show();
```
Upvotes: 2
|
2018/03/15
| 545 | 1,348 |
<issue_start>username_0: I have a list like this:
```
input = [[1,1], [3,3], [5,5], [7,7]]
```
I want this output:
```
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]
```
(The goal is to have the path made of edges `[1,1]-[3,3], [3,3]-[5,5], [5,5]-[7,7]`... I would not be surprised that this question is a duplicate by the way.)
I'am able to get this output like this:
```
> map (\i -> [input!!i, input!!(i+1)]) [0 .. length input-2]
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]
```
Do you have a cleaner solution? There's surely something cleaner.<issue_comment>username_1: You can `zip` `input` with its tail in order to get a list of tuples:
```
Prelude> zip input $ tail input
[([1,1],[3,3]),([3,3],[5,5]),([5,5],[7,7])]
```
From there, if you need it, you can write a function that makes a list out of each tuple, e.g.
```
tupleToList :: (t, t) -> [t]
tupleToList (x, y) = [x, y]
```
This enables you to map over the zipped list:
```
Prelude> fmap tupleToList $ zip input $ tail input
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]
```
Be aware that `tail` is unsafe, in that it throws an exception if the original list is empty.
Upvotes: 2 <issue_comment>username_2: ```
let xs = [[1,1], [3,3], [5,5], [7,7]] in zipWith (\a b -> [a,b]) xs (tail xs)
-- [[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 659 | 2,146 |
<issue_start>username_0: I have a MS SQL Table and one of the rows in the table has specific dates. Example: 2019-11-30 22:00:21.000
I am looking to build a SQL Query that will go to my table and only print the results if the date in this specific column is between TODAY + 30 days
Here is what I have but no joy so far
```
SELECT FOOD_TYPE, BEST_BEFORE
FROM TABLE
WHERE BESTBEFORE < GETDATE() - 30;
```
It does not complain about the syntax but does not show results either<issue_comment>username_1: You might want to try:
```
SELECT FOOD_TYPE, BEST_BEFORE
FROM TABLE
where BESTBEFORE < dateadd(day, 30, getdate())
```
This query will return all records in `TABLE` if the `BESTBEFORE` column is less than the current date plus 30 days.
Upvotes: 1 <issue_comment>username_2: Based on your description, you want:
```
SELECT FOOD_TYPE, BEST_BEFORE
FROM TABLE
WHERE BESTBEFORE < DATEADD(day, 30, GETDATE());
```
Note that `GETDATE()` has a time component and I'm guessing that `BESTBEFORE` does not. The time component should not affect this query. In addition, this version is "sargable" meaning that the query can use an index on `BEST_BEFORE`.
Upvotes: 0 <issue_comment>username_3: You need a `BETWEEN` filter. Keep in mind that `GETDATE()` is `DATETIME` (with time value), you might need to convert to `DATE` if you want complete days (as in my example). Also, using `BETWEEN` means that both limits you are comparing to are inclusive.
```
SELECT FOOD_TYPE, BEST_BEFORE
FROM TABLE
WHERE BESTBEFORE BETWEEN CONVERT(DATE, GETDATE()) AND CONVERT(DATE, GETDATE() + 30)
```
Upvotes: 1 <issue_comment>username_4: Use BETWEEN and CAST as DATE otherwise it won't pick up today's date:
```
SELECT FOOD_TYPE, BEST_BEFORE
FROM TABLE
where BEST_BEFORE between cast(getdate() as date)
and dateadd(day, 30, cast(getdate() as date))
```
Upvotes: 3 [selected_answer]<issue_comment>username_5: You must try this SQL Query. It completes your requirement.
```
SELECT T.FOOD_TYPE, T.BEST_BEFORE
FROM TABLE T with(nolock)
where T.BESTBEFORE Between getdate() AND dateadd(day, 30, getdate())
```
Let me know if question!
Upvotes: 0
|
2018/03/15
| 461 | 1,459 |
<issue_start>username_0: Given the text:
```
This is a #tag and this is another #<EMAIL> and more text.
```
I would like to match the words starting with a hash and ends with a whitespace character ( i don't want to specify a specific pattern for <EMAIL>` ).
I can't use `lookarounds` and would prefer not to use `\b`.
I have tried `#.*\b`, `#.*\s`, which will match more than i asked for. I guess the `*` will also match whitespace so the last check is ignored.
I use <https://regexr.com/> for testing.<issue_comment>username_1: You can match every character except space in the middle.
Try this:
```
#[^\s]+\s
```
[Demo](https://regex101.com/r/5w1xkK/2)
Upvotes: 2 <issue_comment>username_2: You may use
```
#\S+
```
See the [regex demo](https://regex101.com/r/NUlRyq/1).
**Details**
* `#` - a `#` symbol
* `\S+` - 1 or more characters other than whitespace (it can also be written as `[^\s]*`, but `\S` is just shorter).
As a possible enhancement, you can still consider using word and non-word boundaries. E.g., when you want to avoid matching `abc#tagliketext` or when you need to avoid matching punctuation at the end of the hashtag, you may consider using
```
\B#\S+\b
```
See [another regex demo](https://regex101.com/r/NUlRyq/2%5C). The `\B` non-word boundary will fail the match if there is a word char before `#`, and `\b` will stop matching before the rightmost non-word char.
Upvotes: 4 [selected_answer]
|
2018/03/15
| 660 | 2,305 |
<issue_start>username_0: I have a form as part of a VSTO Project application. For various reasons it can end up behind the main Project application window. How do I bring it back to the front? I've tried form.activate and form.bringtofront, but neither of those commands do anything.<issue_comment>username_1: It sounds like you want your form to be [modal](https://ux.stackexchange.com/questions/12045/what-is-a-modal-dialog-window). I'm not sure what form library you're using, but if this were a MS Project VBA form, then you'd set the form's .ShowModal property to True: <https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/showmodal-property>.
Presuming you're using a .NET form, this may be more appropiate: <https://msdn.microsoft.com/en-us/library/c7ykbedk(v=vs.110).aspx>
Upvotes: 0 <issue_comment>username_2: Here is code that I use to show/re-show forms in vb.net MS Project add-ins. If the form gets behind another window, calling ShowTkForm will bring it back to the front:
```
Friend formTk As tk
Friend Sub ShowTkForm()
If formTk Is Nothing OrElse formTk.IsDisposed Then
formTk = New tk
End If
formTk.Show()
End Sub
```
Note: for modeless forms, use the `.Show` method, otherwise use `.ShowDialog`.
For modeless forms, I also like to set the owner of the form as the MS Project application to keep them together. In the Load event of the form:
```
Dim ip As IntPtr = FindWindowByCaption(0, ProjApp.Caption)
SetWindowLong(New HandleRef(Me, Me.Handle), GWL_HWNDPARENT, New HandleRef(Nothing, ip))
```
Which requires:
```
Friend Const GWL_HWNDPARENT = (-8)
Private Function SetWindowLongPtr32(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As HandleRef) As IntPtr
End Function
Private Function SetWindowLongPtr64(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As HandleRef) As IntPtr
End Function
Friend Function SetWindowLong(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As HandleRef) As IntPtr
If (IntPtr.Size = 4) Then
Return SetWindowLongPtr32(hWnd, nIndex, dwNewLong)
End If
Return SetWindowLongPtr64(hWnd, nIndex, dwNewLong)
End Function
Friend Function FindWindowByCaption(ByVal zero As IntPtr, ByVal lpWindowName As String) As IntPtr
End Function
```
Upvotes: 1
|
2018/03/15
| 607 | 2,036 |
<issue_start>username_0: I have a shortcode **[tips]** in which at the end I'm doing:
```
wp_enqueue_script( "tips", plugins_url( "/tips/js/tips.js", PATH ), array("jquery"), TIPS_VERSION, true );
wp_localize_script( "tips", "objTips", $objTips );
```
If there are multiple [tips] shortcodes on the same Page I'd like to pass one `objTips` object with the `$objTips` data from all the shortcodes from that Page.
Right now it's outputting `var objTips = {...}` twice (or more), so JavaScript file tips.js only recognizes the last one. I'd like it to be something like `var objTips = [{...},{...},{...},...];`<issue_comment>username_1: It's possible to have a static counter inside the shortcode function as shown here: [Count how many times shortcode is called and display different content in each « WordPress.org Forums](https://wordpress.org/support/topic/count-how-many-times-shortcode-is-called-and-display-different-content-in-each/).
The shortcode declaration would add the tips to a JS array:
```
add_shortcode( 'tips', function ( $atts, $content = null, $shortcode ) {
static $count = 0;
# https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php
$return = <<
objTips[$count] = "$content";
JS;
$count++;
return $return;
});
add\_action( 'wp\_enqueue\_scripts', function() {
wp\_enqueue\_script( 'tips-script', plugin\_dir\_url( \_\_FILE\_\_ ) . '/tips.js', array( 'jquery' ) );
});
```
And the enqueued JS file would initialize that array and show the final result on document load:
```
var objTips = [];
jQuery( document ).ready( function( $ ) {
console.log(objTips);
});
```
A page with multiple shortcodes would look like this:
```
[tips]one[/tips]
[tips]two[/tips]
[tips]and three[/tips]
```
Result on browser console:
``
Upvotes: 3 [selected_answer]<issue_comment>username_2: Short answer : Yes, multiple localise scripts do work on the same script handle. We are doing it already in our plugin.
Upvotes: 0
|
2018/03/15
| 776 | 3,182 |
<issue_start>username_0: I’ve got a seemingly pretty straightforward Webpack code splitting setup that I’m having trouble migrating to Webpack 4. I have two entries, called `main` and `preview`. I want to do an initial code split into a `vendor` chunk for the vendor modules in `main`, but I want to keep `preview` as a single chunk.
Relevant part of the working configuration in Webpack 3:
```
{
entry: {
main: './src/application.js',
preview: './src/preview.js',
},
plugins: [{
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks({context}) {
if (!context) {
return false;
}
const isNodeModule = context.indexOf('node_modules') !== -1;
return isNodeModule;
},
}),
}]
}
```
Specifically, using the `chunks` property in the `CommonsChunkPlugin` options allows me to do what I need to do easily. Is there an equivalent in Webpack 4’s `optimization.splitChunks` configuration?<issue_comment>username_1: The following Webpack 4 config only splits `main` module vendor dependencies into a separate chunk. Other dependencies for `preview` remains within that chunk.
```
{
entry: {
main: './test/application.js',
preview: './test/preview.js'
},
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
name: 'vendors',
chunks: 'all',
enforce: true,
priority: 1,
test(module, chunks) {
const name = module.nameForCondition && module.nameForCondition();
return chunks.some(chunk => chunk.name === 'main' && /node_modules/.test(name));
}
}
}
}
}
}
```
Shared dependencies are included in the vendors bundle unless we configure the `preview` cacheGroup with higher priority to enforce that all dependencies included here should remain inside this chunk.
For more Webpack 4 related info/config you can review this [webpack-demo](https://github.com/carloluis/webpack-demo) project.
---
In order to enforce splitting all vendors dependencies from `main` and reuse them from `main` and `preview` chunks you must configure the `preview` cacheGroup as:
```
preview: {
name: 'preview',
chunks: 'all',
enforce: true,
priority: 0,
test(module, chunks) {
return chunks.some(chunk => chunk.name === 'preview');
}
}
```
Note that the cacheGroup for `preview` chunk has lower priority than the `vendors` one to ensures that all `main` dependencies which are also dependencies in `preview` are also referenced from the `preview` bundle.
Upvotes: 3 <issue_comment>username_2: Or:
```js
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
// Exclude preview dependencies going into vendors.
chunks: chunk => chunk.name !== "preview"
},
},
},
```
Please read the [documentation of `chunks`](https://webpack.js.org/plugins/split-chunks-plugin/#splitchunkschunks) for more details.
Upvotes: 2
|
2018/03/15
| 611 | 2,541 |
<issue_start>username_0: I want to execute a function inside a remote URL. I know the page URL where the function is and I know the Function name too. The server-side application is built on NodeJs Express. And the function itself look like this
```
function executer(param1, parama2){
//logic
return true;
}
```
Is there any way to achieve this?<issue_comment>username_1: The following Webpack 4 config only splits `main` module vendor dependencies into a separate chunk. Other dependencies for `preview` remains within that chunk.
```
{
entry: {
main: './test/application.js',
preview: './test/preview.js'
},
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
name: 'vendors',
chunks: 'all',
enforce: true,
priority: 1,
test(module, chunks) {
const name = module.nameForCondition && module.nameForCondition();
return chunks.some(chunk => chunk.name === 'main' && /node_modules/.test(name));
}
}
}
}
}
}
```
Shared dependencies are included in the vendors bundle unless we configure the `preview` cacheGroup with higher priority to enforce that all dependencies included here should remain inside this chunk.
For more Webpack 4 related info/config you can review this [webpack-demo](https://github.com/carloluis/webpack-demo) project.
---
In order to enforce splitting all vendors dependencies from `main` and reuse them from `main` and `preview` chunks you must configure the `preview` cacheGroup as:
```
preview: {
name: 'preview',
chunks: 'all',
enforce: true,
priority: 0,
test(module, chunks) {
return chunks.some(chunk => chunk.name === 'preview');
}
}
```
Note that the cacheGroup for `preview` chunk has lower priority than the `vendors` one to ensures that all `main` dependencies which are also dependencies in `preview` are also referenced from the `preview` bundle.
Upvotes: 3 <issue_comment>username_2: Or:
```js
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
// Exclude preview dependencies going into vendors.
chunks: chunk => chunk.name !== "preview"
},
},
},
```
Please read the [documentation of `chunks`](https://webpack.js.org/plugins/split-chunks-plugin/#splitchunkschunks) for more details.
Upvotes: 2
|
2018/03/15
| 641 | 2,398 |
<issue_start>username_0: I have a spring boot application that is throwing the following:
>
> 2018-01-14 01:02:56.863 ERROR 372 --- [io-8080-exec-14] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
>
>
>
The application runs and behaves as expected. I've seen the error in the logs a few times but can't seem to see why/where its happening.
There is no other information in the log about the error.
I've had a look at the logs to see what happened before and after the error occurred and everything seemed fine.
I have also turned the log level to ALL and still the no useful error message.
Any ideas why I am getting this error and how I can get my application to throw more useful errors.
What stand out from the error message is `with path [] threw exception`. I'm not sure what `[]` is.<issue_comment>username_1: >
> Any ideas why I am getting this error and how I can get my application to throw more useful errors.
>
>
>
The root cause is a `NullPointerException` (NPE) thrown at some point in the call stack of the `DispatcherServlet`.
Unfortunately, you don't get a complete stacktrace of the NPE in your log. Have you checkout the standard output for the stacktrace? Normally Spring Boot is really conservative configured when it comes to swallowing stacktraces. Meaning: there should be a point where you can see the complete stacktrace. My guess: a logfile in the working directory or the standard output of the application (e.g. terminal screen).
>
> What stand out from the error message is with path [] threw exception. I'm not sure what [] is.
>
>
>
This is the path part of the request. `[]` means the path is an empty string. Spring used the `[]`-notation to signal you that there is an empty string. Normally it would look like `[/users/34]`.
My guess is: you called something like `http://localhost:8080` so no trailing slash is present, which renders the path part of the url to an empty string.
Upvotes: 2 <issue_comment>username_2: I had the same issue and was able to resolve it by using another JDK.
I switched from openjdk 8 to openjdk 9 (both ubuntu 18.04) by running
`sudo apt install default-jdk`
(check if it update your symlinks with `java -version`
Upvotes: -1
|
2018/03/15
| 677 | 2,559 |
<issue_start>username_0: Imagine this files paths:
1. */root/subfolder/filename.csv*
2. */root/subfolder/subfolder2/filename2.csv*
Can I extract data from "filename.csv" and "filename2.csv" without explicitly write their paths?
I want to do something like:
```
@var = EXTRACT column FROM "/root/{*}.csv" USING Extractors.Csv(skipFirstNRows:1);
```
**Is it possible?**<issue_comment>username_1: Yes you can! The formatting is almost exactly what you thought it would be. It's done through filesets in U-SQL, and they allow you to search entire directories of folders and also extract information from the path. You define wildcard characters of your choice anywhere in the folder path, and then save that character as a virtual column in your extract statement.
```
DECLARE @file_set_path string = "/Samples/Data/AmbulanceData/vehicle{vid}_{date:MM}{date:dd}{date:yyyy}.csv";
@data =
EXTRACT vehicle_id int,
entry_id long,
event_date DateTime,
latitude float,
longitude float,
speed int,
direction string,
trip_id int?,
vid int, // virtual file set column
date DateTime // virtual file set column
FROM @file_set_path
USING Extractors.Csv();
```
Notice the regular wild card character in the path {vid}, and how it's saved in the extract statement as a new column with the same name (that you can then use to filter your query). The date virtual column is a special feature of filesets that allows you to automatically bundle dates in filesets into a single DateTime object.
Filesets also work in directory paths the same way - you could have a set of subfolders divided by date and version, and use "/Samples/{date:yyyy}/{date:MM}/{date:dd}/{type}/RCV\_{vid}.csv" and store the virtual columns identically as above.
Let me know if you have any more questions!
Upvotes: 0 <issue_comment>username_2: Unfortunately, this feature (a Kleene-\* like recursive folder navigation) is not yet available in filesets, but is on our long term roadmap. Please file/upvote for this feature at <http://aka.ms/adlfeedback>.
The current work-around is to have one step wild card `EXTRACT`s for each level you expect to encounter and then UNION ALL them together. E.g.,
```
@d1 = EXTRACT ... FROM "/fixpath/{*}" USING ... ;
@d2 = EXTRACT ... FROM "/fixpath/{*}/{*}" USING ...;
@d3 = EXTRACT ... FROM "/fixpath/{*}/{*}/{*}" USING ...;
....
@data =
SELECT * FROM @d1 UNION ALL SELECT * FROM @d2 UNION ALL SELECT * FROM @d3 UNION ALL ...;
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 358 | 1,045 |
<issue_start>username_0: I have a rather big select control on my form and I want to take advantage of the space next to it:
[](https://i.stack.imgur.com/PV0bT.png)
I don't want to use a table since this will cause the wrong effect on mobile devices. What I need is this:
[](https://i.stack.imgur.com/2BpTz.png)
Here is my code:
```
label1
option label
option 1
option 2
option 3
option 4
option 5
option 6
option 7
option 8
option 9
label2
label3
```<issue_comment>username_1: Nest the form in two 50% width (col-6) grid columns...
<https://www.codeply.com/go/GJXkHUC1At>
```
label1
label2
label3
option label
option 1
option 2
option 3
option 4
option 5
option 6
option 7
option 8
option 9
```
Upvotes: 2 <issue_comment>username_2: I'd rather use Daemonite for Bootstrap 4 and use Floating labels for advanced forms : <https://daemonite.github.io/material/docs/4.0/material/text-fields/>
Upvotes: 0
|
2018/03/15
| 230 | 782 |
<issue_start>username_0: When I want to use the mathematical methods in Java like `abs` `acos` I have to put it like this: `Math.abs(int a)`, `Math.acos(double a)`.
But what does it really mean?
Is `Math` the name of the class or some object? How does it work?<issue_comment>username_1: >
> The class Math contains methods for performing basic numeric
> operations such as the elementary exponential, logarithm, square root,
> and trigonometric functions.
>
>
>
<https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html>
Upvotes: 1 <issue_comment>username_2: Math class has static methods. So you can invoke it like:
```
int absolute = Math.abs(-123);
// absolute now has +123
```
A static method can be invoked without creating an instance of a class.
Upvotes: 2
|
2018/03/15
| 461 | 1,586 |
<issue_start>username_0: I'm having some problems with Jquery/Ajax.
This is my code for the form :
```
Email
Name
Phone
Register
```
And this is my code to AJAX/Jquery:
```
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
```
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.<issue_comment>username_1: You dont have submit class. You have id="submit"
```
$("#submit").on("click", function(e) {
```
Use this and it should work.
Also change `type="submit"` to `type="button"` or in your js code you need to add
```
e.preventDefault();
```
Upvotes: 0 <issue_comment>username_2: Your code doesn't work because you were using the `class` selector token `.` (dot) instead of the `id` selector token `#` hashtag. Further details can be found on the [documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors)
Change this instruction
```
$(".submit").on("click", function(e) // …
```
to
```
$("#submit").on("click", function(e) // …
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 470 | 1,612 |
<issue_start>username_0: I have installed several versions of the JDK with brew cask:
```
MacBook-Pro:bin myusername$ brew cask list
java java8 soapui
```
And set the default one to be java8:
```
MacBook-Pro:bin myusername$ jenv global
1.8.0.162
```
but when I lanuch maven it does not found `$JAVA_HOME` and fallbacks to using `java_home`:
```
MacBook-Pro:bin myusername$ /usr/libexec/java_home
/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
```
The maven script:
```
#!/bin/bash
JAVA_HOME="${JAVA_HOME:-$(/usr/libexec/java_home)}" exec "/usr/local/Cellar/maven@3.2/3.2.5/libexec/bin/mvn" "$@"
```
I could change the `mvn` script but if I can fix the `JAVA_HOME` issue it would be really much better. Any hints?<issue_comment>username_1: For this you have to enable the jenv maven plugin. From the [documentation](https://github.com/gcuisinier/jenv#plugins):
>
> Let's say you want Maven to use the JDK activated with Jenv, not the >default JAVA\_HOME configuration. You need to activate Jenv's maven plugin.
>
>
>
```
$ jenv enable-plugin maven
maven plugin activated
```
>
> Note: The enable-plugin functionality is system wide not local to the shell, or temporary - you only need to do each one once.
>
>
>
Upvotes: 2 <issue_comment>username_2: Make sure maven is not using this file to set JAVA\_HOME
~/.mavenrc
If so, delete it and make sure that java\_home is set elsewhere (either using jenv or explicitly setting JAVA\_HOME as per your need.
Upvotes: 0
|
2018/03/15
| 895 | 3,036 |
<issue_start>username_0: Table data is:
```
Info
----------------------------------------
num name age expenseN cost group
1 a 20
2 b 21
InfoDetail
----------------------------------------
num expenseN cost group
1 001 10.00 x
2 001 20.00 x
3 002 20.00 x
4 003 30.00 y
```
This is code:
```
public class _infoRepository
{
public string name { get; set; }
public int age { get; set; }
public string expenseN { get; set; }
public decimal cost { get; set; }
public string group { get; set; }
}
public class _infoDetailRepository
{
public string expenseN { get; set; }
public decimal cost { get; set; }
public string group { get; set; }
}
List result = new List();
var info = \_infoRepository.Query(p => p.name = "a").FirstOrDefault();
var listInfoDetail = \_infoDetailRepository.Query(p => p.group == "x").ToList();
for (int i = 0; i < listInfoDetail.Count; i++)
{
result.Add(new Info()
{
name = info.name,
age = info.age,
expenseN = listInfoDetail[i].expenseN,
cost = listInfoDetail[i].cost,
group = listInfoDetail[i].group
});
}
return result;
```
After running this code, the result of the `result` variable is as follows:
```
result
--------------------------------------------------
num name age expenseN cost group
1 a 20 001 10.00 x
2 a 20 001 20.00 x
3 a 20 002 20.00 x
```
However, that was not the result I wanted, the result I expected was like this:
```
result
--------------------------------------------------
num name age expenseN cost group
1 a 20 001 30.00 x
2 a 20 002 20.00 x
```
After all, i want to group by and sum the `result` variable to give me the desired result. Someone please help me in this situation, thanks<issue_comment>username_1: Update your for loop like:
```
for (int i = 0; i < listInfoDetail.Count; i++)
{
if (result.Count(j => j.expenseN == listInfoDetail[i].expenseN) == 0)
{
result.Add(new Info
{
name = info.name,
age = info.age,
expenseN = listInfoDetail[i].expenseN,
cost = listInfoDetail.Where(j => j.expenseN == listInfoDetail[i].expenseN).Sum(j => j.cost),
group = listInfoDetail[i].group
});
}
}
```
Upvotes: 0 <issue_comment>username_2: the `listInfoDetail` Must be grouped
Instead of
```
var listInfoDetail = _infoDetailRepository.Query(p => p.group ==
"x").ToList();
```
Use
```
var listInfoDetail =_infoDetailRepository.Query(p => p.group =="x")
.ToList().GroupBy(P=>new {P.expenseN, P.group})
.Select(P=>new
{P.Key.expenseN, P.Key.group, cost=P.Sum(p=>p.cost)}
);
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,147 | 3,700 |
<issue_start>username_0: I am writing a query which unpivots the table. The issue is that based on the mapping file I would like to either input values as a constant or variable.
For example - if in mapping file the ExtDate is constant, e.g. ExtDate = '2017-12-31' I want to use this value (2017-12-31). However if ExtDate starts with 'Var' I would like to use variable values - e.g. when ExtDate = VarOpenDate, then I want to fulfill the column with values from column OpenDate. Below exemplary rows from MappingFile:
```
CREATE TABLE MappingFile (ColNum INT, Variable CHAR(50), IsUsed CHAR(50), ID CHAR(50), ExtDate CHAR(50), DataDate CHAR(50), ValueDate CHAR(50), Flag CHAR(50), Unit CHAR(50))
INSERT INTO MappingFile VALUES (1, 'ClientId', 'YES', 'VarAcctID', '2017-12-31', 'VarSigningDate', 'VarSigningDate', 'X', '')
INSERT INTO MappingFile VALUES (2, 'ProductGroup', 'YES', 'VarAcctID', 'VarOpenDate', 'VarSigningDate', 'VarSigningDate', 'X', '')
INSERT INTO MappingFile VALUES (3, 'ProductType', 'YES', 'VarAcctID', 'VarOpenDate', 'VarSigningDate', 'VarSigningDate', 'X', '')
```
In order to do this I wrote a code below (this is a simplification, as there are more columns and whole query is in the inserting while loop).
```
DECLARE @I INT = 2
DECLARE @COL CHAR(50)
DECLARE @ID CHAR(50)
DECLARE @EDT CHAR(50)
DECLARE @DDT CHAR(50)
DECLARE @DTS CHAR(50) = 'dataset_name'
SET @ID = (SELECT ID FROM MappingFile WHERE ColNum = @I)
SET @EDT = (SELECT ExtDate FROM MappingFile WHERE ColNum = @I)
SET @DDT = (SELECT DataDate FROM MappingFile WHERE ColNum = @I)
SET @COL = (SELECT Variable FROM MappingFile WHERE ColNum = @I)
EXEC('
SELECT ''' + @DTS + ''',
CASE WHEN SUBSTRING(''' + @ID + ''', 1, 3) = ''Var'' THEN ' + @ID + ' ELSE ''' + @ID + ''' END,
CASE WHEN SUBSTRING(''' + @EDT + ''', 1, 3) = ''Var'' THEN ' + @EDT + ' ELSE ''' + @EDT + ''' END,
CASE WHEN SUBSTRING(''' + @DDT + ''', 1, 3) = ''Var'' THEN ' + @DDT + ' ELSE ''' + @DDT + ''' END,
''' + @COL + ''',
' + @COL + '
FROM ' + @DTS + '
WHERE ' + @COL + ' IS NOT NULL
')
```
Unfortunately in case when ExtDate is constant string the query gives me an error. It is caused by the fact that the result expression:
```
THEN ' + @EDT + '
```
returns string which is not a name of column. This gives me an error, altough it shouldn't because if
```
SUBSTRING(''' + @ID + ''', 1, 3) <> ''Var''
```
then the result of the case is
```
' ELSE ''' + @DDT + '''
```
which is not a column name, but a constant string.<issue_comment>username_1: Update your for loop like:
```
for (int i = 0; i < listInfoDetail.Count; i++)
{
if (result.Count(j => j.expenseN == listInfoDetail[i].expenseN) == 0)
{
result.Add(new Info
{
name = info.name,
age = info.age,
expenseN = listInfoDetail[i].expenseN,
cost = listInfoDetail.Where(j => j.expenseN == listInfoDetail[i].expenseN).Sum(j => j.cost),
group = listInfoDetail[i].group
});
}
}
```
Upvotes: 0 <issue_comment>username_2: the `listInfoDetail` Must be grouped
Instead of
```
var listInfoDetail = _infoDetailRepository.Query(p => p.group ==
"x").ToList();
```
Use
```
var listInfoDetail =_infoDetailRepository.Query(p => p.group =="x")
.ToList().GroupBy(P=>new {P.expenseN, P.group})
.Select(P=>new
{P.Key.expenseN, P.Key.group, cost=P.Sum(p=>p.cost)}
);
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,486 | 4,976 |
<issue_start>username_0: I have a JSON file that I wish to access, based on HTML option value attribute.
I can access the data, and pick stuff out, but like I wrote earlier, I like to do it based on what is chosen from the list.
So I wanna map option value attribute with p in the json file.
So my list looks like this
```
Choose city...
Place1
Place2
Place3
```
And my JSON looks like this:
```
{
data: [{
date: "2018031406",
p: [{
lon: -7.777,
lat: xxxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100225.25,
temperature: 4.34227,
wind - dir: 122.00003,
wind - speed: 13.022041,
weather - symbol: 3
},
{
lon: -6.666,
lat: xxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100230.75,
temperature: 3.77977,
wind - dir: 120.87503,
wind - speed: 13.006416,
weather - symbol: 3
}
]
},
{
date: "2018031407",
p: [{
lon: -7.777,
lat: xxxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100225.25,
temperature: 4.34227,
wind - dir: 122.00003,
wind - speed: 13.022041,
weather - symbol: 3
},
{
lon: -6.666,
lat: xxxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100230.75,
temperature: 3.77977,
wind - dir: 120.87503,
wind - speed: 13.006416,
weather - symbol: 3
}
]
}
]
}
```
So the layout is based on what time it is, so I have this set up in jQuery:
```
jQuery(document).ready(function() {
var location = 'folder/folder2/folder3/area/area.json';
jQuery.getJSON(location, function(json) {
function pad2(n) {
return n < 10 ? '0' + n : n
}
var date_now = new Date();
date_test = date_now.getFullYear().toString() + pad2(date_now.getMonth() + 1) + pad2(date_now.getDate()) + pad2(date_now.getHours());
var index = json.data.findIndex(function(item, i) {
return item.date === date_test
});
//This I can use to see which index number is the current hour
//I have weather data a couple of hours backwards, and alot forward (in time).
//console.log(index);
//Manually fetch data
/*--------------------Temperature--------------------------------------*/
//Lets say - index+1 is date: "2018031407" and p[1] is the second p from json file - which indicates the hour now +1 (date) and area (p).
var some_temp = JSON.stringify(json.data[index + 1].p[1]["temperature"]);
//console.log(some_temp);
var some_temp2 = Math.round(some_temp);
console.log(some_temp2);
jQuery(".div_temp").prepend(some_temp2);
/*------------------------Temperature ends----------------------------------------*/
});
});
```
How should I approach the task? Having difficulties getting on. I'm a noob at this.
An exaple would be that Place1 should equal p[0], Place2 equal p[1] etc...<issue_comment>username_1: If I understand the question right, you first need to pick the right data set based on the date property and then you will filter it again based on the place.
You can do this by using the filter method as your data is in an array.
```
var yourJson = "{}"; // your json variable
var dataForDate = yourJson.data.filter(function( obj ) {
return obj.date == '2018031406'; // your filter criteria
});
```
`dataForDate` will be another array and if you have only one matching property, you can access it by `dataForDate[0]`
After this you can implement the same filter function if you want to filter location data based on some property.
If you want to loop through all the `p`s you can do the following
```
$.each( dataForDate[0].p, function( index, value ){
// you can access all the properties here
// example
// value.lat
});
```
Upvotes: 1 <issue_comment>username_2: This is what I ended up using...
```
//Put the json file to a variable
var location = 'folder/script.json';
//make a function called json, using the locaction variable
jQuery.getJSON(location, function(json) {
jQuery("select").change(function(){
jQuery(this).find("option:selected").each(function(){
var optionValue = jQuery(this).attr("value");
var i;
for (i = 0; i < JSON.stringify(json.data[index].p.length); ++i) {
//console.log(i);
if (i == optionValue) {
console.log(optionValue);
var some_temp = JSON.stringify(json.data[index].p[i]["temperature"]);
var some_temp2 = Math.round(some_temp);
jQuery(".temp_div").html(some_temp2);
}
}
});
}).change();
});
```
Upvotes: 1 [selected_answer]
|
2018/03/15
| 549 | 2,046 |
<issue_start>username_0: For example I have 2 main models in my django app:
```
class Employee(Model):
name = CharField(max_length=50)
class Client(Model):
title = CharField(max_length=50)
```
Abstract base class for phones:
```
class Phone(Model):
number = CharField(max_length=10)
class Meta:
abstract = True
```
Inherited separate classes for Employee and for Client:
```
class EmployeePhone(Phone):
employee = ForeignKey(Employee, on_delete=CASCADE, related_name='employee_phones')
class ClientPhone(Phone):
client = ForeignKey(Client, on_delete=CASCADE, related_name='client_phones')
```
It works but I don't like it, I would prefer to keep just one Phone model instead of 3. I know I could use Generic-Models but unfortunately that's not longer an option, because my app is actually REST-API and it seems to be impossible to create Generic-Object while creating Parent-Object. So is there any solution to keep things clean and DRY ?<issue_comment>username_1: How about keeping 1 Phone class and linking Employee and Customer to Phone via a Foreign Key and removing the abstract :).
Upvotes: 0 <issue_comment>username_2: How about moving `EmployeePhone` (`ClientPhone`) as a ManyToManyField in `Employee` (`Client`) model related to `Phone` model?
```
class Employee(Model):
name = CharField(max_length=50)
phones = ManyToManyField(Phone, ...)
```
Upvotes: 0 <issue_comment>username_3: Other answers present good ideas how you can normalise the database, but if you'd like to keep the schema the same and just avoid repeating the same thing in the code, maybe a [custom field subclass](https://docs.djangoproject.com/en/2.0/howto/custom-model-fields/#writing-a-field-subclass) is what you're after?
Example:
```
# fields.py
class PhoneField(models.CharField):
def __init__(self, **kwargs):
kwargs.setdefault('max_length', 50)
...
super().__init__(**kwargs)
# models.py
class Employee(models.Model):
phone = PhoneField()
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 711 | 2,838 |
<issue_start>username_0: I am new. Trying to do a database retrieve demo to login a system, here is my function code:
I will call `goLogin` function and pass in the input id and password for validation and I will also get all the id from Database for checking purpose. After ID is correct, only go check the password.
```
public void goLogin(String id, String pass){
String[99] allID = getAllIDFromDB();
for(int i=0;i
```
My peers say I was using too much if else and I can shorten the code and make the program better, and I faced some issue on looping for example when ID and Password are correct, the program will still continue the loop.
Is there any suggestion to make this function better?<issue_comment>username_1: First of all, Why retrieve all the user IDs from the database instead make sql query to retrieve the row of this user based on this id.
something like this:
```
Select * from `users` where id = {id};
```
And if you want to stop looping a wrong password was found, add break in the else scope.
Upvotes: 1 <issue_comment>username_2: Yes, you could even do:
```
Select * from `users` where id = {id} and password = {<PASSWORD>}
```
Also, to compare `String`s in Java, you should use `string1.equals(string2)`, not the `==` operator.
Upvotes: 0 <issue_comment>username_3: In my opinion, the main issue of your program is your logic to implement the Login Function.
Login Function implementation can be implemented with various pattern, Based on your program code I will assume you just want a Most Basic Login Function that allow the program to do validation on user input ID and Password.
Actually, this Basic validation can be done in your Database Query. You can just take the user input ID and Password and let Database Query to do filtering and determine if the user input ID and Password is valid or invalid.
First use this Query:
```
Select DATABASEID From Database Where DATABASEID=inputID and DATABASEPASSWORD=inputPassword;
```
Java Code:
```
public void goLogin(String id, String pass){
// Since i changed the Query, you need to pass in the ID and Password to let the Query to filtering
String DatabaseID = getIDFromDB(id, pass);
// Simple Logic, If DatabaseID have value which mean the ID and Password is correct
// Because the Database Query will return null if the ID and Password is Wrong
if(DatabaseID!=null){
System.out.println("ID and Password is Correct.");
}else{
System.out.println("ID or Password is Incorrect.");
}
}
```
This Logic is very simple, but also come with some drawback, the only Advantage Compare to your code are:
1. Still able to do basic validation on User Input ID and Password.
2. Remove `for loop` and other unnecessary `if else`.
3. Only access database for once.
Hope this would help.
Upvotes: 1 [selected_answer]
|
2018/03/15
| 1,876 | 6,454 |
<issue_start>username_0: I have create sample React Native project and following the tutorial as per react native website.
I have try to run the application IOS simulator, its throwing error as below ,
```
** BUILD FAILED **
The following build commands failed:
PhaseScriptExecution Install\ Third\ Party /Users/Test/Documents/REACTJS/SampleReactNative/ios/build/Build/Intermediates.noindex/React.build/Debug-iphonesimulator/double-conversion.build/Script-190EE32F1E6A43DE00A8543A.sh
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/SampleReactNative.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/SampleReactNative.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
```
my environment setup information,
* node version v9.8.0 npm version 5.6.0 react-native-cli: 2.0.1
react-native: 0.54.2 xcode 9.2
Please help us to resolve the issues.<issue_comment>username_1: Do you have CFBundleIdentifier in your Info.plist?
If not than add it for eg. com.ios.learning
[](https://i.stack.imgur.com/Bwaf7.png)
Upvotes: 0 <issue_comment>username_2: I have the same problem right after init:
`react-native init myapp
cd myapp
react-native run-ios`
..although run-android was fine.
Not a solution but a workaround for the moment, maybe be to init using a lower version of RN:
`react-native init myapp --version react-native@0.51.0`
That builds okay.
Similar in an existing project, install an older version of RN.
Other versions before 0.54.2 might work but I haven't tried.
(edited 2018/4/2)
Found my solution from this link: <https://github.com/facebook/react-native/issues/18238>
>
> RN 0.54 requires types available since iOS 11. So you have to upgrade your xcode and set minimum iOS version in your app to 11
>
>
>
In short, upgraded OSX & Xcode to the latest. (As of today, OSX 10.13.4 Xcode & 9.3)
Upvotes: 2 <issue_comment>username_3: Run the command:
```
react-native upgrade
react-native run-ios
```
or:
```
react-native run-android
```
Upvotes: 2 <issue_comment>username_4: This may happen because of some library files not found.You need to follow some steps That I have done and it is worked perfectly for me.
1.) go to Xcode project -> Target -> select build Phase -> Go to target dependies -> Click on + -> add "react" and press add.
2.) Xcode > Product -> scheme > manage sceme -> click on + button -> targetName(React) -> Okay -> make shared of this by select checkbox under shared column.
3.) Clean your project and try to build, If it is getting some error like "**glog/logging.h** file not found" or "**cofig.h** file not found" in Xcode and "CFBundleIdentifier not exist" then do not worry. You are just one step far. This is may occurs if you are missing config.h file, For this you need to update config.h file. For this
4.) follow below steps
a.) close your Xcode
b.) Open terminal with the project (Or you can directly left click your project and drag your folder to closed terminal, [It will automatically take the path from your that corresponding folder])
c.) write command
>
> cd node\_modules/react-native/third-party/glog-0.3.4/
>
>
>
d.) Run the configure scripted file by the command
>
> ./configure
>
>
>
e.) now close terminal and go to terminal with your project root path. now try final run your iOS project by
>
> react-native run-ios
>
>
>
Upvotes: 2 <issue_comment>username_5: Usually, this error comes up due to inconsistent versions (either of react-native, OS or XCode). I had the same issue with react-native `v0.57.0` on MacOS Sierra and XCode `v9.x`.
All I had to do was to upgrade to High Sierra and then XCode to `v10.0`.
Otherwise, you'd have to use an older version of react-native either by [downgrading it](https://stackoverflow.com/questions/38024203/proper-mechanism-to-downgrade-react-native)
or by initialising a project with an older version
```
react-native init test --version react-native@0.x.x
```
Upvotes: 0 <issue_comment>username_6: For **XCODE 10.0**,
I did two things
1) [check out this answer](https://stackoverflow.com/a/41854111/6631254)
which basically says
Go to File -> Project settings
Click the Advanced button
Select "Custom" and select "Relative to Workspace" in the pull down
Change "Build/Products" to "build/Build/Products"
2) If (1) doesn't work for you then open your project from xcode
go to project navigator and select your project name --> go to info --> use **debug** for command-lines builds.
[do this](https://i.stack.imgur.com/bIfvW.png)
3) go to terminal and `react-native run-ios`
Upvotes: 2 <issue_comment>username_7: Try to add CFBundleIdentifier in the Info.plist as:
```
CFBundleIdentifier
org.reactjs.native.example.$(PRODUCT\_NAME:rfc1034identifier)
```
Upvotes: 1 <issue_comment>username_8: npm uninstall react-native
delete ios and android folder
then run :
npm install react-native
react-native upgrade
Upvotes: -1 <issue_comment>username_9: I experienced this issue due to the xcode 12 upgrade, and I solved my problem by upgrading my rn by using this command:
```
react-native upgrade
```
then go to podfile change your:
```
pod 'ReactCommon/callinvoker', :path => "../node_modules/react-native/ReactCommon"
```
to:
```
pod 'React-callinvoker', :path => "../node_modules/react-native/ReactCommon/callinvoker"
```
Upvotes: 1 <issue_comment>username_10: In my case, just delete the `build` directory, `Pods` directory, `node_modules` directory and running `yarn install`, `pod install` and `npx react-native run-ios` solves the issue.
Upvotes: 0 <issue_comment>username_11: React Native is trying to install your app on a different app name for some reason. What you can do is in Xcode --> build settings --> packaging --> change the product name to the one given in the path which the simulator is trying to install.
Look at this: <https://amala-gopal.medium.com/entry-cfbundleidentifier-does-not-exist-6098b90516f6>
Upvotes: 0
|
2018/03/15
| 877 | 3,066 |
<issue_start>username_0: I'm trying to learn vue and with that I want to integrate it with laravel too..
I simply want to send the user id from blade to vue component so I can perform a put request there.
Let's say I have this in blade:
```
```
How can I send Auth::user()->id into this component and use it.
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!<issue_comment>username_1: If you are serving files through Laravel
Then here is the trick that you can apply.
In Your `app.blade.php`
```
@if(auth()->check())
window.User = {!! auth()->user() !!}
@endif
```
Now you can access `User` Object which available globally
Hope this helps.
Upvotes: 2 <issue_comment>username_2: To pass down data to your components you can use `props`. Find more info about props over [here](https://v2.vuejs.org/v2/guide/components.html#Props). [This](https://v2.vuejs.org/v2/style-guide/#Prop-definitions-essential) is also a good source for defining those props.
You can do something like:
```
```
OR
```
```
And then in your `Example.vue` file you have to define your prop. Then you can access it by `this.userId`.
Like :
```
export default {
props: ['userId'],
mounted () {
// Do something useful with the data in the template
console.dir(this.userId)
}
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_3: Just to add for those who still get error.
For me this still gives error in console and instead showing html page I saw white screen.
```
[Vue warn]: Error compiling template:
invalid expression: Unexpected identifier in
Coupling to connect 2 rods М14 CF-10
Raw expression: :product="Coupling to connect 2 rods М14 CF-10"
```
Though in error I can see that $item->title is replaced with its value.
So then I tried to do like that
And I have fully working code.
/components/askquestionmodal.vue
```
{{ product }}
export default {
name: "AskQuestionModal",
props: ['product'],
mounted() {
console.log('AskQuestionModal component mounted.')
}
}
```
Upvotes: -1 <issue_comment>username_4: Calling component,
```
```
In component,
```
export default {
props: ['userId'],
mounted () {
console.log(userId)
}
}
```
Note - When adding value to prop **userId** you need to use **user-id** instead of using camel case.
Upvotes: 0 <issue_comment>username_5: <https://laravel.com/docs/8.x/blade#blade-and-javascript-frameworks>
Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
```
var app = <?php echo json\_encode($array); ?>;
```
However, instead of manually calling json\_encode, you may use the @json Blade directive. The @json directive accepts the same arguments as PHP's json\_encode function. By default, the @json directive calls the json\_encode function with the JSON\_HEX\_TAG, JSON\_HEX\_APOS, JSON\_HEX\_AMP, and JSON\_HEX\_QUOT flags:
```
var app = @json($array);
var app = @json($array, JSON\_PRETTY\_PRINT);
```
Upvotes: 0
|
2018/03/15
| 918 | 3,409 |
<issue_start>username_0: What I want to do is get data user and copy to a new user (create a new user). This is what I'm doing:
```
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private int roleId;
@Column(name = "role")
private String role;
public Role() {
}
}
@Entity
@Table(name = "usuario")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int id;
@Column(name = "email")
private String email;
@Column(name = "password", nullable=false, length=60)
private String password;
@Column(name = "name", unique=true, nullable=false, length=6)
private String name;
@Column(name = "last_name")
private String lastName;
@Column(name = "active", nullable=false)
private int active;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set roles;
public Users() {
}
}
```
I get data from one existing user:
```
Optional user = usersRepository.findByName(name);
//create a new User to persist
Users newUser = new Users();
newUser.setName("new name");
newUser.setActive(1);
newUser.setEmail(user.get().getEmail());
newUser.setLastName(user.get().getLastName());
newUser.setPassword(user.get().getPassword());
Set roles = user.get().getRoles();
newUser.setRoles(roles);
usersRepository.save(newUser);
```
I get this message:
**Found shared references to a collection: model.authentication.Users.roles;
nested exception is org.hibernate.HibernateException: Found shared references to a collection: model.authentication.Users.roles**
**UPDATE 1 (SOLVED)**
```
Optional user = usersRepository.findByName(codalojamiento);
Users newUser = new Users();
newUser.setName("new name");
newUser.setActive(1);
newUser.setEmail(user.get().getEmail());
newUser.setLastName(user.get().getLastName());
newUser.setPassword(user.get().getPassword());
Set newRoles = new HashSet();
Set roles = user.get().getRoles();
for (Role r : roles) {
newRoles.add(r);
}
newUser.setRoles(newRoles);
usersRepository.save(newUser);
```
Any suggestion?
Thanks<issue_comment>username_1: In JPA `Find` method also flushes the data. Here when you have retreived the `user` using `find` method it's moved to managed state.
Then you have taken the roles collection from `user` object and assigned it to `newUser`. Now basically you have two entities have same collection references which is not allowed.
Either you can detach `user` from persistence context before saving `newUser` or clone the roles collection before adding it to `newUser`.
Upvotes: 1 <issue_comment>username_2: There are multiple things that could go wrong:
* Since you are linking a user to multiple roles, but at the same time, multiple users can have the same role, the relation should be @ManyToMany, not @OneToMany.
* Secondly, if you insist on having a @OneToMany relationship, you are linking the new user to the roles of the existing user, so a solution might be to create new roles for that user that are identical to the roles of the first user
Personally, i would suggest using a @ManyToMany, and that should fix the problem
Upvotes: 2
|
2018/03/15
| 576 | 2,499 |
<issue_start>username_0: I'm a novice looking to learn by doing - i'm writing a small windows form app which will display various text output based on the selection from a dropdownbox
I have searched for how to do this but so far I've not found an answer. I simply want the IOPS.text value to display in a text box, based on what value has been selected from the combobox
What I have so far is this:
```
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
//Insert values for block size
{
comboBox1.SelectedValue = ("4Kb");
ShowIOPS.Text = ("4096");
}
{ comboBox1.SelectedValue = ("8Kb");
ShowIOPS.Text = ("8192");
}
{
comboBox1.SelectedValue = ("16Kb");
ShowIOPS.Text = ("16384");
}
{
comboBox1.SelectedValue = ("32Kb");
ShowIOPS.Text = ("32768");
}
{ comboBox1.SelectedValue = ("64Kb");
ShowIOPS.Text = ("65536"); }
```
Whats happening now is that no matter what combobox value is selected, it displays the botom iops.text value in the textbox
I'm sure I've missed something very very simple and obvious, but any help would be greatly appreciated!<issue_comment>username_1: In JPA `Find` method also flushes the data. Here when you have retreived the `user` using `find` method it's moved to managed state.
Then you have taken the roles collection from `user` object and assigned it to `newUser`. Now basically you have two entities have same collection references which is not allowed.
Either you can detach `user` from persistence context before saving `newUser` or clone the roles collection before adding it to `newUser`.
Upvotes: 1 <issue_comment>username_2: There are multiple things that could go wrong:
* Since you are linking a user to multiple roles, but at the same time, multiple users can have the same role, the relation should be @ManyToMany, not @OneToMany.
* Secondly, if you insist on having a @OneToMany relationship, you are linking the new user to the roles of the existing user, so a solution might be to create new roles for that user that are identical to the roles of the first user
Personally, i would suggest using a @ManyToMany, and that should fix the problem
Upvotes: 2
|
2018/03/15
| 580 | 2,248 |
<issue_start>username_0: When i'm trying to mock external HTTP API with MockServer, mockserver returns `java.lang.IllegalArgumentException`
This is the test code:
```
new MockServerClient("localhost", 1080)
.when(request("/messages")
.withMethod("POST")
.withQueryStringParameters(
param("subject", "integration-test-subject")
)
).respond(response().withStatusCode(200));
```
This is the exception:
```
java.lang.IllegalArgumentException: Exception while parsing
[
{
"httpRequest":{
"method":"POST",
"path":"/messages",
"queryStringParameters":{
"subject":[
"integration-test-subject"
]
}
},
"httpResponse":{
"statusCode":200
},
"times":{
"remainingTimes":0,
"unlimited":true
},
"timeToLive":{
"unlimited":true
}
}
] for Expectation
```
And this is the Jackson exception:
```
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of FIELD_NAME token
at
[
Source:(String)" {
"httpRequest":{
"method":"POST",
"path":"/messages",
"queryStringParameters":{
"subject":[
"integration-test-subject"
]
}
},
"httpResponse":{
"statusCode":200
},
"times":{
"remainingTimes":0,
"unlimited":true
},
"timeToLive":{
"unlimited":true
}
}
```
I'm trying to send `application/x-www-form-urlencoded` request with body
```
subject:integration-test-subject
```
When `.withQueryStringParameters(param("subject", "integration-test-subject"))` is not present in test, then it goes OK.
How to fix this?<issue_comment>username_1: the solution of this problem is to add to your project:
```
com.fasterxml.jackson.core
jackson-databind
2.9.3
```
im my project with Spring Boot 2 this solution worked fine.
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is an issue in GitHub with an explanation
<https://github.com/jamesdbloom/mockserver/issues/451>
you can just update to 5.4.1
Upvotes: 2
|
2018/03/15
| 321 | 1,072 |
<issue_start>username_0: I have the following `RegExp` `myRegexp`, that matches numbers in a string:
```
var myRegexp = new RegExp('[0-9]+');
```
Then I have the following code that extracts numbers from a string and returns an array:
```
var string = '123:456';
var nums = new Array();
while(myRegexp.test(string)) {
nums.length++;
nums[nums.length - 1] = RegExp.lastMatch;
string = RegExp.rightContext;
}
```
Should return an array of two elements: "123", and "456".
However, `RegExp.lastMatch` and `RegExp.rightContext` are deprecated/non-standard API, and not portable. How can I rewrite this logic using portable JS API?
Thanks,<issue_comment>username_1: the solution of this problem is to add to your project:
```
com.fasterxml.jackson.core
jackson-databind
2.9.3
```
im my project with Spring Boot 2 this solution worked fine.
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is an issue in GitHub with an explanation
<https://github.com/jamesdbloom/mockserver/issues/451>
you can just update to 5.4.1
Upvotes: 2
|
2018/03/15
| 376 | 1,149 |
<issue_start>username_0: HTML
```
```
Controller::
```
$scope.link = "https://stackoverflow.com"
```
When clicking on the link inside input box, it should clickable and redirected to StackOverflow page.<issue_comment>username_1: it's not an angular question, but rather a DOM one.
an input element can't contain childNodes, hence the answer is no,
However, using [contentEditable](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content) something like this is quite possible:
```css
.pseudo-input {
width: 250px;
height: 30px;
border: 1px solid #ccc;
line-height: 30px;
}
.pseudo-input a {
cursor: pointer;
}
```
```html
You can [click me!](http://google.com)
```
Upvotes: 0 <issue_comment>username_2: You can use regex for making clickable URL in the string
**In controller:**
```
var regex = '/(\b(ftp|http|https):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig'
var link = "https://stackoverflow.com";
var clickableLink = link.replace(regex, function (url) {
return '<' + url + '>';
});
console.log("clickableLink::", clickableLink);
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 422 | 1,306 |
<issue_start>username_0: I'm trying to POST a file as a base64 string to my API from a react app using axios. Whenever the file seems to exceed a certain (small ~150ko) size, the request is not sent and axios/xhr throws a Network error:
```
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
```
Any ideas?<issue_comment>username_1: it's not an angular question, but rather a DOM one.
an input element can't contain childNodes, hence the answer is no,
However, using [contentEditable](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content) something like this is quite possible:
```css
.pseudo-input {
width: 250px;
height: 30px;
border: 1px solid #ccc;
line-height: 30px;
}
.pseudo-input a {
cursor: pointer;
}
```
```html
You can [click me!](http://google.com)
```
Upvotes: 0 <issue_comment>username_2: You can use regex for making clickable URL in the string
**In controller:**
```
var regex = '/(\b(ftp|http|https):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig'
var link = "https://stackoverflow.com";
var clickableLink = link.replace(regex, function (url) {
return '<' + url + '>';
});
console.log("clickableLink::", clickableLink);
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 467 | 1,424 |
<issue_start>username_0: I need to delete multiple table data with an unique id.
I need to delete that table data if child table does not exist.
I tried `isnull` and if null option but its not working:-
```
SELECT * FROM carbrand
INNER JOIN carmodel
INNER JOIN carversion
WHERE
(
(carmodel.brandid = carbrand.recid) OR
(carmodel.brandid = '')
)
AND
(
(carversion.brandid = carbrand.recid) OR
(carversion.brandid = '')
)
AND carbrand.recid = 17
```<issue_comment>username_1: it's not an angular question, but rather a DOM one.
an input element can't contain childNodes, hence the answer is no,
However, using [contentEditable](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content) something like this is quite possible:
```css
.pseudo-input {
width: 250px;
height: 30px;
border: 1px solid #ccc;
line-height: 30px;
}
.pseudo-input a {
cursor: pointer;
}
```
```html
You can [click me!](http://google.com)
```
Upvotes: 0 <issue_comment>username_2: You can use regex for making clickable URL in the string
**In controller:**
```
var regex = '/(\b(ftp|http|https):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig'
var link = "https://stackoverflow.com";
var clickableLink = link.replace(regex, function (url) {
return '<' + url + '>';
});
console.log("clickableLink::", clickableLink);
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 757 | 2,694 |
<issue_start>username_0: I'm using react-select and I'm customizing it,I didn't found an option to do this. Is there some workaround I can use to keep dropdown open when I'm styling it?<issue_comment>username_1: Open dropdown and then right click on dropdown... it will drown a pop over and on inspector.. now you can work upon your dropdown.
Upvotes: -1 <issue_comment>username_2: If you are using Google Chrome to debug. You can hover over the select drop down and press `Ctrl`+`Shift`+`C` simultaneously and it should be automatically selected in the debug window
Upvotes: 1 <issue_comment>username_3: If you're using V2 there's a `menuIsOpen` prop you can use to keep the menu open at all times.
If you're using Chrome and you have the React Developer Tools plugin, you can inspect your component in the React tab of the console and manually toggle this property right from your browser. For V1, you can toggle the `isOpen` state to achieve the same behavior.
Upvotes: 6 <issue_comment>username_4: In chrome, got to Elements > Event Listeners > open "blur" > with the mouse go to the right of where it is written "document", then you can see a button "Remove" > click on it
Upvotes: 7 <issue_comment>username_5: Maybe this could help:
```
(this.selectRef =el)}
onBlur={() => {
setTimeout(
() =>
this.selectRef.setState({
menuIsOpen: true,
}),
50
);
}}
/>
```
Upvotes: 2 <issue_comment>username_6: Beforehand I exec `window.onkeydown = () => {debugger}` in js console and after expanding the dropdown I click any key
It's important to keep developer tools open
Upvotes: 3 <issue_comment>username_7: By using the [Chrome React extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), you can force the "isOpen" (v3: "menuIsOpen") state value to true on the Select component.
more info here: <https://github.com/JedWatson/react-select/issues/927#issuecomment-313022873>
Upvotes: 2 <issue_comment>username_8: Simple hack goes this way
Run this command on your console open the menu and then wait for 5 seconds and the debugger will automatically be applied and screen will be freezed.
```
setTimeout(() => {debugger;}, 5000)
```
Upvotes: 4 <issue_comment>username_9: That's work for me:
```
menuIsOpen={true}
```
Upvotes: 5 <issue_comment>username_10: You can use the `menuIsOpen` props. It was on the react-select documentation and it works!
Docs: <https://react-select.com/props>
Screenshot:
[](https://i.stack.imgur.com/xUEmT.png)
Upvotes: 2 <issue_comment>username_11: in select component send this as props
```
menuIsOpen={true}
```
Upvotes: 2
|
2018/03/15
| 853 | 2,938 |
<issue_start>username_0: I use PostgreSQL 10.3.
The following statements give the same result: `true`;
```
SELECT ROW() IS NULL;
SELECT ROW() IS NOT NULL;
```
and the next one
```
SELECT ROW() = ROW();
```
gives:
```
"ERROR: cannot compare rows of zero length"
```
So, if a row is of **zero length**, then is it **unknown**, **not unknown** or **both**?
And, how can I check if a **row** is of zero length or not?
Tia<issue_comment>username_1: Open dropdown and then right click on dropdown... it will drown a pop over and on inspector.. now you can work upon your dropdown.
Upvotes: -1 <issue_comment>username_2: If you are using Google Chrome to debug. You can hover over the select drop down and press `Ctrl`+`Shift`+`C` simultaneously and it should be automatically selected in the debug window
Upvotes: 1 <issue_comment>username_3: If you're using V2 there's a `menuIsOpen` prop you can use to keep the menu open at all times.
If you're using Chrome and you have the React Developer Tools plugin, you can inspect your component in the React tab of the console and manually toggle this property right from your browser. For V1, you can toggle the `isOpen` state to achieve the same behavior.
Upvotes: 6 <issue_comment>username_4: In chrome, got to Elements > Event Listeners > open "blur" > with the mouse go to the right of where it is written "document", then you can see a button "Remove" > click on it
Upvotes: 7 <issue_comment>username_5: Maybe this could help:
```
(this.selectRef =el)}
onBlur={() => {
setTimeout(
() =>
this.selectRef.setState({
menuIsOpen: true,
}),
50
);
}}
/>
```
Upvotes: 2 <issue_comment>username_6: Beforehand I exec `window.onkeydown = () => {debugger}` in js console and after expanding the dropdown I click any key
It's important to keep developer tools open
Upvotes: 3 <issue_comment>username_7: By using the [Chrome React extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), you can force the "isOpen" (v3: "menuIsOpen") state value to true on the Select component.
more info here: <https://github.com/JedWatson/react-select/issues/927#issuecomment-313022873>
Upvotes: 2 <issue_comment>username_8: Simple hack goes this way
Run this command on your console open the menu and then wait for 5 seconds and the debugger will automatically be applied and screen will be freezed.
```
setTimeout(() => {debugger;}, 5000)
```
Upvotes: 4 <issue_comment>username_9: That's work for me:
```
menuIsOpen={true}
```
Upvotes: 5 <issue_comment>username_10: You can use the `menuIsOpen` props. It was on the react-select documentation and it works!
Docs: <https://react-select.com/props>
Screenshot:
[](https://i.stack.imgur.com/xUEmT.png)
Upvotes: 2 <issue_comment>username_11: in select component send this as props
```
menuIsOpen={true}
```
Upvotes: 2
|
2018/03/15
| 1,167 | 3,755 |
<issue_start>username_0: I have an array and a hash:
```
a = [
{ :color => "blue", :name => "wind" },
{ :color => "red", :name => "fire" },
{ :color => "white", :name => "wind" },
{ :color => "yellow", :name => "wind" },
{ :color => "green", :name => nil },
{ :color => "black", :name => "snow" }
]
b = { blue: 'blue', white: 'white', red: 'red', green: 'green', black: 'black' }
```
I need to find out unique names based on the input hash to get this:
```
['wind', 'fire', 'snow']
```
I've tried:
```
names = a.map { |i| [i[:color], i[:name]] }
.delete_if { |key, value| value.nil? }
resultant_names = []
b.values.each do |c|
if names[c]
resultant_names << names[c]
end
end
resultant_names.uniq
```
I need a better approach for this. This one has too many loops.<issue_comment>username_1: While your result does not make sense to me (e.g. it is missing snow) this will work
```
a.map(&:values).reverse.to_h.values_at(*b.values).compact.uniq
#=> ["wind","fire"]
```
To break it down:
```
a.map(&:values).reverse.to_h
#=> {"white"=>"wind", "green"=>nil, "yellow"=>"wind", "red"=>"fire", "blue"=>"wind"}
```
You'll notice snow is missing because when we reverse the list `["white","wind"]` will overwrite `["white","snow"]` when converted to a `Hash`
Then we just collect the values for the given colors from
```
b.values
#=> ["blue", "white", "red", "green"]
a.map(&:values).reverse.to_h.values_at(*b.values)
#=> ["wind", "wind", "fire", nil]
```
Then `Array#compact` will remove the `nil` elements and `Array#uniq` will make the list unique.
If snow was intended you could skip the reversal
```
a.map(&:values).to_h.values_at(*b.values).compact.uniq
#=> ["wind", "snow", "fire"]
```
**Either way this is a strange data structure and these answers are only to help with the problem provided as the duplicate colors can cause differing results based on the order in `a`.**
Upvotes: 2 <issue_comment>username_2: I believe you want 'snow' to be in your output array, as there is no other logical explanation. Your code would work if you were to add `.to_h` on the end of line 2, but as you note, it is not very clean or efficient. Also, by converting to a Hash, as a result of duplicate keys, you would potentially lose data.
Here's a tighter construct that avoids the data loss problem:
```
def unique_elements(a, b)
color_set = b.values.to_set
a.map { |pair| pair[:name] if color_set.include?(pair[:color]) }.compact.uniq
end
```
First we take the values of `b` and convert them to a set, so that we can efficiently determine if a given element is a member of the set.
Next we map over `a` choosing the names of those members of `a` for which the `[:color]` is included in our color set.
Finally we eliminate `nils` (using `compact`) and choose unique values.
```
>> unique_elements(a, b)
#> ["wind", "fire", "snow"]
```
Upvotes: 1 <issue_comment>username_3: I would begin by converting `a` to a more useful data structure.
```
h = a.each_with_object({}) { |g,h| h[g[:color]] = g[:name] }
#=> {"blue"=>"wind", "red"=>"fire", "white"=>"wind", "yellow"=>"wind",
# "green"=>nil, "black"=>"snow"}
```
We may then simply write
```
h.values_at(*b.values).compact.uniq
# => ["wind", "fire", "snow"]
```
This approach has several desireable characteristics:
* the creation of `h` makes the method easier to read
* debugging and testing is made easier by creating `h` as a separate step
* `h` need only be created once even if several values of `b` are to be evaluated (in which case we may wish to make `h` an instance variable).
`h` could be chained to the second statement but I've chosen not to do so for the reasons given above (especially the last one).
Upvotes: 1
|
2018/03/15
| 810 | 3,174 |
<issue_start>username_0: I want the seekbar progress to work with user input like the range is between 1-100 and if I enter 50 the thumb should come in middle. Any help would be highly appreciated. Thanks in advance.
ColorSlider.java
================
```
public class ColorSlider extends AppCompatActivity {
private SeekBar seekBar = null;
private View view;
private TextView progress;
private ShapeDrawable shape;
private EditText userInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_slider);
seekBar = (SeekBar)findViewById(R.id.seekBar);
progress = (TextView)findViewById(R.id.progress);
userInput = (EditText)findViewById(R.id.userInput);
LinearGradient test = new LinearGradient(0.f, 0.f, 320.f, 320.f, new int[] { 0xFF0000FF, 0xFF00FF00, 0xFFFF0000},
null, Shader.TileMode.CLAMP);
shape = new ShapeDrawable(new RectShape());
shape.getPaint().setShader(test);
seekBar.setProgressDrawable((Drawable) shape);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
progress.setText(" "+i);
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
```
[](https://i.stack.imgur.com/HfJsN.png)
activity\_color\_slider.xml
---------------------------
```
```<issue_comment>username_1: Add a `TextWatcher` to `Edittext` and set The progress accordingly .
```
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String text = editable.toString();
if(!TextUtils.isEmpty(text)){
seekBar.setProgress(Integer.parseInt(text));
}
}
});
```
Make sure `Edittext` should have `inputType` as `number` . Add `android:inputType="number` to `Edittext`.
**NOTE**:- This will set progress leniently(ex: 50->50%, 10->10%). If you want to show progress with some unit like number 10-> 1% then you need to calculate it inside `afterTextChanged()`
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try this
And implement textwatcher for Edittext
```
youredittext.addTextChangedListener(new TextWatcher()
{
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
seekbar.setProgress(Integer.parseInt(s));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int aft )
{
}
@Override
public void afterTextChanged(Editable s)
{
}
});
```
Upvotes: 1
|
2018/03/15
| 702 | 2,558 |
<issue_start>username_0: I have this code:
```
from subprocess import Popen, PIPE
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# Create some widgets
self.setGeometry(500, 500, 300, 300)
self.pushButton = QtWidgets.QPushButton(
'Print', self)
self.pushButton.setGeometry(20, 20, 260, 30)
self.pushButton.clicked.connect(self.print_widget)
xlabel = "Hello World"
def print_widget(self):
p = Popen('echo "This is a test." + xlabel | lpr', shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
app = QtWidgets.QApplication(sys.argv)
gui = App()
gui.show()
app.exec_()
```
When the push button is clicked, the terminal will execute the command:
```
echo "This is a test." + xlabel | lpr
```
and the output will be: [](https://i.stack.imgur.com/hjyVy.jpg)
But the Output I want is "This is a test. Hello World" but obviously my syntax is wrong and I need help.<issue_comment>username_1: Add a `TextWatcher` to `Edittext` and set The progress accordingly .
```
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String text = editable.toString();
if(!TextUtils.isEmpty(text)){
seekBar.setProgress(Integer.parseInt(text));
}
}
});
```
Make sure `Edittext` should have `inputType` as `number` . Add `android:inputType="number` to `Edittext`.
**NOTE**:- This will set progress leniently(ex: 50->50%, 10->10%). If you want to show progress with some unit like number 10-> 1% then you need to calculate it inside `afterTextChanged()`
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try this
And implement textwatcher for Edittext
```
youredittext.addTextChangedListener(new TextWatcher()
{
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
seekbar.setProgress(Integer.parseInt(s));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int aft )
{
}
@Override
public void afterTextChanged(Editable s)
{
}
});
```
Upvotes: 1
|
2018/03/15
| 435 | 1,825 |
<issue_start>username_0: I am creating more pages in ionic 2, when i refresh the page it always redirect to the root page index, how to prevent it.
### Example:
I created login page and welcome page after logging in if i press refresh it automatically moves to root page as login.<issue_comment>username_1: Add a `TextWatcher` to `Edittext` and set The progress accordingly .
```
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String text = editable.toString();
if(!TextUtils.isEmpty(text)){
seekBar.setProgress(Integer.parseInt(text));
}
}
});
```
Make sure `Edittext` should have `inputType` as `number` . Add `android:inputType="number` to `Edittext`.
**NOTE**:- This will set progress leniently(ex: 50->50%, 10->10%). If you want to show progress with some unit like number 10-> 1% then you need to calculate it inside `afterTextChanged()`
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try this
And implement textwatcher for Edittext
```
youredittext.addTextChangedListener(new TextWatcher()
{
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
seekbar.setProgress(Integer.parseInt(s));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int aft )
{
}
@Override
public void afterTextChanged(Editable s)
{
}
});
```
Upvotes: 1
|
2018/03/15
| 417 | 1,360 |
<issue_start>username_0: I have the following table on my DataBase:
**TimeRank(user-id, name, time)**
I would like to order the table by time and get the position of an specific ID on the table, for example:
*The user nº 68 is on the 3rd position.*
I only need to do a query that returns the position of the user.
MySQL don't have the function row\_number, so I don't know how to do it.<issue_comment>username_1: ```
SELECT x.user-id,
x.name,
x.time,
x.position
FROM (SELECT t.user-id,
t.name,
t.time,
@rownum := @rownum + 1 AS position
FROM TABLE TimeRank t
JOIN (SELECT @rownum := 0) r
ORDER BY t.time) x
WHERE x.user-id = 123
```
Alternative:
```
SELECT user-id,
(SELECT COUNT(*) FROM TimeRank WHERE time <= (SELECT time FROM TimeRank WHERE user-id = 123)) AS position,
time,
name
FROM TimeRank
WHERE user-id = 123
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can generate a position column with a variable
```
set @pos=0;
select pos,user_id
from (select @pos:=@pos+1 pos,user_id from TimeRank order by time) s
where user_id=68;
```
If indexing is a concern, you can add a column to your table and update it with
```
set @pos=0;
update TimeRank set position=(@pos:=@pos+1) order by time;
```
Upvotes: 0
|
2018/03/15
| 579 | 2,286 |
<issue_start>username_0: I have troubles with saving an account credentials inside an IPhoneSimulator's Keychain. I cannot use *AccountSaver.Create().Save(credentials, "app")* without *Entitlements.plist*. However when I add it to my project, compilation error shows up:
>
> Could not find any available provisioning profiles for iOS.
>
>
>
I've added iOS Development certifcate to my account on Mac and tried to create a free provisioning profile but failed due to a lack of IPhone device.
Suprisingly, when I tried to build dummy project with added Keychain to Entitlements inside Xcode on my Mac and run it on a simulator no compilation errors occured.
My questions are: **Do I have to make Apple Developer Account to test my Xamarin.iOS app inside IPhoneSimulator or is it possible without it and I'm doing something wrong? If so, what should I do to be able to compile my app?**
I use Visual Studio 2017 on Windows 8 connected to a Mac Agent (Mac Mini).
P.S.: Most posts states, that simulator doesn't need provisioning profile, but according to [this thread](https://forums.xamarin.com/discussion/39674/iphonesimulator-build-results-in-no-valid-ios-code-signing-keys-found-in-keychain/p1 "Xamarin Forum Thread"):
>
> Starting with Xamarin.iOS 8.10, if the Entitlements.plist file is set at all for the iPhoneSimulator build configuration, then codesigning **is required** and thus an iOS code signing certificate is required to be installed in your keychain. ~ [Xamarin Forum](https://forums.xamarin.com/discussion/39674/iphonesimulator-build-results-in-no-valid-ios-code-signing-keys-found-in-keychain/p1 "Xamarin Forum Thread")
>
>
><issue_comment>username_1: Some time has passed since I asked this question, but I think it deserves an answer not only in the comments.
As @wottle wrote it is required to be enrolled i Apple Developer Program in order to have access to Keychain.
I sugest also to use Xamarin.Essentials' SecureStore instead of AccountSaver.
Upvotes: 2 [selected_answer]<issue_comment>username_2: We have a bunch of Apple Store applications that had their Apple Distribution profiles expired. The issue was gone once we regenerated the Apple Distribution Certificate and created a new Distribution Profile for the impacted Applications.
Upvotes: 0
|
2018/03/15
| 1,222 | 4,520 |
<issue_start>username_0: I have a survey app - you create a Survey and it saves the Response. It's registered in Django Admin. I can see the Survey and submit a Response. When I click **Response** in Admin, I get the following error:
>
> ValueError at /admin/django\_survey/response/
> Cannot query "response 5f895af5999c49929a522316a5108aa0": Must be "User" instance.
>
>
>
So I checked the SQL database and for `django_survey_response` I can see that there is a response, but the column `user_id` is `NULL`.
I suspected that there's an issue with my *Views* and/or *Forms* and I'm not saving the logged in User's details, so I've tried to address that.
However, now I get
>
> NameError at /survey/1/
>
>
> global name 'user' is not defined
>
>
>
How do I resolve this? I want the form to save **Response** with the logged in user's ID.
The Traceback:
>
> django\_survey\views.py
>
>
>
```
def SurveyDetail(request, id):
survey = Survey.objects.get(id=id)
category_items = Category.objects.filter(survey=survey)
categories = [c.name for c in category_items]
print 'categories for this survey:'
print categories
if request.method == 'POST':
form = ResponseForm(request.POST, survey=survey) <.........................
if form.is_valid():
response = form.save()
return HttpResponseRedirect("/confirm/%s" % response.interview_uuid)
else:
form = ResponseForm(survey=survey)
print form
```
>
> django\_survey\forms.py
>
>
>
```
def __init__(self, *args, **kwargs):
# expects a survey object to be passed in initially
survey = kwargs.pop('survey')
self.survey = survey
self.user = user <.........................
super(ResponseForm, self).__init__(*args, **kwargs)
self.uuid = random_uuid = uuid.uuid4().hex
# add a field for each survey question, corresponding to the question
# type as appropriate.
data = kwargs.get('data')
```
It might be worth noting that previously, instead of `user`, the model's field was called `interviewee`. I changed this and ran migrations again.
I am also using **userena**.<issue_comment>username_1: In your view when you initialize your form you need to pass it the user (current user in this case)? similar to this `form = ResponseForm(request.POST, survey=survey, user=request.user)`. Then in the `__init__` of your form pop the user object `user = kwargs.pop('user')`. I believe that will resolve your issue.
Upvotes: 1 <issue_comment>username_2: The error message in this instance is python trying to tell you that you are attempting to access a variable `user` that has not been defined in the scope of your method.
Let's look at the first few lines of the `__init__()` method:
```
def __init__(self, *args, **kwargs):
# expects a survey object to be passed in initially
survey = kwargs.pop('survey')
self.survey = survey
self.user = user
```
We can see where the `survey` variable is defined: `survey = kwargs.pop('survey')`. It is passed into the form as a keyword argument and extracted in the forms `__init__`. However underneath you attempt to do the same thing with `user` but haven't actually defined it above. The correct code would look like:
```
def __init__(self, *args, **kwargs):
# expects a survey object to be passed in initially
survey = kwargs.pop('survey')
user = kwargs.pop('user')
self.survey = survey
self.user = user
```
However, this still won't work because we aren't passing the `user` variable to the form via kwargs. To do that we pass it in when we initialise the form in your `views.py`. What isn't clear is what user object you are expecting to pass in. the `request.user`? or does the `Survey` object have a user attribute? in which case you would not need to pass user in and would just use `survey.user` etc.
django\_survey\views.py
```
def SurveyDetail(request, id):
survey = Survey.objects.get(id=id)
category_items = Category.objects.filter(survey=survey)
categories = [c.name for c in category_items]
print 'categories for this survey:'
print categories
if request.method == 'POST':
form = ResponseForm(request.POST, survey=survey, user=request.user)
if form.is_valid():
response = form.save()
return HttpResponseRedirect("/confirm/%s" % response.interview_uuid)
else:
form = ResponseForm(survey=survey, user=request.user)
print form
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 1,073 | 3,901 |
<issue_start>username_0: I'm implementing a tableview, which has 3 sections(section count remain static) and each section contain several rows.
**Behaviour 1:** Add section header to only the third section.
***How did I achieve:***
```
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 2 {
//create and return header view
}
return UIView(frame: CGRect(x: 0, y:0, width: tableView.width, height: UIScreen.main.scale))
}
```
**Behaviour 2:** TableViewCells shouldn't have separator. But, Sections should be separated with a thin line. (similar to tableviewcell separator)
***What did I try:***
* Add a one pixel height, tableView width UIView, with all required properties set(color, etc) and add it as a sub-view to the section header view's
* Add drop shadow with CGPoint(0,1) to the section header views
None of them worked out.
***How did I achieve this:***
1. Find last cell in every section,
2. Create an UIView with 1px height, tableView's width and add it as a subview to the last cell
Though this seem to work. I feel, there must be a better way of doing this, rather than adding line to bottom of every section's last tableView cell. Does anyone know a better way of implementing such behaviour?<issue_comment>username_1: Using `heightForHeaderInSection` method of `UITableViewDelegate` and return section wise height as per you want
```
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 2 {
return 1 // return height as per your requirement
}
return 0 // return height as per your requirement
}
```
Upvotes: 2 <issue_comment>username_2: This should work for adding "section separator lines" and a head view *only* on the 3rd section:
```
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// if it's the 3rd section, return a view with desired content for the section header
if section == 2 {
let v = UIView(frame: CGRect(x: 0, y:0, width: tableView.frame.width, height: 30))
v.backgroundColor = .yellow
let label = UILabel(frame: CGRect(x: 8.0, y: 4.0, width: v.bounds.size.width - 16.0, height: v.bounds.size.height - 8.0))
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.text = "Header for Third Section"
v.addSubview(label)
return v
}
// not the 3rd section, so don't return a view
return nil
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// if it's the 3rd section
if section == 2 {
return 30
}
return 0
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// UIView with darkGray background for section-separators as Section Footer
let v = UIView(frame: CGRect(x: 0, y:0, width: tableView.frame.width, height: 1))
v.backgroundColor = .darkGray
return v
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Section Footer height
return 1.0
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Set the Style of the Table View to **Grouped**: [](https://i.stack.imgur.com/FRnfp.png)
Upvotes: 2 <issue_comment>username_4: Simple solution of this Just add the footer view inside the tableview.Set height of the footer view to be a specific height.
Swift:
```
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = UIColor.grey
return view
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
```
Upvotes: 2
|
2018/03/15
| 293 | 1,046 |
<issue_start>username_0: I have XML specified the following:
```
```
I would like to have a list of the news in my response. However when I would like to create Java object with jaxb2 the xml returns the folllowing error when I run mvn clean compile -X:
`org.xml.sax.SAXParseException: cos-st-restricts.1.1: The type 'newsList' is atomic, so its {base type definition}, 'tns:news', must be an atomic simple type definition or a built-in primitive datatype.`
How I should change my XML to be able to compile?<issue_comment>username_1: In addition to using the built-in list types, you can create new list types by derivation from existing atomic types. **You cannot create list types from existing list types, nor from complex types.**
<https://www.w3.org/TR/xmlschema-0/#ListDt>
This is from one of my working XSD, a user with multiple addresses:
```
```
Note that **addressData** is a complexType.
I guess this is what you need:
```
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
xml version="1.0"?
```
Upvotes: 0
|
2018/03/15
| 945 | 3,447 |
<issue_start>username_0: Premise
=======
I'm using the Google Elevation Service to get elevations of all nodes along a path, drawn onto a Leaflet map by a user. This allows me to generate an elevation chart. At the moment, if I make more than 2 requests (there is a limit of 512 locations per request), I always hit an `OVER_QUERY_LIMIT`.
Usage Policy
============
>
> * 2,500 free requests per day, calculated as the sum of client-side and server-side queries; enable billing to access higher daily quotas, billed at $0.50 USD / 1000 additional requests, up to 100,000 requests daily.
> * 512 locations per request.
> * 50 requests per second\*, calculated as the sum of client-side and server-side queries combined.
>
>
>
*From the [Google Elevation Service Site](https://developers.google.com/maps/documentation/javascript/elevation#quotas)*
I know I'm not hitting the 2500 requests a day (can see in the developer console how many have been made). I also know that there are definitely 512 locations per request, which leaves the only quota to be hitting being the 50 requests per second.
Method
======
To deal with large volumes of nodes I am doing the following:
1. Input list of nodes to function
2. Take first chunk (512 locations) from list
3. Make API call with that chunk
4. Append returned elevations to an array
5. Wait for 1 second
6. Loop from 2 to 5 until list is depleted
Code in action: [Codepen](https://codepen.io/edprince/pen/ZrPPqG)
If I make the waiting time massive in between each request (say 5 seconds), the requests are sent fine, but from what I can tell, I should be able to send 50 requests a second - so a list of 10,000 nodes should take 20 requests, and theoretically not even need a wait - but even with the wait its hitting the error.<issue_comment>username_1: First check answers from [here](https://stackoverflow.com/questions/36266442/inaccurate-google-maps-elevation-service-response-when-splitting-a-too-large-pat)
I am not sure but you can check with [this](https://github.com/mpetazzoni/leaflet-gpx) and [this](https://github.com/MrMufflon/Leaflet.Elevation) leaflet plugin.
**Google articles already [documented](https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits) same issues which you are facing currently. And given some [solutions also](https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits#solutions)**
I checked your Codepen also.
Still if you have only Google elevation service option then you need to check with some logic like:
* Try to replicate same code with different Google API key and merge results.
* Check is it possible to import Google API script cdn in for loop where you use 5-6 different API keys.
Finally last option is **Use a Google Maps APIs for Work license**
Important: Please change or use demo Google API key which you used in codepen. Because anybody can use your key. or protect it from Google API console Under Accept requests from these HTTP referrers (websites), this is where you limit the key to your domain name.
Upvotes: 2 <issue_comment>username_2: There appears to be another limit: 1024 locations during a 5 second window. So 2 request of 512 locations each, 4 at 256, 8 at 128, etc, all work but then you have to wait 5 seconds for the next request. I think the 50 requests per second limit only kicks in if the total location count is 1024 or less.
Upvotes: 2 [selected_answer]
|
2018/03/15
| 1,833 | 6,281 |
<issue_start>username_0: I'm using jobScheduler to get background location updates. But each time the job is scheduled, FusedLocationProviderClient is null. Why is that? I've checked if(FusedLocationProviderClient == null) condition and each time the job is scheduled, the code under it runs (that means fusedLocationProviderClient is null after it is initialized.) Please have a look at the code below. Moreover locationAvailability is often false, hence onLocationResult is not called that gives null location value. How can I optimize FusedLocationProviderClient. One more thing, are fusedLocationProviderClient always being null and locationAvailability giving false related?
```
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.e("onStartJob", "onStartJob");//for debug
jobP = jobParameters;
if (!checkAndRequestPermissions()) {
Toast.makeText(this, "Please provide location permission for paramount app.", Toast.LENGTH_LONG).show();
provider = null;
} else {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
if (mLocationRequest == null) {
Log.e("onStartJob", "LocationRequest initialized"); //for debug
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100 * 1000);
mLocationRequest.setFastestInterval(60 * 1000);
}
if (client == null) {
Log.e("onStartJob", "client initialized"); //for debug
client = LocationServices.getFusedLocationProviderClient(this);
client.requestLocationUpdates(mLocationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Log.e("onLocationResult ", "onLocationResult");
onLocationChanged(locationResult.getLastLocation());
}
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.e("onLocationAvailability", locationAvailability + "");;
}
},
Looper.myLooper());
}
try {
provider = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE) + "";
gpsProvider = provider;
} catch (Settings.SettingNotFoundException e) {
Log.e("provider", "gps provider error");
}
}
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.e("onStopJob", "onStopJob");//for debug
if (ul != null) {
ul.cancel(true);
}
return true;
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude() + "";
longitude = location.getLongitude() + "";
Log.e("latitude" , latitude);
}
```
The log values in the above code is shown below:
```
03-15 17:09:25.889 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob
03-15 17:09:25.900 10687-10687/com.myProject.com.jobschedulers E/onstartJob: client initialized
03-15 17:09:25.957 10687-10687/com.myProject.com.jobschedulers E/onLocationResult: onLocationResult
03-15 17:09:25.960 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: true]
03-15 17:23:26.975 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob
03-15 17:23:26.993 10687-10687/com.myProject.com.jobschedulers E/onstartJob: client initialized
03-15 17:23:27.017 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: false]
03-15 17:41:32.672 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob
03-15 17:41:32.690 10687-10687/com.myProject.com.jobschedulers E/onstartJob: client initialized
03-15 17:41:32.741 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: false]
03-15 17:53:17.335 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob
03-15 17:53:17.351 10687-10687/com.myProject.com.jobschedulers E/onstartJob: client initialized
03-15 17:53:17.383 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: false]
```<issue_comment>username_1: First check answers from [here](https://stackoverflow.com/questions/36266442/inaccurate-google-maps-elevation-service-response-when-splitting-a-too-large-pat)
I am not sure but you can check with [this](https://github.com/mpetazzoni/leaflet-gpx) and [this](https://github.com/MrMufflon/Leaflet.Elevation) leaflet plugin.
**Google articles already [documented](https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits) same issues which you are facing currently. And given some [solutions also](https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits#solutions)**
I checked your Codepen also.
Still if you have only Google elevation service option then you need to check with some logic like:
* Try to replicate same code with different Google API key and merge results.
* Check is it possible to import Google API script cdn in for loop where you use 5-6 different API keys.
Finally last option is **Use a Google Maps APIs for Work license**
Important: Please change or use demo Google API key which you used in codepen. Because anybody can use your key. or protect it from Google API console Under Accept requests from these HTTP referrers (websites), this is where you limit the key to your domain name.
Upvotes: 2 <issue_comment>username_2: There appears to be another limit: 1024 locations during a 5 second window. So 2 request of 512 locations each, 4 at 256, 8 at 128, etc, all work but then you have to wait 5 seconds for the next request. I think the 50 requests per second limit only kicks in if the total location count is 1024 or less.
Upvotes: 2 [selected_answer]
|
2018/03/15
| 461 | 1,740 |
<issue_start>username_0: Can we provide conditions to **trans** or **Lang** method other than pluralization ones, so it checks locale & the condition both to provide the required translations
>
> For Example: We have some translations in English for Organisation 1. And
> different translations in English for Organisation 2. Now according to user login for organisation, the translations should be shown.
> Remember the locale is same.
>
>
><issue_comment>username_1: I think you shouldn't use translations for the name of an Organisation, but just create a variable that you directly output. However you could misuse trans\_choice in combination with a Constant to use that number to change the output.
```
abstract class Organisation
{
const Organisation1 = 1;
const Organisation2 = 2;
const Organisation3 = 3;
// etc
}
```
Translation
```
// en/organisations.php
'organisation' => '{1} Coca Cola|{2} 1 Pesi|[3, Inf] Unilever :org'
// in your views
trans_choice('organisations.organisation', ['org' => Organisation::Organisation1 ])
```
So to recapture: the "amount" is now just a number that represents an Organisation like an Enum does.
Upvotes: 1 <issue_comment>username_2: Why not go with something like that:
```
@lang("organistation.$organisationId.text")
```
And in resources/lang/en/organisation.php:
```
php
return [
'first_organization_id' = [
'text' => 'This text belongs to first organisation!',
'text2' => 'Other text belongs to first organisation!'
],
'second_organization_id' => [
'text' => 'This text belongs to second organisation!',
'text2' => 'Other text belongs to second organisation!'
]
];
```
etc.
Upvotes: 3 [selected_answer]
|
2018/03/15
| 606 | 2,127 |
<issue_start>username_0: I am using Active Choices Plugin to dinamically load parameters. I want to read last line of a $workspace file as a parameter.
In this example, when selecting "pedro" username it should display linea 1" because is the last line of the document that is in "/var/lib/jenkins/workspace/Aa.test1.txt"
This is how the job is configured:
[](https://i.stack.imgur.com/UBhPD.png)
And this is when trying to build the job with parameters:
[](https://i.stack.imgur.com/BdX8g.png)
If I execute it in Jenkins Script console it displays the output correctly...
[](https://i.stack.imgur.com/whhvD.jpg)
Thank you.<issue_comment>username_1: I think you shouldn't use translations for the name of an Organisation, but just create a variable that you directly output. However you could misuse trans\_choice in combination with a Constant to use that number to change the output.
```
abstract class Organisation
{
const Organisation1 = 1;
const Organisation2 = 2;
const Organisation3 = 3;
// etc
}
```
Translation
```
// en/organisations.php
'organisation' => '{1} Coca Cola|{2} 1 Pesi|[3, Inf] Unilever :org'
// in your views
trans_choice('organisations.organisation', ['org' => Organisation::Organisation1 ])
```
So to recapture: the "amount" is now just a number that represents an Organisation like an Enum does.
Upvotes: 1 <issue_comment>username_2: Why not go with something like that:
```
@lang("organistation.$organisationId.text")
```
And in resources/lang/en/organisation.php:
```
php
return [
'first_organization_id' = [
'text' => 'This text belongs to first organisation!',
'text2' => 'Other text belongs to first organisation!'
],
'second_organization_id' => [
'text' => 'This text belongs to second organisation!',
'text2' => 'Other text belongs to second organisation!'
]
];
```
etc.
Upvotes: 3 [selected_answer]
|
2018/03/15
| 588 | 2,110 |
<issue_start>username_0: **Goal**: migration from Spring Boot 1.x (webMvc) to version 2 (webFlux) and Spring Cloud Edgware SR2 to FinchleyM8 (awaiting release version).
**Problem**: Feign -> OpenFeign. OpenFeign under the hood uses RxJava but WebFlux - Reactor3. At the current moment when I using Mono as returned type, I have got an error:
>
> Caused by: org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class reactor.core.publisher.Mono]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `reactor.core.publisher.Mono` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
>
>
>
**Code example**:
```
@FeignClient(name = "thirdpartyresource", url = "${third.party.resource.url}")
public interface ThirdPartyResource {
@PostMapping(value = "/validate", consumes = APPLICATION_FORM_URLENCODED_VALUE)
Mono validate(MultiValueMap multiValueMap); // WORKS BAD
// Single validate(MultiValueMap multiValueMap); WORKS WELL
}
```
**Question**:
Do I need to create my own converter Single to Mono or it's some problems of spring-cloud-starter-openfeign and all should work OOTB?<issue_comment>username_1: You can use those methods to adapt:
For `Single rxJavaSingle`
```
Mono.from(RxReactiveStreams.toPublisher(rxJavaSingle))
```
For `Completable rxJavaCompletable`
```
Mono.from(RxReactiveStreams.toPublisher(rxJavaCompletable))
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: The `reactor.core.publisher.Mono` belongs to the `spring-boot-starter-webflux` jar.
Get the latest version of it from the [mvn repository](https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux).
Then add it to your pom.xml
```
org.springframework.boot
spring-boot-starter-webflux
2.5.3
```
Also do remove `spring-boot-starter-web` from your pom.xml, just in case if you have it.
```
```
This fixed the issue!
Upvotes: 2
|
2018/03/15
| 288 | 996 |
<issue_start>username_0: In admin i want to display diff. list\_filter for superuser and staff user. How it possible.
When superuser is logged in:
```
list_filter = ('is_active', 'membership_type', 'is_blocked')
```
and for staff user with limited permission list\_filters should be:
```
list_filter = ('is_active',)
```<issue_comment>username_1: Add this method to Admin class
```
def get_list_filter(self, request):
if request.user.is_superuser:
return ('is_active', 'membership_type', 'is_blocked')
return ('is_active',)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I find solution of above problem. I change list\_filters in changelist\_view function.
```
def changelist_view(self, request, extra_context=None):
if request.user.is_superuser:
self.list_filter = ('is_active', 'membership_type', 'is_blocked')
else:
self.list_filter = ('is_active',)
return super(CustomUserAdmin, self).changelist_view(request)
```
Upvotes: 0
|
2018/03/15
| 709 | 2,689 |
<issue_start>username_0: I would like to create a form using BootStrap 4 that looks like the forms that BootStrap 3 allowed one to create easily. i.e. I would like a bold label right-aligned within a specific size (e.g. col-sm-4), and next to it I would like an input field whose width is controlled by an enclosing div tag with a class like col-sm-4 (as an example). How can I do this? I have spent an hour or so now battling with .css and BS4 to create this, but have been unable to achieve the effect I desire. Any hints would be great.
The code below will produce the effect I wish for but will not allow me to have different sized inputs (they all default to the same size)
css:
```
div.form-inline label.col-sm-3 {
justify-content: flex-end;
font-weight:650;
}
```
html:
```
City
```
If I instead use form-group, then I can alter the size of the input fields using the enclosing tags, but then the css (even when I change it to be .form-group instead of .form-inline) fails to align the label correctly and set it to bold. So I guess I'm looking for either the correct .css or an example of how to achieve the whole effect simply (as it was with BS3). I must be missing something obvious because I can not believe that the BS4 developers would make it so difficult to achieve the same look as BS3 allowed without any of the .css hacks etc that I am having to do. Though I do notice that every one of the examples given in the BS4 documentation has the label left-aligned, so perhaps they have decided to make that formatting decision for every BS4 user, but that seems a bit unlikely (and unfriendly).<issue_comment>username_1: In order for `col-*` to work they MUST be inside a `.row` or `.form-row`.
There's no need for any extra CSS:
<https://codeply.com/go/0Vkxbmgb4c>
```
City
```
<https://getbootstrap.com/docs/4.0/components/forms/#form-grid>
Upvotes: 2 <issue_comment>username_2: If you have several of these that you are converting from BS3 to BS 4, then the way that ZimSystem has suggested as an answer will be extremely tiresome to implement - being as you will have to change every single instance of this. Just create some css (as it seemed you were actually asking for) with the following .css and use find and replace to replace every instance of control-label with col-form-label. This approach is much easier than the approach suggested above, and uses a more modular approach (in that you only have to write the css markup once - modularity should be every programmer's approach in my opinion). Ensure this css is loaded AFTER BS4 css has loaded.
```
.col-form-label
{
font-weight:600;
text-align:right;
}
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 862 | 2,509 |
<issue_start>username_0: I have dropdown fields on an event website with variable names so I'm unsure on how to capture the data with $\_POST
An example is
```
tkt-slctr-qty-346[]
tkt-slctr-qty-358[]
```
Is there a way to capture the data with $\_POST by using wildcards at all?
EDIT: here is the html
```
0
1
2
3
4
5
6
7
8
9
10
```<issue_comment>username_1: Instead of having the id as part of the "name" (which will be used as the key in the `$_POST` array, PHP supports using array notation directly:
```
name="tkt-slctr-qty[346]"
name="tkt-slctr-qty[358]"
```
You can then iterate over these under a single key:
```
if (!empty($_POST['tkt-slctr-qty']) && is_array($_POST['tkt-slctr-qty'])) {
foreach ($_POST['tkt-slctr-qty'] as $id => $qty) {
// handle each id/qty value
}
}
```
If you *do* have multiple select boxes for each id as well, append `[]` to each, and create an inner loop:
```
name="tkt-slctr-qty[346][]"
...
name="tkt-slctr-qty[358][]"
```
And then handle it in an inner loop:
```
if (!empty($_POST['tkt-slctr-qty']) && is_array($_POST['tkt-slctr-qty'])) {
foreach ($_POST['tkt-slctr-qty'] as $id => $qtys) {
if (is_array($qtys)) {
foreach ($qtys as $qty) {
// handle each qty if there are multiple fields.
}
}
}
}
```
Upvotes: 2 <issue_comment>username_2: You can get post variables to an array then iterate through it while you filter.
```
foreach($_POST as $key => $value) {
$pos = strpos($key , "tkt-slctr-qty-");
if ($pos === 0){
// do something with $value
}
}
```
Upvotes: 2 <issue_comment>username_3: When you submit those arrays, PHP will receive them this way:
```
$_POST['tkt-slctr-qty-358'][0]
$_POST['tkt-slctr-qty-358'][1]
// ...
```
If you mean to capture the numbers at the end of the key dynamically, it works the following:
```
foreach ($_POST as $k => $v) {
if (strpos($k, 'tkt-slctr-qty-') === 0) {
foreach ($v as $innerValue) {
echo 'Key: ' . $k . ' has value: ' . $innerValue . '
';
}
}
}
```
Upvotes: 2 <issue_comment>username_4: You have to Iterate through the $\_POST array holding the collection. Follow the pattern below
```
$counter = count($_POST['tkt-slctr-qty-346']);
$image = '';
for($i=0; $i< $counter; $i++)
{
$data = $_POST['tkt-slctr-qty-346'][$i];
//Then Write the code that processes the data here
}
```
Upvotes: 0
|
2018/03/15
| 1,326 | 4,129 |
<issue_start>username_0: I would like to replace middle of word with \*\*\*\*.
For example :
```
ifbewofiwfib
wofhwifwbif
iwjfhwi
owfhewifewifewiwei
fejnwfu
fehiw
wfebnueiwbfiefi
```
Should become :
```
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
So far I managed to replace all but the first 2 chars with:
```
sed -e 's/./*/g3'
```
Or do it the long way:
```
grep -o '^..' file > start
cat file | sed 's:^..\(.*\)..$:\1:' | awk -F. '{for (i=1;i<=length($1);i++) a=a"*";$1=a;a=""}1' > stars
grep -o '..$' file > end
paste -d "" start stars > temp
paste -d "" temp end > final
```<issue_comment>username_1: I would use Awk for this, if you have a GNU Awk to set the field separator to an empty string ([How to set the field separator to an empty string?](https://stackoverflow.com/q/31135251/1983854)).
This way, you can loop through the chars and replace the desired ones with "\*". In this case, replace from the 3rd to the 3rd last:
```
$ awk 'BEGIN{FS=OFS=""}{for (i=3; i<=NF-2; i++) $i="*"} 1' file
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Following `awk` may help you on same. It should work in any kind of `awk` versions.
```
awk '{len=length($0);for(i=3;i<=(len-2);i++){val=val "*"};print substr($0,1,2) val substr($0,len-1);val=""}' Input_file
```
Adding a non-one liner form of solution too now.
```
awk '
{
len=length($0);
for(i=3;i<=(len-2);i++){
val=val "*"};
print substr($0,1,2) val substr($0,len-1);
val=""
}
' Input_file
```
***Explanation:*** Adding explanation now for above code too.
```
awk '
{
len=length($0); ##Creating variable named len whose value is length of current line.
for(i=3;i<=(len-2);i++){ ##Starting for loop which starts from i=3 too till len-2 value and doing following:
val=val "*"}; ##Creating a variable val whose value is concatenating the value of it within itself.
print substr($0,1,2) val substr($0,len-1);##Printing substring first 2 chars and variable val and then last 2 chars of the current line.
val="" ##Nullifying the variable val here, so that old values should be nullified for this variable.
}
' Input_file ##Mentioning the Input_file name here.
```
Upvotes: 1 <issue_comment>username_3: If `perl` is okay:
```
$ perl -pe 's/..\K.*(?=..)/"*" x length($&)/e' ip.txt
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
* `..\K.*(?=..)` to match characters other than first/last two characters
+ See [regex lookarounds](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) section for details
* `e` modifier allows to use Perl code in replacement section
* `"*" x length($&)` use length function and string repetition operator to get desired replacement string
Upvotes: 2 <issue_comment>username_4: You can do it with a repetitive substitution, e.g.:
```
sed -E ':a; s/^(..)([*]*)[^*](.*..)$/\1\2*\3/; ta'
```
### Explanation
This works by repeating the substitution until no change happens, that is what the `:a; ...; ta` bit does. The substitution consists of 3 matched groups and a non-asterisk character:
* `(..)` the start of the string.
* `([*]*)` any already replaced characters.
* `[^*]` the character to be replaced next.
* `(.*..)` any remaining characters to replace and the end of the string.
### Alternative GNU sed answer
You could also do this by using the hold space which might be simpler to read, e.g.:
```bash
h # save a copy to hold space
s/./*/g3 # replace all but 2 by *
G # append hold space to pattern space
s/^(..)([*]*)..\n.*(..)$/\1\2\3/ # reformat pattern space
```
Run it like this:
```
sed -Ef parse.sed input.txt
```
### Output in both cases
```none
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
Upvotes: 2
|
2018/03/15
| 1,193 | 3,980 |
<issue_start>username_0: I'm creating a proxy-service with a log-mediator in WSO2 Enterprise Integrator 6.1.1 and I have 2 simple questions:
1)Is it possible to costumize the format of the logged request/response? Actually what I see in the WSO2 consolle is the XML rapresentation of my request/response, and I would like to change them in other format (for example JSON).
2)Is it possible to costumize the file name/location where WSO2 logs the request/response?
Thanks in advance!<issue_comment>username_1: I would use Awk for this, if you have a GNU Awk to set the field separator to an empty string ([How to set the field separator to an empty string?](https://stackoverflow.com/q/31135251/1983854)).
This way, you can loop through the chars and replace the desired ones with "\*". In this case, replace from the 3rd to the 3rd last:
```
$ awk 'BEGIN{FS=OFS=""}{for (i=3; i<=NF-2; i++) $i="*"} 1' file
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Following `awk` may help you on same. It should work in any kind of `awk` versions.
```
awk '{len=length($0);for(i=3;i<=(len-2);i++){val=val "*"};print substr($0,1,2) val substr($0,len-1);val=""}' Input_file
```
Adding a non-one liner form of solution too now.
```
awk '
{
len=length($0);
for(i=3;i<=(len-2);i++){
val=val "*"};
print substr($0,1,2) val substr($0,len-1);
val=""
}
' Input_file
```
***Explanation:*** Adding explanation now for above code too.
```
awk '
{
len=length($0); ##Creating variable named len whose value is length of current line.
for(i=3;i<=(len-2);i++){ ##Starting for loop which starts from i=3 too till len-2 value and doing following:
val=val "*"}; ##Creating a variable val whose value is concatenating the value of it within itself.
print substr($0,1,2) val substr($0,len-1);##Printing substring first 2 chars and variable val and then last 2 chars of the current line.
val="" ##Nullifying the variable val here, so that old values should be nullified for this variable.
}
' Input_file ##Mentioning the Input_file name here.
```
Upvotes: 1 <issue_comment>username_3: If `perl` is okay:
```
$ perl -pe 's/..\K.*(?=..)/"*" x length($&)/e' ip.txt
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
* `..\K.*(?=..)` to match characters other than first/last two characters
+ See [regex lookarounds](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) section for details
* `e` modifier allows to use Perl code in replacement section
* `"*" x length($&)` use length function and string repetition operator to get desired replacement string
Upvotes: 2 <issue_comment>username_4: You can do it with a repetitive substitution, e.g.:
```
sed -E ':a; s/^(..)([*]*)[^*](.*..)$/\1\2*\3/; ta'
```
### Explanation
This works by repeating the substitution until no change happens, that is what the `:a; ...; ta` bit does. The substitution consists of 3 matched groups and a non-asterisk character:
* `(..)` the start of the string.
* `([*]*)` any already replaced characters.
* `[^*]` the character to be replaced next.
* `(.*..)` any remaining characters to replace and the end of the string.
### Alternative GNU sed answer
You could also do this by using the hold space which might be simpler to read, e.g.:
```bash
h # save a copy to hold space
s/./*/g3 # replace all but 2 by *
G # append hold space to pattern space
s/^(..)([*]*)..\n.*(..)$/\1\2\3/ # reformat pattern space
```
Run it like this:
```
sed -Ef parse.sed input.txt
```
### Output in both cases
```none
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
```
Upvotes: 2
|
2018/03/15
| 423 | 1,674 |
<issue_start>username_0: How to make the menu reappear if the user doesnt press any key like 3 in this case to exit the program.
```
import java.util.Scanner;
public class New {
public static void main(String[] args) {
System.out.println("Enter 1 to create folder/ 2 to create file/ 3 to exit");
Scanner scan= new Scanner(System.in);
int choice= scan.nextInt();
while(true) {
if(choice==1) {
System.out.println("Creating folder");
}
else if(choice==2) {
System.out.println("Creating file");
}
else {
System.out.println("Exiting");
}
}
}
}
```<issue_comment>username_1: You have to put the System.out.println() statement inside the loop.
```
public class New {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
while(true) {
System.out.println("Enter 1 to create folder/ 2 to create file/ 3 to exit");
int choice= scan.nextInt();
if(choice==1) {
System.out.println("Creating folder");
}
else if(choice==2) {
System.out.println("Creating file");
}
else if (choice==3){
System.out.println("Exiting");
}
}
}
```
Upvotes: 1 <issue_comment>username_2: You can use do while loop.
```
do{
choice = sc.nextInt();
if(choice==1) {
System.out.println("Creating folder");
}
else if(choice==2) {
System.out.println("Creating file");
}
}while(choice!=3);
```
Upvotes: 0
|
2018/03/15
| 1,007 | 3,625 |
<issue_start>username_0: I was trying to make a **react-native app** with **redux**, which is a **counter**. I was using [snack.expo.io](https://snack.expo.io/) website in PC and **expo app** in Android, as I can't run it plainly in my system due to limitations .The app runs but when i click any of the buttons, it shows the error:
**" Failed to install module 'react-redux':
Attempted to import missing module 'redux'
imported from App.js"**
[The snack.expo.io page i made is given here](https://snack.expo.io/B1eqJ1OKM)
I did add the **'redux'** and **'react-redux'** into the **package.json** file. Still it shows the same error.
What did I do wrong, or is there any other way to use 'redux' and 'react-redux' in expo?
I saw the same app being run on a system using npm and all. So I suspect it is a problem with snack.expo.io, as the import for the libraries mentioned are not working.
Do look through the code and let me know what I can do.
**Update:**
The documentation in which all modules available in snack contains 'redux' and 'react-redux' as shown in the answer by Tetsuya3850.
<https://forums.expo.io/t/modules-available-in-snack/1651><issue_comment>username_1: I think the packages that you could use in snack are limited. (<https://forums.expo.io/t/modules-available-in-snack/1651>)
But the limitation is changing real-time?
(<https://forums.expo.io/t/adding-new-modules-to-expo-snack/1496/4>)
Upvotes: 0 <issue_comment>username_2: Snack is constantly changing and right now and it seems to be throwing the wrong error. I downloaded your snack and ran it with `exp` [the expo command line tool](https://docs.expo.io/versions/latest/guides/exp-cli.html#content). This revealed a few syntax errors which can be simply resolved!
* `counterActions.AddNumber -> counterActions.addNumber`
* `counterActions.DecrementCount -> counterActions.decrementCount`
* There is also another error related to formatting: `Actions must be plain objects. Use custom middleware for async actions.`
I'll share this with TC the dev working on snack, he's pretty good at
fixing these kinds of problems.
---
**A lazy man's opinion of Redux**
It looks like you are running into some of the usual errors of standard Redux.
Standard Redux gives me chest pain - I highly recommend using **[Rematch](https://github.com/rematch/rematch)**!
* Rematch is a standard format for Redux, you may have noticed that
everyone formats a little different.
* A lot less code and much easier to manage. Because of how it's structured you tend to use more shallow redux objects which can really help performance.
* Async is built in... so yeah
* Here is a counter example using rematch <https://snack.expo.io/@bacon/rematch-example> notice how little code is used, there are also more features in this example than in the snack provided above.
* It can be weird incorporating with `react-navigation` but <NAME> the dev currently working on react-navigation says you should avoid using redux with it anyways. ♀️
* I am **not affiliated** with Rematch even though this seems like a very bias review.
Upvotes: 2 [selected_answer]<issue_comment>username_3: For thouse who came here with this same problem, you can manually add it to the dependency list.
Go to package.json, at dependencies use the following format
"package": "version", you may want to chack the currently version of you package
ie:
```
"dependencies":{
"redux": "4.0.5",
"react-redux": "7.2.1",
}
```
You may have other dependencies before or after.
[enter image description here](https://i.stack.imgur.com/Oft4R.png)
Upvotes: 0
|
2018/03/15
| 2,166 | 8,516 |
<issue_start>username_0: I am new in both React and GatsbyJS. I am confused and could not make figuring out in a simple way to load data from third-party Restful API.
For example, I would like to fetch data from randomuser.me/API and then be able to use the data in pages.
Let’s say something like this :
```js
import React from 'react'
import Link from 'gatsby-link'
class User extends React.Component {
constructor(){
super();
this.state = {
pictures:[],
};
}
componentDidMount(){
fetch('https://randomuser.me/api/?results=500')
.then(results=>{
return results.json();
})
.then(data=>{
let pictures = data.results.map((pic,i)=>{
return(

)
})
this.setState({pictures:pictures})
})
}
render() {
return ({this.state.pictures})
}
}
export default User;
```
But I would like to get the help of GraphQL in order to filter & sort users and etc…..
Could you please help me to find the sample to how I can fetch data and insert them into GraphQL on `gatsby-node.js`?<issue_comment>username_1: If you want to use GraphQL to fetch your data, you have to create a `sourceNode`. The doc about [creating a source plugin](https://www.gatsbyjs.org/docs/create-source-plugin/#create-source-plugin) could help you.
Follow these steps to be able to query `randomuser` data with GraphQL in your Gatsby project.
1) Create nodes in gatsby-node.js
---------------------------------
In your root project folder, add this code to `gatsby-node.js`:
```js
const axios = require('axios');
const crypto = require('crypto');
exports.sourceNodes = async ({ actions }) => {
const { createNode } = actions;
// fetch raw data from the randomuser api
const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
// await for results
const res = await fetchRandomUser();
// map into these results and create nodes
res.data.results.map((user, i) => {
// Create your node object
const userNode = {
// Required fields
id: `${i}`,
parent: `__SOURCE__`,
internal: {
type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
// contentDigest will be added just after
// but it is required
},
children: [],
// Other fields that you want to query with graphQl
gender: user.gender,
name: {
title: user.name.title,
first: user.name.first,
last: user.name.last,
},
picture: {
large: user.picture.large,
medium: user.picture.medium,
thumbnail: user.picture.thumbnail,
}
// etc...
}
// Get content digest of node. (Required field)
const contentDigest = crypto
.createHash(`md5`)
.update(JSON.stringify(userNode))
.digest(`hex`);
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
return;
}
```
>
> I used `axios` to fetch data so you will need to install it: `npm install --save axios`
>
>
>
### Explanation:
The goal is to create each node for each piece of data you want to use.
According to the [createNode documentation](https://www.gatsbyjs.org/docs/bound-action-creators/#createNode), you have to provide an object with few required fields (id, parent, internal, children).
Once you get the results data from the randomuser API, you just need to create this node object and pass it to the `createNode()` function.
Here we map to the results as you wanted to get 500 random users `https://randomuser.me/api/?results=500`.
Create the `userNode` object with the required and wanted fields.
You can add more fields depending on what data you will want to use in your app.
Just create the node with the `createNode()` function of the Gatsby API.
2) Query your data with GraphQL
-------------------------------
Once you did that, run `gatsby develop` and go to <http://localhost:8000/___graphql>.
You can play with GraphQL to create your perfect query. As we named the `internal.type` of our node object `'RandomUser'`, we can query `allRandomUser` to get our data.
```
{
allRandomUser {
edges {
node {
gender
name {
title
first
last
}
picture {
large
medium
thumbnail
}
}
}
}
}
```
3) Use this query in your Gatsby page
-------------------------------------
In your page, for instance `src/pages/index.js`, use the query and display your data:
```
import React from 'react'
import Link from 'gatsby-link'
const IndexPage = (props) => {
const users = props.data.allRandomUser.edges;
return (
{users.map((user, i) => {
const userData = user.node;
return (
Name: {userData.name.first}

)
})}
);
};
export default IndexPage
export const query = graphql`
query RandomUserQuery {
allRandomUser {
edges {
node {
gender
name {
title
first
last
}
picture {
large
medium
thumbnail
}
}
}
}
}
`;
```
That is it!
Upvotes: 7 <issue_comment>username_2: Many thanks, this is working fine for me, I only change small parts of the gastbyjs-node.js because it makes an error when use sync & await, I think I need change some section of a build process to use babel to allow me to use sync or await.
Here is the code which works for me.
```
const axios = require('axios');
const crypto = require('crypto');
// exports.sourceNodes = async ({ boundActionCreators }) => {
exports.sourceNodes = ({boundActionCreators}) => {
const {createNode} = boundActionCreators;
return new Promise((resolve, reject) => {
// fetch raw data from the randomuser api
// const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
// await for results
// const res = await fetchRandomUser();
axios.get(`https://randomuser.me/api/?results=500`).then(res => {
// map into these results and create nodes
res.data.results.map((user, i) => {
// Create your node object
const userNode = {
// Required fields
id: `${i}`,
parent: `__SOURCE__`,
internal: {
type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
// contentDigest will be added just after
// but it is required
},
children: [],
// Other fields that you want to query with graphQl
gender: user.gender,
name: {
title: user.name.title,
first: user.name.first,
last: user.name.last
},
picture: {
large: user.picture.large,
medium: user.picture.medium,
thumbnail: user.picture.thumbnail
}
// etc...
}
// Get content digest of node. (Required field)
const contentDigest = crypto.createHash(`md5`).update(JSON.stringify(userNode)).digest(`hex`);
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
resolve();
});
});
}
```
Upvotes: 3 <issue_comment>username_3: The answers given above work, except the query in step 2 seems to only return one node for me. I can return all nodes by adding totalCount as a sibling of edges. I.e.
```
{
allRandomUser {
totalCount
edges {
node {
id
gender
name {
first
last
}
}
}
}
}
```
Upvotes: 1 <issue_comment>username_4: The accepted answer for this works great, just to note that there's a deprecation warning if you use `boundActionCreators`. This has to be renamed to `actions` to avoid this warning.
Upvotes: 2 <issue_comment>username_5: You can get data at the frontend from APIs using react `useEffect`. It works perfectly and you will no longer see any error at builtime
```
const [starsCount, setStarsCount] = useState(0)
useEffect(() => {
// get data from GitHub api
fetch(`https://api.github.com/repos/gatsbyjs/gatsby`)
.then(response => response.json()) // parse JSON from request
.then(resultData => {
setStarsCount(resultData.stargazers_count)
}) // set data for the number of stars
}, [])
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 561 | 2,550 |
<issue_start>username_0: The fields in my Rate Table are Route, VehicleMasterId, VehicleType, Material, Client, UnitRate etc.
The priority order on which I have to fetch a single row is : VehicleNo > Route > Client > VehicleType, Material
Suppose I have 2 rows with same data except 1 has Client and Vehicle Type and the other one has VehicleNo.Then based on my priority, I should pick the rate of the row with VehicleNo.
To excute this In linq I have first picked all the rows with matching data. Here is my code.
```
public RateMasterDataModel GetRateMasterforCn(Consignment cn){
// I will always pass all the above fields in cn
var rateMaster = (from rate in Context.RateMaster
where rate.FromDate <= cn.Cndate
&& rate.ToDate >= cn.Cndate
&& (rate.VehicleTypeId != null ? rate.VehicleTypeId == cn.VehicleTypeId : true)
&& (rate.VehicleMasterId != null ? rate.VehicleMasterId == cn.VehicleMasterId : true)
&& (rate.ClientId != null ? rate.ClientId == cn.ClientId : true)
&& (rate.RouteId != null ? rate.RouteId == cn.RouteId : true)
&& (rate.MaterialMasterId != null ? rate.MaterialMasterId == cn.MaterialMasterId : true)
select new RateMasterDataModel
{
RateMasterId = rate.RateMasterId,
FromDate = rate.FromDate,
ToDate = rate.ToDate,
ClientId = rate.ClientId ,
VehicleMasterId = rate.VehicleMasterId,
VehicleTypeId = rate.VehicleTypeId,
MaterialMasterId = rate.MaterialMasterId,
UnitRate = rate.UnitRate,
LoadTypeId = rate.LoadTypeId,
LoadingPointId = rate.RouteId,
CalculationMasterId = rate.CalculationMasterId
}).ToList();
}
```
Please suggest how to filter after this.<issue_comment>username_1: You mean to say if the row which doesn't have the vehicalno. filld-up then the row having Route must be selected.is it correct?
Upvotes: 0 <issue_comment>username_2: You can use below code to get records ordered by VehicleNo > Route
```
.OrderBy(v=>v.VehicleNo).ThenBy(r=>r.RouteId)
```
Add multiple `.ThenBy()` clause as per your column requirement for sorting the data.
Upvotes: 2 [selected_answer]
|
2018/03/15
| 432 | 1,668 |
<issue_start>username_0: I've been stuck on this problem for a few weeks now with no avail.
I am saving the contents of an array-list to a text file so that when the user opens the activity, the array list loads itself up for the user.
When i try to read the text file, and add the contents to the array-list, I get the following input inside the arraylist "Java.io.ObjectInputStream@b37391"
My array list will then look like this
[hello , leon, java.io.ObjectInputStream@b373791]
How can I read the text from the text file and display its contents on the array list
I have supplied the code used below, I have read many tutorials and stackoverflow questions but nothing seems to work. Some advice will be greatly appreciated.
```
try {
File f = new File(getFilesDir(), "anxfile.txt");
FileInputStream readtheting = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(readtheting);
ois.readObject();
arrayList.add(String.valueOf(ois));
adapter.notifyDataSetChanged();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
```<issue_comment>username_1: You mean to say if the row which doesn't have the vehicalno. filld-up then the row having Route must be selected.is it correct?
Upvotes: 0 <issue_comment>username_2: You can use below code to get records ordered by VehicleNo > Route
```
.OrderBy(v=>v.VehicleNo).ThenBy(r=>r.RouteId)
```
Add multiple `.ThenBy()` clause as per your column requirement for sorting the data.
Upvotes: 2 [selected_answer]
|
2018/03/15
| 520 | 1,567 |
<issue_start>username_0: I am trying open `*.mp4` file with `opencv`. I am trying with following code but I am unable to do this. How can solve this issue?
```
import cv2
cap = cv2.VideoCapture("test.mp4")
# cap = cv2.VideoCapture("test.avi") # it's also not working
cap.isOpened() # Output: False
```
* N.B:
+ OS : ubuntu 16.04
+ OpenCv version: 3.3.0<issue_comment>username_1: try updating opencv.
also, this might help: [Cannot open ".mp4" video files using OpenCV 2.4.3, Python 2.7 in Windows 7 machine](https://stackoverflow.com/questions/13834399/cannot-open-mp4-video-files-using-opencv-2-4-3-python-2-7-in-windows-7-machi)
Upvotes: -1 <issue_comment>username_2: I don't know if this post up-to-date. However, I had the same problem on Ubuntu 18.4 and had installed the opencv via conda:
```
conda install --channel https://conda.anaconda.org/menpo opencv3
```
And it turned out that menpo is not supported anymore. After installing from conda-forge, the problem disappeared:
```
conda install -c conda-forge opencv
```
You can surely check if the mpeg support is there:
```
python -c "import cv2; print(cv2.getBuildInformation())" | grep -i ffmpeg
```
it should return "YES"
Upvotes: 2 <issue_comment>username_3: install this package, it enable ffmpeg in opencv:
```
pip install opencv-contrib-python
```
Upvotes: 2 <issue_comment>username_4: Install this package
>
> pip install VideoCapture
>
>
>
```
import cv2
cap = cv2.VideoCapture("test.mp4")
# cap = cv2.VideoCapture("test.avi")
cap.isOpened()
cap.release()
```
Upvotes: 1
|
2018/03/15
| 538 | 1,652 |
<issue_start>username_0: This link explains the way to change the Text on Menu - <https://github.com/marmelab/admin-on-rest/blob/master/docs/Resource.md#options>
But I would like to know how to change the Text which is rendered on right side panel i.e. when one clicks on the drawer menu. I see that if my code is like this :
>
>
> >
> > then the Title is rendered as **V2/Posts List**. How do I give a custom title ?
> >
> >
> >
>
>
><issue_comment>username_1: try updating opencv.
also, this might help: [Cannot open ".mp4" video files using OpenCV 2.4.3, Python 2.7 in Windows 7 machine](https://stackoverflow.com/questions/13834399/cannot-open-mp4-video-files-using-opencv-2-4-3-python-2-7-in-windows-7-machi)
Upvotes: -1 <issue_comment>username_2: I don't know if this post up-to-date. However, I had the same problem on Ubuntu 18.4 and had installed the opencv via conda:
```
conda install --channel https://conda.anaconda.org/menpo opencv3
```
And it turned out that menpo is not supported anymore. After installing from conda-forge, the problem disappeared:
```
conda install -c conda-forge opencv
```
You can surely check if the mpeg support is there:
```
python -c "import cv2; print(cv2.getBuildInformation())" | grep -i ffmpeg
```
it should return "YES"
Upvotes: 2 <issue_comment>username_3: install this package, it enable ffmpeg in opencv:
```
pip install opencv-contrib-python
```
Upvotes: 2 <issue_comment>username_4: Install this package
>
> pip install VideoCapture
>
>
>
```
import cv2
cap = cv2.VideoCapture("test.mp4")
# cap = cv2.VideoCapture("test.avi")
cap.isOpened()
cap.release()
```
Upvotes: 1
|
2018/03/15
| 865 | 3,055 |
<issue_start>username_0: I'm using Laravel 5.6 and Vuejs 2. I'm a beginner in Vuejs and stuck at the layout structure. I want to use laravel for backend API and frontend completely on Vuejs so that i can move to different pages without refreshing the browser.
I have created these in the components folder
```
Components
-INCLUDES
- navbar.vue
- footer.vue
-PAGES
- about.vue
- contact.vue
-AUTHENTICATION
- login.vue
- register.vue
- resetpassword.vue
```
I have installed Vue router and made a routes.js file in assets
My question is how to make a layout with the components above so that navbar and footer stay on every page and page components load without refreshing when clicking on the links.<issue_comment>username_1: You should have a main component, such as `app.vue` where you import the router and display the `router-view`. Then, you can also use your navigation and footer components in there. Something like this:
```
```
In your app.js file (or main.js, something like that)
```
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);
//import here page components
import App from './App.vue'
import Home from './components/Home.vue'
//Routes
const routes = [
{ path: '/', name: 'home', component: Home }
//other routes here
];
const router = new VueRouter({
mode: 'history',
routes // short for `routes: routes`
});
//Vue Init
new Vue({
el: '#app',
router,
render: h => h(App)
})
```
My file structure with Vue and Laravel
[](https://i.stack.imgur.com/gtox4.png)
Upvotes: 2 [selected_answer]<issue_comment>username_2: The file structure should consists of -
[](https://i.stack.imgur.com/ZaPrY.png)
It should consists of src folder containing store, components and assets as crucial elements to any vue boilerplate.
can be also written as now onwards. It only displays the components that are included in `routes.js` which is below `app.vue`.
app.vue
```
Home
Post a picture
```
routes.js can be in router folder in src, but here I have taken it in src folder as I don't have much to do with vue-router.
routes.js
```
import Vue from 'vue'
import Router from 'vue-router'
import homeview from '../components/homeview'
import detailview from '../components/detailview'
import postview from '../components/postview'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Homeview',
component: homeview
},
{
path: '/detailview',
name: 'detailview',
component: detailview
},
{
path: '/postview',
name: 'Postview',
component: postview
}
]
})
```
main.js
```
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
Vue.config.productionTip = false
Vue.use(axios);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '',
components: { App }
})
```
Upvotes: -1
|
2018/03/15
| 859 | 2,614 |
<issue_start>username_0: How to get distinct words of a column based on group by of another column
I need to get distinct colB words for each colA value
my dataframe:
```
colA colB
US California City
US San Jose ABC
UK London 123
US California ZZZ
UK Manchester
UK London
```
Reqd dataframe (df):
```
col A colB
US California
US City
US ABC
US ZZZ
US San
US Jose
UK London
UK 123
UK Manchester
```
EDIT:
Thanks to @jezrael, I was able to get the desired dataframe
I have another dataframe (df2)
```
ColC ColA ColB
C1 US California
C1 US ABC
C2 UK LONDON
```
For each value of column (colC), i need the intersection of colB strings with the previously obtained dataframe.
Required:
```
ColC n(df2_colBuniq) n(df_df2_intersec_colB)
C1 2 2
C2 1 1
```
I tried looping through each unique colC value, but for the large data frame I have, it is taking quite some time. Any suggestions?<issue_comment>username_1: Use:
* [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) and select `colB`
* [`split`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html) by whitespaces to `DataFrame`
* reshape by [`stack`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html) to `Series`
* [`reset_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html) for column from `index`
* [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html)
---
```
df = (df.set_index('colA')['colB']
.str.split(expand=True)
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='colB')
.drop_duplicates()
)
print (df)
colA colB
0 US California
1 US City
2 US San
3 US Jose
4 US ABC
5 UK London
6 UK 123
8 US ZZZ
9 UK Manchester
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: We can using `get_dummies`
```
df.set_index('colA').colB.str.get_dummies(sep=' ').sum(level=0).replace(0,np.nan).stack().reset_index()
Out[13]:
colA level_1 0
0 US ABC 1.0
1 US California 2.0
2 US City 1.0
3 US Jose 1.0
4 US San 1.0
5 US ZZZ 1.0
6 UK 123 1.0
7 UK London 2.0
8 UK Manchester 1.0
```
Upvotes: 1
|
2018/03/15
| 602 | 2,049 |
<issue_start>username_0: On the time of page loaded get\_switch() function which globally created on app.js page will be call then return a method. i want to execute these return methods.
demo.js
```
const return_functions = get_switch('BTC');
function get_btc()
{
console.log('btc');
}
function get_bch()
{
console.log('bch');
}
```
app.js
```
global.get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
return 'get_btc()';
break;
case 'BCH':
return 'get_bth()';
break;
default:
console.log('default');
}
}
```
As shown in example above i have passed BTC in get\_switch. and that function return us get\_btc() function. so i want to call get\_btc function on same time.
If this is not possible in this way so please guide me with your idea and suggest me how can i do this.<issue_comment>username_1: You could just invoke the functions directly
```
function get_btc() {}
function get_bch() {}
global.get_switch = function (coin_name) {
switch(coin_name){
case 'BTC':
return get_btc();
break;
case 'BCH':
return get_bch();
break;
default:
console.log('default');
}
}
```
Upvotes: 0 <issue_comment>username_2: You can store all function into a class, and then call them using the name of the currency.
I've added something else tho, which is the use of an enumerate to handle your currencies.
```js
class CurrencyHandlingClass {
// Store all currency type into an enumerate
static get CURRENCY_TYPES() {
return {
BTC: 'Btc',
BTH: 'Bth',
};
}
// Method to get Btc
static getBtc() {
console.log('btc');
}
// Method to get Bhc
static getBth() {
console.log('bth');
}
}
// Here the name of the function you wanna call
const currencyName1 = CurrencyHandlingClass.CURRENCY_TYPES.BTC;
const currencyName2 = CurrencyHandlingClass.CURRENCY_TYPES.BTH;
// Execute the method
CurrencyHandlingClass[`get${currencyName1}`]();
CurrencyHandlingClass[`get${currencyName2}`]();
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 1,162 | 5,079 |
<issue_start>username_0: I always use REST API when I get or post some data.
But WebSocket can also do that.
So, I am confused about the difference between WebSocket and REST API
when I try to get or post some data.<issue_comment>username_1: You can provide a REST API along with a WebSocket API for different purposes. It's up to your requirements and it depends on what you want to achieve.
For example, a WebSocket API can be used to provide real-time notifications while the REST API can be used to manage your resources.
There are a few details you should be aware of:
* REST is a protocol independent architectural style frequently implemented over the HTTP protocol and it's supposed to be stateless.
* WebSocket is a bi-directional, full-duplex and persistent connection protocol, hence it's stateful.
Just to mention one example of application that provides different APIs: Stack Exchange provides a [REST API](https://api.stackexchange.com/docs) along with a [WebSocket API](https://meta.stackexchange.com/q/218343/278120).
Upvotes: 3 <issue_comment>username_2: I haven't yet fully understood what a REST API is, but I guess you refer to it in a broarder way so as to web systems that provide structured data referd to a specific resource as can be a customer, or a product, upon a `POST` or `GET` call over http.
The main difference from a practical and simplistic approach is that `HTTP` `GET` / `POST` are request - response protocols. The server will send a response upon a request sent by the client.
In the case of `Websockets`, communication is bidirectional. Either the server or the client can send information to the counterpart at any time.
To visualize the difference a page that provides stock market data if using `HTTP` `GET` will issue a new request to the server each X seconds to get the updated price. Using websockets, the SERVER could directly send the new price to the web browser as soon as it has changed.
You may also be interested in looking into `long polling` which is a techinc used with HTTP GET / POST to provide similar functionality as Websockets (though it is a totally different thing)
Upvotes: 2 <issue_comment>username_3: A REST API uses HTTP as the underlying protocol for communication, which in turn follows the request and response paradigm. However, with WebSockets, although the communication still starts off over HTTP, it is further elevated to follow the WebSockets protocol if both the server and the client are compliant with the protocol (not all entities support the WebSockets protocol).
Now with WebSockets, it is possible to establish a full duplex and persistent connection between the client and a server. This means that unlike a request and a response, the connection stays open for as long as the application is running, and since it is full duplex, two way simultaneous communication is possible i.e now the server is capable of initiating a communication and 'push' some data to the client.
This is the primary concept use in the realtime technology where you are able to get new updates in the form of server push without the client having to request (refresh the page) repeatedly. Examples of such applications are Uber car's location tracking, Push Notifications, Stock market prices updating in realtime etc.
Here's a video from a presentation I gave earlier this month about websockets and how they are different than using the regular REST APIs: <https://www.youtube.com/watch?v=PJZ06MLXGwA&list=PLZWI9MjJG-V_Y52VWLPZE1KtUTykyGTpJ&index=2>
Upvotes: 5 [selected_answer]<issue_comment>username_4: WebSockets are, just like sockets, an interface between two adjacent layers.
Specifically, in ARPANET reference model, sockets are an interface between Transport layer and Application layer; in OSI reference model, they represent an interface between Session layer and Transport layer. Interface means that they reside "in between" layers (at their boundary).
WebSockets are the sockets interface that was "migrated" from the Session/Transport layer boundary to the Session/Presentation boundary of the OSI model. This was done in order to overcome limitations of sockets in the world of web where all communications are "free" by default only on the port 80, the port of HTTP traffic. HTTP protocol, which sits on top of (guaranteed delivery) TCP Transport layer, is part of the Session layer in OSI model thus it can be considered as a "transport" as well for the layer above, the Presentation layer.
Since "I" in "API" stands for "Interface", both sockets and WebSockets are a form of API, although the term API belongs to a modern jargon. REST API is also an interface between Session and Presentation layers of the OSI model.
The difference between the REST API interface and WebSockets interface is that WebSockets is a full duplex persistent TCP connection established via 3-way handshake protocol over HTTP. REST API over HTTP is, just like HTTP, a Request/Response (non-standard) protocol where a TCP connection is created on each new request i.e. it is not persistent.
Upvotes: 0
|
2018/03/15
| 364 | 1,328 |
<issue_start>username_0: I know that `$(".el").load(function()...` is deprecated from version 3.0, but now i'm in a situation where I need a plugin that's using `.load` rather than `.on("load", function()`
Is there any way to allow the use of `.load(function()` in version > 3.0 without using jQuery Migrate? Also, loading another version of jQuery isn't an option either as this seems a bit over the top for a single line of code.
EDIT: as pointed out in comment, I cannot rely on changing the plugin code as i'm using wordpress and the changes will be removed when updating.<issue_comment>username_1: You can do something like this? Apply both jQuery version with noConflict.
```
var jQuery\_1\_1\_3 = $.noConflict(true);
var jQuery\_3.2.1 = $.noConflict(true);
```
Now in your js instead of $ just use jQuery\_3.2.1.
for example,
```
jQuery_3.2.1(document).ready(....)
```
By this way you won't have to change the plugin code.
Upvotes: 1 <issue_comment>username_2: To make it work, you can opt to use [jQuery.migrate](https://github.com/jquery/jquery-migrate).
This plugin adds functions removed from jQuery core. This shouldn't be used in production but should be used to fix problems you are having with your scripts.
[jQuery.migrate for Wordpress](https://pt.wordpress.org/plugins/jquery-migrate/)
Upvotes: 0
|
2018/03/15
| 621 | 2,262 |
<issue_start>username_0: How do i replace multiple words with an empty string "" in a string with java. I tried with for loop to replace those in single quotes by adding then in an array like below, but it replaces one word per printout.
```
String str = "this house 'is' really 'big' and 'attractive'.";
String[] values={"is","big","attractive"};
for(String s: values){
String replaced = str.replace(s, "");
System.out.println( replaced );
}
```
I'm getting this output:
```
> this house ' ' really 'big' and 'attractive'.
> this house 'is' really ' ' and 'attractive'.
> this house 'is' really 'big' and ' '.
```
What I need is this:
```
> this house ' ' really ' ' and ' '.
```<issue_comment>username_1: ```
System.out.println(str.replaceAll("is|big|attractive", ""));
```
Upvotes: 3 <issue_comment>username_2: You re-start each iteration from the original `String`, which you don't modify.
You could change the `String` your `str` refers to and use that, like this:
```
for(String s: values){
str = str.replace(s, "");
System.out.println( str );
}
```
Upvotes: 1 <issue_comment>username_3: You are re-initializing`replaced` in every iteration. So you end up with a string in which only the last element of array `values` is replaced.
To get the desired output, try this:
```
String replaced = str;
for(String s: values){
replaced = replaced.replace(s, "");
}
```
Upvotes: 0 <issue_comment>username_4: **Why your approach is wrong**
Strings in Java are immutable - when you call replace , it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
`str= str.replace(s, "");` instead of `String replaced = str.replace(s, "");`
Also, write this code after the for loop: `System.out.println(str);` and omit `System.out.println( replaced );` as its placement is inside the for loop right now resulting into multiple statements getting printed.
Note that after doing all this, code would print `th house '' really '' and ''.` and NOT the desired output.
**Why follow username_1's answer OR use a generic regex expression**
Even after correcting your code, you would NOT get the desired results, hence :)
Upvotes: 2 [selected_answer]
|
2018/03/15
| 498 | 1,881 |
<issue_start>username_0: There is a text, it may be one line or multiple lines, I want set any style(e.g `background-color: red`) when one line and `background-color: black` when 2 lines.(note: both for the **whole** text rather than first/second/... line)
Is there any way to implement this?(don't use javascript)<issue_comment>username_1: ```
System.out.println(str.replaceAll("is|big|attractive", ""));
```
Upvotes: 3 <issue_comment>username_2: You re-start each iteration from the original `String`, which you don't modify.
You could change the `String` your `str` refers to and use that, like this:
```
for(String s: values){
str = str.replace(s, "");
System.out.println( str );
}
```
Upvotes: 1 <issue_comment>username_3: You are re-initializing`replaced` in every iteration. So you end up with a string in which only the last element of array `values` is replaced.
To get the desired output, try this:
```
String replaced = str;
for(String s: values){
replaced = replaced.replace(s, "");
}
```
Upvotes: 0 <issue_comment>username_4: **Why your approach is wrong**
Strings in Java are immutable - when you call replace , it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
`str= str.replace(s, "");` instead of `String replaced = str.replace(s, "");`
Also, write this code after the for loop: `System.out.println(str);` and omit `System.out.println( replaced );` as its placement is inside the for loop right now resulting into multiple statements getting printed.
Note that after doing all this, code would print `th house '' really '' and ''.` and NOT the desired output.
**Why follow username_1's answer OR use a generic regex expression**
Even after correcting your code, you would NOT get the desired results, hence :)
Upvotes: 2 [selected_answer]
|
2018/03/15
| 2,543 | 9,049 |
<issue_start>username_0: first of all sorry for English
So i already have "user - posts" one to many association, which means that each post can have just ONE author, and now i want to add "favorite posts" button to user profile, and "add to favorite" button to each post, so the question is how to implement this correct way? should i rework my user - post association?
or create some another model? I,m a bit confused. Thank in advance !
**Actually i want this result :**
**@user.posts** #return all posts created by this user
**@user.favorite\_posts** #return posts added to favorites by this user
Here is my User model:
```
class User < ApplicationRecord
mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings
enum role: [ :user, :admin ]
def calculate_average
ratings.blank? ? 0 : ratings.map(&:value).inject(:+) / ratings.count.to_f
end
end
```
Post model:
```
class Post < ApplicationRecord
mount_uploader :image, ImageUploader
validates :body, presence: true
validates :title, presence: true, length: { maximum: 50}
belongs_to :user
has_many :comments, dependent: :destroy
end
```
**EDIT**
**Alright look how i've done this, it works exactly the way I wanted it.**
**Here is my user model:**
```
class User < ApplicationRecord
mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings
has_many :favorites, dependent: :destroy
has_many :favorite_posts, through: :favorites, source: "post"
enum role: [ :user, :admin ]
def calculate_average
ratings.blank? ? 0 : ratings.map(&:value).inject(:+) / ratings.count.to_f
end
end
```<issue_comment>username_1: You need [`many-to-many`](http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association) relationships for the favorite post, at first run this command to create a table `favorite_posts`
```
rails g model FavoritePost user:references post:references
```
Then
```
rails db:migrate
```
Then add these to your model would look like this:
```
#=> model/user.rb
class User < ApplicationRecord
has_many :favorite_posts, dependent: :destroy # or you can use only this line except second if you will face any problem
has_many :posts, through: :favorite_posts
end
#=> model/post.rb
class Post < ApplicationRecord
has_many :favorite_posts, dependent: :destroy
has_many :users, through: :favorite_posts
end
#=> model/favorite_post.rb
class FavoritePost < ApplicationRecord
belongs_to :user
belongs_to :post
end
```
That was relation part, now create a favorite post part. For the fresh code you can create a controller, i.e.
```
rails g controller favorites
```
Then your routes file:
```
resources :favorites
```
An example of the new routes using `rake routes`:
```
favorites GET /favorites(.:format) favorites#index
POST /favorites(.:format) favorites#create
new_favorite GET /favorites/new(.:format) favorites#new
edit_favorite GET /favorites/:id/edit(.:format) favorites#edit
favorite GET /favorites/:id(.:format) favorites#show
PATCH /favorites/:id(.:format) favorites#update
PUT /favorites/:id(.:format) favorites#update
DELETE /favorites/:id(.:format) favorites#destroy
```
In your view file add something like this:
```
# For creating favorite
<%= link_to "Favorite", favorites_path(user: current_user, post: post.id), class: 'btn bf-save-btn', method: :post, data: {disable_with: "Saving..."}, title: "Add to favorite" %>
# For deleting favorite list
<%= link_to "Unfavorite", favorite_path(post.id), class: 'btn af-save-btn', method: :delete, data: {disable_with: "Removing...."}, title: "Remove from favorite" %>
```
In `favorites_controller.rb`:
```
def index
@saves = current_user.favorite_post
end
# index.html.erb
<% @saves.each do |fav| %>
<%= link_to fav.post.post_title, post_path(fav.post) %>
<% end %>
def create
@save = FavoritePost.new(post_id: params[:post], user: current_user)
respond_to do |format|
if @save.save
flash[:success] = 'Saved'
format.html { redirect_to request.referer }
format.xml { render :xml => @save, :status => :created, :location => @save }
else
format.html { redirect_to request.referer }
format.xml { render :xml => @save.errors, :status => :unprocessable_entity }
end
end
end
def destroy
post = Post.find(params[:id])
@save = FavoritePost.where(user_id: current_user.id, post_id: post.id).first
respond_to do |format|
if @save.destroy
flash[:error] = 'Unsaved'
format.html { redirect_to request.referer, status: 303 }
format.js { redirect_to request.referer, status: 303 }
# format.xml { head :ok }
end
end
end
```
That's it for favorite / unfavorite functionality. Now you need to create some logic for when to show `Favorite` and when `Unfavorite`.
For this requirements has many ways, at first you need to understand this then you can whatever you want.
Also, to achieve this without reloading your page you can try some `Ajax`.
**Update**
```
class User < ApplicationRecord
mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings
# Newly added
has_many :favorite_posts, dependent: :destroy # or you can use only this line except second if you will face any problem
has_many :posts, through: :favorite_posts
enum role: [ :user, :admin ]
def calculate_average
ratings.blank? ? 0 : ratings.map(&:value).inject(:+) / ratings.count.to_f
end
end
```
Hope it will help.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Create a new model for 'UserFavoritePost' stored post\_id and user\_id. And create a custom association for favorite\_posts
```
class UserFavoritePost < ApplicationRecord
belongs_to :post
belongs_to :user
end
class User < ApplicationRecord
has_many :posts, dependent: :destroy
has_many :user_favorite_posts
has_many :favorite_posts, throught: :user_favorite_posts, class: 'Post'
end
```
Upvotes: 1 <issue_comment>username_3: username_1's answer does not provide a direct access to favorite posts, so the index view requires a loop. Prasanna's approach solves this, but his answer has been unfairly accused of incomplete and plagiarism :-). So here is the complete approach:
You need a **many to many** relationship, that´s true, so you need a join model and table. But this model is auxiliary. No important logic should be there, and I don´t think it deserves a controller or views.
```
class User < ApplicationRecord
has_many :posts, dependent: :destroy # Posts created by this user
has_many :favs, dependent: :destroy
has_many :fav_posts, through: :favs # Favorite posts for this user
end
class Post < ApplicationRecord
belongs_to :user
has_many :favs, dependent: :destroy
has_many :fav_users, through: :favs # Users who have this post as favorite
end
class Fav < ApplicationRecord
belongs_to :user
belongs_to :post
end
```
This allows to access all posts created by the user and all his favorite posts using two different methods in the user class.
```
@posts = current_user.posts # Posts created by this user
@fav_posts = current_user.fav_posts # Favorite posts
```
In the view:
```
<% current\_user.name %>
========================
Your posts
----------
<%= render @posts %>
Your favorite posts from other users
------------------------------------
<%= render @fav_posts %>
```
You don't need a controller to create, view or delete favorite posts. Just handle this logic in the User or Post controllers. For example, to favorite or unfavorite a post just add fav and unfav methods in the PostsController.
```
def fav
current_user.fav_posts << Post.find(params[:id])
end
def unfav
current_user.favs_posts.destroy(Post.find(params[:id]))
end
```
In the view:
```
<%= link_to "Favorite", fav_post_path(id: post.id) %>
<%= link_to "Unfavorite", unfav_post_path(id: post.id) %>
```
You should add these methods in your routes:
```
post '/posts/:id/fav', to: 'posts#fav', as: 'fav_post'
post '/posts/:id/unfav', to: 'posts#unfav', as: 'unfav_post'
```
Upvotes: 1
|
2018/03/15
| 929 | 3,277 |
<issue_start>username_0: I am currently receiving the following error -
"Version string portion was too short or too long"
When using this statement -
```
records = records.OrderBy(r => new Version(r.RefNo)).ToList();
```
To order a list of string's called RefNo. It fails on 25.1.2.1.2 so i assume it is because it has four decimal points? as it works ok with 3....
Is the max four deciaml points for system.version?
Thanks<issue_comment>username_1: See [MSDN](https://msdn.microsoft.com/de-de/library/y0hf9t2e(v=vs.110).aspx)
Costructor `public Version(string version)`
>
> A string containing the major, minor, build, and revision numbers,
> where each number is delimited with a period character ('.').
>
>
>
Makes a total of 4 numbers.
Means the string is limited to 4 numbers, 5 lead to an error.
Also the costructors with `int`'s as parameters only support 1 to 4 parameters.
Upvotes: 1 <issue_comment>username_2: A [`Version`](https://msdn.microsoft.com/en-us/library/y0hf9t2e(v=vs.110).aspx) can only have 4 parts:
>
> major, minor, build, and revision, in that order, and all separated by
> periods.
>
>
>
That's why your approach fails. You could create an extension-method which handles this case, f.e.:
```
public static Version TryParseVersion(this string versionString)
{
if (string.IsNullOrEmpty(versionString))
return null;
String[] tokens = versionString.Split('.');
if (tokens.Length < 2 || !tokens.All(t => t.All(char.IsDigit)))
return null;
if (tokens.Length > 4)
{
int maxVersionLength = tokens.Skip(4).Max(t => t.Length);
string normalizedRest = string.Concat(tokens.Skip(4).Select(t => t.PadLeft(maxVersionLength, '0')));
tokens[3] = $"{tokens[3].PadLeft(maxVersionLength, '0')}{normalizedRest}";
Array.Resize(ref tokens, 4);
}
versionString = string.Join(".", tokens);
bool valid = Version.TryParse(versionString, out Version v);
return valid ? v : null;
}
```
Now you can use it in this way:
```
records = records
.OrderBy(r => r.RefNo.TryParseVersion())
.ToList();
```
With your sample this new version string will be parsed(successfully): `172.16.31.10`
Upvotes: 3 [selected_answer]<issue_comment>username_3: sorry for the late reply but here is the finished extension method i used with a couple of alterations -
```
public static Version ParseRefNo(this string refNoString)
{
if (string.IsNullOrEmpty(refNoString))
return null;
String[] tokens = refNoString.Split('.');
if (tokens.Length < 2 || !tokens.All(t => t.All(char.IsDigit)))
return null;
if (tokens.Length > 4)
{
int maxVersionLength = tokens.Skip(4).Max(t => t.Length);
string normalizedRest = string.Concat(tokens.Skip(4).Select(t => t.PadLeft(maxVersionLength, '0')));
tokens[3] = $"{tokens[3].PadLeft(maxVersionLength, '0')}{normalizedRest}";
Array.Resize(ref tokens, 4);
}
refNoString = string.Join(".", tokens);
Version v = null;
bool valid = Version.TryParse(refNoString, out v);
return valid ? v : null;
}
```
Upvotes: 0
|
2018/03/15
| 709 | 2,566 |
<issue_start>username_0: To make it really simple, let's say I've got an application with passwords stored somewhere (it doesn't matter where).
The php runs:
⋅ `$hash = password_hash($user_input, PASSWORD_DEFAULT);` when the user modifies the password, and then stores `$hash`,
⋅ `$Access = password_verify($user_input, $hash)` when the user tries to log-in.
I would like to be sure and check if the stored password is actually hashed.
In some unusual cases, it can happen that the password is chosen and written manually by someone. So I'd like the php to be able to know when the password is not hashed, and hash it to store it back in a secure form.
Something like:
```
if (!is_hashed($hash)) {
// Hash the password
password_hash($hash, PASSWORD_DEFAULT);
}
```
Is there an easy way to check if a string is the hash of the password or a regular string ?<issue_comment>username_1: password\_hash returns the hashed password if it succeeds or false if it fails.
```
if(!password_hash($password)) {
// do stuff
}
```
Upvotes: 0 <issue_comment>username_2: >
> The php runs:
>
>
> * `password_hash($user_input);` when the user modifies the password and stores it,
> * `$Access = password_verify($user_input, $hash)` when the user tries to log-in.
>
>
>
At this point, passwords that aren't saved as hashes, but as unhashed passwords, would fail the verification, as access is only granted if the *hashed* input matches the saved data, which should be / has to be a hash.
As for identifying if something is a has or not, as I commented, both are just some character string. You can't tell a hash apart from some random passwords. But hashes have a very specific length, so you could find non-hashed passwords that way.
Upvotes: 0 <issue_comment>username_3: You can use the function [`password_get_info()`](http://php.net/manual/en/function.password-get-info.php) to get informations about hashed passwords. It will always return an array like this:
```
[
'algo' => int,
'algoName' => 'name of algorithm|unknown',
'options' => [/*options for algo, or empty if unknown */]
]
```
In case your hash was not really hashed, the function will return the `unknown` case array, which looks like this:
```
[
'algo' => 0,
'algoName' => 'unknown',
'options' => []
]
```
You can check if the algorithm is unknown and hash it then:
```
$hashInfo = password_get_info($hash);
if ($hashInfo['algoName'] === 'unknown') {
$hash = password_hash($hash, PASSWORD_DEFAULT);
//Save new hash to DB
}
```
Upvotes: 1
|
2018/03/15
| 809 | 3,323 |
<issue_start>username_0: I have a kubernetes cluster that is running on AWS EC2 instances and weave as networking(cni). I have disabled the docker networking(ipmask and iptables) as it is managed by weave(to avoid network conflicts).
I have deployed my Jenkins on this cluster as K8s pod and this jenkins uses jenkins kubernetes plugin to spawn dynamic slaves based on pod and container template which I have defined. These slaves container have docker client in it which connects to the host docker engine via docker.sock
So when I run any job in Jenkins it starts a slave and on this it clones a git repo and starts building the Dockerfile present inside the repo.
My sample dockerfile looks like this:
```
FROM abc:123
RUN yum update
```
So when container starts building this it tries connecting to redhat repo to update the local repo and fails here. To debug I logged in to this container and try wget/CURL some packages and finds that there is no internet connectivity in this container.
I suspect that while building docker starts intermediate containers and those containers are not managed by weave so they do not have internet connectivity.
Need suggestions.
Related question: [Internet connection inside Docker container in Kubernetes](https://stackoverflow.com/questions/47003225/internet-connection-inside-docker-container-in-kubernetes/47008722#47008722)<issue_comment>username_1: You can try to [attach weave networking dynamically](https://www.weave.works/docs/net/latest/tasks/manage/dynamically-attach-containers/) as a part of your build job. Is it definitely possible to change active network of container on the flight with weave.
Maybe you will need to use some additional container with [Weave Docker Api Proxy](https://github.com/weaveworks/weave/blob/master/site/tasks/weave-docker-api/using-proxy.md) or you can use a different way to communicate with Weave network on your nodes.
So, the main idea is just attach your containers where you running builds to the Kubernetes pods network, where you have an external access.
Also, and maybe it will be better, you can create another one Weave virtual network with access to the Internet and attach your contenders to it.
Upvotes: 1 <issue_comment>username_2: You're right - the `docker build` process runs in a different context, and Weave Net doesn't attach those automatically.
Even more complicated, Kubernetes will connect via CNI whereas Docker has its own plugin API. I believe it's possible to have both on a machine at the same time, but rather complicated.
Maybe look at some of the [ways to build images without using Docker](https://www.projectatomic.io/blog/2018/03/the-many-ways-to-build-oci-images/) ?
Upvotes: 0 <issue_comment>username_3: Ok finally after lot of struggle I find the solution.
So when ever K8s starts a pod it starts a sidecart container whose role is basically to provide network to pod containers.
So while running docker build if I pass it's container ID as network then my intermediate contexts start getting internet connectivity via this container.
So changes looks something like this:
```
docker build -t "some name" --network container:\$(docker ps | grep \$(hostname) | grep k8s_POD | cut -d\" \" -f1) -f infra/docker/Dockerfile .
```
Hope this helps. :D
Upvotes: 5 [selected_answer]
|
2018/03/15
| 878 | 3,049 |
<issue_start>username_0: HTML File
```
```
JS file
```
var num1,num2,sum;
function add(){
num1 = document.getElementById('num1').value;
num2 = document.getElementById('num2').value;
sum = num1 + num2;
return document.getElementById('sum').value = sum;
}
```
Just started to code without the use of Udemy. I'm stuck here for about 5 hrs. I know its simple but I can't get my JS to connect with my HTML. I put in the number in num1 and num2 places in the HTML when I press the button the screen does a quick refresh, the numbers in num1 and num 2 disappear and the last input box is left blank. Please help with my first solo lvl. 1 coding project.<issue_comment>username_1: The problem is that clicking the button will call `add()` but also submit the form, which here will reload the page. Remove the tags, you don't need them.
Next, an input's `.value` is text, even if you have `type="number"`, which means you need to turn `num1` and `num2` into numbers first.
I also turned the sum element into a given that it is for output, not input.
```js
var num1, num2, sum;
function add() {
var num1String = document.getElementById('num1').value;
var num2String = document.getElementById('num2').value;
num1 = Number(num1String);
num2 = Number(num2String);
sum = num1 + num2;
document.getElementById('sum').innerHTML = sum;
}
```
```html
Add
```
Upvotes: 2 <issue_comment>username_2: The big hiccup is the element in the HTML -- it's trying to submit the page as a form's native behavior should. The page submission reloads the page (or tries to load an expected page) which clears out your results before you can see them.
```js
var num1,num2,sum;
function add(){
num1 = document.getElementById('num1').value;
num2 = document.getElementById('num2').value;
// input from the HTML comes back as text/strings
// convert them into float numbers
// (3.14 for example vs. Integer numbers like 3)
// Otherwise 1 + 3 would be 13 instead of 4
sum = parseFloat(num1) + parseFloat(num2);
// Update the input value with the calculated
// sum
// .toFixed() restricts how far the decimals will go
// this helps curve a JS problem where
// 5.6 + 2.3 = 7.89999999... instead of 7.9
document.getElementById('sum').value = sum.toFixed(2);
// you don't have to return anything with this
// function, but if anything just return true
return true;
}
```
```html
Add
```
Upvotes: 0 <issue_comment>username_3: Couple of points to be noted:
1. Form name was `add`,same as js function,which was causing `'is not a function error'`
2. Button type needs to explicitly set as `button`,else it submits the form
3. The num values from text fields needs to be parsed for actual values using `parseInt`
**JS update**
```
var num1,num2,sum;
function add(){
num1 = document.getElementById('num1').value;
num2 = document.getElementById('num2').value;
sum = parseInt(num1) + parseInt(num2);
return document.getElementById('sum').value = sum;
}
```
**HTML Update**
```
```
Upvotes: 0
|
2018/03/15
| 1,180 | 4,390 |
<issue_start>username_0: I have bottom navigation bar with center item that looks like on this picture:
[](https://i.stack.imgur.com/BD50Xl.png)
How to implement such a thing in Flutter?
I found that every icon that I put into BottomNavigatonBarItem is fitted inside navigation bar's bounds. But I need it to be hanged out above.<issue_comment>username_1: You can a `Stack` to display widgets on the top of each others.
Combined with the property `overflow`: `Overflow.visible`, and an alignment that fits your need.
The following example will achieve thing as in your picture : A floating button horizontally centered, top aligned with the bottom bar.
```
return new Scaffold(
bottomNavigationBar: new Stack(
overflow: Overflow.visible,
alignment: new FractionalOffset(.5, 1.0),
children: [
new Container(
height: 40.0,
color: Colors.red,
),
new Padding(
padding: const EdgeInsets.only(bottom: 12.0),
child: new FloatingActionButton(
notchMargin: 24.0,
onPressed: () => print('hello world'),
child: new Icon(Icons.arrow_back),
),
),
],
),
);
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Google recently added something called `BottomAppBar` and it provides a better way of doing this. Simply add `BottomAppBar` in the scaffold, create a navigation FAB, and add a label to the FAB if you want it to have text
```
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: const Text('Tasks - Bottom App Bar')),
floatingActionButton: FloatingActionButton.extended(
elevation: 4.0,
icon: const Icon(Icons.add),
label: const Text('Add a task'),
onPressed: () {},
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerDocked,
bottomNavigationBar: BottomAppBar(
hasNotch: false,
child: new Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: Icon(Icons.menu),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
)
],
),
),
);
}
```
Result:
[](https://i.stack.imgur.com/uONDG.png)
Upvotes: 3 <issue_comment>username_3: You can also do this using FloatingActionButtonLocation and Expanded widget like this:
```
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: _buildTodoList(),
floatingActionButton: new FloatingActionButton(
onPressed: _pushAddTodoScreen,
tooltip: 'Increment',
child: new Icon(Icons.add),
elevation: 4.0,
),
bottomNavigationBar: BottomAppBar(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(child: IconButton(icon: Icon(Icons.home)),),
Expanded(child: IconButton(icon: Icon(Icons.show\_chart)),),
Expanded(child: new Text('')),
Expanded(child: IconButton(icon: Icon(Icons.tab)),),
Expanded(child: IconButton(icon: Icon(Icons.settings)),),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
```
Preview:

Upvotes: 3 <issue_comment>username_4: In addition to the inputs by @Raunak, you can also use the "border" attribute of the FloatingActionButton to get a seamless border to generate the desired effect - code snippet is below:
```
Widget buildFab() {
FloatingActionButton fab = FloatingActionButton(
backgroundColor: Color(0xFF9966CC),
child: Icon(Icons.add),
shape: CircleBorder(
side: BorderSide(
color: Colors.white,
width: 3.0,
),
),
tooltip: "Add...",
onPressed: () {
print("fab is pressed!!!");
}
);
return fab;
}
```
More better if you wrap the FAB inside a Material and add shadow effects to it - as below:
```
Material buildFabWithShadow() {
return Material(
shadowColor: Color(0x802196F3),
shape: CircleBorder(),
elevation: 16.0,
child: buildFab(),
);
```
When tried, I got the below for effect [1](https://i.stack.imgur.com/VRSMc.png)- please note that the Border width can be adjusted to your wish!
Upvotes: 0
|
2018/03/15
| 1,536 | 5,561 |
<issue_start>username_0: In the code below I made a small script that basically calculates the square root of a number inputted by the user. A pop up shows up and the user inputs his number he wants to work out the square root of. The script works fine as I tested it. My problem is that **a**, the value I want to display is not being displayed. Can someone please point out what the problem is?
```js
function evaluate() {
var input = prompt("Please enter your input");
var array = new Array();
function squareroot(x, y) {
if (!y) {
// Take an initial guess at the square root
y = x / 2;
}
var z = x / y; // Divide the inputted number by the initial guess
var a = (z + y) * 1 / 2; // *Use average of y and z as our new guess
if (y == a) {
// *The new guess is the same as the old guess; further guesses
// *can get no more accurate so we return this guess
return y;
}
// Recursively solve for closer and closer approximations of the square root
return squareroot(x, a);
}
document.writeln("Your calculation is: ");
document.writeln(a);
}
evaluate();
```
```css
body {
color: white;
background-color: black;
font-weight: bold;
font-size: 20px;
text-align: center;
margin-top: 250px;
}
```
```html
Online RPN Calculator
---------------------
```<issue_comment>username_1: First, you never call `squareroot` function anywhere in your code.
Second, you only get the value from `prompt` but you never use it.
[A simple `prompt()` explanation](https://www.w3schools.com/jsref/met_win_prompt.asp).
Third, the variable `a` is not accessible by `evaluate` function because it is scoped inside `squareroot` function.
[More about JavaScript scoping here](https://www.w3schools.com/js/js_scope.asp).
**In-depth explanation 1 & 2**
In your `evaluate` function, the first thing you do is defining variable `input` and assigning it to `prompt()` function.
The way prompt function works is that it pauses script execution until the user provide the prompt with an answer.
With this, you can then check whether or not `input` is provided by using `if-else`.
```
if (input !== null){
// Run this code if `input` is provided.
}
```
or
```
// Stops the function
if (input === null){
return;
}
```
In the demo below, I use it to run `squareroot` function if its value is provided and use it as the first parameter `x` of `squareroot`.
**In-depth explanation 3**
In your original code, the variable `a` is defined inside `squareroot` function. Therefore, the `evaluate` function cannot see its value because of [scoping](https://www.w3schools.com/js/js_scope.asp). Hence the line `document.write(a)` cannot get the value of `a` because to them, `a` is undefined.
Every variable defined in `evaluate` function can be seen by `squareroot` function.
Using this, we can define variable `a` in the `evaluate` function instead of `squareroot` function.
So that `document.write(a)` knows what `a` is.
```js
function evaluate() {
var array = new Array();
var a = undefined;
var input = prompt("Please enter your input");
if (input) squareroot(input);
function squareroot(x,y) {
if (!y) {
// Take an initial guess at the square root
y = x/2;
}
var z = x / y; // Divide the inputted number by the initial guess
a = (z + y) * 1/2; // *Use average of y and z as our new guess
if (y == a) {
// *The new guess is the same as the old guess; further guesses
// *can get no more accurate so we return this guess
return y;
}
// Recursively solve for closer and closer approximations of the square root
return squareroot(x, a);
}
document.writeln("Your calculation is: ");
document.writeln(a);
}
evaluate();
```
Upvotes: 0 <issue_comment>username_2: You should pass your `input` value from user input into the function that you want to make calculation or any other math operation.
Your code seems confusing.
Upvotes: -1 <issue_comment>username_3: You need to call the squareroot function. Changing `document.writeln(a);` to `document.writeln(squareroot(input));` will make it work. Also added a check that an input was given that is not NaN to avoid infinite recursion. `if (!isNaN(input) && input)`
Upvotes: 1 [selected_answer]<issue_comment>username_4: as noticed by @n8wrl, you don't provide user input to your function and you have scope issue for 'a' variable.
```html
Squareroot calculator
body {
color: white;
background-color: black;
font-weight: bold;
font-size: 20px;
text-align: center;
margin-top: 250px;
}
function squareroot(x, y) {
if (!y) {
// Take an initial guess at the square root
y = x / 2;
}
var z = x / y; // Divide the inputted number by the initial guess
var a = (z + y) \* 1 / 2; // \*Use average of y and z as our new guess
if (y == a) {
// \*The new guess is the same as the old guess; further guesses
// \*can get no more accurate so we return this guess
return y;
}
// Recursively solve for closer and closer approximations of the square root
return squareroot(x, a);
}
var input = prompt("Please enter your input");
document.writeln("Your calculation is: ");
document.writeln(input);
Online RPN Calculator
---------------------
```
Upvotes: -1 <issue_comment>username_5: I have made the following changes please check on this one
Upvotes: 0
|
2018/03/15
| 1,448 | 3,458 |
<issue_start>username_0: I have following 2 rows in a file:
`16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10`
`6.7 5.4 6.39`
I am able to split 1st row by using "\\s+" regex. But I cannot split 2nd row.
I want to split above strings in such a way that I will get following output:
```
row[1] = [16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10]
row[2] = [6.7, 5.4, null, null, 6.39, null, null, null, null]
```
Below is the screenshot of what I have to parse :
[](https://i.stack.imgur.com/zsKr8.png)<issue_comment>username_1: TO me this seems like a fixed width file .
Please try following regex
```
.{7}
```
You can change value within curly braces depending on width of column,
```
.{column_width_goes_here}
```
Sample
<https://regex101.com/r/SZZxbB/1>
Upvotes: -1 <issue_comment>username_2: You can use streams and split rows then cells, resulting in a list of lists:
```
List> matrix = Arrays.asList(text.split("\n"))
.stream()
.map(line -> Arrays.asList(line.split("\\s+")))
.collect(Collectors.toList())
```
This gives you a 2D array/list of the values.
When tested with:
```
String text = "16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10\n" + " 6.7 5.4 6.39";
```
That outputs:
```
[[16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10], [, 6.7, 5.4, 6.39]]
```
Upvotes: 0 <issue_comment>username_3: It seems that your inputs has a fixed length (7) between the start of the first number to the next start number :
```
16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10
^^^^^^^--------(7)
```
In this case you can split your input using this regex `(?<=\\G.{7})` [take a look at this](https://stackoverflow.com/questions/3760152/split-string-to-equal-length-substrings-in-java/3761521#3761521) :
```
String text1 = "16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10";
String text2 = "6.7 5.4 6.39 ";
String[] split1 = text1.split("(?<=\\G.{7})");
String[] split2 = text2.split("(?<=\\G.{7})");
```
**Outputs**
```
[16.1 , 14.3 , 8.8 , 7.0 , 7.85 , 13.29 , 18.75 , 13.08 , 13.10]
[6.7 , 5.4 , , , 6.39 , , , , ]
```
Better Solution
---------------
If you want to get null instead of empty you can use :
```
List result = Arrays.asList(text2.split("(?<=\\G.{7})"))
.stream()
.map(input -> input.matches("\\s\*") ? null : input.trim())
.collect(toList());
```
**Outputs**
```
[16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10]
[6.7, 5.4, null, null, 6.39, null, null, null, null]
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: Use [Guava's `Splitter.fixedLength(int)`](http://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/base/Splitter.html#fixedLength-int-)
=============================================================================================================================================================
```
String[] rows = {
"16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10",
"6.7 5.4 6.39 "
};
Splitter splitter = Splitter.fixedLength(7);
for(String row: rows) {
List data = splitter.splitToList(row);
for (int i = 0; i < data.size(); i++) {
System.out.printf("Column %d: %s%n", i+1, data.get(i));
}
}
```
Upvotes: 0
|
2018/03/15
| 607 | 2,201 |
<issue_start>username_0: I'm using Jest at [enter link description here](https://github.com/searchbox-io/Jest/tree/master/jest) in my spring boot application.
Then I created the client with the example code :
```
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://myhost:9200")
.multiThreaded(true)
JestClient client = factory.getObject();
```
Everything is fine. I can use this client to do all the queries I want. Happy till now.
Then the problem, when the application starts up, ElasticsearchJestHealthIndicator class is auto-initialized. But the problem is I don't know where to set the config that it will need, so it uses the default value as http://localhost:9200, which leads me to this problem:
>
> WARN [on(2)-127.0.0.1] s.b.a.h.ElasticsearchJestHealthIndicator : Health check failed
> io.searchbox.client.config.exception.CouldNotConnectException: Could not connect to http://localhost:9200
> at io.searchbox.client.http.JestHttpClient.execute(JestHttpClient.java:70)
> at io.searchbox.client.http.JestHttpClient.execute(JestHttpClient.java:60)
>
>
>
Can someone show me how to properly config it , or turn it off ?<issue_comment>username_1: A quick search in the reference documentation shows that Spring Boot will configure for you a `JestClient` (you can just inject it anywhere you need), and that the following configuration properties apply:
```
spring.elasticsearch.jest.uris=http://search.example.com:9200
spring.elasticsearch.jest.read-timeout=10000
spring.elasticsearch.jest.username=user
spring.elasticsearch.jest.password=<PASSWORD>
```
See [here for more on this](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html#boot-features-connecting-to-elasticsearch-jest).
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> The Jest client has been deprecated as well, since both Elasticsearch and Spring Data Elasticsearch provide official support for REST clients.
>
>
>
See <https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-elasticsearch>
Upvotes: 0
|
2018/03/15
| 798 | 2,587 |
<issue_start>username_0: I am using SQLITE database in Android.
Create table query is:
```
String CREATE_TBookOrder = "CREATE TABLE IF NOT EXISTS BookOrder (" +
" `OrderId` INTEGER ," +
" `OrderDate` DATE ," +
" `OrderTotal` DOUBLE " +
")";
```
I am trying to fetch data between dates using following query:
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55 AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
```
But I am receiving zero records in response.
And my code to fetch data is:
```
String queryStr = "SELECT OrderId , OrderTotal FROM BookOrder WHERE OrderId = 55 AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')";
sqLiteDatabase = this.getWritableDatabase();
cursor = sqLiteDatabase.rawQuery(queryStr, null);
if (cursor.moveToFirst()) {
do {
Log.d("data", "sub OrderId " + cursor.getInt(0));
Log.d("data", "sub OrderTotal " + cursor.getFloat(1));
Log.d("data", "--------------");
} while (cursor.moveToNext());
}
sqLiteDatabase.close();
```
This runs smoothly on SQL Server but it's not running successfully in SQLITE Android.<issue_comment>username_1: I read your problem, I think there is the issue of the date DataType. Please check this [link](https://stackoverflow.com/questions/29971762/sqlite-database-select-the-data-between-two-dates/29971871), maybe it solves your problem.
Upvotes: -1 <issue_comment>username_2: Assuming that the date is stored as a string in the format yyyy-mm-dd then you need to inform the query that you are dealing with dates in the query.
So instead of :-
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55
AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
```
You could use :-
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55
AND (date(OrderDate) BETWEEN date('2018-01-01') AND date('2018-12-12'))
```
You may wish to check out [SQL As Understood By SQLite - Date And Time Functions](https://www.sqlite.org/lang_datefunc.html)
Upvotes: 0 <issue_comment>username_3: Solved It After trying a lot of options.
What Worked for me is ,
first i changed the data type of the date column to DATETIME.
then before inserting the date into the column i converted it into yyyy-MM-dd hh:mm:ss format.
And at the time of retrieving the date i used the following query ,
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55 AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
where first Date is Inclusive and second date is Exclusive.
Upvotes: -1 [selected_answer]
|
2018/03/15
| 592 | 1,855 |
<issue_start>username_0: This runs:
```
template
struct u {z Z;};
template
class n;
template <>
class n<3>: public u
{
public:
const int N = 3;
n() : u({3}){}
};
```
But the repeated use of a magic number instead of template parameter is a risk of error.
This is unfortunately not possible:
```
template
class n: public u
{
public:
const int N = T;
n() : u({T})
{}
};
```
is there a better way?<issue_comment>username_1: I read your problem, I think there is the issue of the date DataType. Please check this [link](https://stackoverflow.com/questions/29971762/sqlite-database-select-the-data-between-two-dates/29971871), maybe it solves your problem.
Upvotes: -1 <issue_comment>username_2: Assuming that the date is stored as a string in the format yyyy-mm-dd then you need to inform the query that you are dealing with dates in the query.
So instead of :-
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55
AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
```
You could use :-
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55
AND (date(OrderDate) BETWEEN date('2018-01-01') AND date('2018-12-12'))
```
You may wish to check out [SQL As Understood By SQLite - Date And Time Functions](https://www.sqlite.org/lang_datefunc.html)
Upvotes: 0 <issue_comment>username_3: Solved It After trying a lot of options.
What Worked for me is ,
first i changed the data type of the date column to DATETIME.
then before inserting the date into the column i converted it into yyyy-MM-dd hh:mm:ss format.
And at the time of retrieving the date i used the following query ,
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55 AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
where first Date is Inclusive and second date is Exclusive.
Upvotes: -1 [selected_answer]
|
2018/03/15
| 1,116 | 4,256 |
<issue_start>username_0: Architecture: I have a web application from where I'm interacting with the Datastore and a client (raspberry pi) which is calling methods from the web application using Google Cloud Endpoints.
I have to add that I'm not very familiar with web applications and I assume that something's wrong with the setConsumed() method because I can see the call of /create in the app engine dashboard but there's no entry for /setConsumed.
I'm able to add entities to the Datastore using objectify:
```
//client method
private static void sendSensorData(long index, String serialNumber) throws IOException {
SensorData data = new SensorData();
data.setId(index+1);
data.setSerialNumber(serialNumber);
sensor.create(data).execute();
}
//api method in the web application
@ApiMethod(name = "create", httpMethod = "post")
public SensorData create(SensorData data, User user) {
// check if user is authenticated and authorized
if (user == null) {
log.warning("User is not authenticated");
System.out.println("Trying to authenticate user...");
createUser(user);
// throw new RuntimeException("Authentication required!");
} else if (!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
log.warning("User is not authorised, email: " + user.getEmail());
throw new RuntimeException("Not authorised!");
}
data.save();
return data;
}
//method in entity class SensorData
public Key save() {
return ofy().save().entity(this).now();
}
```
However, I'm not able to delete an entity from the datastore using the following code.
**EDIT:** There are many logs of the create-request in Stackdriver Logging, but none of `setConsumed()`. So it seems like the calls don't even reach the API although both methods are in the same class.
**EDIT 2:** The entity gets removed when I invoke the method from the Powershell so the problem is most likely on client side.
```
//client method
private static void removeSensorData(long index) throws IOException {
sensor.setConsumed(index+1);
}
//api method in the web application
@ApiMethod(name = "setConsumed", httpMethod = "put")
public void setConsumed(@Named("id") Long id, User user) {
// check if user is authenticated and authorized
if (user == null) {
log.warning("User is not authenticated");
System.out.println("Trying to authenticate user...");
createUser(user);
// throw new RuntimeException("Authentication required!");
} else if (!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
log.warning("User is not authorised, email: " + user.getEmail());
throw new RuntimeException("Not authorised!");
}
Key serialKey = KeyFactory.createKey("SensorData", id);
datastore.delete(serialKey);
}
```<issue_comment>username_1: I read your problem, I think there is the issue of the date DataType. Please check this [link](https://stackoverflow.com/questions/29971762/sqlite-database-select-the-data-between-two-dates/29971871), maybe it solves your problem.
Upvotes: -1 <issue_comment>username_2: Assuming that the date is stored as a string in the format yyyy-mm-dd then you need to inform the query that you are dealing with dates in the query.
So instead of :-
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55
AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
```
You could use :-
```
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55
AND (date(OrderDate) BETWEEN date('2018-01-01') AND date('2018-12-12'))
```
You may wish to check out [SQL As Understood By SQLite - Date And Time Functions](https://www.sqlite.org/lang_datefunc.html)
Upvotes: 0 <issue_comment>username_3: Solved It After trying a lot of options.
What Worked for me is ,
first i changed the data type of the date column to DATETIME.
then before inserting the date into the column i converted it into yyyy-MM-dd hh:mm:ss format.
And at the time of retrieving the date i used the following query ,
SELECT OrderId , OrderTotal FROM BookOrder
WHERE OrderId = 55 AND ( OrderDate BETWEEN '2018-01-01' AND '2018-12-12')
where first Date is Inclusive and second date is Exclusive.
Upvotes: -1 [selected_answer]
|
2018/03/15
| 1,304 | 4,420 |
<issue_start>username_0: I have an array of objects that each consists of a string, double and integer for each object in the array. I'd like to know how it is possible to sort this array by the first value (string) alphabetically.
I tried `Arrays.sort(data)` but I receive an error as I think it stops when it reaches the double.
>
> Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
> at java.lang.Double.compareTo(Double.java:49)
>
>
>
Here is my code:
```
for (int i = 0; i < Database.getStockArray().size(); i++) {
String item = Database.getStockArray().get(i).getItem();
double price = Database.getStockArray().get(i).getPrice();
int quantity = Database.getStockArray().get(i).getQuantity();
Object[] data = {item, price, quantity};
model.addRow(data);
}
```<issue_comment>username_1: Convert `double` and `int` to `String`, for example
```
String p = Double.toString(price);
String q = Integer.toString(quantity);
```
and then you can sort all values as strings.
Upvotes: 0 <issue_comment>username_2: If u want to sort based on object property, The proper way is do it by Comparator interface and Collections.sort().
Upvotes: -1 <issue_comment>username_3: You are mixing together two different things:
1. Your three-membered array of item, price and quantity is actually a record (struct, object) and should be implemented as class. It's nonsense to sort record members.
2. You can then sort collection or array of such class' instances using `Comparator.comparing(Data::getItem)` (assuming you name your class `Data`). If you really want to represent your record as array, which I consider ugly, use `Comparator.comparing((Data data) -> data[0])`.
Upvotes: 0 <issue_comment>username_4: >
> I'd like to know how it is possible to sort this array by the first value (string) alphabetically.
>
>
>
You need to define a comparator to sort your specific object array using the first cell, cast it into a String an simply compare with those value. (You might need to manage `null` if this can happen!
```
new Comparator() {
@Override
public int compare(Object[] o1, Object[] o2) {
String s1 = (String) o1[0];
String s2 = (String) o2[0];
return s1.compareTo(s2);
}
};
```
This can be validate with :
```
List list = new ArrayList<>();
list.add(new Object[] { "b", 5 });
list.add(new Object[] { "a", 42 });
list.add(new Object[] { "c", 12 });
Collections.sort(list, new Comparator() {
@Override
public int compare(Object[] o1, Object[] o2) {
String s1 = (String) o1[0];
String s2 = (String) o2[0];
return s1.compareTo(s2);
}
});
//To print each array in the order
list.stream().map(Arrays::toString).forEach(System.out::println);
```
>
> [a, 42]
>
>
> [b, 5]
>
>
> [c, 12]
>
>
>
Upvotes: 0 <issue_comment>username_5: Based on your code I will make the following assumptions:
You have an list of objects which somehow look this:
```
class StockItem {
private final String item;
private final double price;
private final int quantity;
StockItem(String item, double price, int quantity) {
this.item = item;
this.price = price;
this.quantity = quantity;
}
public String getItem() {
return item;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
}
```
And you are trying to put them into a [DefaultTableModel](https://docs.oracle.com/javase/8/docs/api/javax/swing/table/DefaultTableModel.html)
What you need to do is to first sort the elements in the list, then you can iterate over it making an `Object[]` for each item and adding it to the model:
```
List stockArray = Arrays.asList(
new StockItem("foo", 7.99, 47),
new StockItem("bar", 4.59, 12),
new StockItem("baz", 0.98, 1057)); // Database.getStockArray();
// 1.
Collections.sort(stockArray, Comparator.comparing(StockItem::getItem));
DefaultTableModel model = new DefaultTableModel();
// 2.
for (StockItem e : stockArray) {
model.addRow(new Object[] {
e.getItem(), e.getPrice(), e.getQuantity()
});
}
```
Or if you prefer using streams:
```
stockArray.stream()
.sorted(Comparator.comparing(StockItem::getItem))
.map(e -> new Object[] {e.getItem(), e.getPrice(), e.getQuantity()})
.forEach(model::addRow);
```
Upvotes: 0
|
2018/03/15
| 856 | 3,080 |
<issue_start>username_0: I'm trying to make a set of components for repetitive use. The components I'm looking to create are various form fields like *text*, *checkbox* and so on.
I have all the data in *data* on my parent vue object, and want that to be the one truth also after the user changes values in those fields.
I know how to use props to pass the data to the component, and emits to pass them back up again. However I want to avoid having to write a new "method" in my parent object for every component I add.
```
```
My component is something like:
```
Vue.component('vuefield-checkbox',{
props: ['vmodel', 'label'],
data(){
return {
value: this.vmodel
}
},
template:`
{{label}}
`
});
```
I have this Vue object:
```
var vueObject= new Vue({
el: '.vue-parent',
data:{
someNumber:0,
someBoolean:false,
anotherBoolean: true,
someObject:{
name:'My object',
active:false
},
imageAd: {
}
},
methods: {
valueChange: function (newVal) {
this.carouselAd.autoOrder = newVal;
}
}
});
```
See this jsfiddle to see example: [JsFiddle](https://jsfiddle.net/minde281/xj8nx5ae/4/)
The jsfiddle is a working example using a hard-coded method to set one specific value. I'd like to eighter write everything inline where i use the component, or write a generic method to update the parents data. Is this possible?
* Minde<issue_comment>username_1: You can use v-model on your component.
When using `v-model` on a component, it will bind to the property `value` and it will update on `input` event.
HTML
```
Parents someObject.active: {{someObject.active}}
```
Javascript
```
Vue.component('vuefield-checkbox',{
props: ['value', 'label'],
data(){
return {
innerValue: this.value
}
},
template:`
{{label}}
`
});
var vueObject= new Vue({
el: '.vue-parent',
data:{
someNumber:0,
someBoolean:false,
anotherBoolean: true,
someObject:{
name:'<NAME>',
active:false
},
imageAd: {
}
}
});
```
Example fiddle: <https://jsfiddle.net/hqb6ufwr/2/>
Upvotes: 2 [selected_answer]<issue_comment>username_2: As an addition to username_1 answer - `v-model` field and event can be customized:
From here: <https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model>
>
> By default, v-model on a component uses value as the prop and input as
> the event, but some input types such as checkboxes and radio buttons
> may want to use the value prop for a different purpose. Using the
> model option can avoid the conflict in such cases:
>
>
>
```
Vue.component('my-checkbox', {
model: {
prop: 'checked',
event: 'change'
},
props: {
checked: Boolean,
// this allows using the `value` prop for a different purpose
value: String
},
// ...
})
```
>
> The above will be equivalent to:
>
>
>
```
```
Upvotes: 0
|
2018/03/15
| 250 | 873 |
<issue_start>username_0: Listing all the available environments is as simple as:
```none
$ conda env list
```
Now how does one list the currently installed kernels, without having to go to the path:
```none
$ ls /home/{{user}}/.local/share/jupyter/kernels/
```<issue_comment>username_1: With Jupyter installed you get the list of currently installed kernels with:
```none
$ jupyter kernelspec list
python2 /usr/local/lib/python2.7/dist-packages/ipykernel/resources
testenv /home/{{user}}/.local/share/jupyter/kernels/sparkenv
```
Upvotes: 8 [selected_answer]<issue_comment>username_2: For those that come here because VSCode can't find the kernel although it is shown when using `jupyter kernelspec list`, try updating `pyzmq`.
```bash
pip install pyzmq --upgrade
```
---
Based on [this answer](https://stackoverflow.com/a/72937056/11671779)
Upvotes: 1
|
2018/03/15
| 1,940 | 7,663 |
<issue_start>username_0: My view models are fundamentally flawed because those that use a driver will complete when an error is returned and resubscribing cannot be automated.
An example is my `PickerViewModel`, the interface of which is:
```
// MARK: Picker View Modelling
/**
Configures a picker view.
*/
public protocol PickerViewModelling {
/// The titles of the items to be displayed in the picker view.
var titles: Driver<[String]> { get }
/// The currently selected item.
var selectedItem: Driver { get }
/\*\*
Allows for the fetching of the specific item at the given index.
- Parameter index: The index at which the desired item can be found.
- Returns: The item at the given index. `nil` if the index is invalid.
\*/
func item(atIndex index: Int) -> String?
/\*\*
To be called when the user selects an item.
- Parameter index: The index of the selected item.
\*/
func selectItem(at index: Int)
}
```
An example of the `Driver` issue can be found within my `CountryPickerViewModel`:
```
init(client: APIClient, location: LocationService) {
selectedItem = selectedItemVariable.asDriver().map { $0?.name }
let isLoadingVariable = Variable(false)
let countryFetch = location.user
.startWith(nil)
.do(onNext: { _ in isLoadingVariable.value = true })
.flatMap { coordinate -> Observable> in
let url = try client.url(for: RootFetchEndpoint.countries(coordinate))
return Country.fetch(with: url, apiClient: client)
}
.do(onNext: { \_ in isLoadingVariable.value = false },
onError: { \_ in isLoadingVariable.value = false })
isEmpty = countryFetch.catchError { \_ in countryFetch }.map { $0.items.count == 0 }.asDriver(onErrorJustReturn: true)
isLoading = isLoadingVariable.asDriver()
titles = countryFetch
.map { [weak self] response -> [String] in
guard let `self` = self else { return [] }
self.countries = response.items
return response.items.map { $0.name }
}
.asDriver(onErrorJustReturn: [])
}
}
```
The `titles` drive the `UIPickerView`, but when the `countryFetch` fails with an error, the subscription completes and the fetch cannot be retried manually.
If I attempt to `catchError`, it is unclear what observable I could return which could be retried later when the user has restored their internet connection.
Any `justReturn` error handling (`asDriver(onErrorJustReturn:)`, `catchError(justReturn:)`) will obviously complete as soon as they return a value, and are useless for this issue.
I need to be able to attempt the fetch, fail, and then display a **Retry** button which will call `refresh()` on the view model and try again. How do I keep the subscription open?
If the answer requires a restructure of my view model because what I am trying to do is not possible or clean, I would be willing to hear the better solution.<issue_comment>username_1: I would shift some responsibilities to the view controller.
One approach would be to have the view model produce an Observable which as a side effect updates the view model properties. In the following code example, the view controller remains in charge of the view bindings, as well as triggering the refresh in `viewDidLoad()` and via a button tap.
```swift
class ViewModel {
let results: Variable<[String]> = Variable([])
let lastFetchError: Variable = Variable(nil)
func fetchRequest() -> Observable<[String]> {
return yourNetworkRequest
.do(onNext: { self.results.value = $0 },
onError: { self.lastFetchError.value = $0 })
}
}
class ViewController: UIViewController {
let viewModel = ViewModel()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.results
.asDriver()
.drive(onNext: { yourLabel.text = $0 /\* .reduce(...) \*/ })
.disposed(by: disposeBag)
viewModel.lastFetchError
.asDriver()
.drive(onNext: { yourButton.isHidden = $0 == nil })
.disposed(by: disposeBag)
yourButton.rx.tap
.subscribe(onNext: { [weak self] in
self?.refresh()
})
.disposed(by: disposeBag)
// initial attempt
refresh()
}
func refresh() {
// trigger the request
viewModel.fetchRequest()
.subscribe()
.disposed(by: disposeBag)
}
}
```
Upvotes: 0 <issue_comment>username_2: Regarding ViewModel structuring when using RxSwift, during intensive work on a quite big project I've figured out 2 rules that help keeping solution scalable and maintainable:
1. Avoid any UI-related code in your viewModel. It includes RxCocoa extensions and drivers. ViewModel should focus specifically on business logic. Drivers are meant to be used to drive UI, so leave them for ViewControllers :)
2. Try to avoid Variables and Subjects if possible. AKA try to make everything "flowing". Function into function, into function and so on and, eventually, in UI. Of course, sometimes you need to convert non-rx events into rx ones (like user input) - for such situations subjects are OK. But be afraid of subjects overuse - otherwise your project will become hard to maintain and scale in no time.
Regarding your particular problem. So it is always a bit tricky when you want retry functionality. [Here](https://github.com/ReactiveX/RxSwift/issues/729) is a good discussion with RxSwift author on this topic.
**First way**. In your example, you setup your observables on `init`, I also like to do so. In this case, you need to accept the fact that you DO NOT expect a sequence that can fail because of error. You DO expect sequence that can emit either result-with-titles or result-with-error. For this, in RxSwift we have `.materialize()` combinator.
In ViewModel:
```
// in init
titles = _reloadTitlesSubject.asObservable() // _reloadTitlesSubject is a BehaviorSubject
.flatMap { \_ in
return countryFetch
.map { [weak self] response -> [String] in
guard let `self` = self else { return [] }
self.countries = response.items
return response.items.map { $0.name }
}
.materialize() // it IS important to be inside flatMap
}
// outside init
func reloadTitles() {
\_reloadTitlesSubject.onNext(())
}
```
In ViewController:
```
viewModel.titles
.asDriver(onErrorDriveWith: .empty())
.drive(onNext: [weak self] { titlesEvent in
if let titles = titlesEvent.element {
// update UI with
}
else if let error = titlesEvent.error {
// handle error
}
})
.disposed(by: bag)
retryButton.rx.tap.asDriver()
.drive(onNext: { [weak self] in
self?.viewModel.reloadTitles()
})
.disposed(by: bag)
```
**Second way** is basically what CloackedEddy suggests in his answer. But can be simplified even more to avoid Variables. In this approach you should NOT setup your observable sequence in viewModel's `init`, but rather return it anew each time:
```
// in ViewController
yourButton.rx.tap.asDriver()
.startWith(())
.flatMap { [weak self] _ in
guard let `self` = self else { return .empty() }
return self.viewModel.fetchRequest()
.asDriver(onErrorRecover: { error -> Driver<[String]> in
// Handle error.
return .empty()
})
}
.drive(onNext: { [weak self] in
// update UI
})
.disposed(by: disposeBag)
```
Upvotes: 2 <issue_comment>username_3: All answers are good, but i want to mentioned about [`CleanArchitectureRxSwift`](https://github.com/sergdort/CleanArchitectureRxSwift). This framework really help me to find the way how rx can be applied to my code. The part about "backend" mobile programming (request, parsers, etc) can be omitted, but work with viewModel/viewController has really interesting things.
Upvotes: 0
|
2018/03/15
| 474 | 1,881 |
<issue_start>username_0: I want to tie weights of the `embedding` layer and the `next_word` prediction layer of the decoder. The embedding dimension is set to 300 and the hidden size of the decoder is set to 600. Vocabulary size of the target language in NMT is 50000, so embedding weight dimension is `50000 x 300` and weight of the linear layer which predicts the next word is `50000 x 600`.
So, how can I tie them? What will be the best approach to achieve weight tying in this scenario?<issue_comment>username_1: **Weight Tying** : Sharing the weight matrix between *input-to-embedding* layer and *output-to-softmax* layer; That is, instead of using two weight matrices, we just use only one weight matrix. The intuition behind doing so is to combat the problem of *overfitting*. Thus, *weight tying* can be considered as a form of regularization.
This has been implemented in [word language model in PyTorch examples](https://github.com/pytorch/examples/blob/master/word_language_model/model.py#L28)
Upvotes: 2 <issue_comment>username_2: Did you check the code that username_1 shared? Because it is written that if the hidden size and the embedding sizes are not equal then raise an exception. So, this means if you really want to tie the weights then you should decrease the hidden size of your decoder to 300.
On the other hand, if you rethink your idea, what you really want to do is to eliminate the weight tying. Why? Because basically, you want to use a transformation which needs another matrix.
Upvotes: 0 <issue_comment>username_3: You could use linear layer to project the 600 dimensional space down to 300 before you apply the shared projection. This way you still get the advantage that the entire embedding (possibly) has a non-zero gradient for each mini-batch but at the risk of increasing the capacity of the network slightly.
Upvotes: 3 [selected_answer]
|
2018/03/15
| 576 | 2,047 |
<issue_start>username_0: I have a Symfony 3.3 contact form that sends an email, and I want to allow optional uploads of a few attachments.
I am attempting to adapt <https://symfony.com/doc/3.3/form/form_collections.html> to fit my needs.
The relevant part of my formBuilder looks like this:
```
->add('attachments', 'collection', array(
'entry_type' => FileType::class,
'entry_options' => array(
'required' => false,
'allow_add' => true,
),
));
```
... and I have just modified my Twig template to look like this ...
```
{% for attachment in form.attachments %}
* {{ form\_widget(attachment) }}
{% endfor %}
```
... at which point a load of my page results in the following message:
>
> Key "prototype" for array with keys "value, attr, form, id, name,
> full\_name, disabled, label, label\_format, multipart, block\_prefixes,
> unique\_block\_prefix, translation\_domain, cache\_key, errors, valid,
> data, required, size, label\_attr, compound, method, action, submitted,
> sonata\_admin\_enabled, sonata\_help, sonata\_admin,
> horizontal\_label\_class, horizontal\_label\_offset\_class,
> horizontal\_input\_wrapper\_class, allow\_add, allow\_delete" does not
> exist.
>
>
>
What am I doing wrong here?<issue_comment>username_1: Moving the `allow_add` property up a level did the trick. So I now have:
```
->add('attachments', 'collection', array(
'entry_type' => FileType::class,
'entry_options' => array(
'required' => false,
),
'allow_add' => true,
));
```
Upvotes: 1 <issue_comment>username_2: This may help you,please try refer the document:[Symfony form collection](https://symfony.com/doc/3.3/form/form_collections.html)
```
{{ form\_widget(form.tags.vars.prototype.name)|e }}
...
```
Or
```
{% for attachment in form.attachments %}
* {{ form\_row(attachment.name) }}
{% endfor %}
```
Also refer this document
Upvotes: 2
|
2018/03/15
| 931 | 2,836 |
<issue_start>username_0: I encountered this issue, but I'm not sure what to make of it...
```
class Goo
{
char _ch;
string _str;
public:
function dobedo;
// Constructor 1
Goo(string s) : \_str(s)
{
cout << "Constructed: [" << &\_str << "]: " << \_str << endl;
dobedo = [&]()
{
cout << "Dobedo: [" << &\_str << "]: "<< \_str << endl;
};
}
// Constructor 2
Goo(char ch) : \_ch(ch)
{
dobedo = [&]() {
cout << "Dobedo: " << \_ch << endl;
};
}
void show() { cout << "Show: [" << &\_str << "]: " << \_str << endl; }
};
int main()
{
string myStr1("ABCD");
string myStr2("EFGH");
vector goos;
goos.push\_back(Goo(myStr1));
goos.push\_back(Goo(myStr2));
goos[0].dobedo();
goos[1].dobedo();
goos[0].show();
goos[1].show();
return 0;
}
```
For some reason, the function object wasn't able to print \_str, despite being able to locate the memory address:
```
Constructed: [00EFF80C]: ABCD
Constructed: [00EFF7B0]: EFGH
Dobedo: [00EFF80C]:
Dobedo: [00EFF7B0]:
Show: [032F2924]: ABCD
Show: [032F296C]: EFGH
```
I did not have any problems with char variables though.
```
int main()
{
vector goos;
goos.push\_back(Goo('#'));
goos.push\_back(Goo('%'));
goos[0].dobedo();
goos[1].dobedo();
return 0;
}
```
The output gives:
```
Dobedo: #
Dobedo: %
```
Any ideas?<issue_comment>username_1: You have undefined behaviour in your code without defining copy constructor. Default copy constructor copies all members by value. So your lambda object is copied and it holds references to destroyed object - `_str` (when vector had to be reallocated while calling `push_back` method).
Define copy constructor and move constructor for `Goo` class:
```
Goo(const Goo& g)
{
_str = g._str;
dobedo = [&]()
{
cout << "Dobedo: [" << &_str << "]: "<< _str << endl;
};
}
Goo(Goo&& g)
{
_str = move(g._str);
dobedo = [&]()
{
cout << "Dobedo: [" << &_str << "]: "<< _str << endl;
};
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Your output clearly shows that the address of `_str` in constructor isn't the same as one in `show`. It means that your object was copied/moved. It may happen while it is pushed to a vector. BTW, it also may take place when you push/pop other elements to/from a vector as vector doesn't guarantee elements to stay at the same memory address.
When you create `dobedo` functor, all captured fields are copied to it. In the first case it was the address of `_str` which becomes invalid when the object is copied/moved (nobody updates it upon a move/copy!). Occasionally we may find an empty-string like stuff at that address (although accessing it is now a memory violation). In the second case, a character is captured and stored - and it definitely remains valid upon any object location change.
Upvotes: 1
|
2018/03/15
| 972 | 3,459 |
<issue_start>username_0: I am trying to send a form along with an image. **Note**: I don't want to save the image in a database, I want to save it in a folder which I created on the server and just add a link of the image to the database.
From the server side I know how to handle this, but I don't know how to do this from font-end. With other words, how can I send the image using axios to the server.
```
Submit
export default {
name: 'Addproduct',
data(){
return{
image: '',
product:{
specdesc:'',
},
}
},
methods:{
Submit(){
var \_this=this
// console.log(this.image)
console.log(this.selectedCategory.category\_name)
var product = {
specification:this.product.specdesc,
imagename:this.image
}
this.$http.post('http://localhost:3000/api/companyproducts',product)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log("error.response");
});
}
},
}
```
Now my question is how can I upload a image as well as the input name using axios. Moreover I want to use the same method i.e `var product` to send.<issue_comment>username_1: A standard (mostly) approach will be to split the logic in two, if you want to save the image path on your `product`, you firstly need to upload the photo to the server and return their path.
pseudo example:
**component's data**
```js
{
imagePath: '',
productSpect: ''
}
``
``html
Submit`
``
**uploadImage method**
uploadImage (e) {
let img = e.target.files[0]
let fd= new FormData()
fd.append('image', img)
axios.post('/upload-image', fd)
.then(resp => {
this.imagePath = resp.data.path
})
}
**submit method**
submit () {
let data = {
imagePath: this.imagePath,
productSpect: this.productSpect
}
axios.post('/path/to/save', data)
}
**edited method to handle just only 1 image on the server**
Change the input `@change` to just save the img on a property under data():
submit() {
let fd= new FormData()
fd.append('image', this.image)
axios.post('/upload-image', fd)
.then(resp => {
this.imagePath = resp.data.path
let data = {
imagePath: this.imagePath,
productSpect: this.productSpect
}
axios.post('/path/to/save', data)
})
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: There is nothing specific to Vue in this question. To send a POST request with axios, the easiest thing to do is to grab the formData of the html form and pass it as the data argument to Axios. To do this in Vue, just give your form tag a ref, then create a formData from the form.
```
// then in your method...
var myFormData = new FormData(this.$refs.myForm)
axios({
method: 'post',
url: 'myurl',
data: myFormData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
```
Upvotes: 3 <issue_comment>username_3: for upload file I've used vuetify <https://vuetifyjs.com/en/components/file-inputs/>
```
Upload
```
in my vue method I have
```
onUpload() {
let formData = new FormData();
formData.append('file', this.imageData);
axios.post(
"/images/v1/upload"
,formData
,{headers: {"Content-Type": "multipart/form-data"}}
)
.then(response => {
//...
})
.catch(e => {
//...
})
}
```
Best regards!
Upvotes: 2
|
2018/03/15
| 1,588 | 4,832 |
<issue_start>username_0: I have log4j2 jars under $CATALINA\_HOME/lib:
* log4j-api-2.10.0.jar
* log4j-core-2.10.0.jar
* log4j-jul-2.10.0.jar
export JAVA\_OPTS="${JAVA\_OPTS} -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager"
In catalina.properties I've got common classloader and I tried to add log4j-jul-2.10.0.jar again even if it is already under the CATALINA\_HOME/lib, but no success.
common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar","${catalina.home}/lib","${catalina.home}/lib/*.jar","/opt/tomcat/apache-tomcat-8.5.15/lib/log4j-jul-2.10.0.jar"
I have deleted logging.properties under Tomcat and add a new log4j2.xml to path
**ERRORMESSAGE:**
Could not load Logmanager "org.apache.logging.log4j.jul.LogManager"
java.lang.ClassNotFoundException: org.apache.logging.log4j.jul.LogManager
Any idea why LogManager is still missing or should I use some other jars instead. In another messages they are speaking juli.jar and extras, but in their case they have older Tomcat version, 6 or 7.<issue_comment>username_1: `log4j2 jars` must be loaded along with `bootstrap.jar` (tomcat startup) and `tomcat-juli.jar` (logging)
These jars are present in `CATALINA_HOME/bin` directory and are responsible for
initialization of tomcat including logging.
In `CATALINA_HOME/cataline.bat` in case of windows, you will find below code -
```
set "CLASSPATH=%CLASSPATH%%CATALINA_HOME%\bin\bootstrap.jar"
```
Here, you should add log4j2 jars at the classpath so that when tomcat starts, these jars are there.
Upvotes: 1 <issue_comment>username_2: Create in `tomcat\bin\` file `setenv.bat` and add to file:
```
set "CLASSPATH=%CLASSPATH%%CATALINA_BASE%\bin;%CATALINA_BASE%\bin\log4j-core-2.10.0.jar;%CATALINA_BASE%\bin\log4j-api-2.10.0.jar;%CATALINA_BASE%\bin\log4j-jul-2.10.0.jar"
```
copy jars files
```
log4j-api-2.10.0.jar
log4j-core-2.10.0.jar
log4j-jul-2.10.0.jar
```
to folder `tomcat\bin\`
create file `log4j2.xml` in `tomcat\bin` folder
Upvotes: 1 <issue_comment>username_3: I know that this is a little late to answer this question, but I'm sure it could help someone struggling like me trying to configure tomcat so that it uses lo4j.
I've been working on something similar for the past 3 days, and I found out that the extras folder provided by tomcat's website are not what I need. But, you can still grab them using maven. I was able to configure tomcat so that it uses the mentioned jar files ( tomcat-extras-juli.jar and tomcat-extras-juli-adapters.jar ). Just remember to include the VM argument -Dlog4j.debug to make your life easier and catch errors quicker.
Maven repo: <https://mvnrepository.com/artifact/org.apache.tomcat.extras/tomcat-extras-juli-adapters>
I came upon the same problem after I included the mentioned jars provided by tomcat's repository. After a quick analysis I found that the interface org.apache.juli.WebAppProperties was not included in the jar file tomcat-extras-juli.jar which is utilized by the file org.apache.catalina.loader.WebappClassLoaderBase. After researching a bit more, I realized that the tomcat jar files are included in the Maven Repo. I downloaded the mentioned jar files under the same version of tomcat ( currently 8.5 ), plugged those jars in my tomcat installation and everything worked as expected. Now my version of tomcat uses log4j instead of juli.
Upvotes: 3 [selected_answer]<issue_comment>username_4: You just need to add the **log4j2-api**, **log4j2-core** and **log4j2-appserver** libraries into the Tomcat classpath, provide the log4j2 configuration file and remove the $CATALINA\_BASE/conf/logging.properties from your installation.
This is most easily done by:
1. Creating a set of directories in catalina home named log4j2/lib and
log4j2/conf.
2. Placing `log4j2-api-2.x.x.jar`, `log4j2-core-2.x.x.jar`, and
`log4j2-appserver-2.x.x.jar` in the log4j2/lib directory.
3. Creating a file named log4j2-tomcat.xml, log4j2-tomcat.json,
log4j2-tomcat.yaml, log4j2-tomcat.yml, or log4j2-tomcat.properties
in the log4j2/conf directory.
4. Create or modify setenv.sh in the tomcat bin directory to include
`CLASSPATH=$CATALINA_HOME/log4j2/lib/*:$CATALINA_HOME/log4j2/conf`
---
You can force the applications that use the JUL framework to use log4j2 format changing the environment variable LOGGING\_MANAGER. You can do this by adding in the **setenv.sh** file: `LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager"`
Remember that `org.apache.logging.log4j.jul.LogManager` is included in the `log4j-jul-2.x.x.jar` bridge which must be added to your classpath.
---
refs:
<https://db-blog.web.cern.ch/blog/luis-rodriguez-fernandez/2019-03-keeping-your-logs-clean-apache-tomcat-9-log4j2-and-spring-boot>
<https://logging.apache.org/log4j/2.x/log4j-appserver/index.html>
Upvotes: 2
|
2018/03/15
| 570 | 2,057 |
<issue_start>username_0: There are many [examples](https://kotlinlang.org/docs/reference/classes.html#constructors) how to use `init` during class construction, but they are mostly without using actual class properties.
What I need to do is init a class property from database on object init. So far I have this:
```
class MyObj constructor(val id: Long){
var data: MutableMap? = null
init {
data = db.find(id) // more like pseudocode, db fetch is done and result assigned to data property
}
}
```
But it seems a little overcomplicated to me. Is there any better, more elegant way to do this ?<issue_comment>username_1: You can initialize the property directly in the class body:
```
class MyObj(val id: Long) {
val data: MutableMap = db.find(id)
}
```
Then you won't need to declare it as a nullable type, and may be able to use `val` instead of `var`. (I've also removed the `constructor` keyword which is redundant.).
Upvotes: 2 <issue_comment>username_2: You can just write:
```
class MyObj constructor(val id: Long){
val data: Map = mapOf()
}
```
It's equivalent to:
```
class MyObj constructor(val id: Long){
val data: Map
init {
data = mapOf()
}
}
```
Init block is useful if you need introduce some logic for your object initialization, like error checking etc. Ofc you can do it with or without init block. But remember what is more readable:
```
class MyObj constructor(val id: Long){
val data: Map = if (id == 0L) {
mapOf(Pair("", ""))
} else {
throw IllegalStateException()
}
} // without init
class MyObj constructor(val id: Long){
val data: Map
init {
data = if (id == 0L) {
mapOf(Pair("", ""))
} else {
throw IllegalStateException()
}
}
} // with init
```
You can also init this value using lazy (what means property will be initialized as function, but value will be assigned when you first ask for it, not when object is created). I guess taking value from db can be quite long, so it may be useful:
```
val data: Map by lazy { mapOf() }
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 1,550 | 5,270 |
<issue_start>username_0: I'm trying to rearrange data in array to be in hash format but I pretty messed up using nested if
Sample Data
```
[
["England", "London", "University College London ", "Faculty of Law"],
["England", "London", "University College London ", "Faculty of Engineering"],
["England", "London", "Imperial College London", "Faculty of Medicine"],
["England", "Manchester", "University of Manchester", "Faculty of Engineering"]
]
```
Expected Output
```
{:name=>"England",
:level=>1,
:children=>[{:name=>"London",
:level=>2,
:children=>[{:name=>"University College London ",
:level=>3,
:children=>[{:name=>"Faculty of Law",
:level=>4,
:children=>[]},
{:name=>"Faculty of Engineering",
:level=>4, :children=>[]}]},
{:name=>"Imperial College London",
:level=>3,
:children=>[{:name=>"Faculty of Engineering",
:level=>4,
:children=>[]}]
}]
}]
}
```
hope I have provide clear explaination
ps. edit to show what I've tried
first i make array of hash then do something like this
I thought it wouldn't be confused this much
```
result = []
arr.each do |b|
if result.any? {|r| r[:name] == b[:name]}
if result.first[:children].any? {|r| r[:name] == b[:children].first[:name]}
if result.first[:children].any?{|c| c[:children].any? {|r| r[:name] == b[:children].first[:children].first[:name] && c[:name] == b[:children].first[:name] }}
if result.first[:children].any? {|r| r[:children].any? {|c| c[:children].any?{|k| k[:name] == b[:children].first[:children].first[:children].first[:name] && (c[:name] == b[:children].first[:children].first)}}}
else
result.first[:children].any?{|c| c[:children].any? {|r| r[:name] == b[:children].first[:children].first[:name] ; r[:children] << b[:children].first[:children].first[:children].first}}
end #fourth
else
result.first[:children].any? {|r| r[:name] == b[:children].first[:name]; r[:children] << b[:children].first[:children].first}
end
else
result.any? {|r| r[:name] == b[:name] ; r[:children] << b[:children].first}
end
else result << b
end
end
```<issue_comment>username_1: I hope the following code can help you:
```
input = [
["England", "London", "University College London ", "Faculty of Law"],
["England", "London", "University College London ", "Faculty of Engineering"],
["England", "London", "Imperial College London", "Faculty of Medicine"],
["England", "Manchester", "University of Manchester", "Faculty of Engineering"]
]
output = Array.new
input.each do |i|
if output.select { |out| out[:name] == i[0] }.empty?
output << { :name => i[0], :level => 1, :child => [] }
end
level1 = output.select { |out| out[:name] == i[0] }
level1.each do |l1|
if l1[:child].select { |l| l[:name] == i[1] }.empty?
l1[:child] << { :name => i[1], :level => 2, :child => [] }
end
end
level1.each do |l1|
level2 = l1[:child].select { |l| l[:name] == i[1] }
level2.each do |l2|
if l2[:child].select { |l| l[:name] == i[2] }.empty?
l2[:child] << { :name => i[2], :level => 3, :child => [] }
end
end
end
level1.each do |l1|
level2 = l1[:child].select { |l| l[:name] == i[1] }
level2.each do |l2|
level3 = l2[:child].select { |l| l[:name] == i[2] }
level3.each do |l3|
if l3[:child].select { |l| l[:name] == i[3] }.empty?
l3[:child] << { :name => i[3], :level => 4 }
end
end
end
end
end
puts output
```
Upvotes: 0 <issue_comment>username_2: You could do this recursive like this:
```
def map_objects(array, level = 1)
new_obj = []
array.group_by(&:shift).each do |key, val|
new_obj << {:name=>key, :level=>level, :children=>map_objects(val, level + 1)} if key
end
new_obj
end
```
For your array it will return like this:
```
# [
# {:name => "England", :level => 1, :children => [
# {:name => "London", :level => 2, :children => [
# {:name => "University College London ", :level => 3, :children => [
# {:name => "Faculty of Law", :level => 4, :children => []
# },
# {:name => "Faculty of Engineering", :level => 4, :children => []
# }]
# },
# {:name => "Imperial College London", :level => 3, :children => [
# {:name => "Faculty of Medicine", :level => 4, :children => []
# }]
# }]
# },
# {:name => "Manchester", :level => 2, :children => [
# {:name => "University of Manchester", :level => 3, :children => [
# {:name => "Faculty of Engineering", :level => 4, :children => []
# }]
# }]
# }]
# }
# ]
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 418 | 1,550 |
<issue_start>username_0: I have this line of code:
```
map (\(u,v) -> flatTorus n u v) gridUV
```
`Hlint` suggests me to replace it with
```
map (uncurry (flatTorus n)) gridUV
```
What is the motivation of this suggestion ? Is it for shortness only, or something else (performance) ? Because though it is longer, I find the first code more easy to read.
In fact my question is more general,, because this is just an example among others: does `Hlint` suggestions are generally based on a shortness motivation only or are there other improvements behind the suggestions ?<issue_comment>username_1: I think Hlint prefers using `uncurry` because it gives you an invariant representation of the callback. Lambda expressions are inherently sensitive to representation, since
```
\(u, v) -> flatTorus n u v
```
is equivalent to
```
\(x, y) -> flatTorus n x y
```
even though they are textually different.
Using `uncurry` frees readers of the cognitive load of doing alpha equivalence in their head (e.g., recognizing that the above two expressions are the same), but then saddles them with the cognitive load of having to remember a vocabulary of combinators. Ultimately, it's a matter of taste.
Upvotes: 2 <issue_comment>username_2: These are not actually quite equivalent.
```
(\(x, y) -> (,) x y) undefined = undefined
uncurry (,) undefined = (undefined, undefined)
```
Do you should take any suggestion to use `uncurry` with a grain of salt. Think about whether that extra laziness will help, hurt, or make no difference.
Upvotes: 1
|
2018/03/15
| 373 | 1,367 |
<issue_start>username_0: I can deploy files through only hosting which works fine
but I try it with firebase functions it says :
```
Welcome
Firebase Hosting Setup Complete
You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!
OPEN HOSTING DOCUMENTATION
```
my `index.js` Code goes here :-
```
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
```
link to my project:-
```
https://influence-cbc3f.firebaseapp.com/
```<issue_comment>username_1: If you want to deploy functions then use this:
```
firebase deploy --only functions
```
more info here:
<https://firebase.google.com/docs/functions/get-started>
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you're using Angular 6, instead of providing "**dist**" at the following step:
>
> ? what do you want to use as public directory
>
>
>
You will need to provide “**dist/your\_application\_name**”
Check out this excellent article
<https://medium.com/@longboardcreator/deploying-angular-6-applications-to-firebase-hosting-b5dacde9c772>
Upvotes: 0
|