date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/22 | 819 | 2,289 | <issue_start>username_0: Trying to remove trailing zero of arrival\_time, the column data type is **Time**
```
SELECT * FROM TABLE
```
And I got this:
`station_name | arrival_time
--------------+--------------------
Wellington | 06:05:00.000000000`
and I need the result to look like this:
`station_name | arrival_time
--------------+--------------------
Wellington | 06:05:00`
I'm new to CQL, Thanks in advance.<issue_comment>username_1: ```
select station_name, SUBSTRING( Convert(Varchar(20),arrival_time), 0, 9) As arrival_time
from [Table]
```
Used following table and data format
```
CREATE TABLE [dbo].[ArrivalStation](
[station_name] [varchar](500) NULL,
[arrival_time] [Time](7) NULL
) ON [PRIMARY]
INSERT [dbo].[ArrivalStation] ([station_name], [arrival_time]) VALUES (N'Wellington ', N'06:05:00.0000000')
INSERT [dbo].[ArrivalStation] ([station_name], [arrival_time]) VALUES (N'Singapore', N'12:35:29.1234567')
```
Upvotes: -1 <issue_comment>username_2: So you can't actually do that in Cassandra with the `time` type. You can however, do it with a `timestamp`.
```
cassdba@cqlsh:stackoverflow> CREATE TABLE arrival_time2 (station_name TEXT PRIMARY KEY,
arrival_time time, arrival_timestamp timestamp);
cassdba@cqlsh:stackoverflow> INSERT INTO arrival_time2 (station_name , arrival_time , arrival_timestamp)
VALUES ('Wellington','06:05:00','2018-03-22 06:05:00');
cassdba@cqlsh:stackoverflow> SELECT * FROM arrival_time2;
station_name | arrival_time | arrival_timestamp
--------------+--------------------+---------------------------------
Wellington | 06:05:00.000000000 | 2018-03-22 11:05:00.000000+0000
(1 rows)
```
Of course, this isn't what you want either, really. So next you need to set a `time_format` in the `[ui]` section of your `~/.cassandra/cqlshrc`.
```
[ui]
time_format = %Y-%m-%d %H:%M:%S
```
Restart cqlsh, and this should work:
```
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.2 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
<EMAIL>> SELECT station_name,arrival_timestamp
FROm stackoverflow.arrival_time2 ;
station_name | arrival_timestamp
--------------+---------------------
Wellington | 2018-03-22 11:05:00
(1 rows)
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 492 | 1,789 | <issue_start>username_0: How can you take an array and put it into a stack???? I have a card array with a deck of cards that gets shuffled then I need to change it to a stack and print the first number on top. Anyway anyone can help?<issue_comment>username_1: To convert array to an stack you need to first convert it to a list and then create a new stack and add all the elements from the list to that stack.
Here you can see the reference answer.
```
String[] stuff = {"hello", "every", "one"};
List list = Arrays.asList(stuff); //1 Convert to a List
//stack.addAll(list);
//3 Add all items from the List to the stack.
// This won't work instead of use the following
Stack stack = new Stack(); //2 Create new stack
// this will insert string element in reverse order, so "hello" will be on top of the stack, if you want order to be as it is, just loop i over 0 to stuff.length.
for(int i = stuff.length - 1; i >= 0; i--) {
stack.add(stuff[i]);
}
System.out.println(stack.pop());//print First Element of Stack
```
Upvotes: 0 <issue_comment>username_2: You can use [Collections.addAll](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#addAll(java.util.Collection,%20T...))
```
Card[] cardsArray;
Stack cards = new Stack<>();
Collections.addAll(cards, cardsArray);
```
Upvotes: 2 <issue_comment>username_3: There is not a single line command that would change/convert your array into a stack format. You have to do it yourself.
You haven't posted some code either, so we will have to make some assumptions.
If the array consists of Card-type-objects then what you have to do is this:
```
Card[] deck; //your array
Stack deck\_stack = new Stack(); //the newly created stack
//pass the array objects into the stack
for(int i=0; i
```
Upvotes: 0 |
2018/03/22 | 530 | 2,005 | <issue_start>username_0: I have a single product that is called on the homepage using the product shortcode `[product sku=""]`. The product has variations, with each variation having a different description.
I'm having trouble having the variation descriptions come up as a user selects a different option from the drop-down.
Can anyone assist with a solution? Thank you in advance!
PS. Variation description appears well on product single pages.<issue_comment>username_1: To convert array to an stack you need to first convert it to a list and then create a new stack and add all the elements from the list to that stack.
Here you can see the reference answer.
```
String[] stuff = {"hello", "every", "one"};
List list = Arrays.asList(stuff); //1 Convert to a List
//stack.addAll(list);
//3 Add all items from the List to the stack.
// This won't work instead of use the following
Stack stack = new Stack(); //2 Create new stack
// this will insert string element in reverse order, so "hello" will be on top of the stack, if you want order to be as it is, just loop i over 0 to stuff.length.
for(int i = stuff.length - 1; i >= 0; i--) {
stack.add(stuff[i]);
}
System.out.println(stack.pop());//print First Element of Stack
```
Upvotes: 0 <issue_comment>username_2: You can use [Collections.addAll](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#addAll(java.util.Collection,%20T...))
```
Card[] cardsArray;
Stack cards = new Stack<>();
Collections.addAll(cards, cardsArray);
```
Upvotes: 2 <issue_comment>username_3: There is not a single line command that would change/convert your array into a stack format. You have to do it yourself.
You haven't posted some code either, so we will have to make some assumptions.
If the array consists of Card-type-objects then what you have to do is this:
```
Card[] deck; //your array
Stack deck\_stack = new Stack(); //the newly created stack
//pass the array objects into the stack
for(int i=0; i
```
Upvotes: 0 |
2018/03/22 | 485 | 1,950 | <issue_start>username_0: I'm trying to dramatically cut down on pricey DB queries for an app I'm building, and thought I should perhaps just return IDs of a child collection (then find the related object from my React state), rather than returning the children themselves.
I suppose I'm asking, if I use *'pluck'* to just return child IDs, is that more efficient than a general *'get'*, or would I be wasting my time with that?<issue_comment>username_1: Yes,**pluck** method is just fine if you are trying to retrieving a Single Column from tables.
If you use **get()** method it will retrieve all information about child model and that could lead to a little slower process for querying and get results.
So in my opinion, You are using great method for retrieving the result.
Laravel has also different methods for select queries. Here you can look [Selects](https://laravel.com/docs/4.2/queries#selects).
Upvotes: 1 <issue_comment>username_2: The good practice to perform DB select query in a application, is to select columns that are necessary. If `id` column is needed, then `id` column should be selected, instead of all columns. Otherwise, it will spend unnecessary memory to hold unused data. If your mind is clear, `pluck` and `get` are the same:
```
Model::pluck('id')
// which is the same as
Model::select('id')->get()->pluck('id');
// which is the same as
Model::get(['id'])->pluck('id');
```
Upvotes: 1 <issue_comment>username_3: I know i'm a little late to the party, but i was wondering this myself and i decided to research it. It proves that one method is faster than the other.
Using `Model::select('id')->get()` is faster than `Model::get()->pluck('id')`.
This is because `Illuminate\Support\Collection::pluck` will iterate over each returned `Model` and extract only the selected column(s) using a PHP foreach loop, while the first method will make it cheaper in general as it is a database query instead.
Upvotes: 0 |
2018/03/22 | 648 | 2,460 | <issue_start>username_0: I saw some example where the Kubernetes cluster is installed with ingress controller and then the ingress class is added with annotations and host as below.
```
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
spec:
rules:
- host: testsvc.k8s.privatecloud.com
http:
```
I am not sure which service is installed and which IP is configured with the DNS **"k8s.privatecloud.com"** so as to route requests?
How the DNS routing **"k8s.privatecloud.com"** routes requests to Kubernetes cluster? How the ingress to kubernetes bridging works?
Also, There could be many services configured with the hosts rule like,
```
testsvc.k8s.privatecloud.com
testsvc1.k8s.privatecloud.com
testsvc2.k8s.privatecloud.com
```
How the subdomain routing works here when we hit the service testsvc.k8s.privatecloud.com or testsvc1.k8s.privatecloud.com ...
Thanks<issue_comment>username_1: Yes,**pluck** method is just fine if you are trying to retrieving a Single Column from tables.
If you use **get()** method it will retrieve all information about child model and that could lead to a little slower process for querying and get results.
So in my opinion, You are using great method for retrieving the result.
Laravel has also different methods for select queries. Here you can look [Selects](https://laravel.com/docs/4.2/queries#selects).
Upvotes: 1 <issue_comment>username_2: The good practice to perform DB select query in a application, is to select columns that are necessary. If `id` column is needed, then `id` column should be selected, instead of all columns. Otherwise, it will spend unnecessary memory to hold unused data. If your mind is clear, `pluck` and `get` are the same:
```
Model::pluck('id')
// which is the same as
Model::select('id')->get()->pluck('id');
// which is the same as
Model::get(['id'])->pluck('id');
```
Upvotes: 1 <issue_comment>username_3: I know i'm a little late to the party, but i was wondering this myself and i decided to research it. It proves that one method is faster than the other.
Using `Model::select('id')->get()` is faster than `Model::get()->pluck('id')`.
This is because `Illuminate\Support\Collection::pluck` will iterate over each returned `Model` and extract only the selected column(s) using a PHP foreach loop, while the first method will make it cheaper in general as it is a database query instead.
Upvotes: 0 |
2018/03/22 | 1,069 | 3,947 | <issue_start>username_0: I have lots of multiple if-else statements. For code optimization, I need to write one function for all if else logic. As of now my code structure is in below.
input request is in JSONObject(org.json.simple.JSONObject), which have more than 10 values.
```
String s = (String) inputObj.get("test");
String s1 = (String) inputObj.get("test");
String s2 = (String) inputObj.get("test");
String s3 = (String) inputObj.get("test");
if (s != null && s.trim().isEmpty()) {
if (s1 != null && s1.trim().isEmpty()) {
if (s2 != null && s2.trim().isEmpty()) {
if (s3 != null && s3.trim().isEmpty()) {
if (s4 != null && s4.trim().isEmpty()) {
........
} else {
return;
}
} else {
return;
}
} else {
return;
}
} else {
return;
}
} else {
return;
}
```
How to avoid this kind of looping and throw an error message in common method.
Advance thanks.<issue_comment>username_1: Consider adding all your strings to array or ArrayList of string, and looping thru each entry in it, and check them for null or emptiness.
Upvotes: 2 <issue_comment>username_2: You can try this.
```
void main() {
List sList = new ArrayList<>();
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
for(String s : sList){
try {
checkString(s);
}catch (Exception e){
//log or print the exception, however you like
}
}
}
void checkString(String s) throws Exception{
if(s!= null && !s.trim().isEmpty()){
//doStuff
}else{
throw new Exception("String is null or empty !!!");
}
}
```
You should also check [this](http://www.wiki-zero.com/wiki/en/Don't_repeat_yourself) out.
Upvotes: 1 <issue_comment>username_3: ```
public Integer checkIsEmapty(String checkingString){
if(checkingString != null && !checkingString.trim().isEmpty()){
return 1;
}
return 0;
}
public String method(){
String s ="";
String s1 = "hi";
String s2 = "java";
String s3 = null;
String s4 = null;
Integer s1i = checkIsEmapty(s);
Integer s2i = checkIsEmapty(s1);
Integer s3i = checkIsEmapty(s2);
Integer s4i = checkIsEmapty(s3);
Integer s5i = checkIsEmapty(s4);
Integer total = s1i + s2i + s3i + s4i + s5i;
switch (total){
case 1 :
// To DO
case 2 :
// To DO
}
}
in switch used to checking the value, U can pass binary and Integer also
```
Upvotes: 0 <issue_comment>username_4: Like @Emre Acre mentioned,
```
List sList = new ArrayList<>();
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
boolean allDataValid = sList
.stream()
.allMatch(s -> s != null && s.trim().isEmpty());
if(allDataValid) {
......
} else {
return;
}
```
Upvotes: 0 <issue_comment>username_5: ```
public class YourClass{
private boolean isBlankDataPresent(JSONObject inputObj, String[] keys) throws Exception {
for (String key : keys) {
String input = (String) inputObj.get(key);
if( input == null || input.trim().isEmpty())
throw new Exception(key +" is Empty");
}
return false;
}
public boolean validateData(JSONObject inputObj, String[] keys) throws Exception {
boolean isBlankDataPresent= isBlankDataPresent(inputObj, keys);
if (!isBlankDataPresent) {
// do Your Stuff and return true
}
}
}
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 893 | 3,140 | <issue_start>username_0: This is the calendar which we are using in the application, this field is read only i have to select the date automatically, i cant be able to inspect the calendar as the code is disappearing automatically when we click on the calendar because of that i cant be able to write code in selenium
[](https://i.stack.imgur.com/HILmh.png)<issue_comment>username_1: Consider adding all your strings to array or ArrayList of string, and looping thru each entry in it, and check them for null or emptiness.
Upvotes: 2 <issue_comment>username_2: You can try this.
```
void main() {
List sList = new ArrayList<>();
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
for(String s : sList){
try {
checkString(s);
}catch (Exception e){
//log or print the exception, however you like
}
}
}
void checkString(String s) throws Exception{
if(s!= null && !s.trim().isEmpty()){
//doStuff
}else{
throw new Exception("String is null or empty !!!");
}
}
```
You should also check [this](http://www.wiki-zero.com/wiki/en/Don't_repeat_yourself) out.
Upvotes: 1 <issue_comment>username_3: ```
public Integer checkIsEmapty(String checkingString){
if(checkingString != null && !checkingString.trim().isEmpty()){
return 1;
}
return 0;
}
public String method(){
String s ="";
String s1 = "hi";
String s2 = "java";
String s3 = null;
String s4 = null;
Integer s1i = checkIsEmapty(s);
Integer s2i = checkIsEmapty(s1);
Integer s3i = checkIsEmapty(s2);
Integer s4i = checkIsEmapty(s3);
Integer s5i = checkIsEmapty(s4);
Integer total = s1i + s2i + s3i + s4i + s5i;
switch (total){
case 1 :
// To DO
case 2 :
// To DO
}
}
in switch used to checking the value, U can pass binary and Integer also
```
Upvotes: 0 <issue_comment>username_4: Like @Emre Acre mentioned,
```
List sList = new ArrayList<>();
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
boolean allDataValid = sList
.stream()
.allMatch(s -> s != null && s.trim().isEmpty());
if(allDataValid) {
......
} else {
return;
}
```
Upvotes: 0 <issue_comment>username_5: ```
public class YourClass{
private boolean isBlankDataPresent(JSONObject inputObj, String[] keys) throws Exception {
for (String key : keys) {
String input = (String) inputObj.get(key);
if( input == null || input.trim().isEmpty())
throw new Exception(key +" is Empty");
}
return false;
}
public boolean validateData(JSONObject inputObj, String[] keys) throws Exception {
boolean isBlankDataPresent= isBlankDataPresent(inputObj, keys);
if (!isBlankDataPresent) {
// do Your Stuff and return true
}
}
}
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 1,383 | 5,407 | <issue_start>username_0: I have a container running inside Kubernetes cluster (within POD) along side many other containers (in their own PODs) and my container is a common container. Now, I want to pull (copy) the files from other containers to my common container. I investigated for some options and found that kubectl copy can be used. But, for that, I need to include kubectl command line tool inside my common container. I'm not sure if this is right approach. So, I thought of using Java Kubernetes APIs to do the same.
Is there equivalent Kubernetes REST API for Kubectl copy command ? I gone through the kubernetes APIs and could not find any such API ..
Thanks<issue_comment>username_1: That's because [`kubectl cp` is implemented via `tar`](https://github.com/kubernetes/kubernetes/blob/v1.9.6/pkg/kubectl/cmd/cp.go#L42-L43), so what is *actually* happening is `kubectl exec $pod -- tar -cf - /the/container/file | tar -xf -`, which is what I would expect your Java API would need to do, as well.
However, you may -- depending on your needs -- be able to get away with how I used to do it before `kubectl cp` arrived: `kubectl exec $pod -- /bin/cat /the/container/file > local-file` which in your circumstance may be a ton easier since I would expect the API would materialize those bytes as an `InputStream`, saving you the need to get into the tar-format-parsing business
Upvotes: 2 <issue_comment>username_2: I think you should be able to do this using [Fabric8 Kubernetes Java Client](https://github.com/fabric8io/kubernetes-client). I would divide this into two tasks:
1. Copy specified file from your container(`c1`) to your local system
2. Copy file saved to your local system to your other container (say `c2`)
Let's say your have a pod running inside Kubernetes with two containers `c1` and `c2`. Let's take this as an example:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: multi-container-pod
spec:
containers:
- name: c1
image: nginx:1.19.2
ports:
- containerPort: 80
- name: c2
image: alpine:3.12
command: ["watch", "wget", "-qO-", "localhost"]
```
Now I want to transfer a file `/docker-entrypoint.sh` in `c1` to `/tmp/docker-entrypoint.sh` in `c2`. [Fabric8 Kubernetes Client](https://github.com/fabric8io/kubernetes-client) provides fluent DSL to uploading/downloading files from Kubernetes Pods. As @mndanial already pointed out in his answer, copy operation involves encoding/decoding, Fabric8 relies on [`commons-codec`](http://commons.apache.org/proper/commons-codec/) and [`commons-compress`](http://commons.apache.org/proper/commons-codec/). These are optional dependencies and need to be included in your classpath in order to use copy operations. For maven, it would be adding it to `pom.xml` like this:
```xml
commons-codec
commons-codec
${commons-codec.version}
org.apache.commons
commons-compress
${commons-compress.version}
```
**Copying File from Container `c1` to your local system:**
In order to copy you can use `KubernetesClient`'s fluent DSL to specify which file to copy and where to copy in your local system. Here is example code:
```java
try (KubernetesClient client = new DefaultKubernetesClient()) {
// Path Where to copy file to local storage
Path downloadToPath = new File("/home/rohaan/Downloads/docker-entrypoint.sh").toPath();
// Using Kubernetes Client to copy file from pod
client.pods()
.inNamespace("default") // <- Namespace of pod
.withName("multi-container-pod") // <- Name of pod
.inContainer("c1") // <- Container from which file has to be downloaded
.file("/docker-entrypoint.sh") // <- Path of file inside pod
.copy(downloadToPath); // <- Local path where to copy downloaded file
}
```
**Copying File from your local system to other Container (`c2`):**
Now we have to do the opposite of first step, similar to `copy()` `KubernetesClient` offers `upload()` method which allows you to upload file or directories to your target Pod. Here is how you would do it:
```java
try (KubernetesClient client = new DefaultKubernetesClient()) {
// File which was downloaded in Step 1
File fileToUpload = new File("/home/rohaan/Downloads/docker-entrypoint.sh");
client.pods().inNamespace("default")
.withName("multi-container-pod")
.inContainer("c2")
.file("/tmp/docker-entrypoint.sh") // <- Target location in other container
.upload(fileToUpload.toPath()); // <- Local path of downloaded file
}
```
When I executed this, I was able to see my file being copied in desired location:
```sh
~ : $ kubectl exec multi-container-pod -c c2 ls /tmp
docker-entrypoint.sh
```
[Fabric8 Kubernetes Client](https://github.com/fabric8io/kubernetes-client) also allows you to read a file as `InputStream` directly rather than storing it. Here is an example:
```java
try (KubernetesClient client = new DefaultKubernetesClient()) {
try (InputStream is = client.pods()
.inNamespace("default")
.withName("quarkus-84dc4885b-tsck6")
.inContainer("quarkus")
.file("/tmp/jobExample.yml").read()) {
String result = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
System.out.println(result);
}
}
```
Upvotes: 1 |
2018/03/22 | 577 | 2,421 | <issue_start>username_0: I want to integrate GraphQL to my existing ASP.NET Framework (with Entity Framework 4) application which has an MSSQL Server as the backend.
While browsing through the GraphQL libraries for .NET I found 2 libraries - **graphql-dotnet** and **graphql-net**, being suggested on the GraphQL website (Link: <http://graphql.org/code/#c-net>)
It seems that (correct me if I'm wrong) :
1. **graphql-dotnet** (<https://github.com/graphql-dotnet/graphql-dotnet>) - This library only supports in-memory data
2. **graphql-net** (<https://github.com/ckimes89/graphql-net>) - This library works well if we want to work with data which has been stored in DB.
Any suggestion or corrections? Is it possible to perform read/write to/from the DB using the former **(i.e. graphql-dotnet)** library?
Or should I use the **graphql-net** library instead?<issue_comment>username_1: I am one of the contributors to Hot Chocolate.
You can use both frameworks that you have mentioned there.
GraphQL-net is more focused on building a GraphQL schema on IQueryable.
I would say GraphQL-dotnet is the better one of both solution.
There are integrations that support entity framework mapping to GraphQL-dotnet and they are also providing support for DataLoader, which are important to solve N+1 issues when loading data from a backend with GraphQL.
Hot Chocolate is the third framework implementing the GraphQL for .Net Core and .Net Framework (also listed on graphql.org).
It also supports *DataLoader* and also supports Entity Framework. For people interested we have a nice tutorial with Entity Framework here:
<https://github.com/ChilliCream/graphql-workshop>
Upvotes: 5 [selected_answer]<issue_comment>username_2: Well, in our project we decided to use graphql-dotnet lib to get data from API services and sharepoint lists - so, it's sort of proxy one WebAPI service. Now we are in production and it works fine with good performance (except getting data from sharepoint list, but it's issue of SharePoint - not graphql-dotnet lib).
btw, lib itself is more stable than graphql-net and has plenty of active contributes.
One more project or, I'd say component, where we decided to use graphql-dotnet lib has released as well. That component allows you to connect to db and configure GraphQL schemes easily (via json file). Already implemented main features like: sort, pagination and complex filter.
Upvotes: 1 |
2018/03/22 | 645 | 2,064 | <issue_start>username_0: How can we make a span element as img element? More precisely how can we do this,
```
```
I saw this concept in twitter message bar when we put emoji in textarea.
Thank you for you time and concideration. Kindly have a look I would be greatful.
Edit-1
This question is not about using background image. Can we have other option like twitter people do. This is what I saw in twitter page.
```
```
And these lines make an image look like and there is no background image as well.<issue_comment>username_1: You can set it in a class background and add that class to the span
```css
.icon {
background: url("https://abs.twimg.com/emoji/v2/72x72/1f607.png") no-repeat;
width: 100px;
display: inline-block;
height: 100px;
}
```
Upvotes: 2 <issue_comment>username_2: You can do something like this
```css
#abc
{
background:url(http://t2.gstatic.com/images?q=tbn:ANd9GcQCze-mfukcuvzKk7Ilj2zQ0CS6PbOkq7ZhRInnNd1Yz3TQzU4e&t=1) left top;
width:50px;
height:50px;
display: block;
float: left;
}
```
```html
```
Upvotes: 0 <issue_comment>username_3: A `span` doesn't have an attribute where to assign an image, other than `background-image` using the `style` attribute, which won't size the `span` to the image's size (like an `img` does).
A possible workaround, using a custom attribute like `data-src`, could be to use a script and [`insertRule()`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule), and add a pseudo class to the stylesheet.
```js
var span = document.querySelector('span[data-src]');
var src = span.dataset.src;
document.styleSheets[0].insertRule('span[data-src]::before { content: url('+src+'); }', 0);
```
```css
span {
border: 1px dashed gray;
display: inline-block;
}
```
---
Another possible way is to dynamically insert an `img` into the `span`.
---
When it comes to how Twitter does, I guess they use their custom attribute similar, for browsers (or readers) that simply doesn't support emoji's, like and/or a custom font.
Upvotes: 1 |
2018/03/22 | 379 | 1,418 | <issue_start>username_0: The `GetAll` returns an `IEnumerable` and, in this case, it's `null`
```
List notes = noteManager.GetAll(newTaskId).ToList();
```
I'm getting an error like the following:
>
> System.ArgumentNullException: 'Value cannot be null. Parameter name:
> source'
>
>
>
Is this to be expected? Should I always check for null before doing a `ToList()`?<issue_comment>username_1: Gold rule: do not return null for collection types.
>
> Should I always check for null before doing a ToList()?
>
>
>
It depends on who is owner of `GetAll` method. If you - follow rule, if not - better to check.
Upvotes: 4 [selected_answer]<issue_comment>username_2: A best practice is to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection.
You can easily return an empty enumerable instead of null.
```
public IEnumerable GetTest()
{
return GetTestForMe() ?? Enumerable.Empty();
}
```
Using `Enumerable.Empty()` can be seen as more efficient than returning null. Advantage is that `Enumerable.Empty` does not create an object on call so it will put less load on `GarbageCollector`.
`Enumerable.Empty` caches the creation of the empty Collection, so the same Collection will be always be returned.
Upvotes: 3 <issue_comment>username_3: ```
List notes = noteManager.GetAll(newTaskId)?.ToList();
```
this is short code to do NUll CHECK;
Upvotes: 1 |
2018/03/22 | 536 | 1,675 | <issue_start>username_0: i need to add an hyphen after every 4 digit i enter, i am getting this in the console , how can i can achieve this to change in the input in angular 2
Code i used given below
**.ts**
```
mychange(val){
var self = this;
var chIbn = self.storeData.iban_no.split("-").join("");
if (chIbn.length > 0) {
chIbn = chIbn.match(new RegExp('.{1,4}', 'g')).join("-");
}
console.log(chIbn);
self.storeData.iban_no = chIbn;
}
```
**Html**
```
```
**Console**
[](https://i.stack.imgur.com/yj7Gy.png)
**input**
[](https://i.stack.imgur.com/3OwJB.png)
need that hyphen value in input itself<issue_comment>username_1: You need to do changes as below
```
```
you don't need `[(ngModel)]` just keep `[ngModel]` as you are taking care of change event and from method do like this, you don't need `self` in angular `this` will be okay.
```
mychange(val) {
const self = this;
let chIbn = val.split('-').join('');
if (chIbn.length > 0) {
chIbn = chIbn.match(new RegExp('.{1,4}', 'g')).join('-');
}
console.log(chIbn);
this.iban_no = chIbn;
}
```
there is issue in your method too, you need to use `val` instead of property directly as you are trying to modify `val` as assigning value to property.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Create a directive to achieve this.
You can use the `HostBinding` feature to get the element to which the directive is attached to and retrieve the value of the element and do your manipulations to the value.
Upvotes: 0 |
2018/03/22 | 383 | 1,307 | <issue_start>username_0: I disabled SMB1 on Windows Server 2008 R2 using the command:
```
sc.exe config lanmanworkstation depend= bowser/mrxsmb20/nsi
sc.exe config mrxsmb10 start= disabled
```
When I checked again using the command : `Get-Service mrxsmb10` if SMB1 is disabled, then the Status showed "Running"
Someone please tell me why SMB1 is still running even though I disabled it.<issue_comment>username_1: You need to do changes as below
```
```
you don't need `[(ngModel)]` just keep `[ngModel]` as you are taking care of change event and from method do like this, you don't need `self` in angular `this` will be okay.
```
mychange(val) {
const self = this;
let chIbn = val.split('-').join('');
if (chIbn.length > 0) {
chIbn = chIbn.match(new RegExp('.{1,4}', 'g')).join('-');
}
console.log(chIbn);
this.iban_no = chIbn;
}
```
there is issue in your method too, you need to use `val` instead of property directly as you are trying to modify `val` as assigning value to property.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Create a directive to achieve this.
You can use the `HostBinding` feature to get the element to which the directive is attached to and retrieve the value of the element and do your manipulations to the value.
Upvotes: 0 |
2018/03/22 | 836 | 3,036 | <issue_start>username_0: I need to simplify these lines of code to less than 4 if's. Not sure how i can achieve that:
```
for response in response_json:
for appliance in response['versanms.ApplianceStatusResult']['appliances']:
temp_item = OrderedDict()
if 'name' in appliance:
temp_item['name'] = appliance['name']
if 'type' in appliance:
temp_item['type'] = appliance['type']
if 'ping-status' in appliance:
temp_item['ping-status'] = appliance['ping-status']
if 'sync-status' in appliance:
temp_item['sync-status'] = appliance['sync-status']
if 'services-status' in appliance:
temp_item['services-status'] = appliance['services-status']
if 'orgs' in appliance:
temp_item['orgs'] = appliance['orgs']
if 'ownerOrg' in appliance:
temp_item['ownerOrg'] = appliance['ownerOrg']
if 'softwareVersion' in appliance:
temp_item['softwareVersion'] = appliance['softwareVersion']
if 'ipAddress' in appliance:
temp_item['ipAddress'] = appliance['ipAddress']
if appliance is not None:
appliance_list.insert(0, temp_item)
return {'appliance': appliance_list}
```
Need to remove the if's because our code validation tool doesn't like more than 4 if's in one method :(
Thank you<issue_comment>username_1: Replace all of this:
```
if 'name' in appliance:
temp_item['name'] = appliance['name']
if 'type' in appliance:
temp_item['type'] = appliance['type']
if 'ping-status' in appliance:
temp_item['ping-status'] = appliance['ping-status']
if 'sync-status' in appliance:
temp_item['sync-status'] = appliance['sync-status']
if 'services-status' in appliance:
temp_item['services-status'] = appliance['services-status']
if 'orgs' in appliance:
temp_item['orgs'] = appliance['orgs']
if 'ownerOrg' in appliance:
temp_item['ownerOrg'] = appliance['ownerOrg']
if 'softwareVersion' in appliance:
temp_item['softwareVersion'] = appliance['softwareVersion']
if 'ipAddress' in appliance:
temp_item['ipAddress'] = appliance['ipAddress']
```
with a loop:
```
for x in ['name', 'type', 'ping-status', 'sync-status',
'services-status', 'orgs', 'ownerOrg',
'softwareVersion', 'ipAddress']:
if x in appliance:
temp_item[x] = appliance[x]
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: If you want to use all of the values from appliance rather than a select few then a for .. in appliance.keys() will work.
```
appliance = { 'name':'this is the name', 'type': 'this is the type', 'ping-status': 'this is the ping status' }
temp_item = OrderedDict()
for field_name in appliance.keys():
temp_item[field_name] = appliance[field_name]
print temp_item
```
output
{'ping-status': 'this is the ping status', 'type': 'this is the type', 'name': 'this is the name'}
Upvotes: 0 |
2018/03/22 | 557 | 1,781 | <issue_start>username_0: Print respective index value from two arrays in " Javascript " and in "PHP"
```
var a = [ x , y , z]
var b = [ p, q, r]
```
`then => values [x, p] , [ y, q]`
please help me, Thanks you<issue_comment>username_1: Replace all of this:
```
if 'name' in appliance:
temp_item['name'] = appliance['name']
if 'type' in appliance:
temp_item['type'] = appliance['type']
if 'ping-status' in appliance:
temp_item['ping-status'] = appliance['ping-status']
if 'sync-status' in appliance:
temp_item['sync-status'] = appliance['sync-status']
if 'services-status' in appliance:
temp_item['services-status'] = appliance['services-status']
if 'orgs' in appliance:
temp_item['orgs'] = appliance['orgs']
if 'ownerOrg' in appliance:
temp_item['ownerOrg'] = appliance['ownerOrg']
if 'softwareVersion' in appliance:
temp_item['softwareVersion'] = appliance['softwareVersion']
if 'ipAddress' in appliance:
temp_item['ipAddress'] = appliance['ipAddress']
```
with a loop:
```
for x in ['name', 'type', 'ping-status', 'sync-status',
'services-status', 'orgs', 'ownerOrg',
'softwareVersion', 'ipAddress']:
if x in appliance:
temp_item[x] = appliance[x]
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: If you want to use all of the values from appliance rather than a select few then a for .. in appliance.keys() will work.
```
appliance = { 'name':'this is the name', 'type': 'this is the type', 'ping-status': 'this is the ping status' }
temp_item = OrderedDict()
for field_name in appliance.keys():
temp_item[field_name] = appliance[field_name]
print temp_item
```
output
{'ping-status': 'this is the ping status', 'type': 'this is the type', 'name': 'this is the name'}
Upvotes: 0 |
2018/03/22 | 296 | 1,053 | <issue_start>username_0: I'm running Window 10 64-bit. I have a Python project:
```
A:\code\projectFolder\project.py
```
For project.py, I want to import the following file:
```
A:\code\importThisFolder\importThisFile.py
```
On project.py, I've tried using without success:
```
import sys
sys.path.insert(0,'A:\code\importThisFolder')
import importThisFile
```
Can someone please help me with my import issues?<issue_comment>username_1: Don't. Simply move both .py files to the same directory and simply use:
```
import my_file
```
Alternatively, you can move your .py file to your site-packages folder.
Upvotes: -1 <issue_comment>username_2: Okay, looks like I had a mispelling and accidently used the wrong backslash. The appropriate backslash is '\'. I accidently used '/'. Thanks @busybear !
Upvotes: 0 <issue_comment>username_3: the simple solution is to put both file in same directory and then just write import thisfile or from thisfile import file.
if you put both script in same folder then it won't create any issue.
Upvotes: 0 |
2018/03/22 | 5,367 | 19,933 | <issue_start>username_0: I am getting the below error code in my app mostly by android version 4.4 i
am not able to find the error
Hi I'm trying to build a Battery Alarm app, I'm keep getting a java.lang.RuntimeException error. I've read some topics on stackoverflow and their problems seems something wrong with their AndroidManifest.xml. I didn't edit that file at all but I'm still getting this error. Here's the code:
```
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2328)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2386)
at android.app.ActivityThread.access$900 (ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1277)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:136)
at android.app.ActivityThread.main (ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative (Native Method)
at java.lang.reflect.Method.invoke (Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1099)
at dalvik.system.NativeStart.main (Native Method)
Caused by: android.view.InflateException:
at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:719)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:761)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:769)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:769)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:769)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:769)
at android.view.LayoutInflater.inflate (LayoutInflater.java:498)
at android.view.LayoutInflater.inflate (LayoutInflater.java:398)
at android.view.LayoutInflater.inflate (LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView (AppCompatDelegateImplV9.java:288)
at android.support.v7.app.AppCompatActivity.setContentView (AppCompatActivity.java:140)
at www.androidghost.com.batteryalarm.MainActivity.onCreate (MainActivity.java:232)
at android.app.Activity.performCreate (Activity.java:5451)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2292)
Caused by: android.content.res.Resources$NotFoundException:
at android.content.res.Resources.loadDrawable (Resources.java:3063)
at android.content.res.TypedArray.getDrawable (TypedArray.java:602)
at android.view.View. (View.java:3687)
at android.widget.TextView. (TextView.java:913)
at android.widget.Button. (Button.java:108)
at android.support.v7.widget.AppCompatButton. (AppCompatButton.java:66)
at android.support.v7.widget.AppCompatButton. (AppCompatButton.java:62)
at android.support.v7.app.AppCompatViewInflater.createView (AppCompatViewInflater.java:109)
at android.support.v7.app.AppCompatDelegateImplV9.createView (AppCompatDelegateImplV9.java:1021)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView (AppCompatDelegateImplV9.java:1080)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView (LayoutInflaterCompatHC.java:47)
at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:690)
Caused by: org.xmlpull.v1.XmlPullParserException:
at android.graphics.drawable.Drawable.createFromXmlInner (Drawable.java:986)
at android.graphics.drawable.Drawable.createFromXml (Drawable.java:930)
at android.content.res.Resources.loadDrawable (Resources.java:3059)
```
Here is my MainActivit code
```
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout= (LinearLayout) findViewById(R.id.relative_main);
btnTechnology = (Button) findViewById(R.id.btnTechnology);
btnHealth = (Button) findViewById(R.id.btnHealth);
btnStop=(Button) findViewById(R.id.btnStop);
btnPower = (Button) findViewById(R.id.btnPower);
btnTemp = (Button) findViewById(R.id.btntemp);
btnVoltage = (Button) findViewById(R.id.btnVoltage);
btnFab= (FloatingActionButton) findViewById(R.id.btnfab);
layoutButton= (LinearLayout) findViewById(R.id.layoutButton);
layoutContent= (RelativeLayout) findViewById(R.id.layoutContent);
btnCapacity= (Button) findViewById(R.id.btnCapacity);
toolbar = (Toolbar) findViewById(R.id.toolbar_id);
setSupportActionBar(toolbar);
try
{
actionBar=getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.mipmap.home);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
catch (NullPointerException e)
{
e.printStackTrace();
}
mWaveLoadingView = (WaveLoadingView) findViewById(R.id.waveLoadingView);
mWaveLoadingView.setShapeType(WaveLoadingView.ShapeType.CIRCLE);
mWaveLoadingView.setCenterTitleColor(Color.BLACK);
mWaveLoadingView.setBottomTitleSize(20);
mWaveLoadingView.setBorderWidth(4);
mWaveLoadingView.setAmplitudeRatio(60);
mWaveLoadingView.setAnimDuration(3000);
mWaveLoadingView.pauseAnimation();
mWaveLoadingView.resumeAnimation();
mWaveLoadingView.cancelAnimation();
mWaveLoadingView.startAnimation();
try
{
btnStop.setText("Stop Alarm");
btnStop.setTextColor(Color.parseColor("#FFAF22DA"));
Toast.makeText(this, "Alarm Activated", Toast.LENGTH_SHORT).show();
startService(new Intent(this, RegisterAlarmService.class));
}
catch (Exception e)
{
e.printStackTrace();
}
//fetch value from firebase to use check for update
try
{
// 1 Create the singleton Remote Config object
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// To fetch parameter values from the Remote Config Server
long cacheExpiration=0;
mFirebaseRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener()
{
@Override
public void onComplete(@NonNull Task task)
{
if (task.isSuccessful())
{
// Once the config is successfully fetched it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
}
displayDialogMessage();
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
//wheather to show AutoStart dialog or not
mSharedPreferencesPermission=getSharedPreferences("permission",Context.MODE\_PRIVATE);
Cancel\_value= mSharedPreferencesPermission.getString("autostart","Def\_value");
if(Cancel\_value.equals("Def\_value"))
{
if(Build.BRAND.equalsIgnoreCase("xiaomi") || Build.BRAND.equalsIgnoreCase("Letv") || Build.BRAND.equalsIgnoreCase("Honor")|| Build.BRAND.equalsIgnoreCase("oppo") || Build.BRAND.equalsIgnoreCase("vivo"))
{
mAutoPermissionDialog.show(getFragmentManager(),"My Permission");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
mSpringMenu = new SpringMenu(this, R.layout.view\_menu);
mSpringMenu.setFadeEnable(true);
mSpringMenu.setChildSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(20, 5));
mSpringMenu.setDragOffset(0.10f);
mSpringMenu.setDirection(0); //0 For Left and 1 For Right
mListView= (ListView) findViewById(R.id.nev\_listView);
MyAdapter adapter=new MyAdapter(this,title,image);
mListView.setAdapter(adapter);
ListItemListener listener=new ListItemListener(this,getSupportFragmentManager());
mListView.setOnItemClickListener(listener);
try
{
//get the value of checkbox to check the rate dialog will show in future or not
SharedPreferences Ratepreferences=getSharedPreferences("Rates", Context.MODE\_PRIVATE);
boolean check= Ratepreferences.getBoolean("Rate",false); //default value is false means show dialog
SimpleDateFormat dateFormat = new SimpleDateFormat("dd"); //get the system curent date
String compareDate = "15"; //assign the date at which dialog will appear
Date date = new Date();
String getDate = dateFormat.format(date); //convert the system date to string
if(!check) //check wheather the checkbox is selected or not
{
if (getDate.equals(compareDate)) //compare the date
{
RateMeDialog rateMeDialog=new RateMeDialog(); //if all condition meats then show dialog
rateMeDialog.show(getFragmentManager(),"My Rate");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void onResume()
{
mRewardedVideoAd.resume(this);
registerReceiver(myBroadCast, new IntentFilter(Intent.ACTION\_BATTERY\_CHANGED));
try
{
mSharedPreferencesTheft\_Value=getSharedPreferences("theft\_value", Context.MODE\_PRIVATE);
Theft\_Set\_Value=mSharedPreferencesTheft\_Value.getString("thefts\_value","Theft Alarm Off");
mSharedPreferencesTheft\_Image=getSharedPreferences("theft\_image",Context.MODE\_PRIVATE);
Theft\_Set\_Image=mSharedPreferencesTheft\_Image.getInt("thefts\_image",R.mipmap.theft\_off);
btnTheft= (Button) findViewById(R.id.btnTheft);
if (Theft\_Set\_Value.equals("Theft Alarm Off"))
{
btnTheft.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.theft\_off, 0, 0);
btnTheft.setText(Theft\_Set\_Value);
btnTheft.setTextColor(Color.parseColor("#9BA1A8"));
}
else
{
btnTheft.setCompoundDrawablesWithIntrinsicBounds(0,Theft\_Set\_Image, 0, 0);
btnTheft.setText(Theft\_Set\_Value);
btnTheft.setTextColor(Color.parseColor("#FFAF22DA"));
}
}
catch (Exception e)
{
e.printStackTrace();
}
super.onResume();
}
@Override
public void onPause()
{
mRewardedVideoAd.pause(this);
super.onPause();
}
@Override
protected void onDestroy()
{
mRewardedVideoAd.destroy(this);
unregisterReceiver(myBroadCast);
super.onDestroy();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
return mSpringMenu.dispatchTouchEvent(ev);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu\_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()==R.id.navigate)
{
DialogInfo dialogInfo=new DialogInfo();
dialogInfo.show(getFragmentManager(), "My Info");
}
else if(item.getItemId()==android.R.id.home)
{
mSpringMenu.openMenu();
}
return super.onOptionsItemSelected(item);
}
private void displayDialogMessage()
{
String getVersionCode= mFirebaseRemoteConfig.getString("android\_update\_version\_code");
try
{
FireBaseVersionCode=Integer.valueOf(getVersionCode);
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
//Get PackageInfo like VersionCode
PackageManager packageManager=this.getPackageManager();
try
{
PackageInfo info=packageManager.getPackageInfo(this.getPackageName(),0);
VersionCode=info.versionCode;
}
catch (PackageManager.NameNotFoundException e)
{
e.printStackTrace();
}
if(VersionCode System.currentTimeMillis())
{
super.onBackPressed();
return;
}
else
{
Snackbar snackbar=Snackbar.make(linearLayout,"Confirm Exit",Snackbar.LENGTH\_LONG);
View view2=snackbar.getView();
view2.setBackgroundColor(Color.parseColor("#FFAF22DA"));
TextView textView= (TextView) view2.findViewById(android.support.design.R.id.snackbar\_text);
textView.setTextSize(20);
textView.setTextAlignment(View.TEXT\_ALIGNMENT\_CENTER);
snackbar.show();
mBackPressed=System.currentTimeMillis();
}
}
public void Stop(View v)
{
if (btnStop.getText().toString().equals("Stop Alarm"))
{
btnStop.setText("Start Alarm");
Snackbar snackbar=Snackbar.make(linearLayout,"Alarm Deactivated",Snackbar.LENGTH\_LONG);
View view2=snackbar.getView();
view2.setBackgroundColor(Color.parseColor("#FFAF22DA"));
TextView textView= (TextView) view2.findViewById(android.support.design.R.id.snackbar\_text);
textView.setTextSize(20);
textView.setTextAlignment(View.TEXT\_ALIGNMENT\_CENTER);
snackbar.show();
btnStop.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.alarm\_start, 0, 0);
btnStop.setTextColor(Color.parseColor("#9BA1A8"));
stopService(new Intent(this, MyAlarmServiceClass.class));
stopService(new Intent(this, RegisterAlarmService.class));
}
else
{
//this else block will execute only when toggle button is off in setting now here we will on toggle button
btnStop.setText("Stop Alarm");
Snackbar snackbar=Snackbar.make(linearLayout,"Alarm Activated",Snackbar.LENGTH\_LONG);
View view3=snackbar.getView();
view3.setBackgroundColor(Color.parseColor("#FFAF22DA"));
TextView textView= (TextView) view3.findViewById(android.support.design.R.id.snackbar\_text);
textView.setTextSize(20);
textView.setTextAlignment(View.TEXT\_ALIGNMENT\_CENTER);
snackbar.show();
btnStop.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.alarm\_stop, 0, 0);
btnStop.setTextColor(Color.parseColor("#FFAF22DA"));
startService(new Intent(this, RegisterAlarmService.class));
}
}
public void ThetAlarmBtn(View view)
{
mSharedPreferencesTheft\_Value=getSharedPreferences("theft\_value", Context.MODE\_PRIVATE);
SharedPreferences.Editor mEditor=mSharedPreferencesTheft\_Value.edit();
mSharedPreferencesTheft\_Image=getSharedPreferences("theft\_image",Context.MODE\_PRIVATE);
SharedPreferences.Editor editor\_image=mSharedPreferencesTheft\_Image.edit();
if (btnTheft.getText().toString().equals("Theft Alarm Off"))
{
if(status==BatteryManager.BATTERY\_STATUS\_CHARGING)
{
btnTheft.setText("Theft Alarm On");
Snackbar snackbar=Snackbar.make(linearLayout,"Theft Alarm On",Snackbar.LENGTH\_LONG);
View view4=snackbar.getView();
view4.setBackgroundColor(Color.parseColor("#FFAF22DA"));
TextView textView= (TextView) view4.findViewById(android.support.design.R.id.snackbar\_text);
textView.setTextSize(20);
textView.setTextAlignment(View.TEXT\_ALIGNMENT\_CENTER);
snackbar.show();
btnTheft.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.theft\_on, 0, 0);
btnTheft.setTextColor(Color.parseColor("#FFAF22DA"));
Theft\_Get\_Value = "Theft Alarm On";
mEditor.putString("thefts\_value", Theft\_Get\_Value);
mEditor.apply();
Theft\_Get\_Image = R.mipmap.theft\_on;
editor\_image.putInt("thefts\_image", Theft\_Get\_Image);
editor\_image.apply();
startService(new Intent(this, RegisterTheftService.class));
}
else if(status==BatteryManager.BATTERY\_STATUS\_DISCHARGING)
{
Snackbar snackbar=Snackbar.make(linearLayout,"Please Connect Your Device To Charger To Activate Theft Alarm",Snackbar.LENGTH\_LONG);
View view4=snackbar.getView();
view4.setBackgroundColor(Color.parseColor("#FFAF22DA"));
snackbar.show();
}
}
else
{
btnTheft.setText("Theft Alarm Off");
Snackbar snackbar=Snackbar.make(linearLayout,"Theft Alarm Off",Snackbar.LENGTH\_LONG);
View view5=snackbar.getView();
view5.setBackgroundColor(Color.parseColor("#FFAF22DA"));
TextView textView= (TextView) view5.findViewById(android.support.design.R.id.snackbar\_text);
textView.setTextSize(20);
textView.setTextAlignment(View.TEXT\_ALIGNMENT\_CENTER);
snackbar.show();
btnTheft.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.theft\_off, 0, 0);
btnTheft.setTextColor(Color.parseColor("#9BA1A8"));
Theft\_Get\_Value = "Theft Alarm Off";
mEditor.putString("thefts\_value", Theft\_Get\_Value);
mEditor.apply();
Theft\_Get\_Image = R.mipmap.theft\_off;
editor\_image.putInt("thefts\_image", Theft\_Get\_Image);
editor\_image.apply();
stopService(new Intent(this, RegisterTheftService.class));
stopService(new Intent(this, MyTheftServiceClass.class));
}
}
public void OpenInfo(View v)
{
if(!isopen)
{
int x=layoutContent.getRight();
int y=layoutContent.getBottom();
int startRadius=0;
int endRadius= (int) Math.hypot(linearLayout.getWidth(),linearLayout.getHeight());
btnFab.setImageResource(R.mipmap.menu\_close);
Animator animator= ViewAnimationUtils.createCircularReveal(layoutButton,x,y,startRadius,endRadius);
layoutButton.setVisibility(View.VISIBLE);
animator.start();
isopen=true;
}
else
{
int x=layoutContent.getRight();
int y=layoutContent.getBottom();
int startRadius=Math.max(linearLayout.getWidth(),linearLayout.getHeight());
int endRadius= 0;
btnFab.setImageResource(R.mipmap.menu\_open);
Animator animator= ViewAnimationUtils.createCircularReveal(layoutButton,x,y,startRadius,endRadius);
layoutButton.setVisibility(View.VISIBLE);
animator.addListener(new Animator.AnimatorListener()
{
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator)
{
layoutButton.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
animator.start();
isopen=false;
}
}
}
```
Here is my xml code
```
```<issue_comment>username_1: make sure all the ids are correct and is available in the xml layout,and also check if any resource you are loading from drawble is available ,i.e
if a file is available in drawble-v21 ,it should also be availbe in drawable folder.
For more follow this [Android resource not found exception?](https://stackoverflow.com/questions/7727808/android-resource-not-found-exception)
Upvotes: -1 <issue_comment>username_2: If you are using **AppCompat 23.2.0**, setting these flags is required.
If you’re using v2.0 or above of the Gradle plugin, we have a handy shortcut to enable everything:
```
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
```
If you have not updated yet, and are using v1.5.0 or below of the Gradle plugin, you need to add the following to your app’s build.gradle:
```
android {
defaultConfig {
// Stops the Gradle plugin’s automatic rasterization of vectors
generatedDensities = []
}
// Flag to tell aapt to keep the attribute ids around
aaptOptions {
additionalParameters "--no-version-vectors"
}
}
```
Without this flag enabled, you will see this (or similar) error when running your app on devices running **KitKat or lower.**
**## OR ##**
You can also upgrade to **23.4.0**
```
dependencies {
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
}
```
You need to write below code to enable this functionality at the top of your Activity that uses the vectors:
```
static {
AppCompatDelegate.setCompatVectorFromSourcesEnabled(true);
}
```
Checkout more detail about this on the awesome article [AppCompat — Age of the vectors](https://medium.com/@chrisbanes/appcompat-v23-2-age-of-the-vectors-91cbafa87c88)
Upvotes: 0 <issue_comment>username_3: Finally i found the solution of my problem i was using ripple effect in my code
after deleting ripple effect xml file the app is running good in kitkat version
but i don't know why i can not use ripple effect in kitkat version..
Upvotes: 1 [selected_answer] |
2018/03/22 | 234 | 984 | <issue_start>username_0: What is standard project folder structure should I follow for making a component-based project in AngularJS 1.5?<issue_comment>username_1: You can have following type of basic folder structure and also refer to [git app starter](https://github.com/jofftiquez/angular-app-starter-pack)
```
/app
/scripts
/controllers
/directives
/services
/filters
app.js
/views
/styles
/img
/bower_components
index.html
bower.json
```
Upvotes: 0 <issue_comment>username_2: As per my question, I have tried and make beautiful project struct. but it depends on a developer which type of structure they want to follow.
```
/app
/component
/login
login.component.js
login.html
/signup
signup.component.js
signup.html
/layout
/img
/css
/bower_components
index.html
bower.json
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 2,043 | 6,889 | <issue_start>username_0: When you write `int i; cin >> i;` and input `00325` or `325`, both of the inputs behave like `i = 325;`. But why? I think is is more natural if `i`'s value was set to `0` when you input `00325`, and the next `cin >>i;` gave rise to `i = 0;` and the next `cin >> i;` gave rise to `i = 325;`. I know `00325` can be an octal number but I now input number as a decimal number (I'm not using `oct` manipulator).
What written evidence guarantees this behavior? I took a quick look at N4140 but couldn't find any evidence.
Note: What I want is not to know the way of keep the preceding zeros when output, which is discussed in [How can I pad an int with leading zeros when using cout << operator?](https://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator).
---
My question will be solved as soon as someone just give me the sentence like
`preceding zeros are ignored when setting a number-type object as the right operand of <<`
in some reliable document.<issue_comment>username_1: The leading zeros are not ignored; they are accounted for when being processed, but the resulting value saved in a variable is the same as it would be for some other textual inputs.
The same "mathematical" number can have multiple textual representations, sometimes depending on locale. For Arabic figures, `0325` is equal to `+325` and equals to `325`. Depending on chosen locale, the following texts may bear the same numerical value:
* 123,456.89
* 123.456,89
* 123456.89
* 123 456,89 (mind the half-space symbol as thousands separator)
Let's not forget about other writing systems for numbers, like Roman or Herbew, Chinese etc.
The problem with multiple number representations is even deeper than simple human traditions and happens in pure mathematics outside programming. It can be shown that a rational endless fraction like `12.9(9)` [12.9999999…] is equal in all aspects to `13`.
>
> I think is is more natural if i's value was set to 0
>
>
>
That would assume that symbol "0" is treated differently from [1-9] in input parsing. But why?
Upvotes: 1 <issue_comment>username_2: ***Warning:*** *extremely boring answer ahead*
*C++14 [istream.formatting.arithmetic] ¶3*
>
>
> ```
> operator>>(int& val);
>
> ```
>
> The conversion occurs as if performed by the following code fragment (using the same notation as for
> the preceding code fragment):
>
>
>
> ```
> typedef num_get > numget;
> iostate err = ios\_base::goodbit;
> long lval;
> use\_facet(loc).get(\*this, 0, \*this, err, lval);
> if (lval < numeric\_limits::min()) {
> err |= ios\_base::failbit;
> val = numeric\_limits::min();
> } else if (numeric\_limits::max() < lval) {
> err |= ios\_base::failbit;
> val = numeric\_limits::max();
> } else
> val = static\_cast(lval);
> setstate(err);
>
> ```
>
>
The grunt work here is done by `num_get::get`, which is specified at *[facet.num.get.members] ¶1*:
>
>
> ```
> iter_type get(iter_type in, iter_type end, ios_base& str,
> ios_base::iostate& err, long& val) const;
>
> ```
>
> [...]
> *Returns*: `do_get(in, end, str, err, val)`.
>
>
>
`do_get` in turn is defined immediately afterwards (*[facet.num.get.virtuals]*), which specifies in excruciating detail the exact workings of the whole shebang. I won't copy three pages' worth of pain, but just the main points.
In stage 1, an "equivalent stdio format specifier" is determined according to the stream flags, as per table 85 and 86; the default value for `std::ios_base` is `dec | skipws`, so we'll follow that path (which corresponds to `%d`). Also, some other locale and flag-specific characters are determined for the next stage.
In stage 2, characters are read from the stream and accumulated in a buffer; the essential point for your question is that
>
> If it is not discarded, then a check is made to determine if `c` is allowed as the next character of an input field of the conversion specifier returned by Stage 1. If so, it is accumulated
>
>
>
So, the decision to whether keep on reading your zeroes or stop after a single zero depends on the `%d` above; we'll get back to it.
In stage 3, the accumulated characters are finally converted to a `long`
>
> by the rules of one of the functions declared in the header :
>
>
> * For a signed integer value, the function `strtoll`.
>
>
>
---
Both the `%d` specifier and `strtoll` are defined in the C standard (C++14 refers to C99); let's dig them up.
At *C99 §7.19.6.2 ¶12* (when talking about `fscanf`) it is told that
>
> `d` Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the `strtol` function with the value 10 for the `base` argument.
>
>
>
So it all boils down to `strtol`/`strtoll`, that we can find at *C99 §7.20.1.4*. It is specified that the longest sequence of whitespace is skipped, and then the "subject sequence" is considered:
>
> If the value of `base` is zero, the expected form of the subject sequence is that of an integer constant as described in 6.4.4.1, optionally preceded by a plus or minus sign, but not including an integer suffix. If the value of `base` is between 2 and 36 (inclusive), the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by `base`, optionally preceded by a plus or minus sign, but not including an integer suffix. The letters from `a` (or `A`) through `z` (or `Z`) are ascribed the values 10 through 35; only letters and digits whose ascribed values are less than that of base are permitted. If the value of `base` is 16, the characters `0x` or `0X` may optionally precede the sequence of letters and digits, following the sign if present.
>
>
> The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is empty or consists entirely of white-space, or if the first non-white-space character is other than a sign or a permissible letter or digit.
>
>
> If the subject sequence has the expected form and the value of `base` is zero, the sequence of characters starting with the first digit is interpreted as an integer constant according to the rules of 6.4.4.1. If the subject sequence has the expected form and the value of `base` is between 2 and 36, it is used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated (in the return type).
>
>
>
(ibidem, ¶3-5)
As you can see, there are no special provisions for leading zeroes; if it is a valid digit, it goes in the subject sequence, to be processed all in the same batch.
Upvotes: 3 |
2018/03/22 | 962 | 3,858 | <issue_start>username_0: While implementing a custom sidebar navigator , i'm getting double headers. I've tried `headerMode: 'none'` as well as `header:null` , but no use.Following is some portion of my code
```
this.openMenu}
>
this.props.navigation.navigate("CategoryDetail",{id:this.props.cat.term\_id})}>
{this.props.cat.term\_id == '28' ? () : (
.......
........
.....
....
..
```
also code for nested navigator is
```
const StackScreens = StackNavigator({
Main: {
screen: LoginScreen,
navigationOptions:{
header:null,
}
},
RegisterForm: {screen: RegisterForm},
CourseListing:{screen: CourseListing,
navigationOptions:{
header:null,
}
},
Home:{screen: HomeScreen,
},
EconomicNews: {screen: EconomicNews},
EconomicDetails: {screen: EconomicDetails},
CategoryDetail: {screen: CategoryDetail},
DetailedView: {screen: DetailedView},
IndividualSection: {screen: IndividualSection},
Mcq:{screen: Mcq},
QASection: {screen: QASection},
ForgotPassword: {screen: ForgotPassword,
navigationOptions:{
header:null
}
}
})
export const MyDrawer = DrawerNavigator({
Home: {
screen: StackScreens,
},
Profile: {
screen: Profile
},
FAQ: {
screen: Faq
},
LogOut: {
screen: LoginScreen,
navigationOptions: ({navigation}) => ({
tabBarOnPress: (scene, jumpToIndex) => {
return Alert.alert(
'Do you really want to logout?',
[
{text: 'Accept', onPress: () => { navigation.dispatch(NavigationActions.navigate({ routeName: 'LoginScreen' }))
}},
{text: 'Cancel'}
]
);
},
})
}
});
```
[](https://i.stack.imgur.com/ga4W3.png)
Can't figure out this.What's the mistake?Please do help.<issue_comment>username_1: you can hide nested header passing { headerMode: 'none' } as a second argument in your nested StackNavigator.
Like that:
```
const RecentNav = StackNavigator({
RecentScreen: { screen: RecentScreen }
}, {
headerMode: 'none'
});
```
Upvotes: 2 <issue_comment>username_1: Make sure adding headerMode:'none' in the right place,
```
const StackScreens = StackNavigator({
Main: {screen: LoginScreen,},
RegisterForm: {screen: RegisterForm},
CourseListing:{screen: CourseListing,},
Home:{screen: HomeScreen,},
EconomicNews: {screen: EconomicNews},
EconomicDetails: {screen: EconomicDetails},
CategoryDetail: {screen: CategoryDetail},
DetailedView: {screen: DetailedView},
IndividualSection: {screen: IndividualSection},
Mcq:{screen: Mcq},
QASection: {screen: QASection},
ForgotPassword: {screen: ForgotPassword,}
},{
headerMode: 'none', // <----- Add This Here !!
});
export const MyDrawer = DrawerNavigator({
Home: {
screen: StackScreens,
},
Profile: {
screen: Profile
},
FAQ: {
screen: Faq
},
LogOut: {
screen: LoginScreen,
navigationOptions: ({navigation}) => ({
tabBarOnPress: (scene, jumpToIndex) => {
return Alert.alert(
'Do you really want to logout?',
[
{text: 'Accept', onPress: () => { navigation.dispatch(NavigationActions.navigate({ routeName: 'LoginScreen' }))
}},
{text: 'Cancel'}
]
);
},
})
}
},{
headerMode: 'none', // <----- Add This Here !!
});
```
Give this Code a try !!
Upvotes: 1 |
2018/03/22 | 760 | 3,133 | <issue_start>username_0: I use the Python programming language extensively in my research and have a few publications that required the submission of my code base. I do mostly nearest-neighbours type data mining at the moment. I am starting to worry about writing the best possible code as others are beginning to use my code. At the moment, I am iterating over a large number of directories (~100,000) and use a single main() function to sequentially call a series of small functions that each perform an individual task:
```
import os
# ... other libs
def my_function_A():
print('my function A')
def my_function_B():
print('my function B')
def my_function_C():
print('my function C')
# ... 40 or more such functions
def main():
my_function_A() # do task a
my_function_B() # do task b
my_function_C() # do task c
# ....
return result
for dirs in os.listdir(dir_to_iterate_over):
result = main()
# iterate over many directories
```
My senior supervisor expects all functions to perform at most one task but here I am calling a main function that's performing a slew of tasks. I am interested (and slightly concerned) about how this approach affects overall program performance (i.e. what effects this has on dynamic stack allocation, etc.)<issue_comment>username_1: you can hide nested header passing { headerMode: 'none' } as a second argument in your nested StackNavigator.
Like that:
```
const RecentNav = StackNavigator({
RecentScreen: { screen: RecentScreen }
}, {
headerMode: 'none'
});
```
Upvotes: 2 <issue_comment>username_1: Make sure adding headerMode:'none' in the right place,
```
const StackScreens = StackNavigator({
Main: {screen: LoginScreen,},
RegisterForm: {screen: RegisterForm},
CourseListing:{screen: CourseListing,},
Home:{screen: HomeScreen,},
EconomicNews: {screen: EconomicNews},
EconomicDetails: {screen: EconomicDetails},
CategoryDetail: {screen: CategoryDetail},
DetailedView: {screen: DetailedView},
IndividualSection: {screen: IndividualSection},
Mcq:{screen: Mcq},
QASection: {screen: QASection},
ForgotPassword: {screen: ForgotPassword,}
},{
headerMode: 'none', // <----- Add This Here !!
});
export const MyDrawer = DrawerNavigator({
Home: {
screen: StackScreens,
},
Profile: {
screen: Profile
},
FAQ: {
screen: Faq
},
LogOut: {
screen: LoginScreen,
navigationOptions: ({navigation}) => ({
tabBarOnPress: (scene, jumpToIndex) => {
return Alert.alert(
'Do you really want to logout?',
[
{text: 'Accept', onPress: () => { navigation.dispatch(NavigationActions.navigate({ routeName: 'LoginScreen' }))
}},
{text: 'Cancel'}
]
);
},
})
}
},{
headerMode: 'none', // <----- Add This Here !!
});
```
Give this Code a try !!
Upvotes: 1 |
2018/03/22 | 679 | 2,547 | <issue_start>username_0: I'm currently using opencv framework(3.4.1) for object measuring, but I am not able to add `points[4]` to the contours. Please let me know how to add `points[4]` to the `boxContours` in the code below.
I can pass `boxContours` to the `drawContours` only if I add points to the former.
```
cv::findContours( gray, contours, hierarchy, CV_RETR_EXTERNAL,
CV_CHAIN_APPROX_SIMPLE);
NSLog(@"contour size %lu",contours.size());
for (int i = 0; i< contours.size(); i++)
{
cv::RotatedRect rect = cv::minAreaRect(contours[i]);
cv::Point2f points[4];
rect.points(points);
std::vector> boxContours;
cv::drawContours(image, boxContours, i,cvScalar(0,255,0),2);
}
```<issue_comment>username_1: you can hide nested header passing { headerMode: 'none' } as a second argument in your nested StackNavigator.
Like that:
```
const RecentNav = StackNavigator({
RecentScreen: { screen: RecentScreen }
}, {
headerMode: 'none'
});
```
Upvotes: 2 <issue_comment>username_1: Make sure adding headerMode:'none' in the right place,
```
const StackScreens = StackNavigator({
Main: {screen: LoginScreen,},
RegisterForm: {screen: RegisterForm},
CourseListing:{screen: CourseListing,},
Home:{screen: HomeScreen,},
EconomicNews: {screen: EconomicNews},
EconomicDetails: {screen: EconomicDetails},
CategoryDetail: {screen: CategoryDetail},
DetailedView: {screen: DetailedView},
IndividualSection: {screen: IndividualSection},
Mcq:{screen: Mcq},
QASection: {screen: QASection},
ForgotPassword: {screen: ForgotPassword,}
},{
headerMode: 'none', // <----- Add This Here !!
});
export const MyDrawer = DrawerNavigator({
Home: {
screen: StackScreens,
},
Profile: {
screen: Profile
},
FAQ: {
screen: Faq
},
LogOut: {
screen: LoginScreen,
navigationOptions: ({navigation}) => ({
tabBarOnPress: (scene, jumpToIndex) => {
return Alert.alert(
'Do you really want to logout?',
[
{text: 'Accept', onPress: () => { navigation.dispatch(NavigationActions.navigate({ routeName: 'LoginScreen' }))
}},
{text: 'Cancel'}
]
);
},
})
}
},{
headerMode: 'none', // <----- Add This Here !!
});
```
Give this Code a try !!
Upvotes: 1 |
2018/03/22 | 1,256 | 3,738 | <issue_start>username_0: I am building a scheduler that calculates the number of hours each person works for a week. The dataframe looks like this:
```
>df
Shift Monday Tuesday Wednesday Thursday Friday Saturday Sunday
1 09-12 a c a c b b b
2 12-15 b d b d a a e
3 15-18 c e c e d e f
4 18-21 d f e f e f a
5 21-24 e a d d c d d
6 24-03 f b f e a b b
7 03-06 a c a a b a e
8 06-09 b d b f d e f
```
Additionally, I would like to have people who serve Shift 24-03 to have 4 hours instead of 3 hours. So the result would look something like this:
```
name hours
a 30
b 34
c 32
d 31.5
e 34
f 33
```<issue_comment>username_1: We can `gather` into 'long' format, `separate` the 'shift' into numeric columns, then grouped by 'name', get the difference of the two columns and `sum` it
```
library(tidyverse)
gather(df, key, name, -Shift) %>%
separate(Shift, into = c("Start", "End"), convert = TRUE) %>%
mutate(End = ifelse(End < Start, Start + End, End)) %>%
group_by(name) %>%
summarise(hours = sum(End - Start))
```
Upvotes: 2 <issue_comment>username_2: If you make sure your columns are strings and not factors, you can unlist the week-day columns to get a plain vector and then use `table` to count
```
df <- read.table(text="Shift Monday Tuesday Wednesday Thursday Friday Saturday Sunday
1 09-12 a c a c b b b
2 12-15 b d b d a a e
3 15-18 c e c e d e f
4 18-21 d f e f e f a
5 21-24 e a d d c d d
6 24-03 f b f e a b b
7 03-06 a c a a b a e
8 06-09 b d b f d e f",
stringsAsFactors = FALSE)
plain_vec <- unlist(df[,2:8], use.names = FALSE)
```
This gets you to
```
> table(plain_vec)
plain_vec
a b c d e f
11 11 6 10 10 8
```
To count hours, you can replicate rows as many times as you have hours adn adjust the 24-03 by adding an extra row for that.
```
> table(unlist(df[c(rep(c(1:5,7:8), each=3), rep(8,4)), 2:8], use.names=FALSE))
a b c d e f
30 32 18 38 31 26
```
The `use.names=FALSE` is just something I usually do with `unlist`. You don't need it, but usually your code is much faster if vectors do not have to carry their names along with them.
Upvotes: 0 <issue_comment>username_3: I think `gather` from the `tidyr` package will shape the data into a form you want:
```
> df1 = df %>% tidyr::gather(key = "weekday", value = "name", -Shift)
Shift weekday name
1 09-12 Monday a
2 12-15 Monday b
3 15-18 Monday c
4 18-21 Monday d
...
```
Then you can add on a `hours` column using `mutate` and `ifelse`:
```
df2 = df1 %>% mutate(hours = ifelse(Shift == "24-03", 4, 3))
```
And the answer is a simple `group_by` / `summarise` combo:
```
answer = df2 %>% group_by(name) %>% summarise(hours = sum(hours))
```
The `answer` dataframe will look like this:
```
name hours
-----------
a 34
b 36
c 18
d 30
e 31
f 26
```
This isn't quite what you wanted, but I think there's something fishy about your sample data. How can someone have 31.5 hours?
Upvotes: 1 [selected_answer] |
2018/03/22 | 1,126 | 3,620 | <issue_start>username_0: on hover li div will come I got it. my question is by default first div is displayed.i want to show the first div.
Can anyone suggest me?
Help will be appreciated
```js
$('#menu a').hover(function(e){
hideContentDivs();
var tmp_div = $(this).parent().index();
$('.main div').eq(tmp_div).show();
});
function hideContentDivs(){
$('.main div').each(function(){
$(this).hide();});
}
hideContentDivs();
```
```html
* [Topic One](#)
* [Topic Two](#)
* [Topic Three](#)
Page 1
======
First section of content.
Page 2
======
Second section of content
Page 3
======
Third section of content.
```<issue_comment>username_1: Initially hide divs except the first, to ignore the first one you can use jQuery [`:first`](http://api.jquery.com/first-child) pseudo-selector with [`:not()`](http://api.jquery.com/not-selector/) selector or use [`slice()`](http://api.jquery.com/slice/) method.
```
$('.main div:not(:first)').hide();
// or
$('.main div').slice(1).hide();
```
```js
$('#menu a').hover(function(e) {
hideContentDivs();
var tmp_div = $(this).parent().index();
$('.main div').eq(tmp_div).show();
});
function hideContentDivs() {
$('.main div').hide();
}
$('.main div:not(:first)').hide();
```
```html
* [Topic One](#)
* [Topic Two](#)
* [Topic Three](#)
Page 1
======
First section of content.
Page 2
======
Second section of content
Page 3
======
Third section of content.
```
---
You can simplify the code as well by chaining [`hide()`](http://api.jquery.com/hide/) method.
```js
$('#menu a').hover(function(e) {
var tmp_div = $(this).parent().index();
$('.main div').hide().eq(tmp_div).show();
// -------------^----
});
$('.main div:not(:first)').hide();
```
```html
* [Topic One](#)
* [Topic Two](#)
* [Topic Three](#)
Page 1
======
First section of content.
Page 2
======
Second section of content
Page 3
======
Third section of content.
```
---
Although it's better to cache the elements for referring inside the callback.
```js
var $divs =$('.main div');
$('#menu a').hover(function(e) {
var tmp_div = $(this).parent().index();
$divs.hide().eq(tmp_div).show();
});
// select divs except first index
$divs.slice(1).hide();
```
```html
* [Topic One](#)
* [Topic Two](#)
* [Topic Three](#)
Page 1
======
First section of content.
Page 2
======
Second section of content
Page 3
======
Third section of content.
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: you can add $("#page1").show(); to end . It will show first div as default.
```js
$('#menu a').hover(function(e){
hideContentDivs();
var tmp_div = $(this).parent().index();
$('.main div').eq(tmp_div).show();
});
function hideContentDivs(){
$('.main div').each(function(){
$(this).hide();});
}
hideContentDivs();
$("#page1").show();
```
```html
* [Topic One](#)
* [Topic Two](#)
* [Topic Three](#)
Page 1
======
First section of content.
Page 2
======
Second section of content
Page 3
======
Third section of content.
```
Upvotes: 1 <issue_comment>username_3: You can use css style for this.
```js
$('#menu a').hover(function(e){
hideContentDivs();
var tmp_div = $(this).parent().index();
$('.main div').eq(tmp_div).show();
});
function hideContentDivs(){
$('.main div').hide();
}
```
```html
* [Topic One](#)
* [Topic Two](#)
* [Topic Three](#)
Page 1
======
First section of content.
Page 2
======
Second section of content
Page 3
======
Third section of content.
```
Upvotes: 1 |
2018/03/22 | 501 | 1,639 | <issue_start>username_0: *Please note that the following code is a contrived example of accessing a struct via a void pointer and is otherwise meaningless*. My question is, is there an alternate way to cast a void pointer to a struct pointer inline (by using a (CAST\*) style syntax? E.G. can I avoid the line `S_TEST *tester_node_ptr = tester_node.next;` and somehow cast directly in the printf call?
```
#include
#include
#include
//Set up our data structure
typedef struct test{
int field1;
int field2;
char name[50];
void \*next; // We will use this void \* to refer to another struct test "node" for demo purposes
} S\_TEST;
int main(void)
{
S\_TEST tester\_node;
S\_TEST tester\_node2;
tester\_node.field1 = 55;
tester\_node.field2 = 25;
strcpy(tester\_node.name, "First Node");
tester\_node.next = &tester\_node2; // We put the addr of the second node into the void ptr
tester\_node2.field1 = 775;
tester\_node2.field2 = 678;
strcpy(tester\_node2.name, "Second Node");
tester\_node2.next = NULL; // End of list
S\_TEST \*tester\_node\_ptr = tester\_node.next;
printf("The second node's name is: %s", tester\_node\_ptr->name);
return EXIT\_SUCCESS;
}
```<issue_comment>username_1: Well, you should probably just declare `struct test *next` instead of `void *next`. But anyway:
```
printf("The second node's name is: %s", ((S_TEST *)tester_node.next)->name);
```
Upvotes: 2 <issue_comment>username_2: Yes, you may. It's as simple as this
```
((S_TEST *)tester_node.next)->name
```
Though I'd say using a named variable and relying on the implicit conversion is more readable.
Upvotes: 3 [selected_answer] |
2018/03/22 | 383 | 1,356 | <issue_start>username_0: I am using tab panes defined as
```html
* [Personal Information](#personal)
* [Contact](#contact)
* [Parent/Guardian Information](#guardian)
* [Educational Background](#education)
* [Study Prospects](#recommendations)
```
It can be seen that i have selected Contact as First selected Tab, however when I refresh the page< on full page load it automatically changes tab to Personal that is First tab.
Is there any way i can manually switch tabs via javascript etc?<issue_comment>username_1: This is the code you need.
HTML:
```
- [Contact](#contact)
```
JavaScript:
```
window.onload = function() {
document.getElementById('contact').classList.add('active');
};
```
Upvotes: 0 <issue_comment>username_2: There is a solution to change the tabs, so you will need to:
1. Keep the last tab some where.
2. Call the below function when the page refresh.
This how you can call it:
```
activeTab('tab1');
function activeTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
```
Upvotes: 4 <issue_comment>username_3: To piggyback off of Uwe Keim's answer, this is how you would accomplish his solution in angularjs (which I had a need for) - in case this helps someone:
```
$timeout(function () {
angular.element('.nav-tabs a[href="#' + tabname + '"]').tab("show");
}, 0);
```
Upvotes: 0 |
2018/03/22 | 712 | 2,572 | <issue_start>username_0: I'm getting data from a web page with websocket but I need to deploy it with socketIO to client. In my server.js client connects with socketio well but after that data(line1 line2) can't comes properly, always I need to restart server 2-3 times.Then it comes.
Here is my declerations
```
var server = require('http').Server(app);
var io = require('socket.io')(server);
const WebSocket = require('ws')
const wss = new WebSocket('gettingDataAdress');
io.on('connection', function (socket) {
console.log("client connected");
wss.on('open', () => {
console.log("send processing");
//line1
})
wss.on('message', () => {
console.log("getting message processing");
//line2
})
```
After restarting my server.js 2-3 times it can comes to line1 and line2 , it can't directly.However whenever I comment the socketio Part(I mean only websocket working) it works perfect.How can I do that ? Thank you<issue_comment>username_1: You are using two different websockets `ws` and `socket.io`. Use only one to connect to the client and subscribe to the coming messages
Only Socket.io
--------------
```
io.on('connection', function (socket) {
console.log("client connected");
socket.on('open', () => {
console.log("send processing");
//line1
})
socket.on('message', () => {
console.log("getting message processing");
//line2
})
```
Only ws
-------
```
const WebSocket = require('ws');
const ws = new WebSocket('url');
ws.on('open', () => {
//do processing
});
ws.on('message', () => {
//do processing
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: *wanted to write a comment but had no reputation to write, so decide write on here. sorry!*
If you want to subscribe, rather use `socket.io-client`. However, `socket-io` itself is not a proper library to subscribe `wss`.
<https://github.com/socketio/socket.io-client/issues/1208>
>
> actually, Socket.IO is not a WebSocket implementation, it has its own protocol which may use a WebSocket connection to transmit data
> -darrachequesne-(most contributor of socket-io client library)
>
>
>
so If you get data from wss page, then use ws library and spread it by socket-io. I believe that what you are doing is pretty fine. might need to fix a bit though.
[Connecting to GDAX websocket api using socket.io with webpack](https://stackoverflow.com/questions/48835447/connecting-to-gdax-websocket-api-using-socket-io-with-webpack)
there is similar question to get data from ws.
Upvotes: 0 |
2018/03/22 | 811 | 2,754 | <issue_start>username_0: I'm trying to set up unit tests for my PyQt app, and I ran into an unexpected situation.
Basically, the type of item returned from layout.itemAt() is different from the item that was added to the layout, and I'm curious why.
Here's my example code:
```
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QDialog):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.layout = QtWidgets.QVBoxLayout()
self.table = QtWidgets.QTableWidget()
self.layout.addWidget(self.table)
self.setLayout(self.layout)
print(type(self.table))
print(type(self.layout.itemAt(0)))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()
```
When this is run, `type(self.table)` returns as expected, but `type(self.layout.itemAt(0))` -- which is still the table item -- returns , and I can't figue out why they would be different.<issue_comment>username_1: The classes that inherit [`QLayout`](http://doc.qt.io/qt-5/qlayout.html) as [`QBoxLayout`](http://doc.qt.io/qt-5/qboxlayout.html), [`QGridLayout`](http://doc.qt.io/qt-5/qgridlayout.html), [`QFormLayout`](http://doc.qt.io/qt-5/qformlayout.html) and [`QStackedLayout`](http://doc.qt.io/qt-5/qstackedlayout.html) have as their main element the [`QLayoutItem`](http://doc.qt.io/qt-5/qlayoutitem.html#QLayoutItem)(in your case [`QWidgetItem`](http://doc.qt.io/qt-5/qwidgetitem.html)) which is a class that can handle the geometry of other `QLayout`s and `QWidget`s, and that is the object that is being returned with the method [`itemAt()`](http://doc.qt.io/qt-5/qlayout.html#itemAt).
If you want to get the widget you must use the [`widget()`](http://doc.qt.io/qt-5/qlayoutitem.html#widget) method of the [`QLayoutItem`](http://doc.qt.io/qt-5/qlayoutitem.html):
```
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QDialog):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.layout = QtWidgets.QVBoxLayout()
self.table = QtWidgets.QTableWidget()
self.layout.addWidget(self.table)
self.setLayout(self.layout)
assert(self.table == self.layout.itemAt(0).widget())
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: That object type is an intermediate between the widget and the layout that is created by the layout when you add an item (see [here](http://doc.qt.io/qt-5/qwidgetitem.html)). Use `self.layout.itemAt(0).widget()` to get the original widget!
Upvotes: 0 |
2018/03/22 | 1,889 | 7,194 | <issue_start>username_0: Android Login problem. Php is perfectly returning the response in JSON format. But the android activity is not going to next activity. sometimes it is showing Bad network connection and sometimes it is showing passwords don't match error even though the right password
here are my codes
login.php
```
php
include("Connection.php");
if(isset($_POST["email"]) && isset($_POST["password"]))
{
$email=$_POST["email"];
$password=$_POST["password"];
$result = mysqli_query($conn, "select * from user_master where email='$email' && password='$<PASSWORD>'");
if(mysqli_num_rows($result) 0)
{
$isLogin["success"] = 1;
}
else
{
$isLogin["success"] = 0;
}
echo json_encode($isLogin);
}
?>
```
LoginRequest.java
```
package com.talentakeaways.ttpms;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chand on 15-03-2018.
*/
public class LoginRequest extends StringRequest {
private static final String LOGIN_URL = "http://192.168.1.9:80/Ttpms/login.php";
private Map parameters;
LoginRequest(String username, String password, Response.Listener listener, Response.ErrorListener errorListener) {
super(Method.POST, LOGIN\_URL, listener, errorListener);
parameters = new HashMap<>();
parameters.put("email", username);
parameters.put("password", <PASSWORD>);
}
@Override
protected Map getParams() throws AuthFailureError {
return parameters;
}
}
```
Ttpm\_Login.java
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ttpm_login);
setTitle("Login"); //set title of the activity
initialize();
final RequestQueue requestQueue = Volley.newRequestQueue(Ttpm_Login.this);
//onClickListener method for button
bt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//assigning String variables to the text in edit texts
userName = tenantname.getText().toString();
password = <PASSWORD>.getText().toString();
//Validating the String values
if (validateUsername(userName) && validatePassword(password)) {
//Start ProgressDialog
final ProgressDialog progressDialog = new ProgressDialog(Ttpm_Login.this);
progressDialog.setTitle("Please Wait");
progressDialog.setMessage("Logging You In");
progressDialog.setCancelable(false);
progressDialog.show();
//LoginRequest from class LoginRequest
LoginRequest loginRequest = new LoginRequest(userName, password, new Response.Listener() {
@Override
public void onResponse(String response) {
Log.i("Login Response", response);
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
//If Success then start Dashboard Activity
if (jsonObject.getString("success").equals(1)) {
Intent loginSuccess = new Intent(getApplicationContext(), Ttpm\_Dashboard.class);
startActivity(loginSuccess);
finish();
}
//else Invalid
else {
if (jsonObject.getString("success").equals(0))
Toast.makeText(getApplicationContext(), "User Not Found", Toast.LENGTH\_SHORT).show();
// else {
// Toast.makeText(getApplicationContext(), "Passwords Don't Match", Toast.LENGTH\_SHORT).show();
// }
}
} catch (JSONException e) {
e.printStackTrace();
Log.getStackTraceString(e);
Toast.makeText(Ttpm\_Login.this, "Bad Response from the Server", Toast.LENGTH\_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
if (error instanceof ServerError) {
Toast.makeText(Ttpm\_Login.this, "Server Error", Toast.LENGTH\_SHORT).show();
} else if (error instanceof TimeoutError) {
Toast.makeText(Ttpm\_Login.this, "Connection Timed Out", Toast.LENGTH\_SHORT).show();
} else if (error instanceof NetworkError) {
Toast.makeText(Ttpm\_Login.this, "Bad Network Connection", Toast.LENGTH\_SHORT).show();
}
}
});
requestQueue.add(loginRequest);
}
}
});
}
```
Please help thanks In advance.<issue_comment>username_1: You are comparing JSON result with an number which is wrong
try this
```
if (jsonObject.getString("success").equals("1")) {
// Proceed to Login
} else {
if (jsonObject.getString("success").equals("0")) {
}
```
Server is returning `{ "success" : "1" }`
Upvotes: 2 [selected_answer]<issue_comment>username_2: Write this block above `if..else` condition in `PHP` file as
```
$isLogin["success"] = 0; //This will give access outside of If condition.
if(mysqli_num_rows($result) > 0)
{
$isLogin["success"] = 1;
}
echo json_encode($isLogin);
```
And as @username_1 posted, the server is returning `{"success":"1"}`, in your `Activity`'s code write your as
```
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getString("success").equals("1"))
{
//Success
}
else{
//Invalid Login
}
```
Upvotes: 0 <issue_comment>username_3: Please try this code it is very help full to you:
```
String url = Global.BASE_URL + Global.LOGIN_API;
cancel_login_api=url;
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new Response.Listener() {
/\*\* Api response action\*/
@Override
public void onResponse(String response) {
Log.e("AB",response);
/\*\* receiving response from api here\*/
try {
JSONObject obj = new JSONObject(response);
if (API.success(obj))
{
Utils.storeUserPreferences(LoginActivity.this, Global.USER, API.getData(obj));
Toast.makeText(LoginActivity.this, API.rMessage(obj), Toast.LENGTH\_SHORT).show();
Intent skip = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(skip);
} else
{
Toast.makeText(LoginActivity.this, ""+API.rMessage(obj), Toast.LENGTH\_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("AA",response);
}
/\*\* Alert dialog box is dismiss\*/
pd.dismiss();
}
}, new Response.ErrorListener() {
/\*\* method when no response from internet\*/
@Override
public void onErrorResponse(VolleyError error) {
/\*\* Error Log \*/
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.e("AA",""+error.getMessage());
/\*\* Alert dialog box is dismiss\*/
pd.dismiss();
}
}) {
/\*
\*\* Sending parameters to server
\* @params user\_login
\* @params user\_login\_password
\*/
@Override
protected Map getParams() {
/\*\* Pass the parameters to according to the API.\*/
Map params = new HashMap();
params.put("user\_login", edt\_email.getText().toString().trim());
params.put("user\_login\_password", <PASSWORD>());
return params;
}
};
/\*\* Adding request to request queue\*/
AppController.getInstance().addToRequestQueue(jsonObjReq, cancel\_login\_api);
}
```
try this.
Upvotes: 0 |
2018/03/22 | 441 | 1,752 | <issue_start>username_0: I'm trying to implement the google's paging library in my project. All things are already coded and network call is working in **loadInitial**() But it never goes in **loadAfter**(). As code structure is very complex I am not posting code directly here.
**Here's the repository :**
<https://github.com/raghavsatyadev/PagingDemo>
File link : <https://github.com/raghavsatyadev/PagingDemo/blob/master/app/src/main/java/com/rocky/invmx/modules/order/OrdersActivity.java><issue_comment>username_1: You are overriding `getItem(int index)` method in `GenPagingRecyclerAdapter.java` class without calling the `super.getItem(index)`. If you look at the `PagedListAdapter.java` and dig into the method call you will see that this method internally calls the `loadAfter` method. So first the solution to your problem is to remove the `getItem(int index)` from `GenPagingRecyclerAdapter.java` class. Because you are not doing anything in it and if you really want to override `getItem(int index)` then call the `super.getItem(int index)` at start.
Upvotes: 4 [selected_answer]<issue_comment>username_2: It is not an answer to the given question, but really similar problem.
In `onBindViewHolder` use `getItem(int index)` instead of getting item from `currentList`. As the accepted answer says - it is needed to call `getItem` to trigger `loadAfter` in `DataSource`.
Upvotes: 3 <issue_comment>username_3: The solution to this problem of **loadAdapter()** not being invoked after **loadInitial()** has been called is to **REMOVE** the
```
override fun getItem(position: Int): YourDataModel {
return super.getItem(position)
}
```
from you **RecyclerViewAdapter** that is **currently** extending **PagedListAdapter**.
Upvotes: 1 |
2018/03/22 | 1,422 | 5,572 | <issue_start>username_0: I'm a complete beginner in android so please do excuse me if my question is foolish.Basically what I want to do is I want to detect text from occurance of **#** means for example if user is entering `abc #hello` then only `#hello` will be toasted in text change . So I tried to take reference from a github code and able to print all the **# tags** but I want to toast only current tag means if user is typing `abc #hello #hi #bye //here current tag is #bye` so I want to toast only the current tag upto the occurance of space on fly . I wonder how to modify my code to get the desired result.
Code:
```
editTxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>0)
showTags(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
//Methods
private void showTags(CharSequence text) {
int startIndexOfNextHashSign;
int index = 0;
while (index < text.length()- 1){
sign = text.charAt(index);
int nextNotLetterDigitCharIndex = index + 1; // we assume it is next. if if was not changed by findNextValidHashTagChar then index will be incremented by 1
if(sign=='#'){
startIndexOfNextHashSign = index;
nextNotLetterDigitCharIndex = findNextValidHashTagChar(text, startIndexOfNextHashSign);
Toast.makeText(this,text.subSequence(startIndexOfNextHashSign,nextNotLetterDigitCharIndex),Toast.LENGTH_LONG).show();
//setColorForHashTagToTheEnd(startIndexOfNextHashSign, nextNotLetterDigitCharIndex);
}
index = nextNotLetterDigitCharIndex;
}
}
private int findNextValidHashTagChar(CharSequence text, int start) {
int nonLetterDigitCharIndex = -1; // skip first sign '#"
for (int index = start + 1; index < text.length(); index++) {
char sign = text.charAt(index);
boolean isValidSign = Character.isLetterOrDigit(sign) || mAdditionalHashTagChars.contains(sign);
if (!isValidSign) {
nonLetterDigitCharIndex = index;
break;
}
}
if (nonLetterDigitCharIndex == -1) {
// we didn't find non-letter. We are at the end of text
nonLetterDigitCharIndex = text.length();
}
return nonLetterDigitCharIndex;
}
```
[Github Project](https://github.com/Srinu1919/HashTagHelper/tree/master/hashtag-helper/src/main/java/com/volokh/danylo/hashtaghelper)<issue_comment>username_1: ***Try this one***
```
String sampleText = "abc #hello #hi #bye";
String[] wordSplit = sampleText.split(" ");
for (int i = wordSplit.length-1; i >= 0; i--){
if(wordSplit[i].contains("#")){
Toast.makeText(getContext(), wordSplit[i].substring(wordSplit[i].indexOf("#")), Toast.LENGTH_SHORT).show();
break;
}
}
```
Edit: try using this instead of indexOf
```
lastIndexOf("#")
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: So your `TextWatcher` will look like this
```
editTxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s)
{
String[] wordSplit = s.toString().split(" ");
for (int i = wordSplit.length-1; i >= 0; i--){
if(wordSplit[i].contains("#")){
Toast.makeText(getApplicationContext(), wordSplit[i], Toast.LENGTH_SHORT).show();
break;
}
}
}
});
```
Upvotes: -1 <issue_comment>username_3: **try this : may help you**
```
String sampleText = "abc#hello#hi#bye";
String[] wordSplit = sampleText.split("#");
for (int i = wordSplit.length - 1; i >= 0; i--) {
Toast.makeText(this, wordSplit[wordSplit.length - 1], Toast.LENGTH_SHORT).show();
break;
}
```
Upvotes: -1 <issue_comment>username_4: As a reference to [above answer](https://stackoverflow.com/a/49421697/8953835) although it's a great answer but it'll always toast the last hashtag means let's take an example if the entered text is `abc #hi #hello` even if we'll move the cursor to `#hi` and change it to `#bye` it would toast the las tag i.e `#hello` so for solving this we can use *current cursor position*
So the final code is :
```
editTxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s)
{
String sampleText = s.toString().substring(0,editTxt.getSelectionStart());
String[] wordSplit = sampleText.split(" ");
String sign=null;
for (int i = wordSplit.length-1; i >= 0; i--){
if(wordSplit[i].contains("#")){
Toast.makeText(getApplicationContext(), wordSplit[i].substring(wordSplit[i].lastIndexOf("#")), Toast.LENGTH_SHORT).show();
break;
}
}
}
});
```
Upvotes: 0 |
2018/03/22 | 1,538 | 4,951 | <issue_start>username_0: ```
'products': [{ // List of productFieldObjects.
'name': 'Triblend Android T-Shirt',
'item_id': '12345',
'item_price': '15.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'quantity': 1,
'something' : 'anc',
'something2' : 'xyz',
'something3' : 'yyy'
},
{
'name': 'Triblend Android T-Shirt',
'item_id': '12345',
'item_price': '15.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'quantity': 1,
'something' : 'anc',
'something2' : 'xyz',
'something3' : 'yyy'
},
{
'name': 'Triblend Android T-Shirt',
'item_id': '12345',
'item_price': '15.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'quantity': 1,
'something' : 'anc',
'something2' : 'xyz',
'something3' : 'yyy'
}
```
]
The following data has to be filtered out.
```
'products': [{
'name': 'Triblend Android T-Shirt',
'id': '12345',
'price': '45.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black'
'quantity': 3
}]
```
Filter the data from the array and return the single array object if it matches with ID. If there are 3 items quantity and price should be added as well
Current Code
```
var filter = products.filter(function(items){
if(items.id == products.id){
return items;
}
})
```
How can I make this please guide thanks a ton in advance<issue_comment>username_1: The `condense()` `function` below traverses the `array` in its `params` to group `products` by `id` and update their `quantity` and `price` values accordingly until a condensed `array` of `products` is finally `returned`.
See [`Object.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values), [`Array.prototype.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), [`destructuring assignment`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), and [`parseFloat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) for more info.
```js
// Products.
const input = [
{
'name': 'Triblend Android T-Shirt',
'id': '12345',
'price': '15.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'quantity': 1,
},
{
'name': 'Triblend Android T-Shirt',
'id': '12345',
'price': '15.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'quantity': 1
},
{
'name': 'Triblend Android T-Shirt',
'id': '12345',
'price': '15.00',
'brand': 'Google',
'category': 'Apparel',
'variant': 'Black',
'quantity': 1
}
]
// Condense.
const condense = (products) => Object.values(products.reduce((total, product) => {
const {id} = product
const existing = total[id]
if (existing) {
const quantity = parseFloat(existing.quantity) + parseFloat(product.quantity)
const price = (quantity * parseFloat(product.price)).toFixed(2)
return {
...total,
[id]: {
...existing,
quantity,
price
}
}
}
return {...total, [id]: product}
}, {}))
// Proof.
const output = condense(input)
console.log(output)
```
Upvotes: 2 <issue_comment>username_2: You can use `array#reduce` with object destructuring to only select the required key, to create an object with id as key and object as the value using all the extracted values, for the same key add quantity. Then extract out all values from this object using `Object.values()`.
```js
var data = {'products': [{ 'name': 'Triblend Android T-Shirt', 'item_id': '12345', 'item_price': '15.00', 'brand': 'Google', 'category': 'Apparel', 'variant': 'Black', 'quantity': 1,'something' : 'anc','something2' : 'xyz','something3' : 'yyy' }, { 'name': 'Triblend Android T-Shirt', 'item_id': '12345', 'item_price':'15.00', 'brand': 'Google', 'category': 'Apparel', 'variant': 'Black', 'quantity': 1,'something' : 'anc','something2' : 'xyz','something3' : 'yyy' }, { 'name': 'Triblend Android T-Shirt', 'item_id': '12345', 'item_price': '15.00', 'brand': 'Google', 'category': 'Apparel', 'variant': 'Black', 'quantity': 1,'something' : 'anc','something2' : 'xyz','something3' : 'yyy' } ]},
result = Object.values(data.products.reduce((r,{name,item_id: id,item_price: price,brand = '',category = '', variant = '', quantity}) => {
r[id] = r[id] || {name,id,brand,category,variant, price: 0, quantity: 0};
r[id].price += +price;
r[id].quantity += quantity;
return r;
},{}));
console.log(result);
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 2,708 | 9,121 | <issue_start>username_0: I am trying to hit api using retrofit in kotlin
This is my DoinBackGround Method
```
private fun doinBackground() {
Utility.printMessage("in do in background.....")
try {
val hdr = HashMap()
hdr.put("x-csrf-token", Utility.getToken(this.context!!))
val apiInterface = ApiCallRetrofit.getClient(this.mCrypt!!)!!.create(ApiInterface::class.java)
if (what.equals(0)) {
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), getQuery(para))
print("header...")
call = apiInterface.hitApi(url, hdr, body)
} else if (what.equals(1)) {
val imgPart = ArrayList()
if (files != null) {
if (files.size > 0) {
for (i in files.indices) {
imgPart.add(preparePart("image/\*", "document\_file[" + files.get(i).key + "]", files.get(i).file))
}
}
call = apiInterface.hitApiImage(url, hdr, getMap(para), imgPart)
}
call?.enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
try {
Utility.printMessage("messege...." + response.body().message)
val resp = Gson().toJson(response.body())
Utility.printMessage("Response :$resp")
Utility.longLogPrint(response.body().data, "Full response : ")
Utility.printMessage("Error : " + Gson().toJson(response.errorBody()))
onPostExecute(Parseresponce(response.body()))
} catch (e: Exception) {
Parseresponce(null)
e.printStackTrace()
}
}
override fun onFailure(call: Call, t: Throwable) {
t.printStackTrace()
if (progressDialog != null) {
progressDialog?.dismiss()
}
Parseresponce(null)
}
})
}
} catch (e: Exception) {
e.printStackTrace()
}
}
```
And this is my interface where I am defining all the POST methods
```
@POST
abstract fun hitApi(@Url api: String, @HeaderMap header: Map, @Body body: RequestBody): Call
@POST
fun hitApiNoHeader(@Url api: String, @Body requestBody: RequestBody): Call
@POST
fun test(@Url api: String, @HeaderMap headerMap: Map, @Body requestBody: RequestBody): Call
@Multipart
@POST
fun hitApiImage(@Url api: String, @HeaderMap headerMap: Map, @PartMap bodyMap: Map, @Part images: List): Call
```
Whenever I am trying to hit the Api I am getting the following exception :
```
java.lang.IllegalArgumentException: Parameter type must not include a type variable or wildcard: java.util.Map (parameter #2)
for method ApiInterface.hitApi
at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:720)
at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:711)
at retrofit2.ServiceMethod$Builder.parameterError(ServiceMethod.java:729)
at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:193)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
```
This is the line where the exception occurs in doinbackground method
```
call = apiInterface.hitApi(url, hdr, body)
```
I tried @JvmSuppressWildcards before the RequestBody but it did not work, can anyone suggest whats the actual problem over here, plus nothing is printing in the log though I have used print() function should i use LOG.d?<issue_comment>username_1: You have used:
```
@POST
abstract fun hitApi(@Url api: String, @HeaderMap header: Map, @Body body: RequestBody): Call
```
And exception is:
```
Parameter type must not include a type variable or wildcard: java.util.Map (parameter #2)
```
And your hitApi #2 param use wildcard actually:
```
@HeaderMap header: Map
```
Try to specify argument (just change Any to String). Anyway you are not probably going to put Any object than String in your request header.
Upvotes: 0 <issue_comment>username_2: Call it in the below mentioned way.
```
val callWeather = NetworkUtils.getApiInterface().getWeatherResponse("03a7949903004a0bb2590633181104", "1.909,45.909", 7)
callWeather.enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
var api :APIXUResponse? = response.body()
}
override fun onFailure(call: Call, t: Throwable) {
}
})
```
Upvotes: 0 <issue_comment>username_3: Here i have fully example for it.
This dependancy add in gradle
```
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
annotationProcessor 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
```
Here now create **ApiClient.kt** file
```
object ApiClient {
val BASE_URL = "http://yourwebsite/services/"
private var retrofit: Retrofit? = null
val client: Retrofit
get() {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit!!
}
```
}
Now create **APIInterface.kt**
```
@FormUrlEncoded
@POST("users/login")
fun POST_LOGIN(
@Field("imei_number") imei_number: String,
@Field("device_token") device_token: String,
@Field("mobile") mobile: String,
@Field("password") password: String
): Call
@GET("general/init-data")
fun GENERAL\_MODULE(
@Header("Authorization") auth\_key: String
): Call
@GET("event-gallery/list")
fun GET\_Event\_GALLERY(
@Header("Authorization") auth\_key: String
): Call
@GET("event-gallery/photo-list")
fun GET\_Event\_GALLERY\_PHOTO(
@Header("Authorization") auth\_key: String,
@Query("id") id: Int
): Call
```
if Any Header for token the use @Header and also When call @GET that time params use @Query and @Post that time @Fields
Now Response file
```
data class EventListResponse(
@SerializedName("success")
var success: Boolean,
@SerializedName("data")
var data: EventgalleryModel?,
@SerializedName("server_error"),
@SerializedName("eventgallery")
var eventgallery: ArrayList
var server\_error: Boolean,
@SerializedName("message")
var message: String
```
)
Then create Model class of Response
Now time to Activity code
```
private fun loadData() {
card_progress.visibility = View.VISIBLE
val apiService = ApiClient.client.create(ApiInterface::class.java)
val call =
apiService.GET_FEE_INSTALMENT_LIST(PreferenceManager.getAuthKey(this@FeesInstalmentActivity)!!)
call.enqueue(object : Callback {
override fun onResponse(
call: Call,
response: Response
) {
card\_progress.visibility = View.GONE
val data = response.body()!!.data
if (response.code() == 200 && data != null) {
if (response.body()!!.server\_error) {
txt\_no\_data\_fee.visibility = View.VISIBLE
txt\_no\_data\_fee.text = response.body()!!.message
} else {
Log.e("data", data.toString())
if (data != null && data.feesinstalment.isEmpty()) {
txt\_no\_data\_fee.visibility = View.VISIBLE
} else {
txt\_no\_data\_fee.visibility = View.GONE
adapter!!.setItem(data.feesinstalment)
}
}
} else if (response.code() == 401) {
PreferenceManager.removePref(this@FeesInstalmentActivity)
startActivity(
Intent(this@FeesInstalmentActivity, LoginActivity::class.java)
.addFlags(Intent.FLAG\_ACTIVITY\_CLEAR\_TOP or Intent.FLAG\_ACTIVITY\_CLEAR\_TASK or Intent.FLAG\_ACTIVITY\_NEW\_TASK)
)
finish()
} else {
Toast.makeText(
this@FeesInstalmentActivity,
R.string.somethingWrong,
Toast.LENGTH\_SHORT
).show()
}
}
override fun onFailure(call: Call, t: Throwable) {
card\_progress.visibility = View.GONE
Log.e("onFailure", t.message)
txt\_no\_data\_fee.visibility = View.VISIBLE
}
})
}
```
**Adapter**
```
class FeeInstalmentAdapter(
private val context: Context,
private var items: ArrayList
```
) : RecyclerView.Adapter() {
```
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(context).inflate(R.layout.row_fees_instalment_item, parent, false))
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.due_date.text = DateHelper.parseData(items[position].due_date!!, "yyyy-MM-dd", "dd MMM yyyy")
holder.instalment_title.text = items[position].instalment_title
if (items[position].paid_date == null) {
holder.paid_text.visibility = View.GONE
holder.paid_date.text = context.resources.getString(R.string.UnPaid)
holder.paid_date.setTextColor(Color.parseColor("#DC143C"))
} else {
holder.paid_date.text = DateHelper.parseData(items[position].due_date!!, "yyyy-MM-dd", "dd MMM yyyy")
holder.paid_date.setTextColor(Color.parseColor("#58A259"))
}
//holder.paid_date.text = items[position].paid_date
holder.amount.text = "Rs. " + items[position].amount
holder.amount.setTextColor(Color.parseColor("#ED7136"))
}
override fun getItemCount(): Int {
return items.size
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getItemViewType(position: Int): Int {
return position
}
fun setItem(holidays: ArrayList) {
items = holidays
notifyDataSetChanged()
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val due\_date = view.due\_date
val instalment\_title = view.instalment\_title
val paid\_date = view.paid\_date
val amount = view.amount
val paid\_text = view.paidText
}
```
}
Upvotes: 1 |
2018/03/22 | 425 | 1,261 | <issue_start>username_0: I'm trying to **exclude everything except** [a-z] [A-Z] [0-9] and [~!#$].
```
if( $("#name").val().test(/[^a-zA-Z0-9~!#$]/)) {
alert("Disallowed character used.");
return false;
}
```
I thought test would return true if it finds a match and that because I included the caret symbol it should match everything that is not in my expression.
However input such as this works: jAcK%%$21#x
When it shouldn't work because it has symbols I'm trying to disallow.
Where have I gone wrong?
Thanks<issue_comment>username_1: Use `match` instead of `test`, since test is function of `RegExp` instead of `String`
```
var hasBadInput = !!"jAcK%%$21#x".match(/[^a-zA-Z0-9~!#$]/) //true
```
Or reverse the position
```
(/[^a-zA-Z0-9~!#$]/).test("jAcK%%$21#x") //returns true
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: [`Regexp.prototype.test()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) should be called on the regex.
```js
var $name = $("#name");
$name.on("keyup", function(e) {
if(/[^a-zA-Z0-9~!#$]/.test($name.val())) {
console.log("Nope");
return false;
} else {
console.log("Good");
}
})
```
```html
```
Upvotes: 0 |
2018/03/22 | 1,021 | 2,751 | <issue_start>username_0: I want to install Gromacs, and I've followed the steps from this [site](https://bioinformaticsreview.com/20151126/how-to-install-gromacs-5-x-x-on-linux-ubuntu-14-04-lts/) until the part where it tells me to enter this command:
>
> sudo cmake .. -DGMX\_BUILD\_OWN\_FFTW=OFF -DREGRESSIONTEST\_DOWNLOAD=OFF -DCMAKE\_C\_COMPILER=gcc -DREGRESSIONTEST\_PATH= "PUT YOUR PWD PATH HERE WITHOUT QUOTES"/Downloads/regressiontests-5.1.1
>
>
>
Take note that I am in this directory:
>
> name@myname:~/Downloads/gromacs-5.1.1/build$
>
>
>
and this is what I entered in the terminal:
>
> sudo cmake .. -DGMX\_BUILD\_OWN\_FFTW=OFF -DREGRESSIONTEST\_DOWNLOAD=OFF -DCMAKE\_C\_COMPILER=gcc -DREGRESSIONTEST\_PATH= /home/name/Downloads/regressiontests-5.1.1
>
>
>
but this error message appeared:
>
> CMake Error at CMakeLists.txt:55 (include):
> include could not find load file:
>
>
> gmxVersionInfo
>
>
> CMake Error at CMakeLists.txt:64 (include):
> include could not find load file:
>
>
> gmxBuildTypeReference
>
>
> CMake Error at CMakeLists.txt:65 (include):
> include could not find load file:
>
>
> gmxBuildTypeProfile
>
>
> CMake Error at CMakeLists.txt:66 (include):
> include could not find load file:
>
>
> gmxBuildTypeTSAN
>
>
> CMake Error at CMakeLists.txt:67 (include):
> include could not find load file:
>
>
> gmxBuildTypeASAN
>
>
> CMake Error at CMakeLists.txt:68 (include):
> include could not find load file:
>
>
> gmxBuildTypeMSAN
>
>
> CMake Error at CMakeLists.txt:69 (include):
> include could not find load file:
>
>
> gmxBuildTypeReleaseWithAssert
>
>
> CMake Error at CMakeLists.txt:101 (include):
> include could not find load file:
>
>
> gmxCPackUtilities
>
>
> CMake Error at CMakeLists.txt:102 (gmx\_cpack\_init):
> Unknown CMake command "gmx\_cpack\_init".
>
>
> -- Configuring incomplete, errors occurred!
> See also "/home/name/Downloads/gromacs-5.1.1/build/CMakeFiles/CMakeOutput.log".
>
>
>
Please help!<issue_comment>username_1: Use `match` instead of `test`, since test is function of `RegExp` instead of `String`
```
var hasBadInput = !!"jAcK%%$21#x".match(/[^a-zA-Z0-9~!#$]/) //true
```
Or reverse the position
```
(/[^a-zA-Z0-9~!#$]/).test("jAcK%%$21#x") //returns true
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: [`Regexp.prototype.test()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) should be called on the regex.
```js
var $name = $("#name");
$name.on("keyup", function(e) {
if(/[^a-zA-Z0-9~!#$]/.test($name.val())) {
console.log("Nope");
return false;
} else {
console.log("Good");
}
})
```
```html
```
Upvotes: 0 |
2018/03/22 | 665 | 1,993 | <issue_start>username_0: I came to scenario where I only want [0-9 or .] For that I used this regex:
```
[0-9.]$
```
This regex accepts 0-9 and . (dot for decimal). But when I write something like this
```
1,1
```
It also accepts comma (,). How can I avoid this?<issue_comment>username_1: This regex may help you:
```
/[0-9.]+/g
```
Accepts 0 to 9 digits and dot(.).
**Explanation:**
Match a single character present in the list below `[0-9.]+`
**`+` Quantifier** — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
`0-9` a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
`.` matches the character . literally (case sensitive)
You can test it [here](https://regex101.com/r/wXIMo7/10)
[](https://i.stack.imgur.com/fAGfO.png)
Upvotes: 0 <issue_comment>username_2: Once you are looking into a way to parse numbers (you said dot is for decimals), maybe you don't want your string to start with dot neither ending with it, and must accept only one dot. If this is your case, try using:
```
^(\d+\.?\d+|\d)$
```
where:
* `\d+` stands for any digit (one or more)
* `\.?` stands for zero or one of literal dot
* `\d` stands for any digit (just one)
You can see it working [here](https://regex101.com/r/uwmcvJ/3)
---
Or maybe you'd like to accept strings starting with a dot, which is normally accepted being `0` as integer part, in this case you can use `^\d*\.?\d+$`.
Upvotes: 1 <issue_comment>username_3: This regex `[0-9.]$` consists of a character class that matches a digit or a dot at the end of a line `$`.
If you only want to match a digit or a dot you could add `^` to assert the position at the start of a line:
[`^[0-9.]$`](https://regex101.com/r/telA7K/1)
If you want to match one or more digits, a dot and one or more digits you could use:
[`^[0-9]+\.[0-9]+$`](https://regex101.com/r/telA7K/3)
Upvotes: 1 |
2018/03/22 | 833 | 3,148 | <issue_start>username_0: I have a alertdialog box with the linkbutton and ok button.
when the error is generated the message is displayed on alertdialog box.
But when the new error is generated the new message is getting appended with the old message and link button is getting repeated too.
I want to delete the old message and display only new message.
the code snippet is below
```
function AlertDialog(msg) {
var newMsg=msg;
if(msg==="SessionTimeOut")
newMsg="@Resources.commonResources.SessionTimeOut";
$("#dialog-showMsg").text=" ";
$("#dialog-showMsg #sp").append(newMsg,"
","
")
$("#dialog-showMsg").dialog(
open: function(event, ui){
$('', {
'class': 'linkClass',
text: 'Details',
href: '#'
})
.appendTo($(".ui-dialog-content")) //use buttonpane to display link at bottom content
.click(function(){
$(event.target).dialog('close');
});
},
position:{my: "center", at: "center"},
draggable: true,
height: 300,
width: 260,
show: { effect: "Fold" },
hide: { effect: "Fold" },
modal: true,
buttons: {
OK: function() {
if(msg==="SessionTimeOut")
{window.location.href=" /" + "@AppName";}
$(this).dialog("close");}
},
});
return true;
}
```
[sample images](https://i.stack.imgur.com/yWXPF.jpg)<issue_comment>username_1: You are appending message with old one. That's why it is happening. Instead of append, you can use html, than it will work.
```
$("#dialog-showMsg #sp").html(newMsg,"
","
")
```
Upvotes: 1 <issue_comment>username_2: You are appending the message that is the reason
Use
```
$("#dialog-showMsg #sp").html(newMsg,"
","
")
```
**instead of**
```
$("#dialog-showMsg #sp").append(newMsg,"
","
")**
```
Upvotes: 0 <issue_comment>username_3: because you use `append`
`append` will merge old content with new content
so use `html` instead of `append` like,
```
$("#dialog-showMsg #sp").html(newMsg,"
","
")
```
Upvotes: 0 <issue_comment>username_4: You are appending content using jquery, based on [documentation](http://api.jquery.com/append/)
>
> The .append() and .appendTo() methods perform the same task. The major
> difference is in the syntax-specifically, in the placement of the
> content and target. With .append() , the selector expression preceding
> the method is the container into which the content is inserted.
>
>
>
Instead of using append, you should use html injector like this one.
```
$("#dialog-showMsg").text=" ";
$("#dialog-showMsg #sp").html("
"+newMsg+"
");
```
or if you don't want to use html() you can remove the content at first like this one
```
$("#dialog-showMsg").text=" ";
$("#dialog-showMsg #sp").empty();
$("#dialog-showMsg #sp").append(newMsg,"
","
");
```
Cheers
Upvotes: 1 [selected_answer] |
2018/03/22 | 739 | 3,042 | <issue_start>username_0: So I have a call to a function which creates a DB collection to mongoose, then right after it I set some variables which are calls to the same collection. However, the promise is returning before the actual save is made to MongoDB and I'm getting the error on the variables :
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'likes' of null
How do I make sure that the save is complete to the DB before the calls to the variables?
Code below:
```
var dbcreate_stats = await dailyStats.createCollection();
async createCollection(){
var checkUnique = await dailyStats.findOne({formatted_date: newdate}, function(err,docs){
});
if (checkUnique == null) {
var dailyInfo = new dailyStats({
likes: 0,
follows: 0,
comments: 0,
unfollows: 0,
profiles_visited: 0,
new_profiles_found: 0,
formatted_date : newdate,
utc_date: new Date(),
});
// await dailyInfo.save(function(err, objs, numAffected){
// if (err) throw err;
// console.log(numAffected);
// });
dailyStats.create(dailyInfo, function(err,obj, numAffected){
console.log('inserted');
});
}
}
dailyLikes = await dailyStats.dailyLikesCount();
dailyFollows = await dailyStats.dailyFollowsCount();
dailyComments = await dailyStats.dailyCommentsCount();
async daily(){
var foo = await dailyStats.findOne({formatted_date: newdate});
return foo;
}
async dailyLikesCount(){
let daily = await this.daily();
return daily.likes;
}
async dailyFollowsCount(){
let daily = await this.daily();
return daily.follows;
}
async dailyCommentsCount(){
let daily = await this.daily();
return daily.comments;
}
```<issue_comment>username_1: async await work only if function returns Promise.
```
var checkUnique = await dailyStats.findOne({formatted_date: newdate}).exec(); //returns promise
var foo = await dailyStats.findOne({formatted_date: newdate}).exec();
```
This should work
Upvotes: 1 <issue_comment>username_2: dailyStats.findOne should not handle callback it should be returnpromise.
```
dailyStats.findOne(query).exec();
```
And in your create function inside if block it should also return with Promise.
```
var dbcreate_stats = await dailyStats.createCollection();
async createCollection(){
var checkUnique = await dailyStats.findOne({formatted_date: newdate}).exec();// This will return Promise.
if (checkUnique == null) {
var dailyInfo = new dailyStats({
likes: 0,
follows: 0,
comments: 0,
unfollows: 0,
profiles_visited: 0,
new_profiles_found: 0,
formatted_date : newdate,
utc_date: new Date(),
});
return dailyStats.create(dailyInfo);// This will return Promise.
}
}
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 324 | 1,152 | <issue_start>username_0: I have a e-commerce application. All delivered orders have a column "updated\_at". I can with this column calculate average delivery time total delivered orders?
I have count all orders and column updated\_at.
What I need do, that calculate average time?
My code:
```
$deliveryTime = Order::where('status', '8')->count(); //get A count delivered orders..
```<issue_comment>username_1: You can do something like this. It wil return you the average of the orders where status is 8
```
$deliveryTime = Order::where('state', '=', '8')->select(DB::raw('AVG(created_at) as order_average'))->get();
```
Upvotes: 1 <issue_comment>username_2: From OP's question and comment :
**Average delivery time = average of ( date difference of order creation date and order\_delivery\_date)**
>
> order creation date field = `created_at` order delivery date field =
> `updated_at`
>
>
>
```
$averageTime = Order::select(\DB::raw("DATEDIFF(updated_at, created_at)AS day_diff"))->where('status', '8')->get()->avg('day_diff');
```
If it required to round off the value you can use `round($averageTime);`
Upvotes: 1 [selected_answer] |
2018/03/22 | 687 | 2,086 | <issue_start>username_0: I want to show all records of examresult on basis of `category_id`.
Every subject has 2 category IDs. How to show result when one `category_id` of examresult is not present in the result?
I want to show `null` on some column and some value when the `category_id` exists.
This image will give you a clear view of what I want to ask.
Thanks in advance.
```sql
select er.subject_id,er.student_id,er.class_id,
ec.exam_catagory_name,er.catagory_id, er.exam_type_id, sum( er.marks_obtained) subject_marks_obtained, sum(er.total_marks) subject_total_marks from Exam_Results er
join Exam_Subjects es on er.subject_id=es.subject_id
join Exam_Catagories ec on ec.exam_catagory_id=er.catagory_id
where er.student_id=2369 and er.session_id=81 and er.class_id=265
and er.subclass_id=182 and er.term_id=148 and er.shift_id=35
group by er.student_id,er.subject_id,er.class_id,er.catagory_id,er.exam_type_id
,er.term_id,ec.exam_catagory_name
order by er.subject_id
```
**Output:**
[](https://i.stack.imgur.com/Q1pph.png)
There are 20 records, but I want 27 records with both examination and assessment with `null` values in marks. How to show examination and assessment record of `subject_id` and give `null` in marks?
Thanks in advance.<issue_comment>username_1: You can do something like this. It wil return you the average of the orders where status is 8
```
$deliveryTime = Order::where('state', '=', '8')->select(DB::raw('AVG(created_at) as order_average'))->get();
```
Upvotes: 1 <issue_comment>username_2: From OP's question and comment :
**Average delivery time = average of ( date difference of order creation date and order\_delivery\_date)**
>
> order creation date field = `created_at` order delivery date field =
> `updated_at`
>
>
>
```
$averageTime = Order::select(\DB::raw("DATEDIFF(updated_at, created_at)AS day_diff"))->where('status', '8')->get()->avg('day_diff');
```
If it required to round off the value you can use `round($averageTime);`
Upvotes: 1 [selected_answer] |
2018/03/22 | 935 | 4,073 | <issue_start>username_0: The first item in the navigation bar keep highlighting.
When I click other item on the navigation bar, the content will change but the corresponding item will not be highlighted, just keep highlighting the first item.
```
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment=null;
switch (item.getItemId()){
case R.id.number:
fragment=new data();
break;
case R.id.graph:
fragment=new graph();
break;
}
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_drawer, fragment);
fragmentTransaction.commit();
return true;
}
});
```
this is the listener
```
```
this is the xml
```
xml version="1.0" encoding="utf-8"?
```
```
```
this is the meun.xml<issue_comment>username_1: It is included in the Design Support Library, starting with version 25.0.0. You can include it in your build.gradle file with the following line (you'll also need the AppCompat Support Library as the Design Support Library's dependency):
**First use girdle compile both the girdle in your project**
```
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
```
then create xml layout:
```
```
Create a resource file just like a Navigation Drawer or an Overflow menu:
```
xml version="1.0" encoding="utf-8"?
```
display image below:
[](https://i.stack.imgur.com/gGrCm.png)
To achieve different tinting for selected items, you should specify a color list resource as itemBackground and itemTextColor like this:
```
xml version="1.0" encoding="utf-8"?
```
**Finally, you can listen to tab selection events by adding an BottomNavigation.OnNavigationItemSelectedListener via the setOnNavigationItemSelectedListener() method:**
```
bottomNavigationView.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_one:
// Switch to page one
break;
case R.id.action_two:
// Switch to page two
break;
case R.id.action_three:
// Switch to page three
break;
}
return true;
}
});
```
try this code.
Upvotes: 0 <issue_comment>username_2: This usually happens beacause of when **onNavigationItemSelected** method return **false** value. You can check this with remove all code except **return true** inside the **onNavigationItemSelected** method. Just like this;
```
bottomNavigationView.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
return true;
}
});
```
Then you'll see it works but the content was not changed. For change with content, If I were you I'll change the default return value as false like this;
```
bottomNavigationView.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.number:
//Open fragment or do whatever you want.
return true;
case R.id.graph:
//Open another fragment or do whatever you want.
return true;
}
return false;
}
});
```
Upvotes: 2 |
2018/03/22 | 780 | 2,710 | <issue_start>username_0: In the below class error is in the init function where i load the class object I stored in the file to the vector Items.
```
class Item
{
std::string item_code;
std::string item_name;
std::string unit_name;
unsigned int price_per_unit;
double discount_rate;
static std::vector Items;
friend std::ostream& operator<< (std::ostream&, Item&);
public:
static void PrintAll();
static void Init();
~Item();
};
```
Default constructor is the one which reads data from user and writes into file. Below is the code of default constructor.
```
Item::Item(int a)
{
std::cout << "Item name : ";
std::getline(std::cin, item_name);
std::cout << "Unit (Kg/g/Qty) : ";
std::getline(std::cin, unit_name);
std::cout << "Price per unit : ";
std::cin >> price_per_unit;
std::cout << "Discount Rate : ";
std::cin >> discount_rate;
std::cin.ignore();
std::cout << "Product code (has to be unique) : ";
std::getline(std::cin, item_code);
std::ofstream outfile;
outfile.open("Files\\Items.txt", std::ios::out | std::ios::app);
outfile.write((char*)&(*this), sizeof(Item));
outfile.close();
}
```
Below is the Init() function for which read access violation is thrown at.
```
void Item::Init()
{
std::ifstream infile("Files\\Items.txt", std::ios::in);
if (!infile.is_open())
{
std::cout << "Cannot Open File \n";
infile.close();
return;
}
else
{
Item temp;
while (!infile.eof())
{
infile.read((char*)&temp, sizeof(temp));
Item::Items.push_back(temp);
}
}
infile.close();
}
```
Even though i am checking for eof, read access violation is thrown. Please give me some advice on this issue.<issue_comment>username_1: ```
infile.read((char*)&temp, sizeof(temp));
```
This fills the `temp` object with junk from the file. It's supposed to contain valid `std::string` objects and whatever is in the file, it can't possibly be a valid `std::string` object. If you don't see why, consider that creating a valid `std::string` object requires allocating memory to hold the string data -- that's what the `std::string` constructor does. Reading data from a file can't possibly do this.
A file is a stream of bytes. To write data to a file, you need to define some way to represent that data as a stream of bytes. You need to encode its length if it is variable length. To read it back in, you need to handle the variable length case as well. You need to convert the file data to an appropriate internal representation, such as `std::string`. This is called "serialization".
Upvotes: 2 <issue_comment>username_2: std::string size is variable, you can try the following definition
```
char item_code[20];
char item_name[20];
char unit_name[20];
```
Upvotes: 1 |
2018/03/22 | 315 | 1,085 | <issue_start>username_0: Here is my code, Actually when I click on function but not showing alert and not getting error in console. So please tell me how to do.
HTML Code
```
- Home
```
app.js
```
app.controller('myController', function($scope){
$scope.homepage = function(){
alert('hi');
}});
```<issue_comment>username_1: There can be two reasons
1- Not using `ng-app` directive in the root element of your application.
2- You have not defined `ng-controller` properly.
Please follow following working code.
```html
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.homepage = function() {
alert('hi');
}
});
* Home
```
Upvotes: 3 <issue_comment>username_2: **First** You have to add `ng-app = "app"`
**Second** You have to add `ng-controller = "myController"`
**Final**
Please check the updated code:
```js
var app = angular.module("app", []);
app.controller('myController', function($scope){
$scope.homepage = function(){
alert('hi');
}});
```
```html
- Home
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,132 | 3,999 | <issue_start>username_0: I've only started learning Javascript for a few hours, and am trying to use a function to add to a variable using JS within HTML (Sorry if I used the wrong terminology) and it doesn't seem to be changing the result.
```
TODO supply a title
var userID = 1;
var userRep = 0;
function NumUp(userRep) {
userRep = userRep + 1;
}
function NumDown(userRep) {
userRep = userRep - 1;
}
function myFunction() {
document.getElementById("demo").innerHTML = userRep;
}
result goes here
Vote Up
Vote Down
Click me
```
Much thanks for any help you can give.<issue_comment>username_1: Look at the code
```
function NumUp(userRep){
userRep = userRep + 1;
}
```
This `userRep` is a local variable and you are trying to print the value for global variable. so that it is displaying always `0` because global didn't changed.
Also if you didn't mentioned any `type` in `button` element, that will treat as `submit` button. If you don't want to submit the form then just add `type=button`.
Solution is to remove the argument or change the name of that argument in your function.
```js
var userID = 1;
var userRep = 0;
function NumUp(){
userRep = userRep + 1;
}
function NumDown(){
userRep = userRep - 1;
}
function myFunction() {
document.getElementById("demo").innerHTML = userRep;
}
```
```html
result goes here
Vote Up
Vote Down
Click me
```
Upvotes: 2 <issue_comment>username_2: No need to pass the arguments to the method you are calling since that argument is already a global variable.
```
function NumUp() {
userRep = userRep + 1;
}
function NumDown() {
userRep = userRep - 1;
}
```
When you define a function that accepts an argument `userRep`, but don't pass the value when you invoke that function, it will go as `undefined` and adding a number to it will result in `NaN`. **Also that value is localized since you used the argument value for computation instead of the global value** - which is why value doesn't change.
**Demo**
```html
TODO supply a title
var userID = 1;
var userRep = 0;
function NumUp() {
userRep = userRep + 1;
}
function NumDown() {
userRep = userRep - 1;
}
function myFunction() {
document.getElementById("demo").innerHTML = userRep;
}
result goes here
Vote Up
Vote Down
Click me
```
Upvotes: 2 <issue_comment>username_3: I hope this will help. Thank you.
```html
TODO supply a title
var userID = 1;
var userRep = 0;
function NumUp(){
userRep = userRep + 1;
myFunction();
}
function NumDown(){
userRep = userRep - 1;
myFunction();
}
function myFunction() {
document.getElementById("demo").innerHTML = userRep;
}
result goes here
Vote Up
Vote Down
Click me
```
Upvotes: 3 <issue_comment>username_4: remove userRep from NumUp and Numdown which is a localvariable inside the function and its value becomes undefined when you dont provide.
```
function NumUp(){
userRep = userRep + 1;
}
function NumDown(){
userRep = userRep - 1;
}
```
Upvotes: 2 <issue_comment>username_5: Use the following
```
TODO supply a title
var userID = 1;
var userRep = 0;
function NumUp () {
userRep = userRep + 1;
}
function NumDown () {
userRep = userRep - 1;
}
function myFunction (event) {
event.preventDefault();
document.getElementById("demo").innerHTML = userRep;
}
result goes here
Vote Up
Vote Down
Click me
```
Upvotes: 1 <issue_comment>username_6: This will help you, remove userRep from NumUp and Numdown which is a local variable inside the function
```html
TODO supply a title
var userID = 1;
var userRep = 0;
function NumUp() {
userRep = userRep + 1;
}
function NumDown() {
userRep = userRep - 1;
}
function myFunction() {
document.getElementById("demo").innerHTML = userRep;
}
result goes here
Vote Up
Vote Down
Click me
```
Upvotes: 1 |
2018/03/22 | 395 | 1,492 | <issue_start>username_0: I want to use Material-UI Next textfield `error` props [link](https://material-ui-next.com/api/text-field/#textfield), the props type is `boolean`. The previous version of Material-UI props name is `errorText` and the props type is `node` [link](http://www.material-ui.com/#/components/text-field).
Textfield Material-UI previous version using `errorText` props :
```
```
With `errorText` in Material-UI previous version, the code works good for displaying an error state.
Textfield Material-UI Next using `error` props:
```
```
On Material-UI Next `errorText` props changed to `error` with boolean type and only accept true or false value. If i set the `error` props to true, the textfield displaying error state at any time. I just want to displaying error state under certain conditions.
How can i use error state `this.state.error` on Material-UI Next textfield?<issue_comment>username_1: Using a react component state, one can store the `TextField` value and use that as an indicator for an error. Material-UI exposes the `error` and `helperText` props to display an error interactively.
Take a look at the following example:
```
this.setState({ text: event.target.value })}
error={text === ""}
helperText={text === "" ? 'Empty field!' : ' '}
/>
```
Upvotes: 8 [selected_answer]<issue_comment>username_2: I add an example that does not shows an error when the value is empty and validates a regular expression (MAC Address).
```
```
Upvotes: 3 |
2018/03/22 | 225 | 639 | <issue_start>username_0: I am a newbie to scala
I have a list of strings -
`List[String] (“alpha”, “gamma”, “omega”, “zeta”, “beta”)`
I want to count all the strings with length = 4
i.e I want to get output = 2.<issue_comment>username_1: You can do like this:
```
val data = List("alpha", "gamma", "omega", "zeta", "beta")
data.filter(x => x.length == 4).size
res8: Int = 2
```
Upvotes: 3 <issue_comment>username_2: You can just use `count` function as
```
val list = List[String] ("alpha", "gamma", "omega", "zeta", "beta")
println(list.count(x => x.length == 4))
//2 is printed
```
I hope the answer is helpful
Upvotes: 3 |
2018/03/22 | 1,106 | 3,535 | <issue_start>username_0: Mac running Docker Version 17.12.0-ce-mac55 (23011) here.
I have a very bizarre situation with Docker that I absolutely cannot explain!
* I have a Dockerized web service that runs perfectly fine outside of Docker, running off of port 9200 (so: `http://localhost:9200`)
* I can also run several other images locally (nginx, Oracle DB) and I can access them via `localhost:80` and `localhost:1521` respectively
* When I run the container for my Dockerized service, I see (via `docker logs` ) the service startup without any errors whatsoever
* Despite the fact that the container is running without any errors, I absolutely cannot connect to it from my Mac host via `localhost:9200`
**The exact steps to reproduce are:**
1. [Clone this repo](https://github.com/bitbythecron/locations-service)
2. Build the image via `./gradlew clean build && docker build -t locationservice .`
3. Run the container via `docker run -it -p 9200:9200 -d --net="host" --name locationservice locationservice`
4. If you use `docker ps` to obtain the , then you can keep hitting `docker logs` until you see it has started up without errors
5. On my machine, when I try to curl against `localhost:9200`, I get "*connection refused*" errors (see below)
curl error is:
```
curl -X GET http://localhost:9200/bupo
curl: (7) Failed to connect to localhost port 9200: Connection refused
```
Some things I have ruled out:
* `localhost` is absolutely resolveable from the host because we're running in `host` network mode and I have no problem connecting to nginx (port 80) and Oracle (port 1521) containers
* The app is starting up and if you look at the logs you'll see it is starting up listening on 9200
**Any ideas what the problem could be?!**<issue_comment>username_1: Docker for Mac does not support host network mode very well: <https://github.com/docker/for-mac/issues/1031>
So at this moment the solution is to use default bridge mode.
Upvotes: 1 <issue_comment>username_2: Docker for Mac runs in a VM. `--net=host` refers to the Linux VM hosts network stack not OSX. There is no direct network path from OSX to the Docker VM other than mapped ports.
Mapped ports (`docker run -p Y:N`) in Docker for Mac are a little special, in addition to the user [space proxy that runs on the Docker host](https://stackoverflow.com/a/37809857/1318694) normally, Docker for Mac also launches a user space proxy on OSX to listen on the same port and forward connections into the VM. The OSX process isn't started when using `--net=host` (and the Linux one isn't either of course).
```
→ docker run --name nc --rm --net=host -dp 9200:9200 busybox nc -lk -p 9201 -e echo hey
→ docker inspect nc --format '{{ json .NetworkSettings.Ports }}'
{}
→ sudo lsof -Pni | grep 9200
→
```
Then without `--net=host`
```
→ docker run --name nc --rm -dp 9200:9200 busybox nc -lk -p 9201 -e echo hey
→ docker inspect nc --format '{{ json .NetworkSettings.Ports }}'
{"9200/tcp":[{"HostIp":"0.0.0.0","HostPort":"9200"}]}
→ sudo lsof -Pni | grep 9200
vpnkit 42658 matt 28u IPv4 0x57f79853269b81bf 0t0 TCP *:9200 (LISTEN)
vpnkit 42658 matt 29u IPv6 0x57f798532765ca9f 0t0 TCP [::1]:9200 (LISTEN)
```
If your app requires `--net=host` then I would use Vagrant/Virtualbox to spin up a VM with a "Host Only" adapter. This means there is a direct network path that you can access from OSX on the VM. Here's the [Vagrantfile](https://github.com/deployable/docker-debianvm) I use.
Upvotes: 3 [selected_answer] |
2018/03/22 | 732 | 2,363 | <issue_start>username_0: I am using hibernate 4.0.1 in my Portlet application which deployed on Websphere application server, I am referring to datasource configured on the application server from the hibernate configuration, my question is should I use "connection.pool\_size" property OR "c3p0" to set the connection pool size or no ? , As the data source on server already have connection pool size with 10.
In other words, Which take the priority, the Hibernate configuration or the datasource configuration for connection pooling and which is better ?
Thanks in advance.<issue_comment>username_1: Docker for Mac does not support host network mode very well: <https://github.com/docker/for-mac/issues/1031>
So at this moment the solution is to use default bridge mode.
Upvotes: 1 <issue_comment>username_2: Docker for Mac runs in a VM. `--net=host` refers to the Linux VM hosts network stack not OSX. There is no direct network path from OSX to the Docker VM other than mapped ports.
Mapped ports (`docker run -p Y:N`) in Docker for Mac are a little special, in addition to the user [space proxy that runs on the Docker host](https://stackoverflow.com/a/37809857/1318694) normally, Docker for Mac also launches a user space proxy on OSX to listen on the same port and forward connections into the VM. The OSX process isn't started when using `--net=host` (and the Linux one isn't either of course).
```
→ docker run --name nc --rm --net=host -dp 9200:9200 busybox nc -lk -p 9201 -e echo hey
→ docker inspect nc --format '{{ json .NetworkSettings.Ports }}'
{}
→ sudo lsof -Pni | grep 9200
→
```
Then without `--net=host`
```
→ docker run --name nc --rm -dp 9200:9200 busybox nc -lk -p 9201 -e echo hey
→ docker inspect nc --format '{{ json .NetworkSettings.Ports }}'
{"9200/tcp":[{"HostIp":"0.0.0.0","HostPort":"9200"}]}
→ sudo lsof -Pni | grep 9200
vpnkit 42658 matt 28u IPv4 0x57f79853269b81bf 0t0 TCP *:9200 (LISTEN)
vpnkit 42658 matt 29u IPv6 0x57f798532765ca9f 0t0 TCP [::1]:9200 (LISTEN)
```
If your app requires `--net=host` then I would use Vagrant/Virtualbox to spin up a VM with a "Host Only" adapter. This means there is a direct network path that you can access from OSX on the VM. Here's the [Vagrantfile](https://github.com/deployable/docker-debianvm) I use.
Upvotes: 3 [selected_answer] |
2018/03/22 | 2,286 | 4,522 | <issue_start>username_0: I am a beginner in Python and Deep Learning. It might be easy for most of you but how can I do it?
How to convert the below objects into unique numerical values?
```
df['city'].unique()
array(['LIMA', 'VACAVILLE', 'CINCINNATI', 'GLASGOW', 'BOWLING GREEN',
'LANCASTER', 'HOUSTON', 'SPRINGFIELD', 'RAPID CITY', 'FORT WORTH',
'LAREDO', 'NEW YORK', 'CHARLESTON', 'PITTSBURGH',
'WEST VALLEY CITY', 'CAYCE', 'HOT SPRINGS NATIO', 'CANTON',
'FORT WAYNE', 'DU BOIS', 'DAYTON', 'MASON CITY', 'WASHINGTON',
'LAKE OSWEGO', 'FAYETTEVILLE', 'SALT LAKE CITY', 'KNOXVILLE',
'TURLOCK', 'MCALLEN', 'CENTERVILLE', 'ROCHESTER', 'OKLAHOMA CITY',
'GAUTIER', 'DOYLESTOWN', 'ATLANTA', 'MEADVILLE', 'FORT MYERS',
'ERIE', 'BEAUMONT', 'JACKSON', 'CLARKSVILLE', 'BETHLEHEM',
'SAN ANTONIO', 'LAS VEGAS', 'ATHENS', 'SAN LUIS OBISPO', 'SEATTLE',
'BRADENTON', 'TINLEY PARK', 'HUNTLEY', 'SYRACUSE', 'WHEELWRIGHT',
'TOWSON', 'YONKERS', '<NAME>', 'MARION', 'LIVONIA',
'COLORADO SPRINGS', 'CURWENSVILLE', 'SAINT CHARLES', 'PETERSBURG',
'SCOTTSDALE', 'SILVER SPRING', 'PORTLAND', 'BIRMINGHAM',
'CEDARVILLE', 'CLERMONT', 'ASHEVILLE', 'SHREVEPORT', 'DRAPER',
'WAVERLY', 'CANANDAIGUA', 'MOUNT PLEASANT', 'MARIETTA', 'MANKATO',
'HARLINGEN', 'HATCH', 'MOBILE', 'POULSBO', 'GARDEN GROVE',
'GIG HARBOR', 'OCONOMOWOC', 'MOUNT MORRIS', 'ORLANDO',
'DODGE CITY', 'DILLSBURG', 'HUNTSVILLE', 'KANSAS CITY',
'JACKSONVILLE', 'DULUTH', 'CITRUS HEIGHTS', 'ONEONTA', 'LOS LUNAS',
'GIBSONIA', 'ROBINSON', '<NAME>', 'PHOENIX', 'DESTIN',
'SHEPHERD', 'BROOKLYN', 'PLANO', 'WINTERS', 'JAMAICA', 'POWAY',
'LEXINGTON', 'UPLAND', 'NEW ALBANY', 'GREENVILLE',
'JEFFERSON CITY', 'ARLINGTON', 'BUFFALO', 'LOS ANGELES',
'CHARLOTTE', 'WEST LAFAYETTE', 'GARY', 'COOPERSTOWN', 'GREAT BEND',
'DAVISON', 'SMYRNA', 'MISSOURI CITY', 'MEMPHIS',
'FORT WALTON BEACH', 'KISSIMMEE', 'BATAVIA', 'OLDSMAR', 'WYNNE',
'ASHVILLE', 'FT BRAGG', 'TROY', 'SHAKER HTS', 'CLEVELAND HTS',
'HAMBURG'], dtype=object)
```
I am trying to train a model using this data.<issue_comment>username_1: IIUC need [`factorize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html):
```
df = pd.DataFrame({'city':list('abcddf')})
df['city1'] = pd.factorize(df['city'])[0]
```
Or convert to `categorical`s and get [`codes`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cat.codes.html):
```
df['city'] = pd.Categorical(df['city'])
df['city1'] = df['city'].cat.codes
```
---
```
print (df)
city city1
0 a 0
1 b 1
2 c 2
3 d 3
4 d 3
5 f 4
```
Upvotes: 2 <issue_comment>username_2: You can also try [`sklearn.preprocessing.LabelEncoder`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder). As stated in the document, it encodes labels with value between 0 and n\_classes-1.
```
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['city_num'] = le.fit_transform(df['city'])
print(df.head())
# city city_num
# 0 LIMA 72
# 1 VACAVILLE 122
# 2 CINCINNATI 21
# 3 GLASGOW 50
# 4 BOWLING GREEN 10
print(len(df.city.unique()))
# 132
print(len(set(df.city_num)))
# 132
```
You may then convert the numerical column to indicators columns
```
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder()
city_ind = ohe.fit_transform(df.city_num.values.reshape(-1, 1))
print(type(city_ind))
#
print(city\_ind.shape)
# (132, 132)
print(city\_ind[0:2, ].toarray())
# [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.
# 0. 0. 0. 0. 0. 0.]]
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 1,213 | 3,967 | <issue_start>username_0: I am running a web application(wagtail cms) on linux ubuntu. I am getting this error when I run python3 manage.py runserver 0.0.0.0:8000
Please see the error message on the console.
```
Performing system checks...
System check identified no issues (0 silenced).
March 22, 2018 - 15:27:33
Django version 1.11.1, using settings 'ntdl.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py",
line 138, in __call__
response = self.process_request(request)
File "/usr/local/lib/python3.6/dist-
packages/django/middleware/security.py", line 25, in process_request
host = self.redirect_host or request.get_host()
File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line
105, in get_host
if domain and validate_host(domain, allowed_hosts):
File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line
579, in validate_host
if pattern == '*' or is_same_domain(host, pattern):
File "/usr/local/lib/python3.6/dist-packages/django/utils/http.py", line
291, in is_same_domain
pattern = pattern.lower()
AttributeError: 'ellipsis' object has no attribute 'lower'
"GET / HTTP/1.1" 500 11959
Internal Server Error: /favicon.ico
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py",
line 138, in __call__
response = self.process_request(request)
File "/usr/local/lib/python3.6/dist-
packages/django/middleware/security.py", line 25, in process_request
host = self.redirect_host or request.get_host()
File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line
105, in get_host
if domain and validate_host(domain, allowed_hosts):
File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line
579, in validate_host
if pattern == '*' or is_same_domain(host, pattern):
File "/usr/local/lib/python3.6/dist-packages/django/utils/http.py", line
291, in is_same_domain
pattern = pattern.lower()
AttributeError: 'ellipsis' object has no attribute 'lower'
"GET /favicon.ico HTTP/1.1" 500 11965
```
I had gone inside the http.py checked the code it has code below
```
def is_same_domain(host, pattern):
"""
Return ``True`` if the host is either an exact match or a match
to the wildcard pattern.
Any pattern beginning with a period matches a domain and all of its
subdomains. (e.g. ``.example.com`` matches ``example.com`` and
``foo.example.com``). Anything else is an exact string match.
"""
if not pattern:
return False
pattern = pattern.lower()
return (
pattern[0] == '.' and (host.endswith(pattern) or host == pattern[1:])
or
pattern == host
)
```
I am not able see any errors here. Please help me in fixing this error.
With Many Thanks,
<NAME><issue_comment>username_1: I don't have too much Django experience but when I had this problem, with the below code:
```
@api_view([...])
@permission_classes((permissions.AllowAny,))
def blog_list(request):
return Response('successfull attempt')
```
but just by removing the [...] in @api\_view decorator, the problem is solved.
```
@api_view()
@permission_classes((permissions.AllowAny,))
def blog_list(request):
return Response('successfull attempt')
```
Upvotes: 0 <issue_comment>username_2: AttributeError: 'ellipsis' object has no attribute 'predict'
for this error you just try the encoder\_features = autoencoder.predict() immediate after defining autoencoder you get no error
Upvotes: -1 |
2018/03/22 | 737 | 2,246 | <issue_start>username_0: I am only interested in n < 0 case, if n == -3 then I get, 0.001 as desired.
but I reached here through trial and error. Can someone explain to me 'WHY' this works (for n < 0 case only)?
```
public static double power10(int n) {
if(n == 0){
return 1;
}
else if (n > 10){
return 10 * power10(n - 1);
}
else {
return 1.0 / power10(-n);
}
}
```<issue_comment>username_1: In fact, your code doesn't work for either 3 or -3. A stack overflow occurs in both cases. I don't know how you got 0.003.
The error in your code is this:
```
else if (n > 10){
```
It should be `n > 0`. instead.
This recursive algorithm should be quite clear if we turn it into a sentence starting with "the nth power of 10 is...":
>
> The nth power of 10 is:
>
>
> If n is 0, 1
>
>
> If n is positive, 10 \* (n-1)th power of 10
>
>
> If n is negative, 1 / -nth power of 10
>
>
>
You can see that all values of n are covered, whether it be 0, positive or negative. In your incorrect code, you treat cases where `0 < n < 10` as "negative numbers". When you negate those and recurse, you get a real negative number, it goes into the `else` again and they are negated again. But they are still not larger than 10, causing infinite recursion.
Upvotes: 0 <issue_comment>username_2: Your code here probably give out stack overflow error.
Try
```
else if(n>0)
```
Now under the above condition function return n th value of 10 and return 1000 (when n is 3 case), Giving you the answer 0.001.
Upvotes: 0 <issue_comment>username_3: The Following Function works for both negative and positive powers.
```
double Power(int n1,int n2) {
if(n2>=0) {
if(n2==1) {
return n1;
}
if(n2==0) {
return 1;
}
else {
return n1*Power(n1,n2-1);
}
}
else {
if(n2==-1) {
return 1.0/n1;
}
else {
return 1.0/(n1*Power(n1,(-1)*(n2+1)));
}
}
```
It will create following recursion tree for Negative example,
[This link will redirect you to the recursion tree to better understanding, How this function will work recursively.](https://i.stack.imgur.com/FIjCU.jpg)
Upvotes: 2 |
2018/03/22 | 332 | 1,194 | <issue_start>username_0: I want to run Apollo GraphQL server on Google Cloud Functions. It basically boils down to running an Express server with different routes I suppose. Is it possible and if yes then how? Do note that I don't wish to use any Firebase libraries for the same as highlighted here:
1) [Cloud Functions for Firebase and Express](https://stackoverflow.com/questions/43579442/cloud-functions-for-firebase-and-express)
2) <https://codeburst.io/graphql-server-on-cloud-functions-for-firebase-ae97441399c0>
3) <https://codeburst.io/express-js-on-cloud-functions-for-firebase-86ed26f9144c>
Thanks.<issue_comment>username_1: Thanks to the fantastic work by <NAME>, this is possible. Check out <https://github.com/jthegedus/firebase-gcp-examples/tree/main/deprecated/gcp-functions-graphql> for the solution.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Since the link on username_1's answer is dead, here is the official Google Cloud Function integration of GraphQL Server : <https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-cloud-functions>
You are able to run Apollo GraphQL server on Google Cloud Functions with it.
Upvotes: 2 |
2018/03/22 | 300 | 1,198 | <issue_start>username_0: What are my options for passing in additional inputs to ParDo transforms. In my case , I need to pass in about 5000 string objects to my ParDo. From what I understand, these are my options :
a) Pass it as side-input : But I suppose , that passing such as a huge sideinput might deteriorate the performance of my pipeline
b) Pass it as a parameter to the constructor of my ParDo class, and keep it as a class member : Could someone please tell me, that internally, how is this different from passing it as a side input ?
Are there any other ways to pass in additional inputs to a ParDo ?<issue_comment>username_1: Thanks to the fantastic work by <NAME>, this is possible. Check out <https://github.com/jthegedus/firebase-gcp-examples/tree/main/deprecated/gcp-functions-graphql> for the solution.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Since the link on username_1's answer is dead, here is the official Google Cloud Function integration of GraphQL Server : <https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-cloud-functions>
You are able to run Apollo GraphQL server on Google Cloud Functions with it.
Upvotes: 2 |
2018/03/22 | 2,063 | 6,942 | <issue_start>username_0: I have 2 columns; 1 for month and another 1 is year. Both column having random value. I want to combine both column into 1 single column. As example, in column B "Month" I have this 1-12 number representing month and at Column C "Year" like 8 which is 2008 or 10 for 2010.
My objective is to combine both into 1 column and format it as `mmm YYYY` at Column E such as "Jan 2008".The idea is I want to try Concatenate function as learning the VBA. I have below code to test on converting the month from integer to string, yet it gave me an error
>
> "Type Mismatch"
>
>
>
and maybe some error on IF-Then-Else statement. I try to improving it but still getting nowhere. Where is my mistake on the IF statement.
```
Sub DateColumn()
'***Defined Variable
Dim NRows As Integer
Dim Month() As Integer
Dim Year() As Integer
'***Read Data
Sheets("Data").Activate
LastRowData = Range("A4").End(xlDown).Row - 1
NRows = LastRowData
'***Redefined Array
ReDim Month(NRows)
ReDim Year(NRows)
'***Calculate/Convert
For n = 1 To NRows
'Month= convert integer to string
If (Month = 1) Then
Month = "Jan"
ElseIf (Month = 2) Then
Month = "Feb"
ElseIf (Month = 3) Then
Month = "Mar"
ElseIf (Month = 4) Then
Month = "Apr"
ElseIf (Month = 5) Then
Month = "May"
ElseIf (Month = 6) Then
Month = "June"
ElseIf (Month = 7) Then
Month = "July"
ElseIf (Month = 8) Then
Month = "Aug"
ElseIf (Month = 9) Then
Month = "Sept"
ElseIf (Month = 10) Then
Month = "Oct"
ElseIf (Month = 11) Then
Month = "Nov"
ElseIf (Month = 12) Then
Month = "Dec"
Else
End If
Next n
'***Write Output
For n = 1 To NRows
Sheets("Data").Cells(1 + n, 5) = Month()
End Sub
```
I am still new and want "to try and figure" to understand the concept. My code still not properly arranged (sorry) and I want to know how can my code on If-Then-Else be corrected. Thanks Stackoverflow.<issue_comment>username_1: Your issue is that you are attempting to assign a **string** to an **integer**. This is the reason you are receiving the type-mismatch.
```
Dim Month() As Integer
```
but you are trying to use this variable like:
```
Month = "Jan"
```
`"Jan"` is not an Integer, but a string.
---
The next issue is that you are trying to assign different datatypes to the same variable... Again, this would be your month variable (`If Month = 1 Then`)
While you can technically use the type `Variant`, this is not the method you should go with.
Instead, create two variables. If you'd like to use "Month", then maybe something like `Dim intMonth As Integer, strMonth As String`. Assign the column with your Int values to the Integer var, and do the conversion to the String var.
---
I am not entirely sure how many rows you have, but a good rule of thumb is to always declare variables that represent **row numbers** as type `Long` instead of type `Integer`. While you are safe to use Integer on your month & year vars (I'd still use Long anyways), you can run into overflow problems if you have too many rows (integers go up to approx 32.7k, then will overflow afterwards).
---
Next issue, you are using an **array** with `Months()`, but you are referring to `Months` in your If statements as a **non-array**.
```
Sub DateColumn()
Dim ws As Worksheet
Dim NRows As Long
Dim Month As String
Set ws = ThisWorkbook.Worksheets("Data") '<-- remove the .Activate
NRows = ws.Range("A4").End(xlDown).Row - 1
For n = 1 To NRows
Select Case ws.Cells(n, "B").Value '< I think your "Month" col is B?
Case 1
Month = "Jan"
Case 2
Month = "Feb"
Case 3
Month = "Mar"
Case 4
Month = "Apr"
Case 5
Month = "May"
Case 6
Month = "Jun"
Case 7
Month = "Jul"
Case 8
Month = "Aug"
Case 9
Month = "Sep"
Case 10
Month = "Oct"
Case 11
Month = "Nov"
Case 12
Month = "Dec"
Case Else
MsgBox "Unknown Error in month. Row # [" & n & "], row val = [" & _
ws.Cells(n, "B").Value & "]. Please debug"
End Select
ws.Cells(n, "E") = Month & " " & CStr(ws.Cells(n, "C") + 2000)
Next n
End Sub
```
Upvotes: 2 <issue_comment>username_2: See the attached screenshot...
[](https://i.stack.imgur.com/VVOAs.png)
The second last column uses the native worksheet function `DATE` (but it requires the cells to be formatted as `MMM YYYY`), the last column uses the custom user function below (gets you to the `2000`, and does not require cell formatting):
```
Function dateConv(month, year) As String
Dim dtOut As Date
On Error Resume Next
dtOut = CDate("01" & "-" & month & "-" & year)
dateConv = Format(dtOut, "MMM YYYY")
End Function
```
The function above uses the `VBA` converter for dates `CDate` and `Format` the result to the format you target.
Hope this helps...
Upvotes: 2 <issue_comment>username_3: You can use the `DateSerial` function, to get a real date out of the values you keep in column B (month) and column C (year), and then just use `NumberFormat = "mmm yyyy"` to get the the format in column A as you want it.
You can shorten your entire code, to something like this:
```
Option Explicit
Sub DateColumn()
'***Defined Variable
Dim NRows As Long, LastRowData As Long, n As Long
With Sheets("Data")
LastRowData = .Cells(.Rows.Count, "B").End(xlUp).Row ' last row with data in column B, where you keep your months
For n = 1 To LastRowData
.Range("A" & n).Value = DateSerial(2000 + .Range("C" & n).Value, .Range("B" & n).Value, 1)
.Range("A" & n).NumberFormat = "mmm yyyy"
Next n
End With
End Sub
```
If you want to get the String (and not the date) use the code below:
```
For n = 1 To LastRowData
.Range("A" & n).Value2 = Format(DateSerial(2000 + .Range("C" & n).Value, .Range("B" & n).Value, 1), "mmm yyyy")
Next n
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: Your easiest approach is to use the built-in functionality of Excel.
>
> My objective is to combine both into 1 column and format it as mmm
> YYYY at Column E such as "Jan 2008".
>
>
>
Simply place a formula that converts the two cells to a date in Column E, and then format that column to display the date in the format you want. The two pictures below show the formula and the format setting.
[](https://i.stack.imgur.com/a3zOZ.png)
[](https://i.stack.imgur.com/S5kBL.png)
I have used an arbitrary `day` of `1` in my formula because you are only concerned with the month and year.
Upvotes: 1 |
2018/03/22 | 620 | 2,474 | <issue_start>username_0: So i am confused on laravel nested queries.
I am trying to prepared a search function that filters the products that is in the `sales_agreement` table but also if the record has financing i want it to be filtered too.
Below is my sample.
(1) Table Products
```
id product_name price
1 car 500k
2 jeep 200k
3 motor 100k
4 bicycle 5k
```
(2) Sales Agreement
```
id product_id price financing
1 2 500k BPI
2 1 200k MetroBank
3 3 100k
```
Expected Output In my query
```
product_id product_name
2 jeep
1 car
4 bicycle
```
My Query
```
$result = DB::table('products')
->whereNotIn('id',function($q){
$q->select('product_id')->from('sales_agreement');
})->where('product_name','LIKE','%' . $get['q'] . '%')
->select('id','product_name')
->get();
```
This filters all of the products that is not in the sales\_agreement table. But i also want to consider the items that has a Financing record in the sales\_agreement table. In that point i dont have an idea how to do it.
Any comments/suggestion/answer will be much appreciated. Thanks !<issue_comment>username_1: You can try where null
```
$result = DB::table('products')
->whereNotIn('id',function($q){
$q->select('product_id')->from('sales_agreement')
->whereNull('financing');
})->where('product_name','LIKE','%' . $get['q'] . '%')
->select('id','product_name')
->get();
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want to exclude the products that don't have financing record you can do a left join with additional clause
```
$result = DB::table('products as p')
->leftJoin('sales_agreement as s', function ($query) {
$query->on('p.id', '=', 's.product_id')
->whereNull('s.financing');
})
->whereNull('s.product_id')
->where('p.product_name', 'LIKE', '%' . $get['q'] . '%')
->select('p.id', 'p.product_name')
->get();
```
Upvotes: 0 |
2018/03/22 | 882 | 3,838 | <issue_start>username_0: I referred to [this question](https://stackoverflow.com/questions/35387227/get-device-token-with-react-native) to get a device token in order to send push notifications to my app. I created my app using `create-react-native-app`. Here is the code:
```js
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
AppRegistry,
Text,
View,
PushNotificationIOS
} from 'react-native';
type Props = {};
export default class Apptitude extends Component {
constructor() {
console.log('registering evt listerner in launchpad')
PushNotificationIOS.addEventLister('register', (token) => {
this.setState({
deviceToken: token
})
});
}
render() {
return (
);
}
}
PushNotificationIOS.addEventListener('registrationError', (registrationError) => {
console.lo('was error')
console.log(reason.message)
console.log(reason.code)
console.log(reason.details)
})
// yes I'm aware I've added an event listener in the constructor also. Neither of these callbacks fire
PushNotificationIOS.addEventListener('register', (token) => {
console.log('this is the token', token);
});
console.log('requesting permissions')
PushNotificationIOS.requestPermissions();
```
The problem is that the `register` and the `registrationError` events never fire. I am prompted to approve permissions and next time the app starts I can use `checkPermissions()` and confirm that permissions are given. But without the device token, it's impossible to send push notifications to the device. What am I doing wrong?<issue_comment>username_1: How about the Xcode part?
You should import TCTPushNotification on you AppDelegate file
```js
#import
```
and implement the follow code to enable the `notification` and `register` in your app
```js
// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[RCTPushNotificationManager didReceiveLocalNotification:notification];
}
```
For more information use the official docs
<https://facebook.github.io/react-native/docs/pushnotificationios.html>
Upvotes: 1 [selected_answer]<issue_comment>username_2: The other thing to be aware of is that on the simulator the `onRegister` function is not fired, you have to use a real device.
Upvotes: 2 <issue_comment>username_3: Just in case anyone had a similar issue to mine, which was on a real device, the key is to register the events, but then specifically call `PushNotificationIOS.requestPermissions();` after registering the events.
Upvotes: 1 |
2018/03/22 | 645 | 2,146 | <issue_start>username_0: I am having some strange behaviour where `this.props.children` is converting to an object when I spread the result of a `.map()` from the parent.
**example:**
```
const items = [
{ id: 1, name: "Name1" },
{ id: 2, name: "Name2" }
].map((item) => {
return (
);
});
render() {
return (
{}}
>
{...items}
);
}
// DropdownMenu.js
render() {
console.log(this.props.children); // {0: {…}, 1: {…}}
return (
// ...
);
}
```
The weird part is that when I omit the `.map()` and pass the elements directly, they appear in `this.props.children` as an array like expected:
```
render() {
return (
{}}
>
);
}
// DropdownMenu.js
render() {
console.log(this.props.children); // [{…}, {…}]
return (
// ...
);
}
```
Any insight into why this is happening would be greatly appreciated.<issue_comment>username_1: Its not because of map that you get children as object, but because you use spread operator for the items in
```
{}}
>
{...items} {/\*spread operator here \*/}
```
Now that after map items is an array using `{...items }` makes it an object since you wrap your result of spread operator with `{}`, If you write `{items}`, that will be fine
```
{}}
>
{items}
```
Upvotes: 3 <issue_comment>username_2: `{...items}` is passed as childrens in `DropdownMenu.js`.
Its available as a `this.props.children`
`this.props.children` can be array or object depend on how you rendering the children elements.
in your case
```
{}}
>
{...items}
```
items is an array. As we know
```
array is also type of object in javascript
with key equal to element's index and value is element itself
```
`{...items}` : this will passed as a object with key as a element index and value equal to array element.
To fix your problem, you should passed it without using spread operator.
`{items}` : this will passed as an array.
```
{}}
>
{items}
```
Upvotes: 3 <issue_comment>username_3: In my case passing as attr will worked
before
```
function Foo(props) {
return {...props}
}
```
after
```
function Foo(props) {
return
}
```
Upvotes: 2 |
2018/03/22 | 450 | 1,655 | <issue_start>username_0: I've inserted multiple rows data from gridview to database at a time using stored procedure.
Now I've to fetch and display that multiple rows data into GridView and inside GridView I need to call particular value from column to a particular label into GridView.
How can I get that values dynamically? I am not seeing any way to show data.<issue_comment>username_1: Its not because of map that you get children as object, but because you use spread operator for the items in
```
{}}
>
{...items} {/\*spread operator here \*/}
```
Now that after map items is an array using `{...items }` makes it an object since you wrap your result of spread operator with `{}`, If you write `{items}`, that will be fine
```
{}}
>
{items}
```
Upvotes: 3 <issue_comment>username_2: `{...items}` is passed as childrens in `DropdownMenu.js`.
Its available as a `this.props.children`
`this.props.children` can be array or object depend on how you rendering the children elements.
in your case
```
{}}
>
{...items}
```
items is an array. As we know
```
array is also type of object in javascript
with key equal to element's index and value is element itself
```
`{...items}` : this will passed as a object with key as a element index and value equal to array element.
To fix your problem, you should passed it without using spread operator.
`{items}` : this will passed as an array.
```
{}}
>
{items}
```
Upvotes: 3 <issue_comment>username_3: In my case passing as attr will worked
before
```
function Foo(props) {
return {...props}
}
```
after
```
function Foo(props) {
return
}
```
Upvotes: 2 |
2018/03/22 | 360 | 1,443 | <issue_start>username_0: I have requirement in our application, where we need show the date format as per the client OS date format.I have used the following code to do this.
---
```
function getFormatedDateTime(date) {
var dateFormated = moment(date).toDate();
return dateFormated.toLocaleDateString();
};
```
---
this working in IE as expected , means when i changed the date format in my PC the date format in the entire application is changing.
But the problem is it not working in other browsers( Chrome, Fire Fox..etc).
we are using moment.js in our application, is there is any option in this to achieve my requirement.
Can any one help me to solve this.
Thanks in Advance<issue_comment>username_1: You need use to moment with DateTime format like below
moment(date, 'MM/DD/YYYY')
Upvotes: -1 <issue_comment>username_2: You can not get users system time format - JavaScript does not reveal information about the underlying OS, for security reasons.
Try this
```
function getFormatedDateTime(date) {
var dateFormated = new Date();
return dateFormated.toLocaleDateString();
};
```
This doesn't tell your code what the user's selected date format is, but it lets you return a date in whatever the user's format is.
Link for reference: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString>
Change the system date format will reflect on browser restart.
Upvotes: 1 |
2018/03/22 | 932 | 3,294 | <issue_start>username_0: I want to have two, side-by-side ImageViews that spread to take up 50% of the screen each. Over each, I want to arrange an array of Buttons and TextViews. I am doing this in a single `ConstraintLayout`.
When I set up the ImageViews by themselves, they lay out properly using these properties:
```
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1"
```
The ImageViews have constraints like this (there's also a **`1dp`** View separator bar):
```
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/separator_bar"
app:layout_constraintTop_toTopOf="parent"
```
Here's what the split looks like:
[](https://i.stack.imgur.com/UEL6l.png)
However, when I add the `Buttons` and TextViews and chain them together, linking them to the sides of the ImageView and each other, making them essentially "contained" in the ImageView, the ImageView shrinks horizontally so that it is the width of the widgets, almost as if wrap\_content were applied. What's even weirder is that the other ImageView also shrinks, even though I haven't added its widgets yet.
When marked up, the controls look like this:
```
```
(the constraints of the original `ImageView` are unchanged)
Here's what it looks like with just one ImageView anchored to the parent on all four sides. The widgets look fine.
[](https://i.stack.imgur.com/gsQyc.png)
And here's the hot mess when I use the two ImageViews.
[](https://i.stack.imgur.com/og91R.png)
What's going on here? Why does linking a `widget` inside another `widget/view` cause the nice layout that I had before to change? I would assume that the ImageViews were anchored to the parent and shouldn't move, but this is clearly not the case.
I've looked at a bunch of tutorials, but they all seem to show me how to perform a half dozen tricks using the Android Studio GUI and don't really get into the zen of how the layouts are evaluated. I want to actually grok what's going on and not just click some buttons in a GUI design tool. FWIW, I did try the GUI design tool and spent about as much time cleaning up the magic trash it added to my XML (no, I don't need padding, thanks) as I would have saved using the tool, so I essentially abandoned it and now just use it to experiment.
I'm new to Android development, if that isn't clear. This is a toy app for an ungraded Udacity course.
Full XML:
```
xml version="1.0" encoding="utf-8"?
```<issue_comment>username_1: First you have to arrange the image views correctly. Like the `LinearLayout`, you can set weight in `ConstraintLayout`.
```
```
Then try to align button over the `ImageViews`. Hope it helps:)
Upvotes: 0 <issue_comment>username_2: Try this
```
xml version="1.0" encoding="utf-8"?
```
**OUTPUT**
[Here is the good tutorial for this](https://medium.com/@loutry/guide-to-constraintlayout-407cd87bc013)
[](https://i.stack.imgur.com/GoGrV.png)
Upvotes: 1 |
2018/03/22 | 672 | 2,563 | <issue_start>username_0: Here I am overriding the `find()` method
```
class ActiveRecord extends BaseActiveRecord{
public static function find() {
return parent::find()
->where(['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id])
->andWhere(['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]);
}
}
```
Now if I use the condition like this
```
\common\models\Order::find()->where(['stastus'=>'3'])->count();
```
the Active Record global condition is executed before the condition I am
using in Order model and after that the Order Model where overriding
the active record global condition.
And if I use the Active Record condition like this
```
class ActiveRecord extends BaseActiveRecord{
public static function find() {
return parent::find()
->andWhere(['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id])
->andWhere(['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]);
}
}
```
There were in my local model overriding the global condition. Difficult for
me to override each where with and where.<issue_comment>username_1: This is the way how the Yii2 `ActiveRecord` works. When you call method `where()` it reset conditions, even if was not empty and when you call `andWhere()` it add new condition to existing ones.
Upvotes: 0 <issue_comment>username_2: You should change the `where` and `andWhere` to `onCondition` in your `BaseActiveRecord` which I suppose is an alias for **`\yii\db\ActiveRecord`** as the `parent::find()` return object of `ActiveQuery` if you look into the `find()` method it returns below line
**`\yii\db\ActiveRecord`**
```
return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
```
you can see here [**`customizing-query-class`**](http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#customizing-query-classes) to add an extra condition
```
class ActiveRecord extends BaseActiveRecord{
return parent::find ()
->onCondition ( [ 'and' ,
[ '=' , static::tableName () . '.application_id' , 1 ] ,
[ '=' , static::tableName () . '.branch_id' , 2 ]
] );
}
```
Now if you call
```
\common\models\Order::find()->where(['status'=>'3'])->createCommand()->rawSql;
```
it will generate the following query
```
SELECT * FROM `order`
WHERE (`status` = 3)
AND
((`order`.`application_id` = 1) AND (`order`.`branch_id` = 2))
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 632 | 2,247 | <issue_start>username_0: I've created a factory class which allows the user to call a method `Generate` and it populates a jagged array via some logic that generally I don't want the user to deal with.
A lot of index's are null because of the type of grid layout that the factory generates.
But I don't want the user to have to iterate both array indexes and check for null. Is there anyway to simplify this for a user to iterate this array without them needing to worry about it.
For example, to iterate the data they currently have to do:
```
for (int i = Map.MapData.Length - 1; i >= 0; --i)
{
for (int j = Map.MapData[i].Length - 1; j >= 0; --j)
{
// would rather they didn't have to check for null
if (Map.MapData[i][j] == null) continue;
// do stuff with data
}
}
```
This isn't all that user friendly. Is there a way I can make the data be more linear to the user, like using a for each on the data? I'm not entirely sure what I am looking for in order to achieve this, hope some one can point me in the right direction.
Thanks<issue_comment>username_1: If you just want to loop through the elements of the array and discard the indices, you can do an extension method:
```
public static class JaggedArrayExtensions {
public static IEnumerable IterateNonNull(this T[][] array) where T : class {
for (int i = array.Length - 1; i >= 0; --i)
{
for (int j = array[i].Length - 1; j >= 0; --j)
{
// would rather they didn't have to check for null
if (array[i][j] == null) continue;
yield return array[i][j];
}
}
}
}
```
Now you can loop through your jagged array with a `foreach` loop:
```
foreach (var item in jaggedArray.IterateNonNull()) {
// ...
}
```
If this is the first you see `yield return`, read [this](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield).
Upvotes: 2 [selected_answer]<issue_comment>username_2: When *querying* collections (in your case you want all not `null` items) try using *Linq*:
```
var NotNullItems = Map
.SelectMany(line => line // From each line
.Where(x => x != null)); // Filter out all null items
foreach (var item in NotNullItems) {
// do stuff with data
}
```
Upvotes: 2 |
2018/03/22 | 573 | 1,733 | <issue_start>username_0: I found this code from stackoverflow ... and wondering how can I move index position that I want.
I tried to use for loop and [::1]. And by making, len(a)\*[0]...I couldn't make it.
Is there any way to fix items on its position in list?
Second, without using method below, is there another way to reorder items in list?
'''
mylist=['a','b','c','d','e']
myorder=[3,2,0,1,4]
'''
```
a = [1,2,3,4,5,6,7]
b = ((a+a[:0:-1])*len(a))[::len(a)][:len(a)]
[1, 7, 2, 6, 3, 5, 4] <=b
[7, 1, 6, 2, 5, 3, 4] <= the result i want
```
Thanks in advance.<issue_comment>username_1: If you just want to loop through the elements of the array and discard the indices, you can do an extension method:
```
public static class JaggedArrayExtensions {
public static IEnumerable IterateNonNull(this T[][] array) where T : class {
for (int i = array.Length - 1; i >= 0; --i)
{
for (int j = array[i].Length - 1; j >= 0; --j)
{
// would rather they didn't have to check for null
if (array[i][j] == null) continue;
yield return array[i][j];
}
}
}
}
```
Now you can loop through your jagged array with a `foreach` loop:
```
foreach (var item in jaggedArray.IterateNonNull()) {
// ...
}
```
If this is the first you see `yield return`, read [this](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield).
Upvotes: 2 [selected_answer]<issue_comment>username_2: When *querying* collections (in your case you want all not `null` items) try using *Linq*:
```
var NotNullItems = Map
.SelectMany(line => line // From each line
.Where(x => x != null)); // Filter out all null items
foreach (var item in NotNullItems) {
// do stuff with data
}
```
Upvotes: 2 |
2018/03/22 | 498 | 1,698 | <issue_start>username_0: I am attempting to make a chat room for a class project (I have stumped my teacher and he has given me permission to use any sources at my disposal, including asking Stack Overflow which some teachers don't allow). Before the user gets to the chatroom itself I want to make sure the IP address they want is valid. I have gotten my little section of code that checks the IP address from this site and it helped slightly.
[Here's my code so far (sorry it's a link)](https://i.stack.imgur.com/LKUfw.png)
When I run it and input my own IP address (just so I know it is an actual IP address), I get the following error message;
>
> ValueError: invalid literal for int() with base 10: '192.168.0.105'
>
>
>
This is only the start of my code and I am hoping to solve it rather quickly, so any help is greatly appreciated!!<issue_comment>username_1: The issue is in your user input line:
```
int('192.168.0.105')
```
Will throw an error because you can't convert an IP address to an integer, an IP address is *not* an integer.
The function [`socket.inet_aton()`](https://docs.python.org/2/library/socket.html#socket.inet_aton) takes:
>
> an IPv4 address from dotted-quad string format (for example, ‘192.168.127.12’)
>
>
>
So just remove the conversion to `int` and your code should work.
Upvotes: 2 <issue_comment>username_2: You can not type cast string which contains dot which is causing error. Just remove type casting i.e. `int()` prior to `input()`. `inet_aton()` takes care of ip validation internally.
code:
```
import socket
userip = input("enter ip addr")
try:
socket.inet_aton(userip)
except socket.error:
print("invalid ip")
```
Upvotes: 1 |
2018/03/22 | 1,339 | 4,590 | <issue_start>username_0: I've checked my Hyper-V settings and PowerShell Module is enabled. I've also found this documented issue: <https://github.com/docker/machine/issues/4342> but it is not the same issue since I do not have VMware PowerCLI installed. The issue was closed with a push to the repo and is supposedly fixed in 0.14.0-rc1, build e918c74 so I tried it anyways. After replacing my docker-machine.exe, I'm still getting the error and still getting the error even if I reinstall Docker for Windows.
For some more background, this error starting happening after a reinstall because my Docker install had an error: <https://github.com/docker/for-win/issues/1691>, however, I'm not longer getting that issue after reinstalling.<issue_comment>username_1: For those who struggle with this issue in Windows, [Follow the instruction here](https://github.com/docker/machine/issues/4424#issuecomment-377727985)
Upvotes: 3 <issue_comment>username_2: When creating a Hyper-v VM using docker-machine on win10, an error was returned"Error with pre-create check: "Hyper-V PowerShell Module is not available"。
The solution is very simple. The reason is the version of the docker-machine program. Replace it with v0.13.0. The detailed operation is as follows:
1. Download the 0.13.0 version of the docker-machine command. Click to download: 32-bit system or 64-bit system
2. After the download is complete, rename and replace the " docker-machine.exe " file in the " C:\Program Files\Docker\Docker\resources\bin" directory. It is best to back up the original file.
Upvotes: 4 [selected_answer]<issue_comment>username_3: (1),
V0.15 fixed this issue officially:
Fix issue #4424 - Pre-create check: "**Hyper-V PowerShell Module is not available**"
Official Introduction:
<https://github.com/docker/machine/pull/4426>
Address to donload V0.15
<https://github.com/docker/machine/releases>
(2),
I tested this, it works fine.
No need restart docker
It take effect immdiately after the "docker-machine.exe" is replaced with version 0.15
(3),
Backup the original one is a good habit
Upvotes: 0 <issue_comment>username_4: Here is the solution
====================
### `https://github.com/docker/machine/releases/download/v0.15.0/docker-machine-Windows-x86_64.exe`
### Save the downloaded file to your existing directory containing `docker-machine.exe`.
For my system this is the location for `docker-machine.exe`
`/c/Program Files/Docker/Docker/Resources/bin/docker-machine.exe`
### Backup the old file and replace it file with the new one.
`cp docker-machine.exe docker-machine.014.exe`
### Rename the downloaded filename to `docker-machine.exe`
`mv docker-machine-Windows-x86_64.exe docker-machine.exe`
Build Instructions
------------------
1. Create virtual switch in Hyper-V manager named `myswitch`
2. Request Docker to create a VM named `myvm1`
`docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1`
Results
-------
`docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1`
`Running pre-create checks...
(myvm1) Image cache directory does not exist, creating it at C:\Users\username_4\.docker\machine\cache...
(myvm1) No default Boot2Docker ISO found locally, downloading the latest release...
(myvm1) Latest release for github.com/boot2docker/boot2docker is v18.05.0-ce
(myvm1) Downloading C:\Users\username_4\.docker\machine\cache\boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v18.05.0-ce/boot2docker.iso...
(myvm1) 0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100%
Creating machine...
(myvm1) Copying C:\Users\username_4\.docker\machine\cache\boot2docker.iso to C:\Users\username_4\.docker\machine\machines\myvm1\boot2docker.iso...
(myvm1) Creating SSH key...
(myvm1) Creating VM...
(myvm1) Using switch "myswitch"
(myvm1) Creating VHD
(myvm1) Starting VM...
(myvm1) Waiting for host to start...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\Docker\Docker\Resources\bin\docker-machine.exe env myvm1`
Upvotes: 3 <issue_comment>username_5: Just start docker desktop if you are on Windows
Upvotes: 0 |
2018/03/22 | 1,144 | 3,952 | <issue_start>username_0: I'm trying to send Custom ERC20 Token to Owner Wallet Address using transferFrom() function using Web3.js
However all the transactions are failed. Which is the same problem occur on Remix IDE.
Some answers on Stack Overflow say that the `approve()` is needed to call first before the `transferFrom()` function. so, I tried on Remix first, but I got the same problem. And then tried with using Web3.js like below:
```
const myContract = new web3.eth.Contract(abi);
const amount = sendAmount;
let address = myAddress;
myContract.options.address = contractAddress;
myContract.options.from = TokenOwner;
let options = myContract.options;
let data1 = myContract.methods.approve(address, amount).encodeABI();
let data2 = myContract.methods.transferFrom(address, TokenOwner, amount).encodeABI();
const ethAccount = fromPrivateKey(toBuffer("0x..."));
const fromPrivateKeyBuffer = ethAccount.getPrivateKey();
web3.eth.getTransactionCount(TokenOwner, (err, count) => {
if (err) return;
const txData = {
chainId: 0x03,
gasPrice: web3.utils.toHex(42000000000),
gasLimit: web3.utils.toHex(90000),
to: contractAddress,
from: TokenOwner,
value: 0x0,
nonce: web3.utils.toHex(count),
data: data1
};
const tx = new ethTx(txData);
tx.sign(fromPrivateKeyBuffer);
const serializedTx = tx.serialize().toString("hex");
if (!serializedTx) {
return;
} else {
web3.eth.sendSignedTransaction(`0x${serializedTx}`, (err, MuiTXHash) => {
console.log("err : ", err, "Data1-MuiTXHash : ", MuiTXHash);
// START DATA2
web3.eth.getTransactionCount(TokenOwner, (err, count) => {
if (err) return;
const txData2 = {
chainId: 0x03,
gasPrice: web3.utils.toHex(42000000000),
gasLimit: web3.utils.toHex(90000),
to: contarctAddress,
from: TokenOwner,
value: 0x0,
nonce: web3.utils.toHex(count + 1),
data: data2
};
const tx2 = new ethTx(txData2);
tx2.sign(fromPrivateKeyBuffer);
const serializedTx2 = tx2.serialize().toString("hex");
if (!serializedTx2) {
return;
} else {
web3.eth.sendSignedTransaction(`0x${serializedTx2}`, (err, MuiTXHash2) => {
console.log("err : ", err, "Data2-MuiTXHash : ", MuiTXHash2);
});
}
});
// END DATA2
});
}
});
};
```
I got the two Transaction Hash return data and the TransferFrom() transaction is failed again.
What is the problem?
I have to withdraw the custom ERC20 token from a specific address to owner. so I have to use transferFrom() transaction.<issue_comment>username_1: I guess the compiling on Remix had some errors so I created new solidity file with same code on it and deployed it. The new smart contract worked well and no errors occurred. The errors was not about my code. If someone's suffering like this problems, then create a new contract address and I don't recommend using 'At Address' on Remix. This is not work properly at all.
Upvotes: 0 <issue_comment>username_2: I was tried appove() + transferFrom () , allowance() on Solidity working well but on web3 not working error same as you
Upvotes: -1 <issue_comment>username_3: The transferFrom function should be called by the spender (i.e the address to which the TokenOwner has approved to spend). So,
```
const txData2 = {
chainId: 0x03,
gasPrice: web3.utils.toHex(42000000000),
gasLimit: web3.utils.toHex(90000),
to: contarctAddress,
from: address, // spender's address
value: 0x0,
nonce: web3.utils.toHex(count + 1),
data: data2
};
```
And don't forget to use the *spender's private key* to sign the transaction and the *spender's address* in `getTransactionCount`.
Read more here: [Ethereum Wiki](https://theethereum.wiki/w/index.php/ERC20_Token_Standard#Approve_And_TransferFrom_Token_Balance)
Upvotes: 0 |
2018/03/22 | 808 | 2,889 | <issue_start>username_0: I'm currently having an issue with figuring out how I can access req.user so I can get the logged in users id and save it with the items that they save on the web page. That way when they load the web page they only get their items. The only place I know where I have access to req.user is in my /router/auth.js file. I want to figure out a way to access it in a different router file.
**router/auth.js**
```
const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const config = require('../config');
const router = express.Router();
const createAuthToken = function (user) {
return jwt.sign({ user }, config.JWT_SECRET, {
subject: user.username,
expiresIn: config.JWT_EXPIRY,
algorithm: 'HS256'
});
};
const localAuth = passport.authenticate('local', { session: false });
router.use(bodyParser.json());
router.post('/login', localAuth, (req, res) => {
const authToken = createAuthToken(req.user.serialize());
res.json({ authToken });
});
const jwtAuth = passport.authenticate('jwt', { session: false });
router.post('/refresh', jwtAuth, (req, res) => {
const authToken = createAuthToken(req.user);
res.json({ authToken });
});
```
**/router/portfolio.js**
```
router.post('/:id', (req, res) => {
const id = req.params.id;
const { holdings } = req.body;
CryptoPortfolio.findOne({ id }, (err, existingCoin) => {
if (existingCoin === null) {
getCoins(id)
.then(x => x[0])
.then(value =>
CryptoPortfolio.create({
id: value.id,
holdings,
_creator: this is where I want to add req.user.id
}).then(() => value))
.then(newItem => {
res.status(201).json(newItem);
})
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
});
} else {
const capitalizedId = id.charAt(0).toUpperCase() + id.slice(1);
res.json(`${capitalizedId} already in watchlist`);
}
});
});
```<issue_comment>username_1: You can define global variable and use it using middleware.
app.js
```
// Global Vars
app.use(function (req, res, next) {
res.locals.user = req.user
next();
});
```
route.js
```
router.get('/', function(req, res) {
CryptoPortfolio.find({}, function(err, crypto) {
console.log('CryptoPortfolio : ',crypto);
res.render('view/crypto', {
user : res.locals.user // <= here
});
});
});
```
I hope it would be helpful :)
Upvotes: 1 <issue_comment>username_2: I figured out that I wasn't using the code below on any of the necessary routes. Implemented it and I can now access req.user.
```
const jwtAuth = passport.authenticate('jwt', { session: false });
```
Upvotes: 0 |
2018/03/22 | 262 | 947 | <issue_start>username_0: In an Excel sheet, I want to read the values from a column, pick a random value from it and display in another column. Is there any way to do that in java?
Thank you.<issue_comment>username_1: You can define global variable and use it using middleware.
app.js
```
// Global Vars
app.use(function (req, res, next) {
res.locals.user = req.user
next();
});
```
route.js
```
router.get('/', function(req, res) {
CryptoPortfolio.find({}, function(err, crypto) {
console.log('CryptoPortfolio : ',crypto);
res.render('view/crypto', {
user : res.locals.user // <= here
});
});
});
```
I hope it would be helpful :)
Upvotes: 1 <issue_comment>username_2: I figured out that I wasn't using the code below on any of the necessary routes. Implemented it and I can now access req.user.
```
const jwtAuth = passport.authenticate('jwt', { session: false });
```
Upvotes: 0 |
2018/03/22 | 391 | 1,288 | <issue_start>username_0: When I do
```
mix compile
```
I get messages like
```
warning: variable "test_val" is unused
lib/myapp/mymodule.ex:46
```
I'm just hacking on a side project and I don't care about these warnings for now. Is there a way to turn this off?<issue_comment>username_1: It doesn't look possible, but I could be wrong.
<https://groups.google.com/forum/#!topic/elixir-lang-talk/XBnap4u6OkM>
<https://elixirforum.com/t/is-there-a-way-to-suppress-warnings-about-unused-variables/8637/7>
The code that generates the warning (as best I can tell) is `elixir_errors:warn` and that doesn't have any flags to be able to turn off.
<https://github.com/elixir-lang/elixir/search?p=1&q=%3Aelixir_errors.warn&type=&utf8=%E2%9C%93>
Nor does it look like there are any code comments you can add to suppress the errors.
Consider it another facet of elixir's very opinionated viewpoint (right along with the "there's only one formatter, and it has no config")
Upvotes: 2 <issue_comment>username_2: You can stop that particular compiler warning (i. e. `test_val is unused`) by proceeding the value with `_`. That is, rename the value to `_test_val` and you won't get the warning. But if you're warned the variable is unused, maybe you want to double check your code.
Upvotes: 2 |
2018/03/22 | 1,369 | 5,598 | <issue_start>username_0: I'm sure that most of you know that C does not specify which order operands to operators such as + will be evaluated.
E.g. `x = exp1 + exp2` might be evaluated by first evaluating exp1, then exp2, then adding the results. However, it might evaluate exp2 first.
How would I make a C assignment that will assign either 1 or 2 to x depending on whether the left or right operand of + is evaluated first?<issue_comment>username_1: the simplest code to check for this would look something like this:
```
#include
int i;
int inc\_i(void)
{
return ++i;
}
int get\_i(void)
{
return i;
}
int
main (void)
{
i = 0;
printf("%i\n", get\_i() + inc\_i());
i = 0;
printf("%i\n", inc\_i() + get\_i());
}
```
on my system, this prints:
```
$ ./test
1
2
```
which tells me that the left side of the expression is evaluated first. However, while I think that this is an interesting thought experiment, I would not recommend relying on this check to do any meaningful logic in your program - that would be asking for trouble.
Upvotes: 2 <issue_comment>username_2: You can't. Not reliably. Any time you allow a situation like that to happen in your code the C standard calls it "undefined behavior" and allows the compiler to do whatever it wants. And compilers are notorious, especially in the recent decades, for being completely unpredictable when they encounter undefined behavior. The worst part is that it might even be hard to configure the compiler to warn you that such a situation happened (it can't always know). It is your responsibility to never allow a situation like this to happen.
This might sound crazy but it has a good point. CPUs are different. On some it might make sense to do things in one order. On another that same order will be extremely slow, but doing things in another order is very fast. Maybe the next generation of a CPU will change how instructions are executed and now that third order of operations makes the most sense. Maybe the compiler developers figured out a way to generate much better code by doing things a certain way.
Just because you manage to convince the compiler to generate code that generates a particular order of operations one time doesn't mean that it won't change next time you compile. Maybe the order of the operands doesn't matter at all and they are evaluated in whatever order they happen to be stored in some internal data structure in the compiler and that happens to be a hash table with a hash function that changes on every execution, or maybe the hash function changes next time you update the compiler, or you happen to just add another expression before or after in your code which changes the order, or update another program on your computer that also updates a library that the compiler uses and that library happens to change the order of how some things are stored in a data structure which will change the order of how the compiler generates code.
Note. It is possible to write the expression you want where the order of evaluation wouldn't cause undefined behavior, only be "indeterminately sequenced". In that case the compiler isn't free to do whatever it wants, it is just allowed to evaluate the expressions in whatever order it wants. In most practical situations the result is the same.
Upvotes: -1 <issue_comment>username_3: The problem with writing such an expression is that you can't write to the same variable twice inside it, or the code will invoke undefined behavior, meaning there will be a bug and anything can happen. If a variable is modified inside an expression, that same variable is not allowed to be accessed again within the same expression, unless accesses are separated by so-called *sequence points*. (C11 6.5/2) [See this for details](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior-in-c).
So we *can't* write code such as this:
```
// BAD CODE, undefined behavior
_Bool first=false;
x = (first?(first=true,exp1):0) + (first?(first=true,exp2):0);
```
This code invoked undefined behavior because the access to `first` between difference places of the expression are unsequenced.
---
However, it is possible to achieve similar code by using functions. Whenever calling a function, there is a sequence point after the evaluation of the arguments, before the function is called. And there is another sequence point before the function returns. So code such as this is possible:
```
n = expr(1) + expr(2)
```
This merely has unspecified behavior - since the evaluations of the operands to + is unspecified. But there is no unsequenced access anywhere, meaning the code can't crash etc. We simply can't know or assume what result it will give. Example:
```
#include
static int first=0;
int expr (int n)
{
if(first == 0)
{
first = n;
return first;
}
return 0;
}
int main (void)
{
int n;
printf("%d\n", n = expr(1) + expr(2)); // unspecified order of evaluation
first=0;
printf("%d\n", n = expr(1) + expr(2)); // unspecified order of evaluation
return 0;
}
```
This gave the output `1 1` on my system, but it might as well have given the output `1 2`, `2 1` or `2 2`. And the next time I execute the program, it may give a different result - we can't assume anything, except that the program will behave deterministically in an undocumented way.
The main reason why this is left unspecified, it to allow different compilers to optimize their expression parsing trees differently depending on the situation. This in turn enables fastest possible execution time and/or compile time.
Upvotes: 3 |
2018/03/22 | 1,834 | 6,558 | <issue_start>username_0: I want to delay observable to return value until i get new\_token from my HTTP request in subscription. I am also using delay time but i could not able to success .
>
> Error: returning undefined value
>
>
> Expected: new\_token returned from server
>
>
>
```
refreshToken(): Observable {
const token\_refreshed = localStorage.getItem("refresh\_token");
let new\_token: string;
if (token\_refreshed) {
console.log("this refreshed token" + token\_refreshed);
const headers = new HttpHeaders({
'Authorization': "Basic " + btoa("clientId:client-secret"),
'Content-Type': 'application/x-www-form-urlencoded',
'grant\_type': 'refresh\_token',
'refresh\_token': token\_refreshed
});
var creds = "grant\_type=refresh\_token" + "&credentials=true" + "&refresh\_token=" + token\_refreshed;
this.httplclient.post('/api/oauth/token', creds, { headers: headers })
.subscribe(response => {
localStorage.setItem('access\_token', response.access\_token);
new\_token = response.access\_token;
}, err => {
console.log("User authentication failed!");
});
}
console.log('i am returning');
return Observable.of(new\_token).delay(3000);
}
```
Update: Method that is consuming refresh\_token , I am using interceptor so, 401 method is below
```
handle401Error(req: HttpRequest, next: HttpHandler) {
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
console.log('I am handler 401');
// Reset here so that the following requests wait until the token
// comes back from the refreshToken call.
this.tokenSubject.next(null);
return this.authService.refreshToken()
.switchMap((newToken: string) => {
console.log('map token' + newToken);
//I'm getting null new token here from authService.refreshToken()
if (newToken) {
this.tokenSubject.next(newToken);
return next.handle(this.addToken(req, newToken));
}
return this.logoutUser();
})
.catch(error => {
console.log('bad news its catch');
return this.logoutUser();
})
.finally(() => {
this.isRefreshingToken = false;
});
} else {
return this.tokenSubject
.filter(token => token != null)
.take(1)
.switchMap(token => {
console.log('i am switch map else ');
return next.handle(this.addToken(req, token));
});
}
}
```<issue_comment>username_1: Don't subscribe to the `post` requests and if you want to perform some side-effects use the `do` operator instead.
```
if (token_refreshed) {
return this.httplclient.post(...)
.do(response => {
localStorage...
})
.map(response => ...) // map the response to return only the new token?
.delay(3000); // or maybe you don't need this?
}
return Observable.of(new_token).delay(3000);
```
Upvotes: 2 <issue_comment>username_2: You dont need to put a delay. Just pass the value whenever it is available because you can't be sure the value is available after 3000 ms.
```
refreshToken(): Observable {
const tokenObsr = new Subject();
const token\_refreshed = localStorage.getItem("refresh\_token");
if (token\_refreshed) {
console.log("this refreshed token" + token\_refreshed);
const headers = new HttpHeaders({
'Authorization': "Basic " + btoa("clientId:client-secret"),
'Content-Type': 'application/x-www-form-urlencoded',
'grant\_type': 'refresh\_token',
'refresh\_token': token\_refreshed
});
var creds = "grant\_type=refresh\_token" + "&credentials=true" + "&refresh\_token=" + token\_refreshed;
this.httplclient.post('/api/oauth/token', creds, { headers: headers })
.subscribe(response => {
localStorage.setItem('access\_token', response.access\_token);
tokenObsr.next(response.access\_token);
}, err => {
console.log("User authentication failed!");
});
}
console.log('i am returning');
return tokenObsr.asObservable();
}
```
Update: after looking deep into your code i have made the requried changes. `BehavoiurSubject` to `Subject`. Try using it once.
Upvotes: 1 [selected_answer]<issue_comment>username_3: If I understand correctly what you want to achieve, I think you should reorganize your code in order to be able to leverage the Obsersable pattern of RxJs.
Here my suggestion
```
refreshToken(): Observable {
const token\_refreshed = localStorage.getItem("refresh\_token");
let new\_token: string;
if (token\_refreshed) {
console.log("this refreshed token" + token\_refreshed);
const headers = new HttpHeaders({
'Authorization': "Basic " + btoa("clientId:client-secret"),
'Content-Type': 'application/x-www-form-urlencoded',
'grant\_type': 'refresh\_token',
'refresh\_token': token\_refreshed
});
var creds = "grant\_type=refresh\_token" + "&credentials=true" + "&refresh\_token=" + token\_refreshed;
return this.httplclient.post('/api/oauth/token', creds, { headers: headers })
// Do not subscribe here - rather chain operators to transform the Observable returned by http.post into what you really want to emit and return the Observable transformed
.map(response => response.access\_token)
.do(token => localStorage.setItem('access\_token', response.token))
.do(token => console.log('I am returning', token)
}
```
If you do this, than whoever consumes `refreshToken()` method will have to subscribe to the returned Observable and manage the result there, like for instance
```
this.tokenService.refreshToken()
.subscribe(
token => {// do something with the token, maybe move here the localStore.setItem logic},
err => {// handle the error condition}
)
```
Upvotes: 0 <issue_comment>username_4: If you have to await the return of your token, why don't you use a Promise instead of an Observable?
```
this.httplclient.post('/api/oauth/token', creds, { headers: headers }).toPromise().then((t: UserToken) => {
localStorage.setItem('access\_token', t.access\_token);
new\_token = t.access\_token;
}).catch(() => {
console.log("User authentication failed!");
});
```
And if you want to subscribe to changes somewhere else use a Subject.
```
// in your constructor
this.sub = new Subject();
// in your method to get the token
this.httplclient.post('/api/oauth/token', creds, { headers: headers }).toPromise().then((t: UserToken) => {
localStorage.setItem('access\_token', t.access\_token);
new\_token = t.access\_token;
this.sub.next(new\_token);
}).catch(() => {
console.log("User authentication failed!");
});
// getter for the subject
// use asObservable so other components can't use next(..) to push data
get tokenSub(): Observable {
return this.sub.asObservable();
}
// somewhere else
this.yourServer.tokenSub.subscribe((token: String) => {
....
}
```
Upvotes: 0 |
2018/03/22 | 1,577 | 5,272 | <issue_start>username_0: I want to import 3 csv files using 3 buttons separately and merge them into one csv file and save it using a button click.
This is my code:
```
from Tkinter import *
from Tkinter import Tk
from tkFileDialog import askopenfilename
import pandas as pd
from tkFileDialog import asksaveasfilename
import time
class Window(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.initialize()
def initialize(self):
self.geometry("600x400+30+30")
self.wButton = Button(self, text='Product Price List', command = self.OnButtonClick)
self.wButton.pack()
def OnButtonClick(self):
self.top = Toplevel()
self.top.title("Product Price List")
self.top.geometry("300x150+30+30")
self.top.transient(self)
self.wButton.config(state='disabled')
self.topButton = Button(self.top, text="Import Price list CSV", command = self.OnImport1)
self.topButton.pack()
self.topButton = Button(self.top, text="Import Price Adjustment CSV", command = self.OnImport2)
self.topButton.pack()
self.topButton = Button(self.top, text="Import Price Adjustment CSV", command = self.OnImport3)
self.topButton.pack()
self.topButton = Button(self.top, text="Save As", command = self.OnSaveAs)
self.topButton.pack()
self.topButton = Button(self.top, text="CLOSE", command = self.OnChildClose)
self.topButton.pack()
def OnImport1(self):
a = askopenfilename()
def OnImport2(self):
b = askopenfilename()
c = a.OnImport1.merge(b, how='left', left_on='Dynamic_spcMatrix', right_on='Dynamic_spcMatrix' )
def OnImport3(self):
d = askopenfilename()
d = d.dropna(axis=0)
g = d.groupby('Dynamic_spcMatrix')['Attribute_spcName'].apply(lambda x: ', '.join(x.astype(str))) #join attributes usin commas
c['Attribute_spcName'] = c['Dynamic_spcMatrix'].map(g)
c = c[['Type', 'Name', 'Currency_spcCode', 'Product_spcCfg_spcModel_spcId', 'Product_spcName', 'Attribute_spcName', 'Matrix_spcType', 'Start_spcDate', 'End_spcDate', 'Original_spcList_spcPrice', 'Max_spcSale_spcPrice', 'Min_spcSale_spcPrice', 'String_spcMatrix_spcColumn_spc1', 'String_spcMatrix_spcColumn_spc2', 'String_spcMatrix_spcColumn_spc3', 'String_spcMatrix_spcColumn_spc4','Number_spcMatrix_spcColumn_spc1']]
def OnSaveAs(self):
dlg = asksaveasfilename(confirmoverwrite=False)
fname = dlg
if fname != '':
f = open(fname, "a")
new_text = time.time()
f.write(str(new_text)+'\n')
f.close()
c.to_csv(fname, index=False)
def OnChildClose(self):
self.wButton.config(state='normal')
self.top.destroy()
if __name__ == "__main__":
window = Window(None)
window.title("Create Csv")
window.mainloop()
```
I want to import 3 csv files using 3 buttons separately and merge them into one csv file and save it using a button click.
When I run this following error occurs.
```
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\tt20172129\AppData\Local\Continuum\anaconda2\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
File "", line 51, in OnImport2
c = a.OnImport1.merge(b, how='left', left\_on='Dynamic\_spcMatrix', right\_on='Dynamic\_spcMatrix' )
NameError: global name 'a' is not defined
```
I am new to python and also to coding. Hopefully there is someone that can help me so that I can learn. :)<issue_comment>username_1: It is because scope of a is:
```
def OnImport1(self):
a = askopenfilename()
```
and in the scope, a is not defined.:
```
def OnImport2(self):
b = askopenfilename()
c = a.merge(b, how='left', left_on='Dynamic_spcMatrix', right_on='Dynamic_spcMatrix' )
```
Update the code as:
```
a = #Use askopenfilename() return type object to initialize
def OnImport1(self):
global a
a = askopenfilename()
def OnImport2(self):
global a
b = askopenfilename()
c = a.merge(b, how='left', left_on='Dynamic_spcMatrix', right_on='Dynamic_spcMatrix' )
```
It will be able to find a in scope of OnImport2.
Upvotes: 0 <issue_comment>username_2: username_1 is fundamenatally correct, a does not have scope outside of the method on Import1. That is why the code does not work.
His solution - a global - works - but is crude and a great antipattern of why to use a global.
You have to make a architectural decision here.
You have to store the results of a = askopenfilename(), instead of dropping into the global scope, simply keep it at the class scope. Simply had self. in front of a, b, and c, and then you can reference them from any of your other class methods including when you want to write it out (the next time this bug would have showed up)
`def OnImport1(self):
self.a = askopenfilename()`
```
def OnImport2(self):
self.b = askopenfilename()
def OnImport3(self):
self.c = self.a.OnImport1.merge(self.b, how='left', left_on='Dynamic_spcMatrix', right_on='Dynamic_spcMatrix' )
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 545 | 2,352 | <issue_start>username_0: While I am using the JSF and I am trying to find the ValueExpression with below code:
```
public static final ValueExpression createValueExpression(
final FacesContext context, final ELContext elContext,
final String ev, final Class classType) {
return context.getApplication().getExpressionFactory()
.createValueExpression(elContext, ev, classType);
}
```
But When I am running these code on HP fortify says that Interpreting user-controlled instructions at run-time can allow attackers to execute malicious code.
It seems there is a risk of code injection with EL expression evaluation.
But I know there is the code vulnerability so I want to know How Can I prevent the EL injection?
Could anyone help on the same?<issue_comment>username_1: The risk is (just like with e.g. SQL injection) if you let the user provide input that is used in the EL (the ev String as correctly pointed out in the comments) without proper escaping and/or other basic security measures, you'll stand the risk that other code is executed than the one you want.
If this is not the case, you can ignore the warning (hope it is a warning, not a blocking error)
Upvotes: 1 <issue_comment>username_2: Here expression string 'env' can be vulnerable to `Expression Language Injection` which occurs when attackers control data that is evaluated by an `Expression Language interpreter`.
For the solution, A more effective approach may be to perform data validation best practice against untrusted
input and to ensure that output encoding is applied when data arrives on the EL layer, so that
no metacharacter is found by the interpreter within the user content before evaluation. The most
obvious patterns to detect include “${“ and “#{“, but it may be possible to encode or fragment
this data.
So you can create a 'whitelist' pattern to match for the expression 'evn' before creating a value expression(whitelist can be something like: `[a-zA-Z0-9\_.\*#{}]\*').
```
Pattern pattern = Pattern.compile("[a-zA-Z0-9_\.\*#\{\}]*");
Matcher matcher = pattern.matcher(ev);
if (!matcher.matches()) {
String message = "Detected a potential EL injection attack -
value["
+ ev+ "]";
throw new Exception(message);
}
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 601 | 2,141 | <issue_start>username_0: Despite clearly indicating in esignore that I want to ignore everything inside lib directory, vscode is saying 9 problems found in that minimized file.
If I run eslint inside foldera in command line everything is fine
using this [extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
My directory structure:
```
foldera/
.eslintrc
.eslintignore
src/
file.js
lib/
wantoignore.min.js
folderb/
morefiles.js
.eslintrc
.eslintignore
```
**.eslintrc file**
```
{
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2017,
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"no-console": "off"
}
}
```
**.eslintignore**
```
lib/*
```
workspace settings:
```
"eslint.workingDirectories": [
"./client", "./server"
]
```<issue_comment>username_1: I solved this problem following the [official doc](https://github.com/Microsoft/vscode-eslint#settings-options) here.
Basically you need to add the following content to the vscode workspace settings (usually located in your project's `root/.vscode/settings.json`), so that vscode knows which configs to honor when you're working on a specific script file:
```
{
"eslint.workingDirectories": [ "./reactApp" ],
}
```
Upvotes: 3 <issue_comment>username_2: I had a similar problem, figured out need to set workingDirectory to nested folder:
```
module
lib
src
index.ts
.eslintrc.js
.eslintignore
```
VSCode setting should be:
```
"eslint.workingDirectories": [ "./module/lib" ]
```
And not
```
"eslint.workingDirectories": [ "./module" ]
```
Upvotes: 0 <issue_comment>username_3: My solutions is:
**Source map**
```
root/.vscode/settings.json
```
**Script**
```
{
"eslint.workingDirectories": [{ "mode": "auto" }],
}
```
Upvotes: 1 |
2018/03/22 | 534 | 2,267 | <issue_start>username_0: I am able to host the models developed in *SageMaker* by using the deploy functionality. Currently, I see that the different models that I have developed needs to deployed on different ML compute instances.
Is there a way to deploy all models on the same instance, using separate instances seems to be very expensive option. If it is possible to deploy multiple models on the same instance, will that create different endpoints for the models?<issue_comment>username_1: SageMaker is designed to solve deployment problems in scale, where you want to have thousands of model invocations per seconds. For such use cases, you want to have multiple tasks of the same model on each instance, and often multiple instances for the same model behind a load balancer and an auto scaling group to allow to scale up and down as needed.
If you don’t need such scale and having even a single instance for a single model is not economic for the request per second that you need to handle, you can take the models that were trained in SageMaker and host them yourself behind some serving framework such as MXNet serving (<https://github.com/awslabs/mxnet-model-server> ) or TensorFlow serving (<https://www.tensorflow.org/serving/> ).
Please also note that you have control over the instance type that you are using for the hosting, and you can choose a smaller instance for smaller loads. Here is a list of the various instance types that you can choose from: <https://aws.amazon.com/sagemaker/pricing/instance-types/>
Upvotes: 2 <issue_comment>username_2: I believe this is a new feature introduced in AWS sagemaker, please refer below links which exactly does the same.
Yes, now in AWS sagemaker you can deploy multiple models in same ML instance.
In Below Link,
<https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/>
You can find examples,
* multi\_model\_bring\_your\_own
* multi\_model\_sklearn\_home\_value
* multi\_model\_xgboost\_home\_value
Another link which explains multi-model XGboost in details.
<https://aws.amazon.com/blogs/machine-learning/save-on-inference-costs-by-using-amazon-sagemaker-multi-model-endpoints/>
Hope this helps anyone who is looking to solve this issue in future.
Upvotes: 2 |
2018/03/22 | 710 | 2,333 | <issue_start>username_0: For example, if you wanted to accept say 2 input values it would be something like,
```
x = 0
y = 0
line = input()
x, y = line.split(" ")
x = int(x)
y = int(y)
print(x+y)
```
Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space.
How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.<issue_comment>username_1: You can set a parameter how many values there will be and loop the input and put them into a map - or you make it simple 2 liner:
```
numbers = input("Input values (space separator): ")
xValueMap = list(map(int, numbers.split()))
```
this will create a map of INT values - separated by space.
Upvotes: 1 <issue_comment>username_2: You may want to use a `for` loop to repeatedly get input from the user like so:
```
num_times = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(num_times):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)
```
Then, later on, you can use an `if/elif/else` chain to do different actions to the numbers based on the length of the list (found using the `len()` function).
For example:
```
if len(numbers) == 0:
print("Try again") #Or whatever you want
elif len(numbers) == 1:
print(numbers[0])
else:
print(sum(numbers))
```
Upvotes: 0 <issue_comment>username_3: Try something like this. You will provide how many numbers you want to ask the user to input those many numbers.
```
def get_input_count():
count_of_inputs = input("What is the number you want to count? ")
if int(count_of_inputs.strip()) == 0:
print('You cannot have 0 as input. Please provide a non zero input.')
get_input_count()
else:
get_input_and_count(int(count_of_inputs.strip()))
def get_input_and_count(count):
total_sum = 0
for i in range(1,count+1):
input_number = input("Enter number - %s :"%i)
total_sum += int(input_number.strip())
print('Final Sum is : %s'%total_sum)
get_input_count()
```
Upvotes: 0 |
2018/03/22 | 584 | 2,302 | <issue_start>username_0: I have a question about requests.I make first request then I suppose first onSuccess method will be runnning but program make second request immediately.How can i handle it? `Context.getAlarmGroupById` is called 2 times immediately.
my code:
```
function loadAll () {
Context.getAlarmGroupChainById({
id: $stateParams.id
}, onSuccess, onError);
function onSuccess(data, headers) {
vm.temp=data;
var numberGroupChain=vm.temp.length;
for(var i=0; i= vm.temp.length) {
return;
}
Context.getAlarmGroupById({
id:chainId
}, onSuccess, onError);
function onSuccess(data,headers){
index++;
asyncLoop();
}
function onError(data,headers){
index++;
asyncLoop();
}
}
}
```<issue_comment>username_1: **Firstly:** `Car.getGroupId` is an asynchronous function. So you have to ensure that the previous call is completed, before the next call.
**Secondly:** The recursive function is created for replacing the loop, after the `success` function and index increment, the recursive function is called to ensure your required requirement.
**Third:** Change the calling sequence of `asyncLoop(vm.temp[i].id);` after loop:
**Finally:**
Please use the following code:
```
function loadAll () {
var index = 0;
function asyncLoop(chainId) {
if(index >= vm.temp.length) {
return;
}
Context.getAlarmGroupById({
id:vm.temp[index].id
}, onSuccess, onError);
function onSuccess(data,headers){
index++;
asyncLoop();
}
function onError(data,headers){
index++;
asyncLoop();
}
}
function onSuccessParent(data, headers) {
vm.temp=data;
var numberGroupChain=vm.temp.length;
for(var i=0; i
```
}
Upvotes: 2 [selected_answer]<issue_comment>username_2: Here is the pure JavaScript way to do this and it works perfectly fine. Use [Promise.then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then). Do like below:
```
var request1 = new Promise(function(resolve, reject) {
resolve('Success!');
});
request1.then(function(value) {
// make request2 here
});
```
Upvotes: 0 |
2018/03/22 | 2,753 | 10,144 | <issue_start>username_0: I have a long text like below:
```
$postText="It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.";
```
I want to add readmore hyperlink after 170 characters **without cutting off a word and include a trailing whitespace character**.
My coding attempt:
```
if(strlen($postText)>170){
$splitArr=preg_split("/.{170}\S*\s/",$postText,2);
print_r($splitArr);
exit;
$postText=$splitArr[0]."...[read more](http://example.com/seemore-link)";
}
```
Split array always return the first index as `null`. I checked my regex in [REGEX101](https://regex101.com/r/mHZa0H/1), and it shows exactly what I need. Please point out what is wrong.<issue_comment>username_1: There is no need to use [preg\_split](http://php.net/manual/en/function.preg-split.php) you still can trim the characters with [substr](http://php.net/manual/en/function.substr.php).
```
$postText="It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.";
$limit = 170;
$truncated = substr($postText,0,$limit);
$truncated .= "...[read more](http://example.com/seemore-link)";
var_dump($truncated);
```
[**Demo**](http://sandbox.onlinephpfunctions.com/code/218a27d004629e5c1ccee8378cd487efdec25e94)
Upvotes: -1 <issue_comment>username_2: **Why is `preg_split()` returning an empty string for the first element?**
That is because the pattern that you feed the function dictates where it should explode/break. The matched characters are treated as a "delimiter" and are, in fact, discarded using the function's default behavior.
When your input string has at least 170 characters, then optional non-whitespace characters, then a whitespace character -- all of these matched characters become the delimiter. When `preg_split()` splits a string, it will potentially generate zero-length elements depending on the location of the delimiter.
For instance, if you have a string `aa` and split it on `a`, the function will return 3 empty elements -- one before the first `a`, one between the `a`'s, and one after the second `a`.
Code: ([Demo](http://sandbox.onlinephpfunctions.com/code/64955bd2b348a4d9ef302368559d337988b2bc7b))
```
$string = "aa";
var_export(preg_split('/a/', $string));
// output: array ( 0 => '', 1 => '', 2 => '', )
```
To ensure that no empty strings are generated, you can set the fourth parameter of the function to `PREG_SPLIT_NO_EMPTY` (the 3rd parameter must be declared for the 4th parameter to be recognized).
```
var_export(preg_split('/a/', $string, -1, PREG_SPLIT_NO_EMPTY));
// output: array ( )
```
You *could* add the `PREG_SPLIT_NO_EMPTY` parameter to your function call to remove the empty string, but because the substring that you want to keep is used as the delimiter, it is lost in the process.
---
**A greater matter of importance is the fact that `preg_split()` is not the best tool for this job.**
Your posted snippet:
1. checks if the string qualifies for truncation
2. then it attempts to isolate the leading portion of the text
3. then intends to overwrite `$postText` with the element containing leading portion and concatenates the ellipsis hyperlink.
Fortunately, php has a single function that can do all three of these steps without a conditional -- resulting in a clean, direct line of code.
-----------------------------------------------------------------------------------------------------------------------------------------------
Code: ([Demo](http://sandbox.onlinephpfunctions.com/code/baf51fd102fcdbd5940549e9ecd60e1ed5e8b9bf))
```
$postText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.";
$ellipsis = "...[read more](http://example.com/seemore-link)";
echo preg_replace('/.{170}\S*\s\K.+/', $ellipsis, $postText);
```
The beauty in this call is that if the `$postText` doesn't qualify for truncation because it doesn't have 170 characters, optionally followed by non-whitespace characters, followed by a whitespace character, then nothing happens -- the string remains whole.
The `\K` in the pattern commands that the first ~170 characters are *released/forgotten/discarded* as matched characters. Then the `.+` means *match one or more of any character (as much as possible)*. By this pattern logic, there will only be one replacement executed. `preg_replace()` modifies the `$postText` string without any concatenation syntax.
\*note, if your input string may contain newline characters, you should add the `s` pattern modifier so that the `.` will match *any character including newline characters*. Pattern: `/.{170}\S*\s\K.+/s`
\*if you want to truncate your input string at the end of the word beyond the 170th character, you can use this pattern: `/.{170}\S*\K.+/` and you could add a space at the start of the replacement/ellipsis string to provide some separation.
---
Using a non-regex approach is a bit more clunky and requires a conditional statement to maintain the same level of accuracy (so I don't recommend it, but I'll display the technique anyhow).
Using `substr_replace()`, you need to check if there is enough length in the string to offer a valid offset for `strpos()`. If so, you can replace.
Code: ([Demo](https://3v4l.org/8oHrq))
```
$postText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.";
$ellipsis = "...[read more](http://example.com/seemore-link)";
if (($len = strlen($postText)) > 170 && ($pos = strpos($postText, ' ', 170)) && ++$pos < $len){
$postText = substr_replace($postText, $ellipsis, $pos);
}
echo $postText;
```
The above snippet assumes there are only spaces, in the input string (versus tabs and newline characters which you may want to split on).
Upvotes: 2 <issue_comment>username_3: >
> split array always return the first index as null.
>
>
>
It doesn't return [`NULL`](http://php.net/manual/en/language.types.null.php), it returns an empty [string](http://php.net/manual/en/language.types.string.php) (`''`); they are completely different objects with different semantics.
The reason why the first element of the returned array is an empty string is clearly documented in the manual page of [`preg_split()`](http://php.net/manual/en/function.preg-split.php#refsect1-function.preg-split-returnvalues):
>
> **Return Values:**
>
>
> Returns an array containing substrings of `subject` split along boundaries matched by `pattern`, or `FALSE` on failure.
>
>
>
The regex you provide as the first argument to [`preg_split()`](http://php.net/manual/en/function.preg-split.php) is used to match the delimiter, not the pieces. The function you need is [`preg_match()`](http://php.net/manual/en/function.preg-match.php):
```
$postText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.";
preg_match('/^.{170}\S*/', $postText, $matches);
$postText = $matches[0] . " ...[read more](http://example.com/seemore-link)";
```
If `preg_match()` returns `TRUE`, `$matches[0]` contains the string you need.
There are situations when `preg_match()` fails with your original `regex`. For example, if your input string has exactly 170 characters, the `\s` won't match. This is why I removed the `\s` from the `regex` and added a white space in front of the string appended after the match.
Upvotes: 3 [selected_answer]<issue_comment>username_4: Your regex `.{170}\S*\s` is fine but has a little problem. It doesn't guarantee if `\S*` matches rest of a word as it may match an MD5 - 170 characters up to first character of MD5 hash then matching 31 more characters which could be more than this.
You are treating those 170 characters as a delimiter of `preg_split`, hence you didn't have it in output.
Considering these two things in mind, you may come with a better idea:
```
$array = preg_split('~^[\s\S]{1,170}+(?(?!\S{10,})\S*)\K~', $string);
```
[PHP live demo](https://eval.in/976456)
`10` ensures there is no non-whitespace characters more than that. If exists it splits right after 170 characters.
Accessing to `$array[0]` you could add your read more text to it.
Upvotes: 1 |
2018/03/22 | 984 | 4,077 | <issue_start>username_0: my script :
```
function getAllExperiences(){
return new Promise(function(resolve,reject){
var perPage = 10
var page = req.params.page || 1
var type = req.body.type;
var sortAs = req.body.sortAs;
Experiences
.find({status:'live'})
.sort({type:sortAs})//,{duration:durationValue}
.skip((perPage * page) - perPage)
.limit(perPage)
.exec(function(err, results) {
Experiences.count().exec(function(err, count) {
if (err)
{
reject(err);
}else{
var obj =
{
experiences: results,
current: page,
pages: Math.ceil(count / perPage)
};
resolve(obj);
}
})
})
});
}
```
i am sorting according. **price**, **duration**, **ratings**
when i set
```
var type = 'price';
var sortAs = -1;
```
if i set
```
var type = 'price';
var sortAs = 1;
```
if i set
```
var type = 'duration';
var sortAs = -1;
```
or
```
var type = 'duration';
var sortAs = 1;
```
All condition gives me same result. i thing type is not accepting. what am i doing wrong.<issue_comment>username_1: You should change `.sort({type:sortAs})//,{duration:durationValue}` to
```
var sortDefinition = {};
sortDefinition[type] = sortAs;
//then in pipeline
.sort(sortDefinition)
```
Because in your example it will always try to sort by field with name `type`since it's a key name in that code.
Upvotes: 1 <issue_comment>username_2: ```
function getAllExperiences(){
return new Promise(function(resolve,reject){
var perPage = 10
var page = req.params.page || 1
var type = req.body.type;
var sortAs = Number(req.body.sortAs);
var sort = {};
sort[type] = sortAs;
Experiences
.find({status:'live'})
.sort(sort)//,{duration:durationValue}
.skip((perPage * page) - perPage)
.limit(perPage)
.exec(function(err, results) {
Experiences.count().exec(function(err, count) {
if (err)
{
reject(err);
}else{
var obj =
{
experiences: results,
current: page,
pages: Math.ceil(count / perPage)
};
resolve(obj);
}
})
})
});
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: What you are trying to do is
```
{ type: sortAs }
```
where type is being used as object key, what you should do is
```
{ [type]: sortAs }
```
Here type is being used as variable to create dynamic key for the object. thus this will create.
```
{duration: "-1"}
```
Following code should work for you.
```
function getAllExperiences(){
return new Promise(function(resolve,reject){
var perPage = 10
var page = req.params.page || 1
var type = req.body.type;
var sortAs = req.body.sortAs;
Experiences
.find({status:'live'})
.sort({ [type] : sortAs })//, using es6 for generating dynamic property
.skip((perPage * page) - perPage)
.limit(perPage)
.exec(function(err, results) {
Experiences.count().exec(function(err, count) {
if (err)
{
reject(err);
}else{
var obj =
{
experiences: results,
current: page,
pages: Math.ceil(count / perPage)
};
resolve(obj);
}
})
})
});
}
```
Upvotes: 2 |
2018/03/22 | 536 | 1,923 | <issue_start>username_0: I am building a tool which displays Skype persistent chat information along with participants information. For one of the requirement, I need to filter the tblComplianceParticipant table in a given date range.
I tried many different approaches to convert [tblComplianceParticipant](https://technet.microsoft.com/en-us/library/gg558655.aspx).joinedAt column to human-readable format like 'yyyy-mm-dd', etc. but no luck so far. Data in this column are 18 digit numbers, starting with "63" for example 636572952018269911 and 636455769656388453.
These values are also not in 'windows file time' format because <https://www.epochconverter.com/ldap> gives the future dates with above values.
I tried looking at @JonSkeet's answer on [18 digit timestamp to Local Time](https://stackoverflow.com/questions/26729302/18-digit-timestamp-to-local-time) but that is c# specific. I tried to replicate similar logic in SQL but no luck.
Is there any way to convert this 18 digit numbers to normal date format and perform where clause on it?<issue_comment>username_1: The only thing i can think is worth trying:
```
select CAST ([Timestamp Column] as datetime)
```
Which will format it as yyyy-mm-dd 00:00:00:000
This may work for SQL Server 2008 and onwards
Upvotes: -1 <issue_comment>username_2: Online converter which gives desired output: <https://www.venea.net/web/net_ticks_datetime_converter#net_ticks_to_date_time_and_unix_timestamp_conversion>
However, I was looking for underlying logic to convert it myself as I need to perform where clause on it in SQL server stored procedure.
Our Skype administrator provided me with a SQL function (fnDateToTicks) which was part of Skype database (mgc) (Earlier, I didn't have permission so could not see it). I am verifying with him whether it is an internal IP or standard solution by Microsoft so I can share it with the larger community.
Upvotes: 0 |
2018/03/22 | 425 | 1,738 | <issue_start>username_0: I wrote a clojurescript project. It is a reagent component. Now i want to use this component in other clojurescript project. That is what i do: I compiled my cljs project and then i put a result compiled file to js folder in other project. Further i require that file from index.html. At the end i invoke my component from cljs file
```
(.slider-view (.-views js/swipe) (clj->js [[:p "1"]
[:p "2"]
[:p "3"]]))
```
and it works. But i have a question. My project and project where i connect my component have common requirements. For example React and ReactDOM. How to exclude this two references from my project and then connect it from another project? Is there alternative approaches? For example require cljs namespace from another cljs project directly<issue_comment>username_1: The only thing i can think is worth trying:
```
select CAST ([Timestamp Column] as datetime)
```
Which will format it as yyyy-mm-dd 00:00:00:000
This may work for SQL Server 2008 and onwards
Upvotes: -1 <issue_comment>username_2: Online converter which gives desired output: <https://www.venea.net/web/net_ticks_datetime_converter#net_ticks_to_date_time_and_unix_timestamp_conversion>
However, I was looking for underlying logic to convert it myself as I need to perform where clause on it in SQL server stored procedure.
Our Skype administrator provided me with a SQL function (fnDateToTicks) which was part of Skype database (mgc) (Earlier, I didn't have permission so could not see it). I am verifying with him whether it is an internal IP or standard solution by Microsoft so I can share it with the larger community.
Upvotes: 0 |
2018/03/22 | 2,533 | 4,891 | <issue_start>username_0: I have Multimap. Example:
```
00254=[00255, 2074E, 2074E, 2074E, 2074E, 2074E, 2074E, 00010, 00010, 00010, 0006, 0006, 0006, 00010, R01018, R01018, 0006, 0006, R01018, R01018, R01018, 12062, S2202962, S2202962, R01018, 12062, 20466, 12062, 20466, 22636, 20466, 20466, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 00255, 2074E, 2074E, 2074E, 2074E, 2074E]
00256=[00257, 2074E, 2074E, 2074E, 2074E, 00010, 2074E, 2074E, 0006, 00010, 00010, 00010, 0006, 0006, 0006, R01018, R01018, 0006, R01018, R01018, R01018, 12062, S2202962, S2202962, R01018, 12062, 20466, 12062, 20466, 20466, 20466, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 00257, 2074E, 2074E, 2074E, 2074E, 00010]
```
I want to get the number of value including duplicate value.
* 00254=[00255:2, 2074E:11, 00010:4, 0006:5, R01018:6, ...]
* 00256=[00257:2, 2074E:10, 00010:5, 0006:5, R01018:7, ...]
Is it possible to get duplicate number?
Thanks.<issue_comment>username_1: Solution using Java 8 Stream to get the occurrence for a specific value, simply get the `Collection` for a value, then group on the value and count (using the `Collectors` function) to get a `Map` :
```
Multimap maps = ArrayListMultimap.create();
maps.put(1, "foo");
maps.put(1, "bar");
maps.put(1, "foo");
maps.put(2, "Hello");
maps.put(2, "foo");
maps.put(2, "World");
maps.put(2, "World");
Here is the idea to print the occurences per value :
maps.keySet().stream() //Iterate the `keys`
.map(i -> i + " : " + //For each key
maps.get(i).stream() //stream the values.
.collect( //Group and count
Collectors.groupingBy(
Function.identity(),
Collectors.counting()
)
)
)
.forEach(System.out::println);
```
>
> 1 : {bar=1, foo=2}
>
>
> 2 : {Hello=1, foo=1, World=2}
>
>
>
This will generate a `String`, I let you adapt for your need.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Counting occurrences is a perfect use case for [`Multiset`](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Multiset.html), which is
>
> A collection that supports order-independent equality, like `Set`, but may have duplicate elements. A multiset is also sometimes called a bag.
>
>
> Elements of a multiset that are equal to one another are referred to as occurrences of the same single element.
>
>
>
There are few different [`Multiset` implementations](https://github.com/google/guava/wiki/NewCollectionTypesExplained#implementations) you can choose from, and couple of handy [set-like methods in `Multisets` helper class](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Multisets.html).
Here, you could either 1) collect to multiset or 2) use custom multimap with multiset values.
1. Instead of grouping to map, you can collect an immutable multiset:
```
ImmutableMultiset qtyMultiset = multimap.get(key).stream()
.collect(ImmutableMultiset.toImmutableMultiset());
```
or mutable one:
```
HashMultiset qtyMultiset = multimap.get(key).stream()
.collect(Multisets.toMultiset(Function.identity(), e -> 1, HashMultiset::create));
```
2. Or maybe you can use custom multimap in the first place? (Unfortunately, there isn't any `MultisetMultimap` interface nor implementation, hence need for custom instance):
```
Multimap countingMultimap
= Multimaps.newMultimap(new LinkedHashMap<>(), LinkedHashMultiset::create);
```
You can drop `Linked` part if you don't need to preserve order. For your data:
```
countingMultimap.putAll("00254", ImmutableList.of("00255", "2074E", "2074E", "2074E", "2074E", "2074E", "2074E", "00010", "00010", "00010", "0006", "0006", "0006", "00010", "R01018", "R01018", "0006", "0006", "R01018", "R01018", "R01018", "12062", "S2202962", "S2202962", "R01018", "12062", "20466", "12062", "20466", "22636", "20466", "20466", "22636", "22636", "22636", "22636", "22636", "22636", "22636", "22636", "00255", "2074E", "2074E", "2074E", "2074E", "2074E"));
countingMultimap.putAll("00256", ImmutableList.of("00257", "2074E", "2074E", "2074E", "2074E", "00010", "2074E", "2074E", "0006", "00010", "00010", "00010", "0006", "0006", "0006", "R01018", "R01018", "0006", "R01018", "R01018", "R01018", "12062", "S2202962", "S2202962", "R01018", "12062", "20466", "12062", "20466", "20466", "20466", "22636", "22636", "22636", "22636", "22636", "22636", "22636", "22636", "22636", "00257", "2074E", "2074E", "2074E", "2074E", "00010"));
```
returned multimap would be:
```
{00254=[00255 x 2, 2074E x 11, 00010 x 4, 0006 x 5, R01018 x 6, 12062 x 3, S2202962 x 2, 20466 x 4, 22636 x 9], 00256=[00257 x 2, 2074E x 10, 00010 x 5, 0006 x 5, R01018 x 6, 12062 x 3, S2202962 x 2, 20466 x 4, 22636 x 9]}
```
For more information read [Guava Wiki page about `Multiset`](https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset) (which uses word count as an example).
Upvotes: 2 |
2018/03/22 | 446 | 1,559 | <issue_start>username_0: I am learning ionic and i want to align my 3 buttons in left,center and right. i.e. First button in left, second in center and third one in right.
But I don't know how to do it?
Here is My code.
```
Left Icon
Right Icon
```
Can Anyone guide me with this? As I am a beginner and learning ionic.<issue_comment>username_1: You can achieve this using Grid, ionic provide it [grid link](https://ionicframework.com/docs/api/components/grid/Grid/)
It is based on a 12 column layout with different breakpoints based on the screen size.
By default, columns will take up equal width inside of a row for all devices and screen sizes.
```
1 of 2
2 of 2
1 of 3
2 of 3
3 of 3
```
Set the width of one column and the others will automatically resize around it. This can be done using our predefined grid attributes. In the example below, the other columns will resize no matter the width of the center column.
```
1 of 3
2 of 3 (wider)
3 of 3
1 of 3
2 of 3 (wider)
3 of 3
```
So you also can 3 buttons in left,center and right. i.e. First button in left, second in center and third one in right using grid.
```
First
Second
Third
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: In Ionic 5 you can also use justify classes
```
```
Upvotes: 2 <issue_comment>username_3: Ionic React
===========
I adopted the above solutions which were great thanks, but also I needed to get a smaller button right in the middle which the solution below fixes
```
Left
Middle
Right
```
Upvotes: 1 |
2018/03/22 | 190 | 724 | <issue_start>username_0: I'm trying to replace the standard three dot overflow icon with a text button like "More Pizza", so that users will see the option easily.
Any help is greatly appreciated.<issue_comment>username_1: `app:showAsAction="always"` will display the title of the menu on the toolbar
Upvotes: 0 <issue_comment>username_2: option\_menu.xml
```
xml version="1.0" encoding="utf-8"?
```
In Activity
this below code is of `Kotlin`
don't worry if you using java, Android studio will do it for you. :)
```
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.option_menu, menu)
return true
}
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,175 | 4,088 | <issue_start>username_0: I've been using self-signed certificates in the intranet of my small office and after upgrading to iOS 11, the certificates does not work for me. (Chrome and other browsers are happy with them.)
I've got my self-signed root ca file and converted it to .der file, and installed it onto my iPad via web.
[](https://i.stack.imgur.com/ZtTD3.png)
But unlike this [Answer](https://stackoverflow.com/a/44952986/2101976), I can't see my root ca certificate on the Settings > General > About > Certificate Trust settings.
[](https://i.stack.imgur.com/UUnC6.png)
Is there any limitations for the certificates to be trusted in iOS? Both my iPhone and iPad has this problem. Is there anything wrong in my procedure?
I used these codes to make my ca certificate.
```
openssl genrsa -des3 -out rootCA.key 4096
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.crt
openssl x509 -in rootCA.crt -out cert.der -outform DER
```<issue_comment>username_1: Apparently ios does not like certificates without Common Name, so just regenerate it with non empty CN and it will appear in root certificates list
Upvotes: 1 <issue_comment>username_2: If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.
This is very easy to determine by using openssl:
```
$ openssl s_client -showcerts -connect myserver.com:443
```
This will show you output for certificates in the cert chain, something like this:
```
Certificate chain
0 s:/C=US/ST=California/L=SAN FRANCISCO/O=mycompany.com, inc./OU=InfraSec/CN=myserver.com
i:/C=US/O=mycompany.com, inc./CN=mycompany.com Internal CA 1A
-----BEGIN CERTIFICATE-----
....encoded cert in PEM format....
-----END CERTIFICATE-----
```
And it should show a chain of certs all the way to the ROOT CA. Keep following the output, paying attention to the "i:" value which indicates the ISSUER. Finally, you should get to the ROOT CA and can just copy-paste it to a .pem file (be sure to include the BEGIN CERTIFICATE and END CERTIFICATE lines!). Now you will be able to install it on your simulator by dragging-dropping onto simulator window.
If your ROOT CA is not listed, then find the top level in the output, then export it from Keychain Access.app. This assumes you are able to hit the website via Safari/Chrome, so you will have had to manually trust the website first.
My 'openssl s\_client' output ended with the last cert shown with an issuer like this:
>
> i:/C=US/O=mycompany.com, inc./CN=mycompany.com Internal Root CA 1
>
>
>
I am able to hit the target website successfully via Safari/Chrome, so that means Keychain has it stored and trusts it. So, I just launched Keychain Access.app via Spotlight and typed "mycompany" in the search bar. It showed my certificate (Kind=certificate) for "mycompany.com Internal Root CA 1". I just right clicked and selected "Export" and saved it to a .cer file.
Voila! Now I can drag-n-drop it onto my simulator and the ROOT CA will show up under General->About... and I can enable it.
If, for some reason you need to convert PEM file to DER/CER, just use this command:
```
$ openssl x509 -in myfile.pem -out myfile.der -outform DER
```
Hope this helps, I've had to do this dozens of times and figured it's about time I jot down some notes so I don't keep forgetting.
Upvotes: 2 <issue_comment>username_3: Just use following command then airdrop or send yourself that cert via email.
Make sure to answer all the questions when you see prompts
```
openssl genrsa -out privatekey.pem 1024
openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 1825
openssl pkcs12 -export -out public_privatekey.pfx -inkey privatekey.pem -in publickey.cer
```
I had same issue until I used this command. I don't know why this happens but the command works.
Cheers!
Upvotes: 0 |
2018/03/22 | 1,015 | 4,398 | <issue_start>username_0: I'm using a Firebase Firestore for android to store data. I tried to search data from documents.
**My Firestore structure is:**
Collection (Products) - Document (Auto Generated ID) - Field (NumberOfPeople,OfferStartDate,OfferEndDate,OfferPrice,Location)
I wrote query for search data on those fields.
```
CollectionReference collectionOfProducts = db.collection("Products");
collectionOfProducts
.whereEqualTo("Location", location)
.whereGreaterThanOrEqualTo("OfferPrice", offerPrice)
.whereLessThanOrEqualTo("OfferPrice", offerPrice)
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
.get()
```
I want search result like this: An offer which is between start date and end date, where offer price is greater than equal or less than equal on give price range. This query is not working in android studio.
How to do this in firestore firebase?<issue_comment>username_1: To the best of my knowledge, Firestore only lets you use whereThanOrEqualTo() and whereThan() a [single field](https://firebase.google.com/docs/firestore/query-data/queries) and all other filter operations on other fields can only be whereEqualTo().
Some workarounds for your specific case include -
1) Modifying your query to
```
collectionOfProducts
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereEqualTo("Location", location)
.get()
```
And then performing the subsequent filtering on the result in your app code.
Alternately, you can perform your filter on "OfferPrice" and "Location" in your query and the remaining filters can be applied to the query result.
2) You can use [firebase functions](https://firebase.google.com/docs/functions/) or other server code to write logic that performs customized filtering and fetch the result that way.
Upvotes: 1 <issue_comment>username_2: According to the official documentation regarding Cloud Firestore queries, please note that there some [query limitations](https://firebase.google.com/docs/firestore/query-data/queries#query_limitations):
>
> In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons **must all filter on the same field**.
>
>
>
So a Query object that contains a call to both methods:
```
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
```
Is actually **not** possible, as "OfferStartDate" and "OfferEndDate" are different properties.
The best solution I can think of is to use only one of these method calls and do the other filtering on the client.
Another possible solution might be to use denormalization and duplicate the data
in certain intervals. In this way, you'll always know the time periods and you'll be able to create the corresponding queries.
Upvotes: 2 <issue_comment>username_3: i was having same issue with this, but i found a work around that takes sometime to write.
lets say you want to search for a particular keyword(in this case the value of a field inside a document), and you want firebase to search multiple field instead of just looking for 1 particular field.
this is what you want to do.
```
const searchTerm = document.createElement('input')
db.collection('collection').where('field1', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === '0'){
db.collection('collection').where('field2', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === 0) {
db.collection......and repeat
}
})
}
})
```
in summary, the above code is basically telling js to search for the term again with a different field if the result of the previous query is 0. I know this solution might not be able to work if we have a large quantity of fields. But for folks out there that are working with small number fields, this solution might be able to help.
I really do hope firestore one day would allow such feature, but here is the code it worked fine for me.
the problem I have now is to allow search input to be able to search without have me to complete the word. I do currently have an idea how this would be, but just need some time to put together.
Upvotes: 1 |
2018/03/22 | 1,096 | 4,409 | <issue_start>username_0: I have a search box and group of check boxes as shown below:
```html
{{data.name}}
```
And I have `onSelect` and search function as shown below in my ts file:
```ts
onSelect(data: string, isChecked: boolean) {
this.selectedArray = this.Form.controls.selected;
if(isChecked) {
this.selectedArray.push(new FormControl(data));
} else {
let index = this.selectedArray.controls.findIndex(x => x.value == data)
this.selectedArray.removeAt(index);
}
}
search(searchterm): void {
this.data = this.dataCopy.filter(function(tag) {
return tag.name.toLowerCase().indexOf(searchterm) >= 0;
});
}
```
Now the issue that I am facing is when I check the checkbox and search for the term that doesn't exist and then clearing the search term. On doing so, the checkbox that I have checked does not persist its state.
**EDITED:**
Cloned app <https://stackblitz.com/edit/angular-ck8uvj>. Now If i check test and then I search m keyword. And again i cleared my search box. The checkbox that I have checked is not persisted.<issue_comment>username_1: To the best of my knowledge, Firestore only lets you use whereThanOrEqualTo() and whereThan() a [single field](https://firebase.google.com/docs/firestore/query-data/queries) and all other filter operations on other fields can only be whereEqualTo().
Some workarounds for your specific case include -
1) Modifying your query to
```
collectionOfProducts
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereEqualTo("Location", location)
.get()
```
And then performing the subsequent filtering on the result in your app code.
Alternately, you can perform your filter on "OfferPrice" and "Location" in your query and the remaining filters can be applied to the query result.
2) You can use [firebase functions](https://firebase.google.com/docs/functions/) or other server code to write logic that performs customized filtering and fetch the result that way.
Upvotes: 1 <issue_comment>username_2: According to the official documentation regarding Cloud Firestore queries, please note that there some [query limitations](https://firebase.google.com/docs/firestore/query-data/queries#query_limitations):
>
> In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons **must all filter on the same field**.
>
>
>
So a Query object that contains a call to both methods:
```
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
```
Is actually **not** possible, as "OfferStartDate" and "OfferEndDate" are different properties.
The best solution I can think of is to use only one of these method calls and do the other filtering on the client.
Another possible solution might be to use denormalization and duplicate the data
in certain intervals. In this way, you'll always know the time periods and you'll be able to create the corresponding queries.
Upvotes: 2 <issue_comment>username_3: i was having same issue with this, but i found a work around that takes sometime to write.
lets say you want to search for a particular keyword(in this case the value of a field inside a document), and you want firebase to search multiple field instead of just looking for 1 particular field.
this is what you want to do.
```
const searchTerm = document.createElement('input')
db.collection('collection').where('field1', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === '0'){
db.collection('collection').where('field2', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === 0) {
db.collection......and repeat
}
})
}
})
```
in summary, the above code is basically telling js to search for the term again with a different field if the result of the previous query is 0. I know this solution might not be able to work if we have a large quantity of fields. But for folks out there that are working with small number fields, this solution might be able to help.
I really do hope firestore one day would allow such feature, but here is the code it worked fine for me.
the problem I have now is to allow search input to be able to search without have me to complete the word. I do currently have an idea how this would be, but just need some time to put together.
Upvotes: 1 |
2018/03/22 | 952 | 3,811 | <issue_start>username_0: The following is the code that I have written
What I am trying to run in IDLE is:
```
>>> mike = Frog('Mike', 'yell')
>>> course = RaceCourse()
>>> course.addFrog(julie)
TypeError: addFrog() takes 1 positional argument but 2 were given
```
My code for this specific part:
```
def addFrog(self):
self.turtle.pu()
spacing = 350/(Frog.lastBib+1)
Frog.height -= spacing
self.turtle.goto(-250, Frog.height)
```<issue_comment>username_1: To the best of my knowledge, Firestore only lets you use whereThanOrEqualTo() and whereThan() a [single field](https://firebase.google.com/docs/firestore/query-data/queries) and all other filter operations on other fields can only be whereEqualTo().
Some workarounds for your specific case include -
1) Modifying your query to
```
collectionOfProducts
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereEqualTo("Location", location)
.get()
```
And then performing the subsequent filtering on the result in your app code.
Alternately, you can perform your filter on "OfferPrice" and "Location" in your query and the remaining filters can be applied to the query result.
2) You can use [firebase functions](https://firebase.google.com/docs/functions/) or other server code to write logic that performs customized filtering and fetch the result that way.
Upvotes: 1 <issue_comment>username_2: According to the official documentation regarding Cloud Firestore queries, please note that there some [query limitations](https://firebase.google.com/docs/firestore/query-data/queries#query_limitations):
>
> In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons **must all filter on the same field**.
>
>
>
So a Query object that contains a call to both methods:
```
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
```
Is actually **not** possible, as "OfferStartDate" and "OfferEndDate" are different properties.
The best solution I can think of is to use only one of these method calls and do the other filtering on the client.
Another possible solution might be to use denormalization and duplicate the data
in certain intervals. In this way, you'll always know the time periods and you'll be able to create the corresponding queries.
Upvotes: 2 <issue_comment>username_3: i was having same issue with this, but i found a work around that takes sometime to write.
lets say you want to search for a particular keyword(in this case the value of a field inside a document), and you want firebase to search multiple field instead of just looking for 1 particular field.
this is what you want to do.
```
const searchTerm = document.createElement('input')
db.collection('collection').where('field1', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === '0'){
db.collection('collection').where('field2', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === 0) {
db.collection......and repeat
}
})
}
})
```
in summary, the above code is basically telling js to search for the term again with a different field if the result of the previous query is 0. I know this solution might not be able to work if we have a large quantity of fields. But for folks out there that are working with small number fields, this solution might be able to help.
I really do hope firestore one day would allow such feature, but here is the code it worked fine for me.
the problem I have now is to allow search input to be able to search without have me to complete the word. I do currently have an idea how this would be, but just need some time to put together.
Upvotes: 1 |
2018/03/22 | 1,407 | 4,743 | <issue_start>username_0: I'm trying to create some JavaScript code that listens for a click event on an element base on it's class name. This triggers a function that changes the class of the same element, allowing that elements click event to trigger a different function in order to achieve a toggle effect for a button.
However while the initial click event is successful and triggers the function, changing the class name of the element does not cause JavaScript to trigger the new function and instead it's sticking with the original function.
```
function tioDisable(e) {
var tioButton = document.getElementById(e.explicitOriginalTarget.name + '-tioButton');
tioButton.classList.remove('tio-enable');
tioButton.classList.add('tio-disable');
}
var tioDis = document.getElementsByClassName('tio-disable');
for (var i = 0; i < tioDis.length; i++) {
tioDis[i].addEventListener('click',tioDisable);
}
function tioEnable(e) {
var tioButton = document.getElementById(e.explicitOriginalTarget.name + '-tioButton');
tioButton.classList.add('tio-enable');
tioButton.classList.remove('tio-disable');
}
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
`
```
I originally tried with querySelectorAll but I read in research that this created effectively a static list of elements, my research indicates that using getElementsByClassName should create a dynamic list however this is not working for me. Is there a better way of doing this?<issue_comment>username_1: When the code runs for the first time, it will add the `click` event based on the following codes. Because the initial code have the class `tio-enable`.
```
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
```
Now if you click the image, it will call the following function.
```
function tioEnable(e) {
var tioButton = document.getElementById(e.explicitOriginalTarget.name + '-tioButton');
tioButton.classList.add('tio-enable');
tioButton.classList.remove('tio-disable');
}
```
In the above code, you are adding the classname `tio-enable`, which is already having and removing `tio-disable`. So nothing changed from your original content. So this will execute the same scenario again and again.
So what you have to do either change the `click` event listener to `tioDisable` or inside the `tioEnable` function you have to add the class `tio-Disable` and remove the class `tio-Enable`.
Will it work now? **NO.** Because after changing the classnames you didn't bind any event. Still it is binded with the old click listener. So you have to bind the `click` listener for the `tioDisable` classes and do the same for the other function also. Check the below snippet.
```js
function tioDisable(e) {
var tioButton = document.getElementById(e.target.name + '-tioButton');
console.log("called to Disable");
tioButton.classList.remove('tio-enable');
tioButton.classList.add('tio-disable');
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
}
function tioEnable(e) {
var tioButton = document.getElementById(e.target.name + '-tioButton');
console.log("called to Enable");
tioButton.classList.add('tio-disable');
tioButton.classList.remove('tio-enable');
var tioDis = document.getElementsByClassName('tio-disable');
for (var i = 0; i < tioDis.length; i++) {
tioDis[i].addEventListener('click',tioDisable);
}
}
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
```
```css
.tio-enable {
border:2px solid green;
padding:10px;
}
.tio-disable {
border:2px solid red;
padding:10px;
}
```
```html

```
May be there will be simple solution for this. But as per your code, I have given my solution.
Upvotes: 1 <issue_comment>username_2: Can you try this? I think this is what you need.
```
function tioToggle(e) {
var tioButton = e.currentTarget;
tioButton.classList.toggle('tio-enable');
tioButton.classList.toggle('tio-disable');
}
var tioDis = document.getElementsByClassName('tio-disable');
for (var i = 0; i < tioDis.length; i++) {
tioDis[i].addEventListener('click', tioToggle);
}
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click', tioToggle);
}
```
[@username_1 answer](https://stackoverflow.com/a/49422666/2928793) explains why your code was not working.
Upvotes: 0 |
2018/03/22 | 3,268 | 12,722 | <issue_start>username_0: I want to send file attachments in mail using PHP. Below is code I am using which is working but each time loop gets executed the mails are going in separate attachments.
```
/*Uploading docs Array*/
$otherdoc_name = array($_FILES[ 'otherdoc' ][ 'name' ]);
$otherdocCount = count( $_FILES[ 'otherdoc' ][ 'name' ]);
// print_r($otherdocCount); exit();
for ( $i = 0; $i < $otherdocCount; $i++ ) {
//Get the temp file path
$tmpFilePath = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
$i_names = $_FILES[ 'otherdoc' ][ 'name' ][ $i ];
$i_sizes = $_FILES[ 'otherdoc' ][ 'size' ][ $i ];
$i_errors = $_FILES[ 'otherdoc' ][ 'error' ][ $i ];
$i_tmp_names = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
$i_types = $_FILES[ 'otherdoc' ][ 'type' ][ $i ];
$exts = pathinfo( $i_names, PATHINFO_EXTENSION );
$msgs = '';
if ( $i_errors == 0 ) {
if ( $i_sizes > 0 ) {
$otherdoc_name[$i] = rand() . '.' . $exts;
$paths = $folder . $otherdoc_name[$i];
$uploads = copy( $i_tmp_names, $paths );
if ( $uploads ) {
$otherdoc_name[$i] = $otherdoc_name[$i];
/*Mail Function*/
if(isset($otherdoc_name))
{
$from_email = '<EMAIL>'; //from mail, it is mandatory with some hosts
$recipient_email = '<EMAIL>'; //recipient email (most cases it is your personal email)
//Capture POST data from HTML form and Sanitize them,
$sender_name = filter_var($_POST["sender_name"], FILTER_SANITIZE_STRING); //sender name
$reply_to_email = filter_var($_POST["sender_email"], FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING); //get subject from HTML form
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //message
/* //don't forget to validate empty fields
if(strlen($sender_name)<1){
die('Name is too short or empty!');
}
*/
//Get uploaded file data
$file_tmp_name = $tmpFilePath;
$file_name = $i_names;
$file_size = $i_sizes;
$file_type = $i_types;
$file_error = $i_errors;
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$reply_to_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
$sentMail = @mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo 'Thank you for your email';
}else{
die('Could not send mail.');
}
}
/* End Mail Function*/
} else {
$otherdoc_name[$i] = '';
}
} else {
$otherdoc_name[$i] = '';
}
} else {
$otherdoc_name[$i] = '';
}
}
```
I am uploading this files to one folder at present now. Can I send files without uploading directly ?
I want all files should be sent as one mail. Or any other different logic suggestions for me. Please help me out.<issue_comment>username_1: ```
/*Uploading docs Array*/
$otherdoc_name = array($_FILES[ 'otherdoc' ][ 'name' ]);
$otherdocCount = count( $_FILES[ 'otherdoc' ][ 'name' ]);
$from_email = '<EMAIL>'; //from mail, it is mandatory with some hosts
$recipient_email = '<EMAIL>'; //recipient email (most cases it is your personal email)
//Capture POST data from HTML form and Sanitize them,
$sender_name = filter_var($_POST["sender_name"], FILTER_SANITIZE_STRING); //sender name
$reply_to_email = filter_var($_POST["sender_email"], FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING); //get subject from HTML form
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //message
$headers = "MIME-Version: 1.0\r\n";
// print_r($otherdocCount); exit();
for ( $i = 0; $i < $otherdocCount; $i++ ) {
//Get the temp file path
$tmpFilePath = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
$i_names = $_FILES[ 'otherdoc' ][ 'name' ][ $i ];
$i_sizes = $_FILES[ 'otherdoc' ][ 'size' ][ $i ];
$i_errors = $_FILES[ 'otherdoc' ][ 'error' ][ $i ];
$i_tmp_names = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
$i_types = $_FILES[ 'otherdoc' ][ 'type' ][ $i ];
$exts = pathinfo( $i_names, PATHINFO_EXTENSION );
$msgs = '';
if ( $i_errors == 0 ) {
if ( $i_sizes > 0 ) {
$otherdoc_name[$i] = rand() . '.' . $exts;
$paths = $folder . $otherdoc_name[$i];
$uploads = copy( $i_tmp_names, $paths );
if ( $uploads ) {
$otherdoc_name[$i] = $otherdoc_name[$i];
/*Mail Function*/
if(isset($otherdoc_name))
{
/* //don't forget to validate empty fields
if(strlen($sender_name)<1){
die('Name is too short or empty!');
}
*/
//Get uploaded file data
$file_tmp_name = $tmpFilePath;
$file_name = $i_names;
$file_size = $i_sizes;
$file_type = $i_types;
$file_error = $i_errors;
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//header
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$reply_to_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
/* End Mail Function*/
} else {
$otherdoc_name[$i] = '';
}
} else {
$otherdoc_name[$i] = '';
}
} else {
$otherdoc_name[$i] = '';
}
}
$sentMail = @mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo 'Thank you for your email';
}else{
die('Could not send mail.');
}
```
You can simply take the mail function outside the loop? Try above code. Please ignore syntax errors as I have not tested it. But you can follow the logic.
Update
------
Working script in core PHP to send multiple attachments in single mail.
```
php
/** Mail with attachment */
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $bcc, $subject, $message){
$uid = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$uid}x";
$header = "From: ".$from_name." <".$from_mail."\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$mime_boundary."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= nl2br($message)."\r\n\r\n";
$header .= "--".$mime_boundary."\r\n";
foreach($filename as $k=>$v){
$file = $path.$v;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "Content-Type: application/octet-stream; name=\"".$v."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$v."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$mime_boundary."--"."\r\n";
}
if (mail($mailto, $subject, "", $header)) {
//echo "mail send ... OK"; // or use booleans here
return true;
} else {
//echo "mail send ... ERROR!";
return false;
}
}
?>
```
Upvotes: 0 <issue_comment>username_2: Please use PHPMailer, that would be really easy to integrate it into your application.
Download the PHPMailer script from here: <http://github.com/PHPMailer/PHPMailer>
Extract the archive and copy the `src` folder to a convenient place in your project.
Now, sending emails with attachments incredibly easy:
```
require 'phpmailer/src/PHPMailer.php';
use PHPMailer\PHPMailer\PHPMailer;
$email = new PHPMailer();
$email->From = '<EMAIL>';
$email->FromName = '<NAME>';
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->addAddress('<EMAIL>');
$email->addAttachment('PATH_TO_YOUR_FILE_HERE');
return $email->send();
```
It's just that one line: `$email->addAttachment();`
Upvotes: 2 [selected_answer] |
2018/03/22 | 433 | 1,342 | <issue_start>username_0: The HTML structure is this:
```
[](someurl)
```
The code to extract the text:
```
buyers = doc.xpath("//div[@class='image']/a[0]/text()")
```
The output is:
```
[]
```
What did I do wrong?<issue_comment>username_1: Use `@href` to get the value of `href` attribute.
```
buyers = doc.xpath("//div[@class='image']/a[0]/@href")
```
Upvotes: 2 <issue_comment>username_2: Using `attrib['href']` should help.
```
s = """
[](someurl)
"""
from lxml import etree
tree = etree.HTML(s)
r = tree.xpath("//div[@class='image']/a")
print(r[0].attrib['href'])
```
**Output:**
```
someurl
```
Upvotes: 0 <issue_comment>username_3: `/text()` means you are getting text inside that tag, in order to get any attribute's value, do `/@attribute`, so in your case, do `doc.xpath("//div[@class='image']/a[0]/@href")`
Upvotes: 0 <issue_comment>username_4: Your XPath is incorrect because the indexation in XPath (unlike in most programming languages) starts from `1`, but not from `0`!
So correct XPath should be
```
//div[@class='image']/a[1]/@href
```
Note that `a[1]` used instead of `a[0]`
Also `text()` should be used to extract text node. If you need to extract value of specific attribute, you should use `@attribute_name` syntax or `attribute::attribute_name`
Upvotes: 3 |
2018/03/22 | 590 | 2,126 | <issue_start>username_0: ```
#include
using namespace std;
class student
{
string name;
string reg;
public:
void getdata()
{
getline(cin,name);
getline(cin,reg);
}
void printdata()
{
cout<
```
I am trying a basic read and write operation of file handling of objects.
But after executing the above code I am successfully able to write and read but I get an error message `*** Error in ./io: free(): invalid size: 0x00007ffea93f64b0 ***Aborted (core dumped)`
Input:
Fire Blade
, 17HFi394
Output:
Fire Blade , 17HFi394
and an error message : `*** Error in ./io: free(): invalid size: 0x00007ffea93f64b0 ***Aborted (core dumped)`
Can anyone explain this error and what should I do to overcome this problem.<issue_comment>username_1: The problem is because you write a raw `std::string` object to a file, and then read it again. That leads to *undefined behavior*.
This doesn't work because a `std::string` is basically (and simplified) just a pointer to the actual string data. When you write the string object, you write the pointer, and when you read the object back from the file, you read the pointer. The problem is that now you have *two* string object both pointing to the same data. When the first object goes out of scope and is destructed, it will free the string data, leaving the other object with an invalid pointer to data that is no longer owned by your process. When that second object is destructed it will try to free the already free'd data.
And this is only when you save and load the object in a single process. It's even worse if you attempted to load the object in a different process (even if it's the same program), and for modern virtual memory system no two process have the same memory maps.
To save data to a file you should do research about [*serialization*](https://en.wikipedia.org/wiki/Serialization).
Upvotes: 3 [selected_answer]<issue_comment>username_2: std::string size is variable, try the following code:
```
```
char name[256];
char reg[256];
void getdata()
{
std::cin.getline(name, sizeof(name));
std::cin.getline(reg, sizeof(reg));
}
```
```
Upvotes: 0 |
2018/03/22 | 430 | 1,473 | <issue_start>username_0: I want to achieve the JSON transformation using the Jolt processor. I have fields with null in my JSON and I would like to remove all these fields...
```json
{
"myValue": 345,
"colorValue": null,
"degreeDayValue": null,
"depthValue": null,
"distanceValue": null
}
```
...to just keep the `myValue` field.
Can I realize this with a Jolt operation removed?<issue_comment>username_1: It is possible, just not straightforward. Requires two steps.
**Spec::**
```json
[
{
"operation": "default",
"spec": {
// for all keys that have a null value
// replace that null value with a placeholder
"*": "PANTS"
}
},
{
"operation": "shift",
"spec": {
// match all keys
"*": {
// if the value of say "colorValue" is PANTS
// then, match but do nothing.
"PANTS": null,
// otherwise, any other values are ok
"*": {
// "recreate" the key and the non-PANTS value
// Write the value from 2 levels up the tree the "@1"
// to the key from 3 levels up the tree => "&2".
"@1": "&2"
}
}
}
}
]
```
**Produces:**
```json
{
"myValue": 345
}
```
Upvotes: 2 <issue_comment>username_2: To remove `null` values from the internal array use the below spec at the end of your code:
```json
{
"operation": "modify-overwrite-beta",
"spec": {
"*": "=recursivelySquashNulls"
}
}
```
Upvotes: 3 |
2018/03/22 | 563 | 2,122 | <issue_start>username_0: I am trying to edit an exam object but I am getting this error:
Failed to read HTTP message. Required request body is missing.
I believe the error is that You can't send a request body with an HTTP GET request but I don't know how to do it instead.
The user selects an exam to edit and I want the HTML to pass that examId to the controller.
My Controller:
```
@RequestMapping(value = "/editExam.html{examId}", method = {
RequestMethod.GET, RequestMethod.PUT })
public String editExam(@ModelAttribute("exam") @PathVariable(value =
"examId")Long examId, @RequestBody Exam exam,Model model, BindingResult
result) {
examRepository.findOne(examId);
model.addAttribute("examTitle", exam.getExamTitle());
model.addAttribute("examGradeWorth", exam.getExamGradeWorth());
model.addAttribute("examGradeAchieved", exam.getExamGradeAchieved());
exam.setExamTitle(exam.getExamTitle());
exam.setExamGradeWorth(exam.getExamGradeWorth());
exam.setExamGradeAchieved(exam.getExamGradeAchieved());
examRepository.save(exam);
return "editExam";
}
```
editExam.html:
```
| | |
| --- | --- |
| Exam Title: | |
| Exam grade worth | |
| examGradeAchieved | |
| Submit post |
```<issue_comment>username_1: I fixed the error by changing the start of the controller to this:
```
@RequestMapping(value = "/editExam.html/id={examId}", method = { RequestMethod.GET , RequestMethod.POST, RequestMethod.PUT})
```
Upvotes: 0 <issue_comment>username_2: As per best-practices of designing/creating REST APIs, it is advisable that...
* when you are adding any new resource in DB, use `POST` HTTP method
* When you are updating an existing resource, use `PUT` HTTP method
* When you are retrieving resources, use `GET` HTTP method
* When you are deleting any resource, use `DELETE` HTTP method
So in your case, you should use `PUT` HTTP method instead of `GET` while you are updating a resource (exam in your case), and anyway, `GET` HTTP method does not allow user to add a request-body in HTTP request.
Upvotes: 1 |
2018/03/22 | 362 | 1,197 | <issue_start>username_0: We have tried this way. But it is not working. please any one tell alternative method in wordpress
```
$wpdb->query("UPDATE ".$wpdb->prefix."recommend_bets SET `title`='".mysqli_real_escape_string($title)."',`category`='".$catID."',....
```<issue_comment>username_1: When working with database in WordPress you should never use the low lever mysql\_\* or mysqli\_\* functions.
Always use $wpdb methods, in your case you should use [prepare()](https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks):
```
php
$wpdb-query( $wpdb->prepare(
"UPDATE ".$wpdb->prefix."recommend_bets
SET title = %s,
titleb = %s
WHERE ID = %d
",
'static', 'static2', 7
) );
// Or
$wpdb->update(
'table',
array(
'column1' => 'value1', // string
'column2' => 'value2' // integer (number)
),
array( 'ID' => 1 ),
array(
'%s', // value1
'%d' // value2
),
array( '%d' )
);
?>
```
Upvotes: 2 <issue_comment>username_2: You can use `wpdb::_real_escape( string $string )` function.
<https://developer.wordpress.org/reference/classes/wpdb/_real_escape/>
Upvotes: 0 |
2018/03/22 | 322 | 1,075 | <issue_start>username_0: I am beginner developer. How can I get the cursor blinking on a text box on page load using the ajax function in jQuery?<issue_comment>username_1: When working with database in WordPress you should never use the low lever mysql\_\* or mysqli\_\* functions.
Always use $wpdb methods, in your case you should use [prepare()](https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks):
```
php
$wpdb-query( $wpdb->prepare(
"UPDATE ".$wpdb->prefix."recommend_bets
SET title = %s,
titleb = %s
WHERE ID = %d
",
'static', 'static2', 7
) );
// Or
$wpdb->update(
'table',
array(
'column1' => 'value1', // string
'column2' => 'value2' // integer (number)
),
array( 'ID' => 1 ),
array(
'%s', // value1
'%d' // value2
),
array( '%d' )
);
?>
```
Upvotes: 2 <issue_comment>username_2: You can use `wpdb::_real_escape( string $string )` function.
<https://developer.wordpress.org/reference/classes/wpdb/_real_escape/>
Upvotes: 0 |
2018/03/22 | 832 | 3,270 | <issue_start>username_0: If I want to implement Angularjs 4 or 2 with Laravel 5.5 (angular will consume the API from laravel), what should be the best method? 1) Should I create two folders in xampp/htdocs like c:/xampp/htdocs/test-laravel55 and c:/xampp/htdocs/test-angular4 OR 2) Should I create a project of laravel 5.5 like c:/xampp/htdocs/test-laravel55 and put the angularjs4 (e2e, node\_modules, src) files & folders into test-laravel55?
If method 1 is better, can you kindly recommend me some links/ videos to understand how will be the process like CRUD operations, Auth login, etc. Also, if method 2 is better, can you suggest me some links/ videos about the procedure / tutorials, CRUD operations, Auth login etc?
My main moto is "admin user" can login to the admin panel and create some CRUD operations like category creation, product creation etc.<issue_comment>username_1: my approach is to make 2 completely separate projects one for Laravel and you should put it in your localhost root
and the other is for Angular and you can put it anywhere
**Laravel Project**
you will work only with routes and controllers no views required and for sure connecting to database, you can use Postman to test your REST APIs and functionality.
**Angular Project**
you will handle all front-end routes and views here you just call your back-end APIs (laravel project) to get and set data.
when you build the Angular project via `ng build` it will create a folder called `dist` this folder is the client side for your project you should point to it with you domain name once you deploy your project on any hosting service provider and for the Laravel project you may point to it with a subdomain
***Example***
you created a laravel project and hosted it at *app.yourwebsite.com*
you created an Angular project and build it then uploaded the dist folder to *yourwebsite.com*
now when a user hits *yourwebsite.com*
he will see the front-end of your angular app then in behind it calls *app.yourwebsite.com* via HTTP requests to get/set data
you can find more useful info and examples here <https://laravel-angular.io/>
**Answering your questions**
1- dist folder is created via `ng build`
2- you will upload the dist folder only as it contain all compiled angular app
3- any hosting server will be accepted because you will host JS/HTML files only so you don't need any compilers or nodejs/npm environment
Upvotes: 4 [selected_answer]<issue_comment>username_2: what if you want to:
have laravel website at: <http://site.localhost>
and have an Angular admin inside that, at: <http://site.localhost/admin>
I tried to put resources at root of laravel public (assets & js), make my view in resources/views/admin with:
```
Route::get('/admin', function () {
View::addExtension('html', 'php');
return View::make('admin.index');
} )->name('admin');
```
and build with `ng build --prod --aot --base-href /admin`
the problem is now that the base href also applies to CSS, so loading fontawesome looks for: <http://site.localhost/admin/assets/fonts/fontawesome-webfont.ttf?v=4.7.0>
but my assets are on root of public not inside "admin", and if I add an "admin" folder inside public, I get a 'Forbidden' page on site.localhost/admin...
Upvotes: 0 |
2018/03/22 | 433 | 1,184 | <issue_start>username_0: I am using Randtool box package of R to generate Quasi random sequences .
E.g
```
Halton(2,dim=2)
Sobol(3,dim=3)..
```
but i am getting these sequences within `[0,1]` intervals.
For halton`(3,dim=3)` i am getting the following out put
```
0.50 0.3333333 0.2
0.25 0.6666667 0.4
0.75 0.1111111 0.6
```
As we can clearly seen sequences are in `[0,1]` interval. How can we generate these quasi random sequences with customize interval e.g `[-6,6]`?
For example we have random uniform function runif`(6,min=-6,max=6) this will give the random sequences between the interval`[-6,6]`.
Any help will be appreciated.
Thanks!<issue_comment>username_1: If you get a random value a in the range [0, 1] and you want it to be in the range [x, y], do this:
b = a \* (y - x) + x
for [-6, 6] you'll get:
b = a \* (6 - (-6)) + (-6) = a \* 12 - 6
This value will be between -6 and 6.
Upvotes: 2 [selected_answer]<issue_comment>username_2: To transform a [0,1] interval to [-6, 6], first multiply by 12 to get [0,12] and then subtract 6 to shift the interval to [-6, 6]. In short multiply every result from Halton or Sobol by 12, then subtract 6.
Upvotes: 0 |
2018/03/22 | 789 | 2,409 | <issue_start>username_0: I have this php code:
```
php
$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
if(!in_array($animal, $B)) {
echo "$animal doesn't exist<br";
}
}
?>
```
But the if statement never executes. What I'm I doing wrong? What is the proper way to check if a value **doesn't** exist in array?<issue_comment>username_1: ```
php
$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($B as $animal) {
if(!in_array($animal, $A)) {
echo "$animal doesn't exist<br";
}
}
?>
```
Output: `rat doesn't exist`
Upvotes: 2 [selected_answer]<issue_comment>username_2: you need to check exist or not like this
```
php
$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
if(in_array($animal, $B)) {
echo "exist";
}
else{
echo 'not exist';
}
}
?
```
Upvotes: 0 <issue_comment>username_3: Try the below to check which exist and which doesn't.
```
php
$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
if(in_array($animal, $B)) {
echo "$animal exists in \$B<br/";
}
else{
echo "$animal does not exist in \$B
";
}
}
?>
```
Upvotes: 0 <issue_comment>username_4: With use of php `in_array()` and `ternary operator`.
```
$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
$result[] = in_array($animal, $B) ? "$animal exist": "$animal does not exist";
}
var_dump($result);
```
Upvotes: 2 <issue_comment>username_5: Your condition is true every time because all elements of array `A` exists in array `B`. Try adding a new element and then see.
```
php
$A=['dog', 'cat', 'monkey', 'kite'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
if(!in_array($animal, $B)) {
echo "$animal doesn't exist<br";
} else {
echo "$animal exist
";
}
?>
```
Think the logic first before implementing a program.
Upvotes: 0 <issue_comment>username_6: ```
php /*try this function,,
array_key_exists(array_key, array_name)*/
$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
if(array_key_exists($animal, $B)) {
echo "$animal doesn't exist<br";
} else{echo"$animal doesnot exit
";}
```
Upvotes: -1 |
2018/03/22 | 290 | 1,161 | <issue_start>username_0: After doing some [researches](https://stackoverflow.com/questions/45470794/force-outlook-add-in-popup-to-open-with-embedded-browser), I know you may suggest me to use Dialog API for showing the popup. However, the problem is still here if the target website to show is not IE friendly. For Windows client, it is obvious that the dialog API is based on IE engine (, which is not developer friendly). Also, is that really strange that the add-in can even override the setting of user PC?
Ultimately, other than Dialog API, are there any ways for me to open the link from Outlook add-in with selected browser?<issue_comment>username_1: I have attached photo here
[](https://i.stack.imgur.com/F9mLE.png)
Select Manifesto containing project and then hit on F4 button. you will see properties window. Then change Start Action value from dropdown
Upvotes: 0 <issue_comment>username_2: You can use window.open to open the default browser from Desktop Outlook, however this window will be unable to communicate back to your add-in via messageParent and the like.
Upvotes: 1 |
Subsets and Splits