问:
Loop through data in javascript
I am trying to display data in a chart. and I have data passed from my controller as below.

```<code>0: {label: "500", backgroundColor: "rgb(102,205,170,0.5)", borderColor: "rgb(102,205,170,0.5)", data: "13,49,2,2"}
1: {label: "1000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "40,2,41,4"}
2: {label: "1500", backgroundColor: "rgb(112,128,144,0.5)", borderColor: "rgb(112,128,144,0.5)", data: "3,41,0,8"}
3: {label: "2000", backgroundColor: "rgb(220,20,60,0.5)", borderColor: "rgb(220,20,60,0.5)", data: "28,30,40,43"}
4: {label: "2500", backgroundColor: "rgb(240,230,140,0.5)", borderColor: "rgb(240,230,140,0.5)", data: "0,6,20,14"}
5: {label: "3000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "31,26,31,32"}
</code>```

now I want to loop through the data so the result is like

```<code>label: '500',
backgroundColor: rgb(102,205,170,0.5),
borderColor: rgb(102,205,170,0.5),
data: [
    26,2,41,13
],
...
</code>```

What I have tried is as follows

```<code>for (const [key, value] of Object.entries(dataChart)) {
     console.log(key.borderColor);
}
</code>```

here i have am only trying to display borderColor but it says `undefined'

Any help will be appreciated.

答:
When using Object.entries and destructuring each iteration to [key, value], key is the actual key of the current iteration: 0, 1, 2 ... and value if the actual object.

Then if you want to get borderColor :

for (const [key, value] of Object.entries(dataChart)) {
     console.log(value.borderColor); // borderColor is an attribut of value, not key
}
```

Title: Loop through data in javascript

Body:
I am trying to display data in a chart. and I have data passed from my controller as below.

0: {label: "500", backgroundColor: "rgb(102,205,170,0.5)", borderColor: "rgb(102,205,170,0.5)", data: "13,49,2,2"}
1: {label: "1000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "40,2,41,4"}
2: {label: "1500", backgroundColor: "rgb(112,128,144,0.5)", borderColor: "rgb(112,128,144,0.5)", data: "3,41,0,8"}
3: {label: "2000", backgroundColor: "rgb(220,20,60,0.5)", borderColor: "rgb(220,20,60,0.5)", data: "28,30,40,43"}
4: {label: "2500", backgroundColor: "rgb(240,230,140,0.5)", borderColor: "rgb(240,230,140,0.5)", data: "0,6,20,14"}
5: {label: "3000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "31,26,31,32"}

now I want to loop through the data so the result is like

label: '500',
backgroundColor: rgb(102,205,170,0.5),
borderColor: rgb(102,205,170,0.5),
data: [
    26,2,41,13
],
...

What I have tried is as follows

for (const [key, value] of Object.entries(dataChart)) {
     console.log(key.borderColor);
}

here i have am only trying to display borderColor but it says `undefined'

Any help will be appreciated.


来源: stackexchange

问:
Class diagram - Confused about UML association multiplicity

I am little confused about how multiplicity works.

Let's i have a system where the user signs up, fills details about themselves and after signing up they have to fill details separately about their relative.

My question :

I want to indicate that for every User class there is only one Relative class and same backwards.

But what if there are many Users objects and each one is connected to their Relative class

so shouldn't the association be 1..* ?

答:
every User class there is only one Relative class and same backwards.

This sentence is probably the root cause of your confusion. You actually modeled the following:
for every instance of User class there is only one instance of Relative class and same backwards.

ContentLicense: CC BY-SA 4.0


问:
ggplot2 error: missing value where TRUE/FALSE needed. I have no idea
I am taking an online R class in Udemy, here is the code for a Linear regression visualization. I got the error message from the last command. The data from the website about bikesharing: https://www.kaggle.com/c/bike-sharing-demand/data

The data looks like:

```<code>bike <- read.csv("train.csv")
library(ggplot2)
bike$datetime <- as.POSIXct(bike$datetime)
pl <- ggplot(bike, aes(datetime, count)) + geom_point(aes(color = temp),alpha = 0.5)
pl
print(pl)
pl + scale_color_continuous(low='#55D8CE',high='#FF6E2E') +theme_bw()
cor(bike[,c('temp','count')])
ggplot(bike,aes(factor(season),count)) + geom_boxplot(aes(color=factor(season))) +theme_bw()
bike$hour <- sapply(bike$datetime,function(x){format(x,"%H")})
library(dplyr)
pl <- ggplot(filter(bike,workingday==1),aes(hour,count))
pl <- pl + geom_point()
pl
pl <- pl + scale_color_gradientn(colours = c('dark blue','blue','light blue','light green','yellow','orange','red'))
</code>```

the pl looks like:

I got the error message from the last command when I was trying to add colors:
Error in if (!alpha || all(lab_in[, 4] == 1)) { :
  missing value where TRUE/FALSE needed

I have no idea how to solve the problem, anyone can help? thank you so much.

答: I got the same error here. Changing the colour word with a space to hex code solved it for me, e.g. I used scale_colour_gradientn(colours=c("#000066","blue","#b0cceb","#6dcf72","yellow","orange","red"))

Body:
I am taking an online R class in Udemy, here is the code for a Linear regression visualization. I got the error message from the last command. The data from the website about bikesharing: https://www.kaggle.com/c/bike-sharing-demand/data

The data looks like:

bike <- read.csv("train.csv")
library(ggplot2)
bike$datetime <- as.POSIXct(bike$datetime)
pl <- ggplot(bike, aes(datetime, count)) + geom_point(aes(color = temp),alpha = 0.5)
pl
print(pl)
pl + scale_color_continuous(low='#55D8CE',high='#FF6E2E') +theme_bw()
cor(bike[,c('temp','count')])
ggplot(bike,aes(factor(season),count)) + geom_boxplot(aes(color=factor(season))) +theme_bw()
bike$hour <- sapply(bike$datetime,function(x){format(x,"%H")})
library(dplyr)
pl <- ggplot(filter(bike,workingday==1),aes(hour,count))
pl <- pl + geom_point()
pl
pl <- pl + scale_color_gradientn(colours = c('dark blue','blue','light blue','light green','yellow','orange','red'))

the pl looks like:

I got the error message from the last command when I was trying to add colors:
Error in if (!alpha || all(lab_in[, 4] == 1)) { :
  missing value where TRUE/FALSE needed

I have no idea how to solve the problem, anyone can help? thank you so much.


答: What you need to do is value.borderColor instead of key.borderColor

Title: Loop through data in javascript


问:
(Kotlin) How to save hashmap output to file
I am having trouble writing the contents of my hashmap to a file when I select the option. I have successfully read from a file, and utilized various functions to adjust my catalog of products. However, every time I choose my save option. The file clear minus 1 of the products.

Thank you. I appreciate any help in regards to solving this issue.

答:
You should close the file printer after writing all the records to the file.

Move fd.close() out of the for-loop.

```<code>for (record in products) {
    fd.println("${record.key},${record.value.first},${record.value.second}")
    // fd.close() << from here
}
fd.close() // to here
</code>```

Body:
You should close the file printer after writing all the records to the file.

Move fd.close() out of the for-loop.

for (record in products) {
    fd.println("${record.key},${record.value.first},${record.value.second}")
    // fd.close() << from here
}
fd.close() // to here


问:
How to select date from the Textview in Expresso?
```<code>onView(withParent(withId(buttonContainer)),withId(datePickerLaunchViewId)).perform(click());
</code>```

In the above line, I get "Cannot resolve symbol buttonContainer". What is expected there?

In my case, I use a TextView of "inputType=date" and i'm not sure where to perform a click.

I'm tried using the code from here Select Date from Calendar in Android Espresso and have this in the same class.

```<code>onView(isAssignableFrom(DatePicker.class)).perform(PickerActions.setDate(2020, 06, 01));

setDate(R.id.button8, 2017, 1, 1);

public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
        onView(withParent(withId(buttonContainer)),withId(datePickerLaunchViewId)).perform(click());
        onView(isAssignableFrom(DatePicker.class)).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));

        onView(withId(android.R.id.button1)).perform(click());
}
</code>```

答: withId takes a resource ID, which you must reference from the R class. So in your case it'd most likely be R.id.buttonContainer instead of just buttonContainer.

Body:
onView(withParent(withId(buttonContainer)),withId(datePickerLaunchViewId)).perform(click());

In the above line, I get "Cannot resolve symbol buttonContainer". What is expected there?

In my case, I use a TextView of "inputType=date" and i'm not sure where to perform a click.

I'm tried using the code from here Select Date from Calendar in Android Espresso and have this in the same class.

onView(isAssignableFrom(DatePicker.class)).perform(PickerActions.setDate(2020, 06, 01));

setDate(R.id.button8, 2017, 1, 1);

public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
        onView(withParent(withId(buttonContainer)),withId(datePickerLaunchViewId)).perform(click());
        onView(isAssignableFrom(DatePicker.class)).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));

        onView(withId(android.R.id.button1)).perform(click());
}


问:
Filling in missing data in SQL table with overlapping groups
I have some analytics data where a single activity stream for visitor our a website, where for part of the trace there is an id and later on the identifier is a different value. How can I using SQL pad the data so that it is complete.

```<code> id1 | id2 |   timestamp
-----+-----+---------------------
null |   3 |  123450
null |   3 |  123451
null |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |null |  123455
   5 |null |  123456
   5 |null |  123457
...
null |   8 |  123450
null |   8 |  123451
null |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |null |  123455
   9 |null |  123456
   9 |null |  123457
...
</code>```

The two sections above are part of the same group, and I know that because they essentially  some point stops recording the id2.

I want a query or sql and intermediate tables that would enabled me to populate the null values above so that I have:

```<code> id1 | id2 |   timestamp
-----+-----+---------------------
   5 |   3 |  123450
   5 |   3 |  123451
   5 |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |   3 |  123455
   5 |   3 |  123456
   5 |   3 |  123457
...
   9 |   8 |  123450
   9 |   8 |  123451
   9 |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |   8 |  123455
   9 |   8 |  123456
   9 |   8 |  123457
...
</code>```

答:
Assume that there will be one id2 corresponding to one id1 other than null and

only one id1 corresponding to one id2 other than null

```<code>select a.id1, a.id2, b.timestamp
from  (
  select min(id1) id1, id2
  from tbl
  where id1 is not null and id2 is not null
  group by id2
) a right join tbl b
on (a.id1 = b.id1) OR (a.id2 = b.id2)
</code>```

Body:
I have some analytics data where a single activity stream for visitor our a website, where for part of the trace there is an id and later on the identifier is a different value. How can I using SQL pad the data so that it is complete.

 id1 | id2 |   timestamp
-----+-----+---------------------
null |   3 |  123450
null |   3 |  123451
null |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |null |  123455
   5 |null |  123456
   5 |null |  123457
...
null |   8 |  123450
null |   8 |  123451
null |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |null |  123455
   9 |null |  123456
   9 |null |  123457
...

The two sections above are part of the same group, and I know that because they essentially  some point stops recording the id2.

I want a query or sql and intermediate tables that would enabled me to populate the null values above so that I have:

 id1 | id2 |   timestamp
-----+-----+---------------------
   5 |   3 |  123450
   5 |   3 |  123451
   5 |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |   3 |  123455
   5 |   3 |  123456
   5 |   3 |  123457
...
   9 |   8 |  123450
   9 |   8 |  123451
   9 |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |   8 |  123455
   9 |   8 |  123456
   9 |   8 |  123457
...

Body:
Assume that there will be one id2 corresponding to one id1 other than null and

only one id1 corresponding to one id2 other than null

select a.id1, a.id2, b.timestamp
from  (
  select min(id1) id1, id2
  from tbl
  where id1 is not null and id2 is not null
  group by id2
) a right join tbl b
on (a.id1 = b.id1) OR (a.id2 = b.id2)


问:
Using regextract and importrange together make a "duplicate" formula
I have a spreadsheet where I look if the data (website) already exist on the master sheet.

```<code>=if(countif(importrange("Spreadsheet Key","Leads!N:N"),K2)>0,"COMPANY EXISTS!","")
</code>```

But the above formula is not dynamic enough. If there are companies with co.uk and on the master sheet if it's registered under .com, it won't show "COMPANY EXISTS!"

So I changed to the formula to look for works after before and after "." on a website.

```<code>=ARRAYFORMULA(REGEXEXTRACT(UNIQUE(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.","")), "([0-9A-Za-z-]+)\."))
</code>```

But it's not working if I try to incorporate with if and countif.

```<code>=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."),L2:L)>0,"Company Exist!",""))
</code>```

It shows 'Wrong number of arguments to IF. Expected between 2 and 3 arguments, but got 1 arguments'

Can anyone help me out on where I am making the mistake?

Spreadsheet link- https://docs.google.com/spreadsheets/d/1La3oOWiM5KpzRY0MLLEUQC25LzDuQlqTjgFp-VlS8Bo/edit#gid=0

Edited: Made a mistake beforehand, didn't specify on that cell its looking against

答:
try:</p>

```<code>=ARRAYFORMULA(IFNA(IF(IFNA(REGEXEXTRACT(SUBSTITUTE(IMPORTRANGE(
 "1bnz7Y_xVN9Jo80aCBBeMBMJBnMDHkbZQUWnmL20CRi8", "Leads!N:N"),
 "www.", ), "([0-9A-Za-z-]+)\."))>0, "Company Exist!", )))
</code>```

Body:
I have a spreadsheet where I look if the data (website) already exist on the master sheet.

=if(countif(importrange("Spreadsheet Key","Leads!N:N"),K2)>0,"COMPANY EXISTS!","")

But the above formula is not dynamic enough. If there are companies with co.uk and on the master sheet if it's registered under .com, it won't show "COMPANY EXISTS!"

So I changed to the formula to look for works after before and after "." on a website.

=ARRAYFORMULA(REGEXEXTRACT(UNIQUE(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.","")), "([0-9A-Za-z-]+)\."))

But it's not working if I try to incorporate with if and countif.

=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."),L2:L)>0,"Company Exist!",""))

It shows 'Wrong number of arguments to IF. Expected between 2 and 3 arguments, but got 1 arguments'

Can anyone help me out on where I am making the mistake?

Spreadsheet link- https://docs.google.com/spreadsheets/d/1La3oOWiM5KpzRY0MLLEUQC25LzDuQlqTjgFp-VlS8Bo/edit#gid=0

Edited: Made a mistake beforehand, didn't specify on that cell its looking against

Body:
try:

=ARRAYFORMULA(IFNA(IF(IFNA(REGEXEXTRACT(SUBSTITUTE(IMPORTRANGE(
 "1bnz7Y_xVN9Jo80aCBBeMBMJBnMDHkbZQUWnmL20CRi8", "Leads!N:N"),
 "www.", ), "([0-9A-Za-z-]+)\."))>0, "Company Exist!", )))


问:
How to position right an element in SVG?
In my page, I have an SVG. In that I would like to position the following element to right.

```<code><text x="10" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>
</code>```

I know, I can give a value to position it on the x-axis, but is there a way, like in css (right: 0), to position this element always to the right edge? It is important to be an inline style, because later I want to export this SVG using JS.

答:
If you set the x to 100% and text-anchor to end your text will be aligned from the right edge.

    <svg width="100%" height="100">
        <text x="100%" y="50" text-anchor="end" font-size="35" fill="blue">Hello</text>
    </svg>```

Body:
In my page, I have an SVG. In that I would like to position the following element to right.

<text x="10" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>

I know, I can give a value to position it on the x-axis, but is there a way, like in css (right: 0), to position this element always to the right edge? It is important to be an inline style, because later I want to export this SVG using JS.


问:
Image to pixel array in python
Info: I have 30,000 jpg images that I need to convert into (NumPy) pixel arrays.

Problem: I have tried using Pillow to do the image conversions but it does about 2 images a second which would take hours to complete.

```<code>from PIL import Image

for img_num in range(30_000):
   img = Image.open(img_dir+img_num+extension)
   img_list.append(np.array(img))
</code>```

Question: What is the best and fastest way to convert a large number of jpg images to pixel arrays using python.

答:
I think what is taking the longest is the append() function.

Also, you are appending 30000 images to img_list, this means this single variable is extremely heavy in memory, do you actually need it? (if you image had 1000 pixels, you'd already be trying to allocate more than 30Mb)

In PIL and openCV the read oropen` functions directly make them jumpy arrays.

Title: Image to pixel array in python

Body:
Info: I have 30,000 jpg images that I need to convert into (NumPy) pixel arrays.

Problem: I have tried using Pillow to do the image conversions but it does about 2 images a second which would take hours to complete.

from PIL import Image

for img_num in range(30_000):
   img = Image.open(img_dir+img_num+extension)
   img_list.append(np.array(img))

Question: What is the best and fastest way to convert a large number of jpg images to pixel arrays using python.


Title: Loop through data in javascript

Body:
var entries = {
0: {label: "500", backgroundColor: "rgb(102,205,170,0.5)", borderColor: "rgb(102,205,170,0.5)", data: "13,49,2,2"},
1: {label: "1000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "40,2,41,4"},
2: {label: "1500", backgroundColor: "rgb(112,128,144,0.5)", borderColor: "rgb(112,128,144,0.5)", data: "3,41,0,8"},
3: {label: "2000", backgroundColor: "rgb(220,20,60,0.5)", borderColor: "rgb(220,20,60,0.5)", data: "28,30,40,43"},
4: {label: "2500", backgroundColor: "rgb(240,230,140,0.5)", borderColor: "rgb(240,230,140,0.5)", data: "0,6,20,14"},
5: {label: "3000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "31,26,31,32"}
}

for (var prop in entries)
{
    console.log(entries[prop]["data"])
}


问:
Python Pause/Resume Button
I'm trying to make a button that can pause and resume the loop.

In code:

```<code>for index in range(10):
    print index
    // Runs until here, and pause
    // Button pressed
    print index + 10
    // Runs until here, and pause
    // Button pressed
</code>```

In terminal:

```<code>0
// Button pressed
10
// Button pressed
1
// Button pressed
11
...
9
// Button pressed
19
// Button pressed
</code>```

Is there a way that I can do pause and resume the loop with a button?

答:
'''
Import the following in the code
from tkinter import *
import time

The following programme creates a tkinter window with two buttons
(Pause and Quit),simultaneously printing a sequence of numbers
from 1 to numb(numb=20, for illustration here) with a controllable
time delay between prints (2 secs for illustration here). Pressing the
Pause button stops the printing, changing the button text to Resume.
After a while when the Resume button is pressed, the printing continues.
To quit printing, the quit button is pressed.
In the illustration, printing a number is symbolic. It could as well be
display of images with time time delays. When it is desired to view an
image in more detail, the display can be paused when that image is displayed
and resumed when desired to view remaining images.
'''
    from tkinter import *
    import time

```<code>global move,stop
move = 1 #this a variable which can take a value 1 or 0
stop='Initial-Value'  #This is a variable to control the for and while loops.
                      #Assignment of string as variable is optional. It could be
                      #integer as well

def switch():        #controls back and forth switching between Pause and Resume
    global move
    move = not move

def come_out():      # controls the process to be running or quit
    global stop
    stop='stop'

numb=20
root = Tk()
Pause_Button=Button(root,bg='wheat',command=switch)
Pause_Button.place(relwidth=0.25,relx=0.2,rely=0.2)
Quit_Button=Button(root,bg='lightblue',text='Quit',command=come_out)
Quit_Button.place(relwidth=0.25,relx=0.5,rely=0.2)
time.sleep(2)
for s in range(numb):
    if stop=='stop':
        break
    stop='continue_while_loop'
    while s<numb and stop=='continue_while_loop':
        stop='enter_for_loop_again'
        Pause_Button.update()
        if move==1:
            Pause_Button["text"]='Pause'
            print('s2=',s,'\n')
            time.sleep(2)
        else:
            stop='continue_while_loop'
            Pause_Button["text"]='Resume'
        Quit_Button.update()
root.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python Pause/Resume Button

Body:
I'm trying to make a button that can pause and resume the loop.

In code:

for index in range(10):
    print index
    // Runs until here, and pause
    // Button pressed
    print index + 10
    // Runs until here, and pause
    // Button pressed

In terminal:

0
// Button pressed
10
// Button pressed
1
// Button pressed
11
...
9
// Button pressed
19
// Button pressed

Is there a way that I can do pause and resume the loop with a button?

Body:
'''
Import the following in the code
from tkinter import *
import time

The following programme creates a tkinter window with two buttons
(Pause and Quit),simultaneously printing a sequence of numbers
from 1 to numb(numb=20, for illustration here) with a controllable
time delay between prints (2 secs for illustration here). Pressing the
Pause button stops the printing, changing the button text to Resume.
After a while when the Resume button is pressed, the printing continues.
To quit printing, the quit button is pressed.
In the illustration, printing a number is symbolic. It could as well be
display of images with time time delays. When it is desired to view an
image in more detail, the display can be paused when that image is displayed
and resumed when desired to view remaining images.
'''
    from tkinter import *
    import time

global move,stop
move = 1 #this a variable which can take a value 1 or 0
stop='Initial-Value'  #This is a variable to control the for and while loops.
                      #Assignment of string as variable is optional. It could be
                      #integer as well

def switch():        #controls back and forth switching between Pause and Resume
    global move
    move = not move

def come_out():      # controls the process to be running or quit
    global stop
    stop='stop'

numb=20
root = Tk()
Pause_Button=Button(root,bg='wheat',command=switch)
Pause_Button.place(relwidth=0.25,relx=0.2,rely=0.2)
Quit_Button=Button(root,bg='lightblue',text='Quit',command=come_out)
Quit_Button.place(relwidth=0.25,relx=0.5,rely=0.2)
time.sleep(2)
for s in range(numb):
    if stop=='stop':
        break
    stop='continue_while_loop'
    while s<numb and stop=='continue_while_loop':
        stop='enter_for_loop_again'
        Pause_Button.update()
        if move==1:
            Pause_Button["text"]='Pause'
            print('s2=',s,'\n')
            time.sleep(2)
        else:
            stop='continue_while_loop'
            Pause_Button["text"]='Resume'
        Quit_Button.update()
root.mainloop()


问:
How can ONE Ruby-symbol map to MULTIPLE values?
From what I have read so far I know, that a symbol is pointing always to the same value. Unlike a string, which is mutable in Ruby. Means a string might not have the same value all the time.

But if I create a list which hashes like e.g. this one:

```<code>persons = [
           {first_name: "John", last_name: "Doe"},
           {first_name: "Lisa", last_name: "Meyer"}
          ]
</code>```

If I now do:

```<code>persons[1][:first_name]
</code>```

Then I get the correct value "Lisa".

But how does that work?

If a symbol can point to only one exact value:

How can it differentiate between the "first_name"-symbol of the first hash and the "first_name"-symbol of the second, third ... hash?

答:
In your example you select the object at index 1 of your array. </p>

```<code> {first_name: "Lisa", last_name: "Meyer"}
</code>```

<p>How could the value of the first_name key be different than 'Lisa'? </p>

Body:
From what I have read so far I know, that a symbol is pointing always to the same value. Unlike a string, which is mutable in Ruby. Means a string might not have the same value all the time.

But if I create a list which hashes like e.g. this one:

persons = [
           {first_name: "John", last_name: "Doe"},
           {first_name: "Lisa", last_name: "Meyer"}
          ]

If I now do:

persons[1][:first_name]

Then I get the correct value "Lisa".

But how does that work?

If a symbol can point to only one exact value:

How can it differentiate between the "first_name"-symbol of the first hash and the "first_name"-symbol of the second, third ... hash?

Body:
In your example you select the object at index 1 of your array.

 {first_name: "Lisa", last_name: "Meyer"}

How could the value of the first_name key be different than 'Lisa'?


问:
Angular 8 : No provider for HttpClient in service
In order to migrate an Angular 5 project to Angular 8, I've created an empty project with Angular CLI and copied my modules, components and services in my new project structure.
The project builds, but at the execution I've got the classic message "No provider for HttpClient in service" :

```<code>    ERROR NullInjectorError: StaticInjectorError(AppModule)[TimeService -> HttpClient]:
  StaticInjectorError(Platform: core)[TimeService -> HttpClient]:
    NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:4200/vendor.js:50573:27)
    at resolveToken (http://localhost:4200/vendor.js:52359:24)
    at tryResolveToken (http://localhost:4200/vendor.js:52285:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:52148:20)
    at resolveToken (http://localhost:4200/vendor.js:52359:24)
    at tryResolveToken (http://localhost:4200/vendor.js:52285:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:52148:20)
    at resolveNgModuleDep (http://localhost:4200/vendor.js:76198:29)
    at _createClass (http://localhost:4200/vendor.js:76275:32)
    at _createProviderInstance (http://localhost:4200/vendor.js:76231:26)
</code>```

I thing my app.module.ts is ok : I'm importing HttpClientModule and I've put it in @NgModule imports, just after BrowserModule.

```<code>@NgModule({
    declarations: [AppComponent,DelegationsComponent],
    imports:      [BrowserModule,
                  HttpClientModule,
                  GlobalModule.forRoot(),
                  AuthenticationModule,
                   DelegationModule,
                   routing,
                   FormsModule,
                   ReactiveFormsModule,
                   BrowserAnimationsModule,
                   ButtonModule, TableModule, DialogModule, DropdownModule, ToastModule, TabViewModule, InputTextModule, AutoCompleteModule, TooltipModule, CheckboxModule, OverlayPanelModule, MultiSelectModule, CalendarModule ],
    providers:    [APP_ROUTER_PROVIDERS, {provide: APP_BASE_HREF, useValue: getBaseHref()}],
    bootstrap:    [AppComponent]
})
</code>```

The error seems to be in TimeService. In this service, HttpClient is imported and injected in the contructor.

```<code>import {HttpClient} from "@angular/common/http";

@Injectable()
export class TimeService extends BaseService {
    constructor(private http: HttpClient)
</code>```

Then, TimeService is injected in DelegationsComponent.

```<code>import {TimeService} from "utils/time.service";
@Component({
    moduleId: __moduleName,
    selector: 'delegations',
    templateUrl: './delegations.component.html'
})
export class DelegationsComponent implements OnInit, OnDestroy {
    constructor(private timeService: TimeService)
</code>```

And you can see DelegationsComponent in my app.module.ts declarations.

Any idea ?
Thank you

EDIT :
By trying to reproduce the problem on a small example, I've found the cause : time.service.ts is not in my angular app but in a folder outside, because I'm sharing it with two other angular apps. I'm including it thanks to the package.json of my apps :

```<code>"utils": "file:../../../../../utils"
</code>```

So time.service.ts ends in node_modules/utils. If I put it in the src/app directory, it works. Any idea why it doesn't work this way, and how I can share a service amongst several angular apps ?

答:
The error =>

```<code>ERROR NullInjectorError: StaticInjectorError(AppModule)[TimeService -> HttpClient]:
      StaticInjectorError(Platform: core)[TimeService -> HttpClient]:
</code>```

Below solution is worked for me and I am using Angular version-9

=> Need to add => import {HttpClientModule} from '@angular/common/http'; in app.module.ts and also in the [import] array.

Body:
In order to migrate an Angular 5 project to Angular 8, I've created an empty project with Angular CLI and copied my modules, components and services in my new project structure.
The project builds, but at the execution I've got the classic message "No provider for HttpClient in service" :

    ERROR NullInjectorError: StaticInjectorError(AppModule)[TimeService -> HttpClient]:
  StaticInjectorError(Platform: core)[TimeService -> HttpClient]:
    NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:4200/vendor.js:50573:27)
    at resolveToken (http://localhost:4200/vendor.js:52359:24)
    at tryResolveToken (http://localhost:4200/vendor.js:52285:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:52148:20)
    at resolveToken (http://localhost:4200/vendor.js:52359:24)
    at tryResolveToken (http://localhost:4200/vendor.js:52285:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:52148:20)
    at resolveNgModuleDep (http://localhost:4200/vendor.js:76198:29)
    at _createClass (http://localhost:4200/vendor.js:76275:32)
    at _createProviderInstance (http://localhost:4200/vendor.js:76231:26)

I thing my app.module.ts is ok : I'm importing HttpClientModule and I've put it in @NgModule imports, just after BrowserModule.

@NgModule({
    declarations: [AppComponent,DelegationsComponent],
    imports:      [BrowserModule,
                  HttpClientModule,
                  GlobalModule.forRoot(),
                  AuthenticationModule,
                   DelegationModule,
                   routing,
                   FormsModule,
                   ReactiveFormsModule,
                   BrowserAnimationsModule,
                   ButtonModule, TableModule, DialogModule, DropdownModule, ToastModule, TabViewModule, InputTextModule, AutoCompleteModule, TooltipModule, CheckboxModule, OverlayPanelModule, MultiSelectModule, CalendarModule ],
    providers:    [APP_ROUTER_PROVIDERS, {provide: APP_BASE_HREF, useValue: getBaseHref()}],
    bootstrap:    [AppComponent]
})

The error seems to be in TimeService. In this service, HttpClient is imported and injected in the contructor.

import {HttpClient} from "@angular/common/http";

@Injectable()
export class TimeService extends BaseService {
    constructor(private http: HttpClient)

Then, TimeService is injected in DelegationsComponent.

import {TimeService} from "utils/time.service";
@Component({
    moduleId: __moduleName,
    selector: 'delegations',
    templateUrl: './delegations.component.html'
})
export class DelegationsComponent implements OnInit, OnDestroy {
    constructor(private timeService: TimeService)

And you can see DelegationsComponent in my app.module.ts declarations.

Any idea ?
Thank you

EDIT :
By trying to reproduce the problem on a small example, I've found the cause : time.service.ts is not in my angular app but in a folder outside, because I'm sharing it with two other angular apps. I'm including it thanks to the package.json of my apps :

"utils": "file:../../../../../utils"

So time.service.ts ends in node_modules/utils. If I put it in the src/app directory, it works. Any idea why it doesn't work this way, and how I can share a service amongst several angular apps ?

Body:
The error =>

ERROR NullInjectorError: StaticInjectorError(AppModule)[TimeService -> HttpClient]:
      StaticInjectorError(Platform: core)[TimeService -> HttpClient]:

Below solution is worked for me and I am using Angular version-9

=> Need to add => import {HttpClientModule} from '@angular/common/http'; in app.module.ts and also in the [import] array.


答:
In the instructions const [key, value] of Object.entries(dataChart) you're creating 2 variables (key and value). Those 2 variables contains every single element of the array (value) and the index of the element into the array (key). So time by time, key is just a number.

Btw I suggest to use a different approach:

dataChart.forEach(elementOfArray => {
    console.log(elementOfArray.borderColor);
});
```

The forEach is more used in js, it use the concept of callback. It will call the function you pass as param for every single element of the array by passing the array element as param.

Title: Loop through data in javascript

Body:
I am trying to display data in a chart. and I have data passed from my controller as below.

0: {label: "500", backgroundColor: "rgb(102,205,170,0.5)", borderColor: "rgb(102,205,170,0.5)", data: "13,49,2,2"}
1: {label: "1000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "40,2,41,4"}
2: {label: "1500", backgroundColor: "rgb(112,128,144,0.5)", borderColor: "rgb(112,128,144,0.5)", data: "3,41,0,8"}
3: {label: "2000", backgroundColor: "rgb(220,20,60,0.5)", borderColor: "rgb(220,20,60,0.5)", data: "28,30,40,43"}
4: {label: "2500", backgroundColor: "rgb(240,230,140,0.5)", borderColor: "rgb(240,230,140,0.5)", data: "0,6,20,14"}
5: {label: "3000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "31,26,31,32"}

now I want to loop through the data so the result is like

label: '500',
backgroundColor: rgb(102,205,170,0.5),
borderColor: rgb(102,205,170,0.5),
data: [
    26,2,41,13
],
...

What I have tried is as follows

for (const [key, value] of Object.entries(dataChart)) {
     console.log(key.borderColor);
}

here i have am only trying to display borderColor but it says `undefined'

Any help will be appreciated.

Body:
In the instructions const [key, value] of Object.entries(dataChart) you're creating 2 variables (key and value). Those 2 variables contains every single element of the array (value) and the index of the element into the array (key). So time by time, key is just a number.

Btw I suggest to use a different approach:

dataChart.forEach(elementOfArray => {
    console.log(elementOfArray.borderColor);
});

The forEach is more used in js, it use the concept of callback. It will call the function you pass as param for every single element of the array by passing the array element as param.


问:
Drupal 8 Create XML Queue
I'm wondering how I would go about creating an XML file of roughly 17,000 entities with the Drupal 8 Queue.

I have tried batch processing and it takes forever, slows down the site, and most of the time fails.

Thanks!

答:
You need to write your own QueueWorker plugin. A tutorial can be found at https://www.crabsoul.org/blog/drupal-8-queue-api-using-cron-and-manual-callback-handler for example. To sum up:

In the directory modulename/src/Plugin/QueueWorker directory create a file called XmlCreator.php

The contents should be a class XmlCreator extends QueueWorkerBase with a @QueueWorker class annotation.

You should implement the function processItem($data) method.

Like so:

```<code>namespace Drupal\modulename\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;

/**
 *
 * @QueueWorker(
 * id = "xml_creator",
 * title = "XML Creator",
 * )
 */
class XmlCreator extends QueueWorkerBase {

  public function processItem($data) {
</code>```

Each such should create one part of the XML file, write it into an approriate file and later you could just concat them and wrap them in the root element.

processItem will be called for each row in the {queue} table with whatever serialized data is in the data column. So the question as asked can't be answered for we would need to know what is the source you want to process. If it happens to be an integer in some table, I can offer you an actual, production deployed update function which populated a queue with a ginormous amount of entries in a fraction of a second:

```<code>function sd8_update_8046() {
  $db = \Drupal::database();
  $select = $db->select('file_managed');
  $select->addExpression(':name', 'name', [':name' => 'sd8_image_style_regenerate']);
  // the following line is the interesting part.
  $select->addExpression('CONCAT(:prefix, fid, :suffix)', 'data', [':prefix' => 'i:', ':suffix' => ';']);
  $select->addExpression('UNIX_TIMESTAMP()', 'created');
  $select->condition('filemime', 'image/%', 'LIKE');
  $select->condition('created', 1561964400, '>');
  $select->condition('uri', 'public%', 'LIKE');
  $insert = $db->insert('queue');
  $insert->fields(['name', 'data', 'created']);
  $insert->from($select);
  $insert->execute();
}
</code>```

Should you have a different source of truth, you need to adjust accordingly but in general, you want to bypass the DatabaseQueue and use DatabaseQueue::doCreateItem more as a pattern of what Drupal expects in the queue table. You might want to write a batch / multipart update which does an insert with a few hundred values (Insert supports multiple value() calls) and so run only like 90 INSERT () VALUES (), ..., () commands or the DBTNG equivalent of that. Or an INSERT ... SELECT as shown above. Running 18 000 separate INSERT commands is not conducive to success.

Title: Drupal 8 Create XML Queue

Body:
You need to write your own QueueWorker plugin. A tutorial can be found at https://www.crabsoul.org/blog/drupal-8-queue-api-using-cron-and-manual-callback-handler for example. To sum up:

In the directory modulename/src/Plugin/QueueWorker directory create a file called XmlCreator.php

The contents should be a class XmlCreator extends QueueWorkerBase with a @QueueWorker class annotation.

You should implement the function processItem($data) method.

Like so:

namespace Drupal\modulename\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;

/**
 *
 * @QueueWorker(
 * id = "xml_creator",
 * title = "XML Creator",
 * )
 */
class XmlCreator extends QueueWorkerBase {

  public function processItem($data) {

Each such should create one part of the XML file, write it into an approriate file and later you could just concat them and wrap them in the root element.

processItem will be called for each row in the {queue} table with whatever serialized data is in the data column. So the question as asked can't be answered for we would need to know what is the source you want to process. If it happens to be an integer in some table, I can offer you an actual, production deployed update function which populated a queue with a ginormous amount of entries in a fraction of a second:

function sd8_update_8046() {
  $db = \Drupal::database();
  $select = $db->select('file_managed');
  $select->addExpression(':name', 'name', [':name' => 'sd8_image_style_regenerate']);
  // the following line is the interesting part.
  $select->addExpression('CONCAT(:prefix, fid, :suffix)', 'data', [':prefix' => 'i:', ':suffix' => ';']);
  $select->addExpression('UNIX_TIMESTAMP()', 'created');
  $select->condition('filemime', 'image/%', 'LIKE');
  $select->condition('created', 1561964400, '>');
  $select->condition('uri', 'public%', 'LIKE');
  $insert = $db->insert('queue');
  $insert->fields(['name', 'data', 'created']);
  $insert->from($select);
  $insert->execute();
}

Should you have a different source of truth, you need to adjust accordingly but in general, you want to bypass the DatabaseQueue and use DatabaseQueue::doCreateItem more as a pattern of what Drupal expects in the queue table. You might want to write a batch / multipart update which does an insert with a few hundred values (Insert supports multiple value() calls) and so run only like 90 INSERT () VALUES (), ..., () commands or the DBTNG equivalent of that. Or an INSERT ... SELECT as shown above. Running 18 000 separate INSERT commands is not conducive to success.


问:
warning: ignoring broken ref refs/remotes/origin/HEAD
Since a few days ago, every time I press tab key to complete branch names in bash I see the message:

warning: ignoring broken ref refs/remotes/origin/HEAD warning: ignoring broken ref refs/remotes/origin/HEAD

For example, this is what I see when I have a branch called feature/foo and I press tab:

```<code>git checkout f

$ git checkout fwarning: ignoring broken ref refs/remotes/origin/HEAD
warning: ignoring broken ref refs/remotes/origin/HEAD
eature/
</code>```

答:
In my case the problem was the file .git\refs\remotes\origin\master that got corrupted, maybe since my computer was involuntary disconnected from power a few days ago.

I solved it by replacing the file content with the correct reference, a 40 char hex number that can be found in the file .git\FETCH_HEAD.

Body:
Since a few days ago, every time I press tab key to complete branch names in bash I see the message:

warning: ignoring broken ref refs/remotes/origin/HEAD warning: ignoring broken ref refs/remotes/origin/HEAD

For example, this is what I see when I have a branch called feature/foo and I press tab:

git checkout f

$ git checkout fwarning: ignoring broken ref refs/remotes/origin/HEAD
warning: ignoring broken ref refs/remotes/origin/HEAD
eature/


问:
RxSwift on UITextview
I want to call a function every 4 changes in my textview.
how can I perform it with RXswift debounce throttle?
I use UITextViewDelegate to detect changes in my textview.</p>

答:
RxSwift 5.0 tested

```<code>        textField.rx
        .text
        .orEmpty
        .distinctUntilChanged()
        .map { _ in 1}
        .scan(0, accumulator: { $0 + $1 })
        .filter { $0 % 4 == 0 }
        .subscribe(onNext: { (value) in
            print(value)
        })
        .disposed(by: disposeBag)
</code>```

you can change number 4 to 10 if you would like to achieve firing event every 10 element.Good Luck.

Title: RxSwift on UITextview

Body:
RxSwift 5.0 tested

        textField.rx
        .text
        .orEmpty
        .distinctUntilChanged()
        .map { _ in 1}
        .scan(0, accumulator: { $0 + $1 })
        .filter { $0 % 4 == 0 }
        .subscribe(onNext: { (value) in
            print(value)
        })
        .disposed(by: disposeBag)

you can change number 4 to 10 if you would like to achieve firing event every 10 element.Good Luck.


问:
Newline character insertion in Java
How can I insert a newline character in a Java applet program if I am using "label" instead of System.out.println()?

Thanks in advance.

答:
Put a \n in the string.

Like this:

```<code>String twoLineString = "first line\nsecond line";
</code>```

OwnerDisplayName: harsha

Title: Newline character insertion in Java

Body:
Put a \n in the string.

Like this:

String twoLineString = "first line\nsecond line";

OwnerDisplayName: Ben Alpert

ContentLicense: CC BY-SA 2.5


问:
How can I pass *.py to pycco via tox?
The following command works:

```<code>$ pycco *.py
# generates literate-style documentation
# for all .py files in the current folder
</code>```

And the following snippet in my tox.ini file works as expected:

```<code>[testenv:pycco]
deps =
    pycco
commands =
    pycco manage.py
# generates literate-style documentation
# for manage.py
</code>```

But if I try to use a glob:

```<code>[testenv:pycco]
deps =
    pycco
commands =
    pycco *.py
</code>```

...I get the following error:

```<code>  File "/home/user/Documents/project/.tox/pycco/lib/python3.7/site-packages/pycco/main.py", line 79, in generate_documentation
    code = open(source, "rb").read().decode(encoding)
FileNotFoundError: [Errno 2] No such file or directory: '*.py'
</code>```

How can I pass *.py to pycco via tox?

答:
The problem here is that pycco does not support glob expansions. What makes pycco *.py work is that before the execution happens the shell actually transforms *.py to actual files; and then passes that to the OS to run it.

When tox runs your command there's no shell involved, so whatever you write is as is passed on to the OS, so now pycco actually gets as argument *.py hence the error.

You can work around this by either explicitly listing the file paths or using the python interpreter to do the expansion:

python -c 'from glob import glob; import subprocess; subprocess.check_call(["pycco"] + glob("*.py"))'
```

Put the above command inside your tox commands and things will work now as python is now the shell doing the expansion of "*.py" to actual files list.

Title: How can I pass *.py to pycco via tox?

Body:
The following command works:

$ pycco *.py
# generates literate-style documentation
# for all .py files in the current folder

And the following snippet in my tox.ini file works as expected:

[testenv:pycco]
deps =
    pycco
commands =
    pycco manage.py
# generates literate-style documentation
# for manage.py

But if I try to use a glob:

[testenv:pycco]
deps =
    pycco
commands =
    pycco *.py

...I get the following error:

  File "/home/user/Documents/project/.tox/pycco/lib/python3.7/site-packages/pycco/main.py", line 79, in generate_documentation
    code = open(source, "rb").read().decode(encoding)
FileNotFoundError: [Errno 2] No such file or directory: '*.py'

How can I pass *.py to pycco via tox?

Body:
The problem here is that pycco does not support glob expansions. What makes pycco *.py work is that before the execution happens the shell actually transforms *.py to actual files; and then passes that to the OS to run it.

When tox runs your command there's no shell involved, so whatever you write is as is passed on to the OS, so now pycco actually gets as argument *.py hence the error.

You can work around this by either explicitly listing the file paths or using the python interpreter to do the expansion:

python -c 'from glob import glob; import subprocess; subprocess.check_call(["pycco"] + glob("*.py"))'

Put the above command inside your tox commands and things will work now as python is now the shell doing the expansion of "*.py" to actual files list.


问:
read data from firebase and set the value of textview
i faced an issue like user entered enrollment number and verify and read all data from that and set the value to text view

If user enter enrollment 66 then verify that enrollment and read all that data from 66 and set value of text view to marks of subjects.what i need to do if i want to solve Above problem?

I tried:

```<code>reff= FirebaseDatabase.getInstance().getReference().child("Marks");
reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String mm=dataSnapshot.child("mcad").getValue().toString();
        String jm=dataSnapshot.child("java").getValue().toString();
        String nm=dataSnapshot.child("nma").getValue().toString();

        txtmcadmarks.setText(nm);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

答:
First, your Database Reference returns you a list of data so you need to receive your data as a list.

Second, if you want to filter your data base on enrollment then add a query in your database reference.

```<code>    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
    Query query = databaseReference.child("Marks").orderByChild("enrollment").equalTo(66);

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot data: dataSnapshot.getChildren()){
                String mm=data.child("mcad").getValue().toString();
                String jm=data.child("java").getValue().toString();
                String nm=data.child("nma").getValue().toString();

                txtmcadmarks.setText(nm);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

Body:
i faced an issue like user entered enrollment number and verify and read all data from that and set the value to text view

If user enter enrollment 66 then verify that enrollment and read all that data from 66 and set value of text view to marks of subjects.what i need to do if i want to solve Above problem?

I tried:

reff= FirebaseDatabase.getInstance().getReference().child("Marks");
reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String mm=dataSnapshot.child("mcad").getValue().toString();
        String jm=dataSnapshot.child("java").getValue().toString();
        String nm=dataSnapshot.child("nma").getValue().toString();

        txtmcadmarks.setText(nm);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Body:
First, your Database Reference returns you a list of data so you need to receive your data as a list.

Second, if you want to filter your data base on enrollment then add a query in your database reference.

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
    Query query = databaseReference.child("Marks").orderByChild("enrollment").equalTo(66);

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot data: dataSnapshot.getChildren()){
                String mm=data.child("mcad").getValue().toString();
                String jm=data.child("java").getValue().toString();
                String nm=data.child("nma").getValue().toString();

                txtmcadmarks.setText(nm);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });


问:
I write the code in python to count digits of a number but It doesn't work for some numbers
In order to count digits of a number I write this code in python:

```<code>a=int(input('number: '))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')
</code>```

It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...

It say:

```<code>ValueError: invalid literal for int() with base 10: '3**21'
</code>```

3**21 is integer input So why it gives this erroer,and How Should I fix this?

答:
Neither '3^21' nor '3**21' are integers. They are strings with Python expressions that would evaluate to integers if the Python interpreter evaluated them.

```<code>>>> 3^21
22
>>> 3**21
10460353203
</code>```

The int builtin only accepts strings such as '100', '22' or '10460353203'.

(int also has a base argument that defaults to 2 and allows you to issue commands like int('AA', 16), but it still does not allow you do pass the kind of string-expressions you are trying to pass.)

Body:
In order to count digits of a number I write this code in python:

a=int(input('number: '))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')

It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...

It say:

ValueError: invalid literal for int() with base 10: '3**21'

3**21 is integer input So why it gives this erroer,and How Should I fix this?

Body:
Neither '3^21' nor '3**21' are integers. They are strings with Python expressions that would evaluate to integers if the Python interpreter evaluated them.

>>> 3^21
22
>>> 3**21
10460353203

The int builtin only accepts strings such as '100', '22' or '10460353203'.

(int also has a base argument that defaults to 2 and allows you to issue commands like int('AA', 16), but it still does not allow you do pass the kind of string-expressions you are trying to pass.)


问:
jquery ajax sends an array of objects as an object with index keys. How can I stop this?
Let's say I have var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}

I send it like this:

```<code>$.ajax({
            url: "/endpoint",
            type: "POST",
            dataType: "json",
            data: data,
            success: function(response){
                console.log(response);
            }
        });
</code>```

When looking at what I get server side, I see this.

```<code>%{
  "coords" => %{"0" => %{"lat" => "23.23", "lng" => "123.123"}},
  "name" => "Something",
}
</code>```

Why is [{lat: .., lng: ...}] getting converted to {0: {lat: ..., lng: ...}}? How can I stop this? Is this a jquery thing?

答:
You just need to JSON.stringify the data before sending it.

```<code>data: JSON.stringify(data)
</code>```

Also, you need to put contentType: 'application/json'

Body:
Let's say I have var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}

I send it like this:

$.ajax({
            url: "/endpoint",
            type: "POST",
            dataType: "json",
            data: data,
            success: function(response){
                console.log(response);
            }
        });

When looking at what I get server side, I see this.

%{
  "coords" => %{"0" => %{"lat" => "23.23", "lng" => "123.123"}},
  "name" => "Something",
}

Why is [{lat: .., lng: ...}] getting converted to {0: {lat: ..., lng: ...}}? How can I stop this? Is this a jquery thing?

Body:
You just need to JSON.stringify the data before sending it.

data: JSON.stringify(data)

Also, you need to put contentType: 'application/json'


问:
How to format date correctly in LUA script - 05292020
I'm having some difficulty formatting the date in this LUA script. I want it to output the current date in the following format - 05292020. However, I can't get the year to format correctly, so my output is 052920. I've been searching extensively to find a solution but I'm really stuck on this one. Anyone able to point me in the right direction? Thank you in advance!

```<code>function OnEvent(event, arg, family)
  if event == "G_PRESSED" and arg == 1 then

    -- Take the first 8 characters only (1,8)
    local date = string.sub(GetDate(), 1, 8)
    for i = 1, #date do
      local ch = date:sub(i,i)
      if ch == "-" then
        PressAndReleaseKey("minus")
      elseif ch == "," then
        PressAndReleaseKey("comma")
      elseif ch == "." then
        PressAndReleaseKey("period")
      elseif ch == "/" then
      --  PressAndReleaseKey("slash")
      elseif ch == " " then
        PressAndReleaseKey("spacebar")
      elseif ch == ":" then
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey("semicolon")
        ReleaseKey("lshift")
      elseif ch == ch:lower() then
        PressAndReleaseKey(ch)
      else
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey(ch:lower())
        ReleaseKey("lshift")
      end
    end

  end
end
</code>```

答:
This should be a matter to use the correct format with os.date, something like:

```<code>print(os.date("%d%m%Y"))
</code>```

Body:
I'm having some difficulty formatting the date in this LUA script. I want it to output the current date in the following format - 05292020. However, I can't get the year to format correctly, so my output is 052920. I've been searching extensively to find a solution but I'm really stuck on this one. Anyone able to point me in the right direction? Thank you in advance!

function OnEvent(event, arg, family)
  if event == "G_PRESSED" and arg == 1 then

    -- Take the first 8 characters only (1,8)
    local date = string.sub(GetDate(), 1, 8)
    for i = 1, #date do
      local ch = date:sub(i,i)
      if ch == "-" then
        PressAndReleaseKey("minus")
      elseif ch == "," then
        PressAndReleaseKey("comma")
      elseif ch == "." then
        PressAndReleaseKey("period")
      elseif ch == "/" then
      --  PressAndReleaseKey("slash")
      elseif ch == " " then
        PressAndReleaseKey("spacebar")
      elseif ch == ":" then
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey("semicolon")
        ReleaseKey("lshift")
      elseif ch == ch:lower() then
        PressAndReleaseKey(ch)
      else
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey(ch:lower())
        ReleaseKey("lshift")
      end
    end

  end
end

Body:
This should be a matter to use the correct format with os.date, something like:

print(os.date("%d%m%Y"))


问:
How to send images from PC to Android by using Socket?
I send a image using this code in pc:

```<code>public static void sendImage(File image,Socket socket) throws IOException {

    OutputStream outputStream = socket.getOutputStream();

    BufferedImage Bimage = ImageIO.read(image);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write(Bimage, "png", byteArrayOutputStream);

    byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
    outputStream.write(size);
    System.out.println("size");
    outputStream.write(byteArrayOutputStream.toByteArray());
    System.out.println("BT");
    outputStream.flush();
}
</code>```

And I receive the image using this code in android:

```<code>private void show_imageFromService() throws IOException {
    InputStream inputStream = CreateActivity.client.socket.getInputStream();

    byte[] sizeAr = new byte[4];
    inputStream.read(sizeAr);
    int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();

    byte[] imageAr = new byte[size];
    inputStream.read(imageAr);

    Rect rect=new Rect();
    rect.set(imageView.getLeft(),imageView.getTop(),imageView.getRight(),imageView.getBottom());

    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inSampleSize=1;

    Bitmap bmp=BitmapFactory.decodeByteArray(imageAr,0,imageAr.length,options);

    imageView.setImageBitmap(bmp);

}
</code>```

But the image can't show in android, can anyone have other way to deal with this?

答:
I fixed the send code:

```<code>public static void sendImage(File image,Socket socket) throws IOException {

    FileInputStream fileInputStream=new FileInputStream(image);
    int size=fileInputStream.available();

    byte[] imageByte=new byte[size];
    fileInputStream.read(imageByte);

    DataOutputStream dataOutputStream=new DataOutputStream(socket.getOutputStream());
    dataOutputStream.writeInt(imageByte.length);
    System.out.println(imageByte.length);
    dataOutputStream.write(imageByte);
    dataOutputStream.flush();

}
</code>```

And fixed the receiver code:

```<code>private void show_imageFromService() throws IOException {

    DataInputStream dataInputStream=new DataInputStream(CreateActivity.client.socket.getInputStream());
    int size=dataInputStream.readInt();

    byte[] imageAr = new byte[size];
    int len = 0;
    while (len < size) {
        len += dataInputStream.read(imageAr, len, size - len);
    }

    Rect rect=new Rect();
    rect.set(imageView.getLeft(),imageView.getTop(),imageView.getRight(),imageView.getBottom());

    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inSampleSize=1;

    Bitmap bmp=BitmapFactory.decodeByteArray(imageAr,0,imageAr.length,options);

    imageView.setImageBitmap(bmp);

}
</code>```

Now I success to show the image in Android.

Body:
I send a image using this code in pc:

public static void sendImage(File image,Socket socket) throws IOException {

    OutputStream outputStream = socket.getOutputStream();

    BufferedImage Bimage = ImageIO.read(image);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write(Bimage, "png", byteArrayOutputStream);

    byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
    outputStream.write(size);
    System.out.println("size");
    outputStream.write(byteArrayOutputStream.toByteArray());
    System.out.println("BT");
    outputStream.flush();
}

And I receive the image using this code in android:

private void show_imageFromService() throws IOException {
    InputStream inputStream = CreateActivity.client.socket.getInputStream();

    byte[] sizeAr = new byte[4];
    inputStream.read(sizeAr);
    int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();

    byte[] imageAr = new byte[size];
    inputStream.read(imageAr);

    Rect rect=new Rect();
    rect.set(imageView.getLeft(),imageView.getTop(),imageView.getRight(),imageView.getBottom());

    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inSampleSize=1;

    Bitmap bmp=BitmapFactory.decodeByteArray(imageAr,0,imageAr.length,options);

    imageView.setImageBitmap(bmp);

}

But the image can't show in android, can anyone have other way to deal with this?

Body:
I fixed the send code:

public static void sendImage(File image,Socket socket) throws IOException {

    FileInputStream fileInputStream=new FileInputStream(image);
    int size=fileInputStream.available();

    byte[] imageByte=new byte[size];
    fileInputStream.read(imageByte);

    DataOutputStream dataOutputStream=new DataOutputStream(socket.getOutputStream());
    dataOutputStream.writeInt(imageByte.length);
    System.out.println(imageByte.length);
    dataOutputStream.write(imageByte);
    dataOutputStream.flush();

}

And fixed the receiver code:

private void show_imageFromService() throws IOException {

    DataInputStream dataInputStream=new DataInputStream(CreateActivity.client.socket.getInputStream());
    int size=dataInputStream.readInt();

    byte[] imageAr = new byte[size];
    int len = 0;
    while (len < size) {
        len += dataInputStream.read(imageAr, len, size - len);
    }

    Rect rect=new Rect();
    rect.set(imageView.getLeft(),imageView.getTop(),imageView.getRight(),imageView.getBottom());

    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inSampleSize=1;

    Bitmap bmp=BitmapFactory.decodeByteArray(imageAr,0,imageAr.length,options);

    imageView.setImageBitmap(bmp);

}

Now I success to show the image in Android.


问:
margin-top: auto; not working for a flex child
I'm trying to push the footer, inside a flex, to page end. I'm using margin-top: auto to accomplish the same, but it doesn't work. I also tried align-self and align-items, they don't work as well. I also looked at all the SOs. What am I missing?

Codepen for my problem: https://codepen.io/vivekest/pen/XWmvyKq

Thanks in advance!

答:
You need to set height on #all-content

```<code>#all-content{
  ...
  height: 100vh;
}
</code>```

another approach is to set justify-content property on #all-content and remove margin-top from #page-footer

```<code>#all-content{
  ...
  justify-content: space-between;
  height: 100vh;
}

#page-footer{
    width: 100%;
}
</code>```

Body:
You need to set height on #all-content

#all-content{
  ...
  height: 100vh;
}

another approach is to set justify-content property on #all-content and remove margin-top from #page-footer

#all-content{
  ...
  justify-content: space-between;
  height: 100vh;
}

#page-footer{
    width: 100%;
}


问:
Extract links_Using Python
I am looking out to extract links found in "Next" across all pages and append them to lists...............................................................................................................................................................
  Please guide me on this.</p>

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

sub_link=[]
sub_link_edit=[]

 def convert(url):
  if not url.startswith('http://'):
  return 'http:' + url
 return url

next_link = 'https://money.rediff.com/companies/groups/A'

while next_link:
 page = requests.get(next_link)
 soup = BeautifulSoup(page.content,'html.parser')
 pagination_container_company = soup.find_all("table", class_="pagination-container-company")[0].text
 sub_link = re.search('href="(.*)">Next', pagination_container_company).group(1)
 sub_link_edit.append(convert(sub_link))
 next_link=convert(sub_link)

 data_df = pd.DataFrame()
 df = pd.DataFrame(
  {
 'Link': sub_link_edit
  })
 data_df = pd.concat([data_df, df], sort=False)

 print(df.shape)
 tot_sub=len(sub_link_edit)
 print(tot_sub)

 data_df.to_csv('results_1.csv')
</code>```

答:
```<code>import pandas as pd
import requests
from bs4 import BeautifulSoup

def convert(url):

  if not url.startswith('http://'):
    return 'http:' + url
  return url

company_name = []
company_link = []
company_link_edit=[]

sub_link = 'https://money.rediff.com/companies/groups/A'

while sub_link:
  page = requests.get(sub_link)
  soup = BeautifulSoup(page.content, 'html.parser')
  company_A_subpg1 = soup.find_all(class_='dataTable')

  for sub_tab in company_A_subpg1:
    temp = sub_tab.find('tbody')
    all_rows = temp.find_all('tr')
    for val in all_rows:
      a_tag = val.find('a', href=True)
      company_name.append(a_tag.text.strip())
      company_link_edit.append(convert(a_tag.get('href')))

  try:
    sub_link = soup.body.findAll("a", text="Next")[0].get('href')
  except:
    break
  sub_link = convert(sub_link)

print(len(company_name), len(company_link_edit))

data_df = pd.DataFrame()
df=pd.DataFrame(
        {'Name':company_name,
         'Link':company_link_edit
         })
data_df = pd.concat([data_df, df], sort=False)

print(df.shape)

</code>```

Title: Extract links_Using Python

Body:
I am looking out to extract links found in "Next" across all pages and append them to lists...............................................................................................................................................................
  Please guide me on this.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

sub_link=[]
sub_link_edit=[]

 def convert(url):
  if not url.startswith('http://'):
  return 'http:' + url
 return url

next_link = 'https://money.rediff.com/companies/groups/A'

while next_link:
 page = requests.get(next_link)
 soup = BeautifulSoup(page.content,'html.parser')
 pagination_container_company = soup.find_all("table", class_="pagination-container-company")[0].text
 sub_link = re.search('href="(.*)">Next', pagination_container_company).group(1)
 sub_link_edit.append(convert(sub_link))
 next_link=convert(sub_link)

 data_df = pd.DataFrame()
 df = pd.DataFrame(
  {
 'Link': sub_link_edit
  })
 data_df = pd.concat([data_df, df], sort=False)

 print(df.shape)
 tot_sub=len(sub_link_edit)
 print(tot_sub)

 data_df.to_csv('results_1.csv')


问:
Get some data but not all using regex
I have some data like this:

```<code>disconnected, received disassoc: sending station leaving (8)
disconnected, 4-way handshake timeout
disconnected, too weak signal, signal strength -91
disconnected, registered to other interface
</code>```

I would like to get the reason without the number and parentheses.

So not to include any (x) nor -xx where x is number (at the end)

Output should be

```<code>received disassoc: sending station leaving
4-way handshake timeout
too weak signal, signal strength
registered to other interface
</code>```

I think I need some lookahed but not sure.

This does not work:

```<code>disconnected, (?<reason>.*)( -\d+)?
</code>```

reason will still include the -91

This gives only lines with -xx or (x), missing rest of the lines

```<code>disconnected, (?<reason>.+(?=-\d+|\(\d\)))
</code>```

This gives all lines but will also include -xx and (x) in the reason

```<code>disconnected, (?<reason>.+(?=-\d+|\(\d\))?)
</code>```

PS -xx and (x) are always at the end so can use anchor $

答:
You could use an alternation with an optional non capturing group to match both options at the end of the string.

The value is in the named capture group reason.

```<code>disconnected, (?<reason>.*?)(?:\(\d+\)| -\d+)?$
</code>```

In parts

disconnected,  Match disconnected, and a space

(?<reason>.*?) Named capture group reason, match any char as least as possible

(?: Non capture group

\(\d+\) Match 1+ digits between parenthesis

| Or

 -\d+ Match a space - and 1+ digits

)? Close group and make optional

$ End of string

Regex demo

Title: Get some data but not all using regex

Body:
I have some data like this:

disconnected, received disassoc: sending station leaving (8)
disconnected, 4-way handshake timeout
disconnected, too weak signal, signal strength -91
disconnected, registered to other interface

I would like to get the reason without the number and parentheses.

So not to include any (x) nor -xx where x is number (at the end)

Output should be

received disassoc: sending station leaving
4-way handshake timeout
too weak signal, signal strength
registered to other interface

I think I need some lookahed but not sure.

This does not work:

disconnected, (?<reason>.*)( -\d+)?

reason will still include the -91

This gives only lines with -xx or (x), missing rest of the lines

disconnected, (?<reason>.+(?=-\d+|\(\d\)))

This gives all lines but will also include -xx and (x) in the reason

disconnected, (?<reason>.+(?=-\d+|\(\d\))?)

PS -xx and (x) are always at the end so can use anchor $

Body:
You could use an alternation with an optional non capturing group to match both options at the end of the string.

The value is in the named capture group reason.

disconnected, (?<reason>.*?)(?:\(\d+\)| -\d+)?$

In parts

disconnected,  Match disconnected, and a space

(?<reason>.*?) Named capture group reason, match any char as least as possible

(?: Non capture group

\(\d+\) Match 1+ digits between parenthesis

| Or

 -\d+ Match a space - and 1+ digits

)? Close group and make optional

$ End of string

Regex demo


问:
Deceptive site ahead
I have the next error: "Deceptive site ahead". My app is separate in frontend with Angular 8 and backend  with Laravel 5.8. The issue is when I deploy the backend to a subdomain (services), Google Chrome shows me that error. What's wrong?

I've done the same with another easy Laravel project and it's fine, but I don't know why it happens in this project.

I hope someone helps me and sorry for my English.

答:
Nothing to do with your code. Google has blacklisted/marked as unsafe your site for some reason which can harm users. If it is not done by you then you may have some script or file on your server which google has found and thinks it is unsafe. After clearing your files you may try to submit for review.

Check here more detailed information: https://www.malcare.com/blog/deceptive-site-ahead/

Title: Deceptive site ahead


答:
You must eval() the expression first if you want an integer

eval('3**21')
# 10460353203
```
<p>and to simply count digits (like digits number is string length) :</p>
<pre class="lang-py prettyprint-override"><code>num_digits = len(str(eval('3**21')))

print(num_digits)
# 11
</code>```

So your code could be :

a=input('number: ')
num_digits = len(str(eval(a)))

print('number has ',num_digits,'digits')
```

Title: I write the code in python to count digits of a number but It doesn't work for some numbers

Body:
You must eval() the expression first if you want an integer

eval('3**21')
# 10460353203

and to simply count digits (like digits number is string length) :

num_digits = len(str(eval('3**21')))

print(num_digits)
# 11

So your code could be :

a=input('number: ')
num_digits = len(str(eval(a)))

print('number has ',num_digits,'digits')


答:
```<code>persons = [
 { first_name: "John", last_name: "Doe" },
 { first_name: "Lisa", last_name: "Meyer"}
]
</code>```

persons is an array of hashes. Arrays can be accessed by their indexes.

So, the index 0 in persons is { first_name: "John", last_name: "Doe" }.

The index 1 in persons is { first_name: "Lisa", last_name: "Meyer"} and so on:

```<code>p persons[0] # {:first_name=>"John", :last_name=>"Doe"}
p persons[1] # {:first_name=>"Lisa", :last_name=>"Meyer"}
</code>```

Don't get confused in mutability here. It's just you're referring to the wrong data type.

If you want, you can check every hash key from persons and see that they have the same object_id (first_name and last_name). That's because symbols are immutables, allowing Ruby to create only one instance of them as long as your code is running:

```<code>persons.map { |e| e.map { |key, _| [key, key.object_id] }.to_h }
# [{:first_name=>1016988, :last_name=>1017308}, {:first_name=>1016988, :last_name=>1017308}]
</code>```

As per the comment question; no, it doesn't create a new object depending on the scope, e.g.:

```<code>p :first_name.object_id
# 1016668

def persons
  [{ first_name: "John", last_name: "Doe"  },
   { first_name: "Lisa", last_name: "Meyer"}]
end

p persons.map { |e| e.map { |key, _| [key, key.object_id] }.to_h }
# [{:first_name=>1016668, :last_name=>1017308}, {:first_name=>1016668, :last_name=>1017308}]
</code>```

:first_name.object_id is defined outside the scope of the persons method, but while inside the method, it keeps pointing to the same object.

Title: How can ONE Ruby-symbol map to MULTIPLE values?

Body:
From what I have read so far I know, that a symbol is pointing always to the same value. Unlike a string, which is mutable in Ruby. Means a string might not have the same value all the time.

But if I create a list which hashes like e.g. this one:

persons = [
           {first_name: "John", last_name: "Doe"},
           {first_name: "Lisa", last_name: "Meyer"}
          ]

If I now do:

persons[1][:first_name]

Then I get the correct value "Lisa".

But how does that work?

If a symbol can point to only one exact value:

How can it differentiate between the "first_name"-symbol of the first hash and the "first_name"-symbol of the second, third ... hash?

Body:
persons = [
 { first_name: "John", last_name: "Doe" },
 { first_name: "Lisa", last_name: "Meyer"}
]

persons is an array of hashes. Arrays can be accessed by their indexes.

So, the index 0 in persons is { first_name: "John", last_name: "Doe" }.

The index 1 in persons is { first_name: "Lisa", last_name: "Meyer"} and so on:

p persons[0] # {:first_name=>"John", :last_name=>"Doe"}
p persons[1] # {:first_name=>"Lisa", :last_name=>"Meyer"}

Don't get confused in mutability here. It's just you're referring to the wrong data type.

If you want, you can check every hash key from persons and see that they have the same object_id (first_name and last_name). That's because symbols are immutables, allowing Ruby to create only one instance of them as long as your code is running:

persons.map { |e| e.map { |key, _| [key, key.object_id] }.to_h }
# [{:first_name=>1016988, :last_name=>1017308}, {:first_name=>1016988, :last_name=>1017308}]

As per the comment question; no, it doesn't create a new object depending on the scope, e.g.:

p :first_name.object_id
# 1016668

def persons
  [{ first_name: "John", last_name: "Doe"  },
   { first_name: "Lisa", last_name: "Meyer"}]
end

p persons.map { |e| e.map { |key, _| [key, key.object_id] }.to_h }
# [{:first_name=>1016668, :last_name=>1017308}, {:first_name=>1016668, :last_name=>1017308}]

:first_name.object_id is defined outside the scope of the persons method, but while inside the method, it keeps pointing to the same object.


问:
Reading local HTML files into R for data extraction
I have a set of local html files in a folder. Using the code below I am able to import data. As a next step I want to merge a couple of files (all having same format), extract data and the contents into a tabular format for further analysis </p>

```<code>source <- FactivaSource("page1.html")
corpus <- Corpus(source, readerControl = list(language = NA))
inspect(corpus)
meta(corpus[[1]])
</code>```

答:
The easiest way to turn a corpus into a data frame is with tidytext::tidy, e.g.:

library(tm)
library(tidytext)

data("crude") # crude dataset is from `tm` package
tidy(crude)
```

<p>Once you've turned all your corpora into data frames you can combine them in whatever way makes sense - i.e. I would turn the corpora into data frames and then merge them, and not the other way around (although that's probably also possible).</p>

<p><strong>Output</strong>:</p>

```> tidytext::tidy(crude)
# A tibble: 20 x 16
   author datetimestamp       description heading id    language origin topics lewissplit
   <chr>  <dttm>              <chr>       <chr>   <chr> <chr>    <chr>  <chr>  <chr>
 1 NA     1987-02-26 18:00:56 ""          DIAMON… 127   en       Reute… YES    TRAIN
 2 BY TE… 1987-02-26 18:34:11 ""          OPEC M… 144   en       Reute… YES    TRAIN
 3 NA     1987-02-26 19:18:00 ""          TEXACO… 191   en       Reute… YES    TRAIN
 4 NA     1987-02-26 19:21:01 ""          MARATH… 194   en       Reute… YES    TRAIN
 5 NA     1987-02-26 20:00:57 ""          HOUSTO… 211   en       Reute… YES    TRAIN
 6 NA     1987-03-01 04:25:46 ""          KUWAIT… 236   en       Reute… YES    TRAIN
 7 By Je… 1987-03-01 04:39:14 ""          INDONE… 237   en       Reute… YES    TRAIN
 8 NA     1987-03-01 06:27:27 ""          SAUDI … 242   en       Reute… YES    TRAIN
 9 NA     1987-03-01 09:22:30 ""          QATAR … 246   en       Reute… YES    TRAIN
10 NA     1987-03-01 19:31:44 ""          SAUDI … 248   en       Reute… YES    TRAIN
11 NA     1987-03-02 02:05:49 ""          SAUDI … 273   en       Reute… YES    TRAIN
12 NA     1987-03-02 08:39:23 ""          GULF A… 349   en       Reute… YES    TRAIN
13 NA     1987-03-02 08:43:22 ""          SAUDI … 352   en       Reute… YES    TRAIN
14 NA     1987-03-02 08:43:41 ""          KUWAIT… 353   en       Reute… YES    TRAIN
15 NA     1987-03-02 09:25:42 ""          PHILAD… 368   en       Reute… YES    TRAIN
16 NA     1987-03-02 12:20:05 ""          STUDY … 489   en       Reute… YES    TRAIN
17 NA     1987-03-02 12:28:26 ""          STUDY … 502   en       Reute… YES    TRAIN
18 NA     1987-03-02 13:13:46 ""          UNOCAL… 543   en       Reute… YES    TRAIN
19 By BE… 1987-03-02 15:38:34 ""          NYMEX … 704   en       Reute… YES    TRAIN
20 NA     1987-03-02 15:49:06 ""          ARGENT… 708   en       Reute… YES    TRAIN
# … with 7 more variables: cgisplit <chr>, oldid <chr>, places <named list>, people <chr>,
#   orgs <chr>, exchanges <chr>, text <chr>
```

Body:
I have a set of local html files in a folder. Using the code below I am able to import data. As a next step I want to merge a couple of files (all having same format), extract data and the contents into a tabular format for further analysis

source <- FactivaSource("page1.html")
corpus <- Corpus(source, readerControl = list(language = NA))
inspect(corpus)
meta(corpus[[1]])

Body:
The easiest way to turn a corpus into a data frame is with tidytext::tidy, e.g.:

library(tm)
library(tidytext)

data("crude") # crude dataset is from `tm` package
tidy(crude)

Once you've turned all your corpora into data frames you can combine them in whatever way makes sense - i.e. I would turn the corpora into data frames and then merge them, and not the other way around (although that's probably also possible).

Output:

> tidytext::tidy(crude)
# A tibble: 20 x 16
   author datetimestamp       description heading id    language origin topics lewissplit
   <chr>  <dttm>              <chr>       <chr>   <chr> <chr>    <chr>  <chr>  <chr>
 1 NA     1987-02-26 18:00:56 ""          DIAMON… 127   en       Reute… YES    TRAIN
 2 BY TE… 1987-02-26 18:34:11 ""          OPEC M… 144   en       Reute… YES    TRAIN
 3 NA     1987-02-26 19:18:00 ""          TEXACO… 191   en       Reute… YES    TRAIN
 4 NA     1987-02-26 19:21:01 ""          MARATH… 194   en       Reute… YES    TRAIN
 5 NA     1987-02-26 20:00:57 ""          HOUSTO… 211   en       Reute… YES    TRAIN
 6 NA     1987-03-01 04:25:46 ""          KUWAIT… 236   en       Reute… YES    TRAIN
 7 By Je… 1987-03-01 04:39:14 ""          INDONE… 237   en       Reute… YES    TRAIN
 8 NA     1987-03-01 06:27:27 ""          SAUDI … 242   en       Reute… YES    TRAIN
 9 NA     1987-03-01 09:22:30 ""          QATAR … 246   en       Reute… YES    TRAIN
10 NA     1987-03-01 19:31:44 ""          SAUDI … 248   en       Reute… YES    TRAIN
11 NA     1987-03-02 02:05:49 ""          SAUDI … 273   en       Reute… YES    TRAIN
12 NA     1987-03-02 08:39:23 ""          GULF A… 349   en       Reute… YES    TRAIN
13 NA     1987-03-02 08:43:22 ""          SAUDI … 352   en       Reute… YES    TRAIN
14 NA     1987-03-02 08:43:41 ""          KUWAIT… 353   en       Reute… YES    TRAIN
15 NA     1987-03-02 09:25:42 ""          PHILAD… 368   en       Reute… YES    TRAIN
16 NA     1987-03-02 12:20:05 ""          STUDY … 489   en       Reute… YES    TRAIN
17 NA     1987-03-02 12:28:26 ""          STUDY … 502   en       Reute… YES    TRAIN
18 NA     1987-03-02 13:13:46 ""          UNOCAL… 543   en       Reute… YES    TRAIN
19 By BE… 1987-03-02 15:38:34 ""          NYMEX … 704   en       Reute… YES    TRAIN
20 NA     1987-03-02 15:49:06 ""          ARGENT… 708   en       Reute… YES    TRAIN
# … with 7 more variables: cgisplit <chr>, oldid <chr>, places <named list>, people <chr>,
#   orgs <chr>, exchanges <chr>, text <chr>


问:
Localizable.strings from framework is not getting inside framework
I have a project with some basic functionalities which I can reuse and I am trying to use that as a framework in another project. So my podspec includes strings, swift, assets files and all got added in to the project but the strings keys are not taking the value from localizables.strings. Basically it is not getting from the bundle path. Here is the code where I am calling the strings file inside the framework. "path" is getting as nil. It is working fine in the base project</p>

```<code>let bundle: Bundle = .main
if let currentLanguage = languageManager.getCurrentLanguage() {
   if let path = bundle.path(forResource: currentLanguage.rawValue, ofType: "lproj"),
      let bundle = Bundle(path: path) {
          return bundle.localizedString(forKey: self, value: nil, table: nil)
      }
}
</code>```

答:
I fixed the issue.. In podspec, it was

```<code>spec.resource_bundle = { 'AppName' => ['AppName/**/*.{strings}'] }
</code>```

I changed it to

```<code>spec.resources = "AppName/**/*.{xcassets}", "AppName/**/*.{Strings}"
</code>```

Body:
I have a project with some basic functionalities which I can reuse and I am trying to use that as a framework in another project. So my podspec includes strings, swift, assets files and all got added in to the project but the strings keys are not taking the value from localizables.strings. Basically it is not getting from the bundle path. Here is the code where I am calling the strings file inside the framework. "path" is getting as nil. It is working fine in the base project

let bundle: Bundle = .main
if let currentLanguage = languageManager.getCurrentLanguage() {
   if let path = bundle.path(forResource: currentLanguage.rawValue, ofType: "lproj"),
      let bundle = Bundle(path: path) {
          return bundle.localizedString(forKey: self, value: nil, table: nil)
      }
}

Body:
I fixed the issue.. In podspec, it was

spec.resource_bundle = { 'AppName' => ['AppName/**/*.{strings}'] }

I changed it to

spec.resources = "AppName/**/*.{xcassets}", "AppName/**/*.{Strings}"


问:
cannot make changes in context persist
I am working on a simple 3-tier MVC app, and cannot make context changes persist. Here is my code:

Controller:

```<code>    [HttpPost]
    public IActionResult Register(UserDto user)
    {
        userService.Register(user);
        return Ok("profile");
    }
</code>```

Service:

```<code>    public void Register(UserDto userDto)
    {
        User user = new User();
        user.FirstName = userDto.FirstName;
        user.LastName = userDto.LastName;
        user.Type = (UserType) userDto.Type;
        unitOfWork.UserRepository.AddAsync(user);
    }
</code>```

Repository:

```<code>    public Repository(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
        this.dbSet = dbContext.Set<T>();
    }

    public async Task AddAsync(params T[] entities)
    {
        await dbSet.AddRangeAsync(entities);
        await SaveChanges();
    }

    private async Task SaveChanges()
    {
        await dbContext.SaveChangesAsync();
    }
</code>```

Using my debugger, i found out that the dbset.AddRangeAsync does add the entity i set in the request into my dbContext. The problem is, on the next request, the entity is gone from the dbContext, and also does not appear in my database.Can somebody can explain me what am i doing wrong?

答:
Your add method is asynchronous.other methods that call this method must be asynchronous.</p>

```<code> public async Task Register(UserDto userDto)
    {
        User user = new User();
        user.FirstName = userDto.FirstName;
        user.LastName = userDto.LastName;
        user.Type = (UserType) userDto.Type;
       await unitOfWork.UserRepository.AddAsync(user);
    }

    [HttpPost]
    public async Task<IActionResult> Register(UserDto user)
    {
       await userService.Register(user);
        return Ok("profile");
    }
</code>```

Title: cannot make changes in context persist

Body:
I am working on a simple 3-tier MVC app, and cannot make context changes persist. Here is my code:

Controller:

    [HttpPost]
    public IActionResult Register(UserDto user)
    {
        userService.Register(user);
        return Ok("profile");
    }

Service:

    public void Register(UserDto userDto)
    {
        User user = new User();
        user.FirstName = userDto.FirstName;
        user.LastName = userDto.LastName;
        user.Type = (UserType) userDto.Type;
        unitOfWork.UserRepository.AddAsync(user);
    }

Repository:

    public Repository(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
        this.dbSet = dbContext.Set<T>();
    }

    public async Task AddAsync(params T[] entities)
    {
        await dbSet.AddRangeAsync(entities);
        await SaveChanges();
    }

    private async Task SaveChanges()
    {
        await dbContext.SaveChangesAsync();
    }

Using my debugger, i found out that the dbset.AddRangeAsync does add the entity i set in the request into my dbContext. The problem is, on the next request, the entity is gone from the dbContext, and also does not appear in my database.Can somebody can explain me what am i doing wrong?

Body:
Your add method is asynchronous.other methods that call this method must be asynchronous.

 public async Task Register(UserDto userDto)
    {
        User user = new User();
        user.FirstName = userDto.FirstName;
        user.LastName = userDto.LastName;
        user.Type = (UserType) userDto.Type;
       await unitOfWork.UserRepository.AddAsync(user);
    }

    [HttpPost]
    public async Task<IActionResult> Register(UserDto user)
    {
       await userService.Register(user);
        return Ok("profile");
    }


问:
how to colate a list of installed packages into a "one-liner" for re-installing later (using only grep / cut / sed / awk etc, no external tools)
Command:
apt list --installed

Output:

aapt/stable,now 7.1.2.33-7 aarch64 [installed]
abduco/stable,now 0.6-2 aarch64 [installed]
ack-grep/stable,now 3.3.1 all [installed]
antibody/stable,now 6.0.1 aarch64 [installed]
apt/stable,now 1.4.9-27 aarch64 [installed]
```

I would like:

aapt abduco ack-grep antibody apt

Therefore I need:

Only up-to the first / in the first field, but shown in one line, not multiple.

Background info:

I would like to backup a list of installed packages,

But only the name of the package, nothing else,

Shown on one line.

This list can then be appended with sudo apt install to make a quick one-liner for re-installing my packages later on, once I have wiped my system.

答:
This may help you:

apt list --installed | awk -F'/' '{print $1}' | tr '\n' ' '

apt list --installed list the packages.

awk -F'/' '{print $1}' take the first column using / as separator.

tr '\n' ' ' replace the jump lines for spaces.

Body:
Command:
apt list --installed

Output:

aapt/stable,now 7.1.2.33-7 aarch64 [installed]
abduco/stable,now 0.6-2 aarch64 [installed]
ack-grep/stable,now 3.3.1 all [installed]
antibody/stable,now 6.0.1 aarch64 [installed]
apt/stable,now 1.4.9-27 aarch64 [installed]

I would like:

aapt abduco ack-grep antibody apt

Therefore I need:

Only up-to the first / in the first field, but shown in one line, not multiple.

Background info:

I would like to backup a list of installed packages,

But only the name of the package, nothing else,

Shown on one line.

This list can then be appended with sudo apt install to make a quick one-liner for re-installing my packages later on, once I have wiped my system.


答:
You can try

```<code>a=input('number: ') # entered 3**21
if a.isalnum():
    a = int(a)
else:
    exec("a = {}".format(a))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')
</code>```

Output

```<code>number has  11 digits
</code>```

This code will cast a to int only if a contained only digits else it will execute python command to store the expiration that entered to expiration and not int.

Body:
In order to count digits of a number I write this code in python:

a=int(input('number: '))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')

It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...

It say:

ValueError: invalid literal for int() with base 10: '3**21'

3**21 is integer input So why it gives this erroer,and How Should I fix this?

Body:
You can try

a=input('number: ') # entered 3**21
if a.isalnum():
    a = int(a)
else:
    exec("a = {}".format(a))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')

Output

number has  11 digits

This code will cast a to int only if a contained only digits else it will execute python command to store the expiration that entered to expiration and not int.


问:
What's the query to get a list of a user's own posts that they have Liked?
Yes, I know that it's unusual for a user to "like" their own posts but that's what I'm looking for. I also know that you can't query the like table by user to get everything they've liked but that's not what I'm after. I just want their own posts (and later, photos) that they've liked.

I've clearly gotten pathetically rusty in my SQL skills--playing around with statements based off of the examples I've found:

```<code>SELECT source_id,message,created_time FROM stream WHERE source_id=me()
</code>```

and

```<code>SELECT actor_id, post_id, message FROM stream WHERE uid IN (SELECT uid2 FROM like WHERE uid1=me())
</code>```

I imagine what I want is either trivial to do or currently impossible. I expect the former.

答:
To get the post ids that the user likes, it would be something like:

```<code>SELECT post_id
FROM like
WHERE object_id in (SELECT source_id FROM stream WHERE source_id=me())
AND user_id = me()
</code>```

You could expand this to also include photo ids.  And you could nest it another level deep to get more post info by using the like's post_id field.

Body:
Yes, I know that it's unusual for a user to "like" their own posts but that's what I'm looking for. I also know that you can't query the like table by user to get everything they've liked but that's not what I'm after. I just want their own posts (and later, photos) that they've liked.

I've clearly gotten pathetically rusty in my SQL skills--playing around with statements based off of the examples I've found:

SELECT source_id,message,created_time FROM stream WHERE source_id=me()

and

SELECT actor_id, post_id, message FROM stream WHERE uid IN (SELECT uid2 FROM like WHERE uid1=me())

I imagine what I want is either trivial to do or currently impossible. I expect the former.

Body:
To get the post ids that the user likes, it would be something like:

SELECT post_id
FROM like
WHERE object_id in (SELECT source_id FROM stream WHERE source_id=me())
AND user_id = me()

You could expand this to also include photo ids.  And you could nest it another level deep to get more post info by using the like's post_id field.