问:
Can't open "frozen_east_text_detection.pb" in function 'c
the full error says:

cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1132: error: (-2:Unspecified error) FAILED: fs.is_open(). Can't open "frozen_east_text_detection.pb" in function 'c

here i have the code:

```<code>import time
from imutils.object_detection import non_max_suppression
import numpy as np
import cv2
import argparse

imagePath = "C:/xampp/htdocs/Tensorflow/TextDetection-master/images/tabla1.jpg"
east = "frozen_east_text_detection.pb"
newW = 640
newH = 480
min_confidence = 0.5

image = cv2.imread(imagePath) # it is working variable
orig = image.copy()
(H,W) = image.shape[:2]
</code>```

set the new width an height and then determine the ratio in change

```<code>rW = W / float(newW)
rH = H / float(newH)
</code>```

resize the image and grab the new image dimensions

```<code>image = cv2.resize(image, (newW, newH))
(H,W) = image.shape[:2]

"""
In order to perform text detection using OpenCV and the EAST deep learning model,
we need to extract the output feature maps of TWO LAYERS
"""
# Define the TWO output layer names ofr the EAST detector model
# FIRST LAYER : output probabilities of a region containing text or not.
# SECOND LAYER: bounding box coordinates of text.

layerNames = [
    "feature_fusion/Conv_7/Sigmoid",
    "feature_fusion/concat_3"
]

print("[INFO] loading EAST detector")
net = cv2.dnn.readNet( east ) #Load the Nerual Network into memory

# construct a blob from the image and then perform a forward pass of
# the model to obtain the two output layer sets

blob = cv2.dnn.blobFromImage( #https://www.pyimagesearch.com/2017/11/06/deep-learning-opencvs-blobfromimage-works/
    image , 1.0 , (W,H) , (123.68, 116.78, 103.94) , swapRB=True, crop=False
    )
start = time.time()
net.setInput(blob)
(scores, geometry) = net.forward(layerNames)
end = time.time()
print("[INFO] text detection took {:.6f} seconds".format(end-start))

# grab the umber of rows and columns from the scores volume, then
# initialize aour set of bounding box rectagles and corresponding
# cofidence scores

(numRows, numCols) = scores.shape[2:4]
rects = []
confidences = []

# loop over the number of rows
for y in range(0,numRows):
    #extract the scores (probabilities), followed by  the geometrical
    #data used to derive potential bounding box coordinates that
    #surround text
    scoresData = scores[0, 0, y]
    xData0 = geometry[0, 0, y]
    xData1 = geometry[0, 1, y]
    xData2 = geometry[0, 2, y]
    xData3 = geometry[0, 3, y]
    anglesData = geometry[0, 4, y]
    #loop over the number of columns
    for x in range(0, numCols):
        #i our score does not have sufficient probability, ignore it
        if (scoresData[x] < min_confidence):
            continue
        # compute the offset factor as our resulting feature maps will
        # be 4x smaller than the input image
        (offsetX, offsetY) = (x * 4.0 , y * 4.0)
        # extract the rotation angle for the prediction and then
        # compute the sin and cosine
        angle = anglesData[x]
        cos = np.cos(angle)
        sin = np.sin(angle)
        # use the geometry volume to derive the width and height of
        # the bounding box
        h = xData0[x] + xData2[x]
        w = xData1[x] + xData3[x]
        # compute both the starting and ending (x,y)-coordinates for
        # the text prediction bounding box
        endX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]) )
        endY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]) )
        startX = int(endX - w)
        startY = int(endY - h)
        #add the bounding box coordinates and probability score to
        #our respective lists
        rects.append(  (startX, startY, endX, endY)  )
        confidences.append(  scoresData[x]  )

#apply non-maxima suppression to suppress weak, overlapping bounding boxes
boxes = non_max_suppression(np.array(rects) , probs=confidences) #imutils-> https://github.com/jrosebr1/imutils/blob/master/imutils/object_detection.py#L4
#loop over the bounding boxes
for (startX, startY, endX, endY) in boxes:
    # scale the bounding box coordinates based on the respective ratios
    startX = int(startX * rW)
    startY = int(startY * rH)
    endX = int(endX * rW)
    endY = int(endY *rH)
    #draw the bounding box on the image
    cv2.rectangle( orig , (startX,startY) , (endX,endY) , (0,255,0) , 2 )
#show the outut image
cv2.imshow("Text detection",orig)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答: you can fix this by providing the absolute filepath of frozen_east_text_detection.pb from the main function of your code

Body:
the full error says:

cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1132: error: (-2:Unspecified error) FAILED: fs.is_open(). Can't open "frozen_east_text_detection.pb" in function 'c

here i have the code:

import time
from imutils.object_detection import non_max_suppression
import numpy as np
import cv2
import argparse

imagePath = "C:/xampp/htdocs/Tensorflow/TextDetection-master/images/tabla1.jpg"
east = "frozen_east_text_detection.pb"
newW = 640
newH = 480
min_confidence = 0.5

image = cv2.imread(imagePath) # it is working variable
orig = image.copy()
(H,W) = image.shape[:2]

set the new width an height and then determine the ratio in change

rW = W / float(newW)
rH = H / float(newH)

resize the image and grab the new image dimensions

image = cv2.resize(image, (newW, newH))
(H,W) = image.shape[:2]

"""
In order to perform text detection using OpenCV and the EAST deep learning model,
we need to extract the output feature maps of TWO LAYERS
"""
# Define the TWO output layer names ofr the EAST detector model
# FIRST LAYER : output probabilities of a region containing text or not.
# SECOND LAYER: bounding box coordinates of text.

layerNames = [
    "feature_fusion/Conv_7/Sigmoid",
    "feature_fusion/concat_3"
]

print("[INFO] loading EAST detector")
net = cv2.dnn.readNet( east ) #Load the Nerual Network into memory

# construct a blob from the image and then perform a forward pass of
# the model to obtain the two output layer sets

blob = cv2.dnn.blobFromImage( #https://www.pyimagesearch.com/2017/11/06/deep-learning-opencvs-blobfromimage-works/
    image , 1.0 , (W,H) , (123.68, 116.78, 103.94) , swapRB=True, crop=False
    )
start = time.time()
net.setInput(blob)
(scores, geometry) = net.forward(layerNames)
end = time.time()
print("[INFO] text detection took {:.6f} seconds".format(end-start))

# grab the umber of rows and columns from the scores volume, then
# initialize aour set of bounding box rectagles and corresponding
# cofidence scores

(numRows, numCols) = scores.shape[2:4]
rects = []
confidences = []

# loop over the number of rows
for y in range(0,numRows):
    #extract the scores (probabilities), followed by  the geometrical
    #data used to derive potential bounding box coordinates that
    #surround text
    scoresData = scores[0, 0, y]
    xData0 = geometry[0, 0, y]
    xData1 = geometry[0, 1, y]
    xData2 = geometry[0, 2, y]
    xData3 = geometry[0, 3, y]
    anglesData = geometry[0, 4, y]
    #loop over the number of columns
    for x in range(0, numCols):
        #i our score does not have sufficient probability, ignore it
        if (scoresData[x] < min_confidence):
            continue
        # compute the offset factor as our resulting feature maps will
        # be 4x smaller than the input image
        (offsetX, offsetY) = (x * 4.0 , y * 4.0)
        # extract the rotation angle for the prediction and then
        # compute the sin and cosine
        angle = anglesData[x]
        cos = np.cos(angle)
        sin = np.sin(angle)
        # use the geometry volume to derive the width and height of
        # the bounding box
        h = xData0[x] + xData2[x]
        w = xData1[x] + xData3[x]
        # compute both the starting and ending (x,y)-coordinates for
        # the text prediction bounding box
        endX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]) )
        endY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]) )
        startX = int(endX - w)
        startY = int(endY - h)
        #add the bounding box coordinates and probability score to
        #our respective lists
        rects.append(  (startX, startY, endX, endY)  )
        confidences.append(  scoresData[x]  )

#apply non-maxima suppression to suppress weak, overlapping bounding boxes
boxes = non_max_suppression(np.array(rects) , probs=confidences) #imutils-> https://github.com/jrosebr1/imutils/blob/master/imutils/object_detection.py#L4
#loop over the bounding boxes
for (startX, startY, endX, endY) in boxes:
    # scale the bounding box coordinates based on the respective ratios
    startX = int(startX * rW)
    startY = int(startY * rH)
    endX = int(endX * rW)
    endY = int(endY *rH)
    #draw the bounding box on the image
    cv2.rectangle( orig , (startX,startY) , (endX,endY) , (0,255,0) , 2 )
#show the outut image
cv2.imshow("Text detection",orig)
cv2.waitKey(0)
cv2.destroyAllWindows()


来源: stackexchange

问:
Sorting on partition keys during INSERT INTO (Parquet) TABLE with Impala
I have an ETL job where I want to append data from a .csv file into an Impala table. Currently, I do this by creating a temporary external .csv table with the new data (in .csv.lzo format), after which it is inserted into the main table.

The query I use looks like this:

```<code>INSERT INTO TABLE main_table
PARTITION(yr, mth)
SELECT
    *,
    CAST(extract(ts, "year") AS SMALLINT) AS yr,
    CAST(extract(ts, "month") AS TINYINT) AS mth
FROM csv_table
</code>```

where main_table is defined as follows (several columns truncated):

```<code>CREATE TABLE IF NOT EXISTS main_table (
    tid             INT,
    s1              VARCHAR,
    s2              VARCHAR,
    status          TINYINT,
    ts              TIMESTAMP,
    n1              DOUBLE,
    n2              DOUBLE,
    p               DECIMAL(3,2),
    mins            SMALLINT,
    temp            DOUBLE
)
PARTITIONED BY (yr SMALLINT, mth TINYINT)
STORED AS PARQUET
</code>```

The data is on the order of a few GB (55 million rows with some 30 columns), and this takes over an hour to run. I was curious as to why this was the case (as this seems rather long for something that is essentially an append operation), and came across this in the query plan:

```<code>F01:PLAN FRAGMENT [HASH(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))] hosts=2 instances=2
|  Per-Host Resources: mem-estimate=1.01GB mem-reservation=12.00MB thread-reservation=1
WRITE TO HDFS [default.main_table, OVERWRITE=false, PARTITION-KEYS=(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))]
|  partitions=unavailable
|  mem-estimate=1.00GB mem-reservation=0B thread-reservation=0
|
02:SORT
|  order by: CAST(extract(ts, 'year') AS SMALLINT) ASC NULLS LAST, CAST(extract(ts, 'month') AS TINYINT) ASC NULLS LAST
|  materialized: CAST(extract(ts, 'year') AS SMALLINT), CAST(extract(ts, 'month') AS TINYINT)
|  mem-estimate=12.00MB mem-reservation=12.00MB spill-buffer=2.00MB thread-reservation=0
|  tuple-ids=1 row-size=1.29KB cardinality=unavailable
|  in pipelines: 02(GETNEXT), 00(OPEN)
|
01:EXCHANGE [HASH(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))]
|  mem-estimate=2.57MB mem-reservation=0B thread-reservation=0
|  tuple-ids=0 row-size=1.28KB cardinality=unavailable
|  in pipelines: 00(GETNEXT)
|
</code>```

Apparently, most of the time and resources are spent sorting on the partition keys:

```<code>Operator       #Hosts  Avg Time  Max Time   #Rows  Est. #Rows  Peak Mem  Est. Peak Mem  Detail
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
02:SORT             2    17m16s    30m50s  55.05M          -1  25.60 GB       12.00 MB
01:EXCHANGE         2   9s493ms  12s822ms  55.05M          -1  26.98 MB        2.90 MB  HASH(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))
00:SCAN HDFS        2  51s958ms     1m10s  55.05M          -1  76.06 MB      704.00 MB  default.csv_table
</code>```

Why does Impala have to do this? Is there any way to partition the table without having to sort on the partition keys, or a way to speed it up in my case, where the entirety of the .csv files I'm trying to append has only 1 or 2 partition keys?

EDIT: It turns out that this is most likely because I'm using the Parquet file format. My question still applies though: is there a way to speed up the sort when I know there is little to no sorting actually required?

By comparison, an operation like SELECT COUNT(*) FROM csv_table WHERE extract(ts, "year") = 2018 AND extract(ts, "month") = 1 takes around 2-3 minutes, whereas the ORDER BY (as done during the insert) takes over an hour. This example only had the keys (2018,1) and (2018,2).

答:
You can add hint to disable the sort stage.

```<code>INSERT INTO TABLE main_table
PARTITION(yr, mth)  /* +NOCLUSTERED */
SELECT
    *,
    CAST(extract(ts, "year") AS SMALLINT) AS yr,
    CAST(extract(ts, "month") AS TINYINT) AS mth
FROM csv_table
</code>```

As explain here:Optimizer Hints

/* +CLUSTERED / and / +NOCLUSTERED / Hints / +CLUSTERED / sorts
  data by the partition columns before inserting to ensure that only one
  partition is written at a time per node. Use this hint to reduce the
  number of files kept open and the number of buffers kept in memory
  simultaneously. This technique is primarily useful for inserts into
  Parquet tables, where the large block size requires substantial memory
  to buffer data for multiple output files at once. This hint is
  available in Impala 2.8 or higher. Starting in Impala 3.0, /
  +CLUSTERED */ is the default behavior for HDFS tables.

/* +NOCLUSTERED */ does not sort by primary key before insert. This
  hint is available in Impala 2.8 or higher. Use this hint when
  inserting to Kudu tables.

In the versions lower than Impala 3.0, /* +NOCLUSTERED */ is the
  default in HDFS tables.

ContentLicense: CC BY-SA 4.0

Body:
I have an ETL job where I want to append data from a .csv file into an Impala table. Currently, I do this by creating a temporary external .csv table with the new data (in .csv.lzo format), after which it is inserted into the main table.

The query I use looks like this:

INSERT INTO TABLE main_table
PARTITION(yr, mth)
SELECT
    *,
    CAST(extract(ts, "year") AS SMALLINT) AS yr,
    CAST(extract(ts, "month") AS TINYINT) AS mth
FROM csv_table

where main_table is defined as follows (several columns truncated):

CREATE TABLE IF NOT EXISTS main_table (
    tid             INT,
    s1              VARCHAR,
    s2              VARCHAR,
    status          TINYINT,
    ts              TIMESTAMP,
    n1              DOUBLE,
    n2              DOUBLE,
    p               DECIMAL(3,2),
    mins            SMALLINT,
    temp            DOUBLE
)
PARTITIONED BY (yr SMALLINT, mth TINYINT)
STORED AS PARQUET

The data is on the order of a few GB (55 million rows with some 30 columns), and this takes over an hour to run. I was curious as to why this was the case (as this seems rather long for something that is essentially an append operation), and came across this in the query plan:

F01:PLAN FRAGMENT [HASH(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))] hosts=2 instances=2
|  Per-Host Resources: mem-estimate=1.01GB mem-reservation=12.00MB thread-reservation=1
WRITE TO HDFS [default.main_table, OVERWRITE=false, PARTITION-KEYS=(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))]
|  partitions=unavailable
|  mem-estimate=1.00GB mem-reservation=0B thread-reservation=0
|
02:SORT
|  order by: CAST(extract(ts, 'year') AS SMALLINT) ASC NULLS LAST, CAST(extract(ts, 'month') AS TINYINT) ASC NULLS LAST
|  materialized: CAST(extract(ts, 'year') AS SMALLINT), CAST(extract(ts, 'month') AS TINYINT)
|  mem-estimate=12.00MB mem-reservation=12.00MB spill-buffer=2.00MB thread-reservation=0
|  tuple-ids=1 row-size=1.29KB cardinality=unavailable
|  in pipelines: 02(GETNEXT), 00(OPEN)
|
01:EXCHANGE [HASH(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))]
|  mem-estimate=2.57MB mem-reservation=0B thread-reservation=0
|  tuple-ids=0 row-size=1.28KB cardinality=unavailable
|  in pipelines: 00(GETNEXT)
|

Apparently, most of the time and resources are spent sorting on the partition keys:

Operator       #Hosts  Avg Time  Max Time   #Rows  Est. #Rows  Peak Mem  Est. Peak Mem  Detail
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
02:SORT             2    17m16s    30m50s  55.05M          -1  25.60 GB       12.00 MB
01:EXCHANGE         2   9s493ms  12s822ms  55.05M          -1  26.98 MB        2.90 MB  HASH(CAST(extract(ts, 'year') AS SMALLINT),CAST(extract(ts, 'month') AS TINYINT))
00:SCAN HDFS        2  51s958ms     1m10s  55.05M          -1  76.06 MB      704.00 MB  default.csv_table

Why does Impala have to do this? Is there any way to partition the table without having to sort on the partition keys, or a way to speed it up in my case, where the entirety of the .csv files I'm trying to append has only 1 or 2 partition keys?

EDIT: It turns out that this is most likely because I'm using the Parquet file format. My question still applies though: is there a way to speed up the sort when I know there is little to no sorting actually required?

By comparison, an operation like SELECT COUNT(*) FROM csv_table WHERE extract(ts, "year") = 2018 AND extract(ts, "month") = 1 takes around 2-3 minutes, whereas the ORDER BY (as done during the insert) takes over an hour. This example only had the keys (2018,1) and (2018,2).

Body:
You can add hint to disable the sort stage.

INSERT INTO TABLE main_table
PARTITION(yr, mth)  /* +NOCLUSTERED */
SELECT
    *,
    CAST(extract(ts, "year") AS SMALLINT) AS yr,
    CAST(extract(ts, "month") AS TINYINT) AS mth
FROM csv_table

As explain here:Optimizer Hints

/* +CLUSTERED / and / +NOCLUSTERED / Hints / +CLUSTERED / sorts
  data by the partition columns before inserting to ensure that only one
  partition is written at a time per node. Use this hint to reduce the
  number of files kept open and the number of buffers kept in memory
  simultaneously. This technique is primarily useful for inserts into
  Parquet tables, where the large block size requires substantial memory
  to buffer data for multiple output files at once. This hint is
  available in Impala 2.8 or higher. Starting in Impala 3.0, /
  +CLUSTERED */ is the default behavior for HDFS tables.

/* +NOCLUSTERED */ does not sort by primary key before insert. This
  hint is available in Impala 2.8 or higher. Use this hint when
  inserting to Kudu tables.

In the versions lower than Impala 3.0, /* +NOCLUSTERED */ is the
  default in HDFS tables.


问:
How do I convert a JSONObject to class object?
I need to convert a JSONObject to a Location object using gson libraries for an android project of mine. I'm not sure on how to do this. Can anyone help me with this. Thanks in advance.

I have a code something like

```<code>JSONArray input = new JSONArray(extras.getString("loc_json"));
</code>```

I wanted to convert the JSONObject taken from the JSONArray to a Location class object. I just wanted to know whether there is a function that does it directly.

Pardon me if I framed the question in a wrong way. Since I haven't got the direct function, I did it in this way.

```<code> loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;
</code>```

Sorry for the stupid question.

答:
For kotlin

```<code> val objType = object : TypeToken<MyClass>() {

    }.getType()
    var myclassObj = gson.fromJson(value,objType)
</code>```

or

```<code> val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to convert a JSONObject to a Location object using gson libraries for an android project of mine. I'm not sure on how to do this. Can anyone help me with this. Thanks in advance.

I have a code something like

JSONArray input = new JSONArray(extras.getString("loc_json"));

I wanted to convert the JSONObject taken from the JSONArray to a Location class object. I just wanted to know whether there is a function that does it directly.

Pardon me if I framed the question in a wrong way. Since I haven't got the direct function, I did it in this way.

 loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;

Sorry for the stupid question.

Body:
For kotlin

 val objType = object : TypeToken<MyClass>() {

    }.getType()
    var myclassObj = gson.fromJson(value,objType)

or

 val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)


问:
php file_get_contents ('....datafile.xml') - get the datafile from my local desktop?
I have a database that exports xmls only locally (to my computer).  It will not export to a remote server.

I have a php file (located on remote server) that sends the xml to a webserivce.
Can I have the remote php file use "file_get_contents" function to extract xml data from my local computer?

If so, what is the proper syntax?
Thanks in advance.

答: I think you should add a file upload page,upload the local xml file to remote server,the do the the next work.</p>


问:
(Swift) How to get rid of "Left side of mutating operator isn't mutable"
complete error:

Left side of mutating operator isn't mutable: 'abc' is a 'let' constant

Happens because I am trying to change value of a variable sent by parameter to function.

Can I get rid of this, or find some other solution?

Code(My code is much complex, but in effect doing the same as this):

```<code>func generateABC() {
var abc = "this"
abc += "is"

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(abc)) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

abc += "function"
}
</code>```

handleTap function :

```<code>@objc
func handleTap(_ someString: String) {
     someString += "my"
}
</code>```

答:
You can not change a Passed variable's value within function. If you want to change value of someString then you have to store it into another variable and use it further like this.

```<code>@objc
func handleTap(_ someString: String) {
     var newString: String = someString
     newString += "my"
}
</code>```

Body:
complete error:

Left side of mutating operator isn't mutable: 'abc' is a 'let' constant

Happens because I am trying to change value of a variable sent by parameter to function.

Can I get rid of this, or find some other solution?

Code(My code is much complex, but in effect doing the same as this):

func generateABC() {
var abc = "this"
abc += "is"

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(abc)) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

abc += "function"
}

handleTap function :

@objc
func handleTap(_ someString: String) {
     someString += "my"
}

Body:
You can not change a Passed variable's value within function. If you want to change value of someString then you have to store it into another variable and use it further like this.

@objc
func handleTap(_ someString: String) {
     var newString: String = someString
     newString += "my"
}


问:
Time Series Data: Fill gaps in timeseries data and aggregate values
I am novice using VBA to organize some data in an Excel sheet. I also have some experience in Python if that is easier.

I have a .csv file from a model that outputs a discontinuous time series (whenever there is inflow but not every 1-min time step):

Date/Time Drainage cm/BRA
5/10/14 11:00  0
5/10/14 11:01    1
5/10/14
  11:02 2
5/10/14 11:03    2
5/10/14 11:04    1
5/11/14 7:00 1
5/11/14 7:01 0

5/11/14 7:02 1
5/11/14 7:03 1
5/11/14 7:04 0
5/11/14 7:05 0

What I want is to be able to aggregate the data to 2-min time steps. So that I get this:

Date/Time Drainage cm/BRA

 5/10/14 11:00    1
5/10/14 11:02    4
5/10/14
  11:04 1
5/10/14 11:06   0
5/10/14 11:08   0
...

...
 5/11/14 6:58    0
5/11/14 7:00 1
5/11/14 7:02 2
5/11/14 7:04 0

I already have a code that will aggregate the data for me as long as I have a continuous data file (in this example filling in the gaps between 5/10/14 11:04 to 5/11/14 7:00). As you can imagine, with minute data, there is too much to manually fill the gaps not to mention that I have to reproduce this for over 70 output files.

Any suggestions for creating a continuous time series or aggregating to 2-min despite uneven gaps in the time series??

答:
Give this solution a try.  It employs pandas and the following techniques:

Reading a CSV file into a DataFrame

Combining column data

Converting a date/time string to a datetime datatype

Resampling the datetime object to 2 minute intervals

Data Quality Issues:

There are a couple data quality issues in your CSV where:

The data is not actually comma separated

There are spaces in the column names

There are two columns, however three spaces in the data (date, time, drainage)

Give the above, there is a section of the code which addresses these issues.

Sample Code:

```<code>import pandas as pd

# Read Excel file into DataFrame.
df = pd.read_csv('./drainage.csv', sep=' ')

# Address data quality issues:
# Combine date and time columns.
df['Date/Time Drainage'] = df['Date/Time'] + ' ' + df['Drainage']
# Drop unneeded columns.
df.drop(['Date/Time', 'Drainage'], axis=1, inplace=True)
# Ensure Date/Time column is a datetime datatype.
df['Date/Time Drainage'] = pd.to_datetime(df['Date/Time Drainage'], format='%m/%d/%y %H:%M')

# Resample to 2 second intervals and sum results.
df = df.set_index('Date/Time Drainage').resample('2T').sum().reset_index()

# Show results.
print(df)
</code>```

Output:

```<code>     Date/Time Drainage  cm/BRA
0   2014-05-10 11:00:00       1
1   2014-05-10 11:02:00       4
2   2014-05-10 11:04:00       1
3   2014-05-10 11:06:00       0
4   2014-05-10 11:08:00       0
5   2014-05-10 11:10:00       0
...
597 2014-05-11 06:54:00       0
598 2014-05-11 06:56:00       0
599 2014-05-11 06:58:00       0
600 2014-05-11 07:00:00       1
601 2014-05-11 07:02:00       2
602 2014-05-11 07:04:00       0
</code>```

Body:
Give this solution a try.  It employs pandas and the following techniques:

Reading a CSV file into a DataFrame

Combining column data

Converting a date/time string to a datetime datatype

Resampling the datetime object to 2 minute intervals

Data Quality Issues:

There are a couple data quality issues in your CSV where:

The data is not actually comma separated

There are spaces in the column names

There are two columns, however three spaces in the data (date, time, drainage)

Give the above, there is a section of the code which addresses these issues.

Sample Code:

import pandas as pd

# Read Excel file into DataFrame.
df = pd.read_csv('./drainage.csv', sep=' ')

# Address data quality issues:
# Combine date and time columns.
df['Date/Time Drainage'] = df['Date/Time'] + ' ' + df['Drainage']
# Drop unneeded columns.
df.drop(['Date/Time', 'Drainage'], axis=1, inplace=True)
# Ensure Date/Time column is a datetime datatype.
df['Date/Time Drainage'] = pd.to_datetime(df['Date/Time Drainage'], format='%m/%d/%y %H:%M')

# Resample to 2 second intervals and sum results.
df = df.set_index('Date/Time Drainage').resample('2T').sum().reset_index()

# Show results.
print(df)

Output:

     Date/Time Drainage  cm/BRA
0   2014-05-10 11:00:00       1
1   2014-05-10 11:02:00       4
2   2014-05-10 11:04:00       1
3   2014-05-10 11:06:00       0
4   2014-05-10 11:08:00       0
5   2014-05-10 11:10:00       0
...
597 2014-05-11 06:54:00       0
598 2014-05-11 06:56:00       0
599 2014-05-11 06:58:00       0
600 2014-05-11 07:00:00       1
601 2014-05-11 07:02:00       2
602 2014-05-11 07:04:00       0


问:
Prompt auto message when 'zero' as input in win32 code
I have tried tooltip feature in win32 code, when 'OK' clicked the message displays only when we hover on particular box. But the feature Iam expecting is auto display of message at particular box when 'OK' is clicked. Is it possible to add such feature of auto popup? I need some balloon type of error popup.
My exact scenario is to error popup when Zero is given as input in a dialog, when 'OK' is clicked.</p>

```<code>HWND gzui_controls::create_tool_tip_balloon(HWND hdlg, int tool_id, PTSTR text) const { if (!tool_id || !hdlg || !text) { return FALSE; }

HWND hwndTool = GetDlgItem(hdlg, tool_id);
if (WM_LBUTTONUP)
{
HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
        WS_POPUP | SWP_NOMOVE | TTS_NOPREFIX | TTS_BALLOON | BS_PUSHBUTTON,
        CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT,
        hdlg, NULL,
        getModuleInstance(), NULL);

    if (!hwndTool || !hwndTip)
    {
        return (HWND)NULL;
    }

    // Associate the tooltip with the tool.
    TOOLINFO toolInfo = { 0 };
    toolInfo.cbSize = sizeof(toolInfo);
    toolInfo.hwnd = hdlg;
    toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
    toolInfo.uId = (UINT_PTR)hwndTool;
    toolInfo.lpszText = text;
    SendMessage(hwndTip, TTM_ADDTOOL, 0, (LPARAM)&toolInfo);
    return hwndTip;
}
</code>```

答:
The following is an example of balloon tip for display information when input value is not valid.

```<code>#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

// ...

   editHwnd = CreateWindow(L"EDIT",
       NULL,
       WS_VISIBLE | WS_CHILD | ES_MULTILINE | WS_BORDER,
       120,
       10,
       100,
       100,
       hWnd,
       NULL,
       hInst,
       NULL);

// ...

case WM_COMMAND:
    {
        if (HIWORD(wParam) == EN_CHANGE)
        {
            // TODO: Add logic of detecting input value here
            if (editHwnd == (HWND)lParam) // && inputVal == 0
            {
                balloonTip.cbStruct = sizeof(EDITBALLOONTIP);
                balloonTip.pszText = L"Zero is given as input";
                balloonTip.pszTitle = L"Tips";
                balloonTip.ttiIcon = TTI_INFO;
                Edit_ShowBalloonTip(editHwnd, &balloonTip);
            }
        }
    }
    break;
</code>```

Refer to Edit Control, EDITBALLOONTIP structure, Edit_ShowBalloonTip macro

Note  To use Edit_ShowBalloonTip macro, you must provide a manifest specifying
  Comclt32.dll version 6.0.

It will like this:

Body:
I have tried tooltip feature in win32 code, when 'OK' clicked the message displays only when we hover on particular box. But the feature Iam expecting is auto display of message at particular box when 'OK' is clicked. Is it possible to add such feature of auto popup? I need some balloon type of error popup.
My exact scenario is to error popup when Zero is given as input in a dialog, when 'OK' is clicked.

HWND gzui_controls::create_tool_tip_balloon(HWND hdlg, int tool_id, PTSTR text) const { if (!tool_id || !hdlg || !text) { return FALSE; }

HWND hwndTool = GetDlgItem(hdlg, tool_id);
if (WM_LBUTTONUP)
{
HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
        WS_POPUP | SWP_NOMOVE | TTS_NOPREFIX | TTS_BALLOON | BS_PUSHBUTTON,
        CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT,
        hdlg, NULL,
        getModuleInstance(), NULL);

    if (!hwndTool || !hwndTip)
    {
        return (HWND)NULL;
    }

    // Associate the tooltip with the tool.
    TOOLINFO toolInfo = { 0 };
    toolInfo.cbSize = sizeof(toolInfo);
    toolInfo.hwnd = hdlg;
    toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
    toolInfo.uId = (UINT_PTR)hwndTool;
    toolInfo.lpszText = text;
    SendMessage(hwndTip, TTM_ADDTOOL, 0, (LPARAM)&toolInfo);
    return hwndTip;
}

Body:
The following is an example of balloon tip for display information when input value is not valid.

#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

// ...

   editHwnd = CreateWindow(L"EDIT",
       NULL,
       WS_VISIBLE | WS_CHILD | ES_MULTILINE | WS_BORDER,
       120,
       10,
       100,
       100,
       hWnd,
       NULL,
       hInst,
       NULL);

// ...

case WM_COMMAND:
    {
        if (HIWORD(wParam) == EN_CHANGE)
        {
            // TODO: Add logic of detecting input value here
            if (editHwnd == (HWND)lParam) // && inputVal == 0
            {
                balloonTip.cbStruct = sizeof(EDITBALLOONTIP);
                balloonTip.pszText = L"Zero is given as input";
                balloonTip.pszTitle = L"Tips";
                balloonTip.ttiIcon = TTI_INFO;
                Edit_ShowBalloonTip(editHwnd, &balloonTip);
            }
        }
    }
    break;

Refer to Edit Control, EDITBALLOONTIP structure, Edit_ShowBalloonTip macro

Note  To use Edit_ShowBalloonTip macro, you must provide a manifest specifying
  Comclt32.dll version 6.0.

It will like this:


问:
qsort() works in one direction, but not other
This is how I made my comparison function to pass to qsort():

```<code>int charCompare(const void* ptr1, const void* ptr2)
{
   char c1 = *(char*)ptr1;
   char c2 = *(char*)ptr2;
   return c1 - c2;
}
</code>```

And this is the implementation:

```<code>char buffer[SIZE];
/*
 * buffer filled here
 */
qsort(buffer, sizeof(buffer)/sizeof(char), sizeof(char), charCompare);
printf("%s", buffer);
</code>```

Nothing gets printed. I'm pretty sure it's because the null characters are coming before the regular characters, since it works the other way (if I return c2-c1 instead from charCompare). But how would I go about getting rid of the null characters, since I want it to be in order from a to z, not the other way around?

答:
If your initial buffer starts off filled with an ordinary C string, which has only a single null terminator at the end, and you want it to end up that way, then you can just exclude the last spot from the sort:</p>

```<code>qsort(buffer, strlen(buffer), 1, charCompare);
</code>```

Body:
This is how I made my comparison function to pass to qsort():

int charCompare(const void* ptr1, const void* ptr2)
{
   char c1 = *(char*)ptr1;
   char c2 = *(char*)ptr2;
   return c1 - c2;
}

And this is the implementation:

char buffer[SIZE];
/*
 * buffer filled here
 */
qsort(buffer, sizeof(buffer)/sizeof(char), sizeof(char), charCompare);
printf("%s", buffer);

Nothing gets printed. I'm pretty sure it's because the null characters are coming before the regular characters, since it works the other way (if I return c2-c1 instead from charCompare). But how would I go about getting rid of the null characters, since I want it to be in order from a to z, not the other way around?

Body:
If your initial buffer starts off filled with an ordinary C string, which has only a single null terminator at the end, and you want it to end up that way, then you can just exclude the last spot from the sort:

qsort(buffer, strlen(buffer), 1, charCompare);


问:
How to remove top status bar black background
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

```

<p>Manifest:</p>

<pre class="lang-xml prettyprint-override"><code><activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />
</code>```

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

<p>Kotlin (commented lines are tried and failed):</p>

```class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}
```

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

答:
Add this method in your activity

```<code>public static void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
</code>```

before adding this call this below super.onCreate(savedInstanceState); onCreate

```<code>    hideSystemUI();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    }
</code>```

above attribute is use if your device have notch cutout for camera.

Body:
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

Manifest:

<activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Kotlin (commented lines are tried and failed):

class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

Body:
Add this method in your activity

public static void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}

before adding this call this below super.onCreate(savedInstanceState); onCreate

    hideSystemUI();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    }

above attribute is use if your device have notch cutout for camera.


问:
R variable inside a string
I would like to know if it is possible to pass a variable inside a string with R like in php. For example:</p>

```<code>args <- commandArgs(TRUE)
variable1 <- args[1]

variable2 <- "I am argument:",variable1,"text continue"
</code>```

答:
```<code>variable2 <- paste0("I am argument:",variable1,"text continue")
</code>```

Title: R variable inside a string

Body:
I would like to know if it is possible to pass a variable inside a string with R like in php. For example:

args <- commandArgs(TRUE)
variable1 <- args[1]

variable2 <- "I am argument:",variable1,"text continue"


问:
Working with file directories and variables
I have a program that I want to make more dynamic. The current setup is literally typing everything out.

I would like the program to work with a for loop (any other suggestions would be great). My goal is to loop through a specific file that has sub-directories and get the name of each folder (sub-directory),  then get the name of the files within the sub-directory.

To put this in a file string:
C:\Folder 1\Folder 2\File name

From the above, I would like to get the value of Folder 2 and File name.

My code so far:

```<code>for sub_dir in os.listdir(r"C:\Folder 1\"):
    DIR = r'' + sub_dir
    files_found = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
    if(files_found > 0):
        for files in os.listdir(sub_dir):
            file_name = os.path.splitext(files)[0]
</code>```

I get the error --> FileNotFoundError: [WinError 3] The system cannot find the path specified: Folder 2

I appreciate your efforts to help.

答: You should take a look at os.walk</p>

Body:
I have a program that I want to make more dynamic. The current setup is literally typing everything out.

I would like the program to work with a for loop (any other suggestions would be great). My goal is to loop through a specific file that has sub-directories and get the name of each folder (sub-directory),  then get the name of the files within the sub-directory.

To put this in a file string:
C:\Folder 1\Folder 2\File name

From the above, I would like to get the value of Folder 2 and File name.

My code so far:

for sub_dir in os.listdir(r"C:\Folder 1\"):
    DIR = r'' + sub_dir
    files_found = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
    if(files_found > 0):
        for files in os.listdir(sub_dir):
            file_name = os.path.splitext(files)[0]

I get the error --> FileNotFoundError: [WinError 3] The system cannot find the path specified: Folder 2

I appreciate your efforts to help.

Body: You should take a look at os.walk


问:
How to pass structured data from jQuery?
Here's my code in jQuery

```<code>    function link() {

        var items = $.map($('.trSelected', grd), function (i) {
            return i.id.substr(3);
        });

        // alert(items.length);
        // alert(items.join(', '));

        $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
            data: ( { PosId: '@Model.PosId', PosDetailIds: items } ),
            success: function (result) {
                grd.flexReload();
                alert('saved.');
            }
        });

    }
</code>```

Here's my code in ASP.NET MVC controller

```<code>    [HttpPost]
    public JsonResult Link(PosLink posLink)
    {

        var svc = ServiceWirer.GetTxServiceInstance();
        svc.Pos_Link(posLink);

        return Json(new { HasError = false });
    }
</code>```

For reasons unknownst to me, only the PosId is populated, the PosDetailIds is not populated

[UPDATE]

@Raynos:

I even tried this, but no go too:

```<code>public JsonResult Link(Guid PosId, Guid[] PosDetailIds)
</code>```

Only the PosId is populated, the PosDetailIds is still null

Here's the PosLink structure:

```<code>public class PosLink
{
    public Guid PosId { get; set; }
    public Guid[] PosDetailIds { get; set; }
}
</code>```

答:
I solved it now, I used jQuery's $.param

```<code>  $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
        data: $.param( { PosId: '@Model.PosId', PosDetailIds: items }, true ),
        success: function (result) {
            grd.flexReload();
            alert('saved.');
        }
    });
</code>```

Way much better:

```<code>  $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
        traditional : true, // jQuery folks love PHP/Ruby very much :-)
        data:  { PosId: '@Model.PosId', PosDetailIds: items },
        success: function (result) {
            grd.flexReload();
            alert('saved.');
        }
    });
</code>```

Rationale found here: http://forum.jquery.com/topic/jquery-1-4-breaks-asp-net-mvc-parameter-posting

Body:
Here's my code in jQuery

    function link() {

        var items = $.map($('.trSelected', grd), function (i) {
            return i.id.substr(3);
        });

        // alert(items.length);
        // alert(items.join(', '));

        $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
            data: ( { PosId: '@Model.PosId', PosDetailIds: items } ),
            success: function (result) {
                grd.flexReload();
                alert('saved.');
            }
        });

    }

Here's my code in ASP.NET MVC controller

    [HttpPost]
    public JsonResult Link(PosLink posLink)
    {

        var svc = ServiceWirer.GetTxServiceInstance();
        svc.Pos_Link(posLink);

        return Json(new { HasError = false });
    }

For reasons unknownst to me, only the PosId is populated, the PosDetailIds is not populated

[UPDATE]

@Raynos:

I even tried this, but no go too:

public JsonResult Link(Guid PosId, Guid[] PosDetailIds)

Only the PosId is populated, the PosDetailIds is still null

Here's the PosLink structure:

public class PosLink
{
    public Guid PosId { get; set; }
    public Guid[] PosDetailIds { get; set; }
}

Body:
I solved it now, I used jQuery's $.param

  $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
        data: $.param( { PosId: '@Model.PosId', PosDetailIds: items }, true ),
        success: function (result) {
            grd.flexReload();
            alert('saved.');
        }
    });

Way much better:

  $.ajax({ url: '/Pos/Link', type: 'POST', datatype: 'json',
        traditional : true, // jQuery folks love PHP/Ruby very much :-)
        data:  { PosId: '@Model.PosId', PosDetailIds: items },
        success: function (result) {
            grd.flexReload();
            alert('saved.');
        }
    });

Rationale found here: http://forum.jquery.com/topic/jquery-1-4-breaks-asp-net-mvc-parameter-posting


问:
ion-slides won't work before reloading the page
I have a problem with an ion-slide since I updated the @ionic-native/... modules to 5.21.5 and @ionic/angular to 5.0.0, so I stripped the slider down as much as possible to find the problem, without success.

Here's my template

```<code><ion-slides
    [options]="slideOpts"
    pager="true"
    (ionSlideDidChange)="updateSlideIndex()">

    <ion-slide>
      <h1>Slide 1</h1>
    </ion-slide>
    <ion-slide>
      <h1>Slide 2</h1>
    </ion-slide>
    <ion-slide>
      <h1>Slide 3</h1>
    </ion-slide>
</ion-slides>
</code>```

And the TS part:

```<code>  @ViewChild(IonSlides, { static: true }) slides: IonSlides;
  slideOpts = {
    effect: 'slide',
    speed: 1000,
    pager: true,
    initialSlide: 0,
  };
</code>```

After entring the site with the slider via routerLink, the slider is loaded but the slide effect isn't working (it looks like only one slide) and the pagination is missing.

After reloading the page (F5), or going back and clicking the same link again, everything forks fine.

Do I have to downgrade everything now?

答:
A downgrade back to Angular 8, solved the problem for me.

The problem is/was the following:
@ionic-team/ionic/issues/20356

Body:
I have a problem with an ion-slide since I updated the @ionic-native/... modules to 5.21.5 and @ionic/angular to 5.0.0, so I stripped the slider down as much as possible to find the problem, without success.

Here's my template

<ion-slides
    [options]="slideOpts"
    pager="true"
    (ionSlideDidChange)="updateSlideIndex()">

    <ion-slide>

Slide 1

    </ion-slide>
    <ion-slide>

Slide 2

    </ion-slide>
    <ion-slide>

Slide 3

    </ion-slide>
</ion-slides>

And the TS part:

  @ViewChild(IonSlides, { static: true }) slides: IonSlides;
  slideOpts = {
    effect: 'slide',
    speed: 1000,
    pager: true,
    initialSlide: 0,
  };

After entring the site with the slider via routerLink, the slider is loaded but the slide effect isn't working (it looks like only one slide) and the pagination is missing.

After reloading the page (F5), or going back and clicking the same link again, everything forks fine.

Do I have to downgrade everything now?


问:
Skip the filenames whch do not have contents while doing a for loop
I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

```<code>for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done
</code>```

Output

```<code>-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)
</code>```

Desired output..

```<code>-- file6 --
some output
-- file9 --
some output
</code>```

答:
You could try the -q option if you're just interested in the files which has the word string in it.

```<code>for files in *; do
  [[ -f $files ]] || continue          ##: Don't grep directories.
  if grep -q string -- "$files"; then  ##: Don't output anything if string is found.
    echo "$files"                      ##: Print the files which has string in it.
  fi
done
</code>```

This might do what you want though.

```<code>for files in *; do
  [[ -f $files ]] || continue                ##: Don't grep directories.
  if found=$(grep string -- "$files"); then  ##: Save successful match in the variable found
    printf '%s\n %s\n' --"$files"-- "$found"   ##: Print the desired output.
  fi
done
</code>```

Body:
I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done

Output

-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)

Desired output..

-- file6 --
some output
-- file9 --
some output

Body:
You could try the -q option if you're just interested in the files which has the word string in it.

for files in *; do
  [[ -f $files ]] || continue          ##: Don't grep directories.
  if grep -q string -- "$files"; then  ##: Don't output anything if string is found.
    echo "$files"                      ##: Print the files which has string in it.
  fi
done

This might do what you want though.

for files in *; do
  [[ -f $files ]] || continue                ##: Don't grep directories.
  if found=$(grep string -- "$files"); then  ##: Save successful match in the variable found
    printf '%s\n %s\n' --"$files"-- "$found"   ##: Print the desired output.
  fi
done


问:
Repository is not clean. Please commit or stash any changes before updating In Angular 8
Error

Repository is not clean.  Please commit or stash any changes before updating

when i have updated from version 7 to Angular 8.

Angular Guide for upgrade https://update.angular.io/#7.0:8.0

```<code>  D:\app-test> ng update @angular/cli @angular/core
               npm cache verify
</code>```

Repository is not clean.  Please commit or stash any changes before updating.

Update Version

```<code>    PS D:\app-test> ng update
                Using package manager: 'npm'
                Collecting installed dependencies...
                Found 58 dependencies.
                    We analyzed your package.json, there are some packages to update:

                      Name                               Version                  Command to update
                     --------------------------------------------------------------------------------
                      @angular/cdk                       7.2.2 -> 8.0.1           ng update @angular/cdk
                      @angular/core                      7.2.15 -> 8.0.1          ng update @angular/core
                      @angular/core                      7.2.2 -> 7.2.15          ng update @angular/core
                      @angular/material                  7.3.7 -> 8.0.1           ng update @angular/material
                      rxjs                               6.3.3 -> 6.5.2           ng update rxjs

                    There might be additional packages that are outdated.
                    Run "ng update --all" to try to update all at the same time.

                PS D:\app-test> ng update @angular/cdk
                Repository is not clean.  Please commit or stash any changes before updating.
</code>```

i have checked git was not installed in project.

solution that worked

```<code>   git commit
</code>```

After Googling i have This is happening After Angular 8.

Bug

https://github.com/angular/angular-cli/issues/14600

答:
I have tried using mention command for upgrading from angular 8 to angular 9, but was still getting the error.

Then i have tried same command with --force flag and it worked for me.

```<code>ng update @angular/cli @angular/core --allow-dirty --force
</code>```

Body:
Error

Repository is not clean.  Please commit or stash any changes before updating

when i have updated from version 7 to Angular 8.

Angular Guide for upgrade https://update.angular.io/#7.0:8.0

  D:\app-test> ng update @angular/cli @angular/core
               npm cache verify

Repository is not clean.  Please commit or stash any changes before updating.

Update Version

    PS D:\app-test> ng update
                Using package manager: 'npm'
                Collecting installed dependencies...
                Found 58 dependencies.
                    We analyzed your package.json, there are some packages to update:

                      Name                               Version                  Command to update
                     --------------------------------------------------------------------------------
                      @angular/cdk                       7.2.2 -> 8.0.1           ng update @angular/cdk
                      @angular/core                      7.2.15 -> 8.0.1          ng update @angular/core
                      @angular/core                      7.2.2 -> 7.2.15          ng update @angular/core
                      @angular/material                  7.3.7 -> 8.0.1           ng update @angular/material
                      rxjs                               6.3.3 -> 6.5.2           ng update rxjs

                    There might be additional packages that are outdated.
                    Run "ng update --all" to try to update all at the same time.

                PS D:\app-test> ng update @angular/cdk
                Repository is not clean.  Please commit or stash any changes before updating.

i have checked git was not installed in project.

solution that worked

   git commit

After Googling i have This is happening After Angular 8.

Bug

https://github.com/angular/angular-cli/issues/14600

Body:
I have tried using mention command for upgrading from angular 8 to angular 9, but was still getting the error.

Then i have tried same command with --force flag and it worked for me.

ng update @angular/cli @angular/core --allow-dirty --force


答:
Grep can do it alone

```<code>grep -ril 'string' /path/to/search
</code>```

From grep's help

```<code>$ grep --help
...
-r, --recursive           like --directories=recurse
-i, --ignore-case         ignore case distinctions
-l, --files-with-matches  print only names of FILEs with selected lines
...
</code>```

Title: Skip the filenames whch do not have contents while doing a for loop

Body:
Grep can do it alone

grep -ril 'string' /path/to/search

From grep's help

$ grep --help
...
-r, --recursive           like --directories=recurse
-i, --ignore-case         ignore case distinctions
-l, --files-with-matches  print only names of FILEs with selected lines
...


问:
Play YouTube video using webbrowser in python3
I want to play YouTube video using Python3. I can open the YouTube video using webbrowser.open(), but then i need to either press space or mouse click the play button to actually play the video. How to automate this, without using seleinum if possible.

```<code>        try:
        client = webbrowser.get("firefox")
        client.open("https://" + open_url)
    except webbrowser.Error as e:
        print(e)
</code>```

In browser's console (inspect element), if I enter

```<code>document.querySelector('.ytp-play-button').click();
</code>```

the video gets played, is there a way to simply pass this script (anyother alternative will also do the trick).

I am a student, and already know how to use selenium, and was just wondering if there is a simple was to do this one exact thing without selenium.

Oh yeah, when I simply copy past the url into chrome, or firefox tab than video gets played automatically without requiring me to press space or click the play button, if you know the answer to why this than please share it.

Thank you for your feedbacks.

答:
You can play youtube videos using mpv. In the cmd you can play video Like This. Now using subprocess or os module you can run that command and play </p>

```<code>import os
os.system(f"mpv https://www.youtube.com/watch?v=WNeLUngb-Xg")
</code>```

Body:
I want to play YouTube video using Python3. I can open the YouTube video using webbrowser.open(), but then i need to either press space or mouse click the play button to actually play the video. How to automate this, without using seleinum if possible.

        try:
        client = webbrowser.get("firefox")
        client.open("https://" + open_url)
    except webbrowser.Error as e:
        print(e)

In browser's console (inspect element), if I enter

document.querySelector('.ytp-play-button').click();

the video gets played, is there a way to simply pass this script (anyother alternative will also do the trick).

I am a student, and already know how to use selenium, and was just wondering if there is a simple was to do this one exact thing without selenium.

Oh yeah, when I simply copy past the url into chrome, or firefox tab than video gets played automatically without requiring me to press space or click the play button, if you know the answer to why this than please share it.

Thank you for your feedbacks.

Body:
You can play youtube videos using mpv. In the cmd you can play video Like This. Now using subprocess or os module you can run that command and play

import os
os.system(f"mpv https://www.youtube.com/watch?v=WNeLUngb-Xg")


问:
spring-data @Query mapping result issue
I've created a Repository that extends CrudRepository,
this repository has a method with an @Query notation:

Code:

```<code>@Query("select itemType, count(*) as count from Item where  User_id = :userId group by itemType")
List<Map<String, Long>> countItemsForUser(@Param("userId") Long userId);
</code>```

The issue I'm having is that this return a ArrayList of Object(s) and not a List of Map.
I've read somewhere that JPA can't return a Map so that's why I stuff the result in a List>.

I don't know what's the best way to work around this issue or to quickly access the result data.
I've tried casting but that didn't work out either:

```<code>for(Object item: items) {
    Map<String,Long> castedItem = (HashMap<String,Long>)item;
}
</code>```

答:
Most simple way is to use interface. To let Spring wire query alias
 to the interface getter. Example can be found here: https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions
also there is @SqlResultSetMapping. See:
JPA- Joining two tables in non-entity class</p>

Title: spring-data @Query mapping result issue

Body:
I've created a Repository that extends CrudRepository,
this repository has a method with an @Query notation:

Code:

@Query("select itemType, count(*) as count from Item where  User_id = :userId group by itemType")
List<Map<String, Long>> countItemsForUser(@Param("userId") Long userId);

The issue I'm having is that this return a ArrayList of Object(s) and not a List of Map.
I've read somewhere that JPA can't return a Map so that's why I stuff the result in a List>.

I don't know what's the best way to work around this issue or to quickly access the result data.
I've tried casting but that didn't work out either:

for(Object item: items) {
    Map<String,Long> castedItem = (HashMap<String,Long>)item;
}


问:
Cannot locate my php ini file on live server?
I tried different solutions suggested here, but still cannot find the file through cPanel on my live server.

I'm running

```<code>phpinfo();
</code>```

And getting this result:

```<code>Configuration File (php.ini) Path   /opt/alt/php56/etc
</code>```

I cannot find these folders: /opt/alt/php56
But I could find the etc folder, however the file is not there, and I made sure I checked "View hidden files" options

What else could be done?

答:
try:

```<code>php --ini
</code>```

it will print all config files locations

Body:
I tried different solutions suggested here, but still cannot find the file through cPanel on my live server.

I'm running

phpinfo();

And getting this result:

Configuration File (php.ini) Path   /opt/alt/php56/etc

I cannot find these folders: /opt/alt/php56
But I could find the etc folder, however the file is not there, and I made sure I checked "View hidden files" options

What else could be done?

Body:
try:

php --ini

it will print all config files locations


问:
Thread in Android
I have an example like this:

```<code>package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run()
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        //---do some long lasting work here---
        private int doSomeWork()
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}
</code>```

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

```<code>            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);
</code>```

Anybody can tell me why i can't?

答: Take a look at the Handler class.  It provides a simple way to enqueue Runnable callbacks to run on the UI event thread.</p>

Title: Thread in Android

Body:
I have an example like this:

package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run()
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        //---do some long lasting work here---
        private int doSomeWork()
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);

Anybody can tell me why i can't?


问:
React Js conditionally applying class attributes
I want to conditionally show and hide this button group depending on what is passed in from the parent component which looks like this:

```<code>    <TopicNav showBulkActions={this.__hasMultipleSelected} />

</code>```
```<code>    __hasMultipleSelected: function() {
      return false; //return true or false depending on data
    }
</code>```
```<code>    var TopicNav = React.createClass({
    render: function() {
    return (
        <div className="row">
            <div className="col-lg-6">
                <div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">
                    <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                      Bulk Actions <span className="caret"></span>
                    </button>
                    <ul className="dropdown-menu" role="menu">
                      <li><a href="#">Merge into New Session</a></li>
                      <li><a href="#">Add to Existing Session</a></li>
                      <li className="divider"></li>
                      <li><a href="#">Delete</a></li>
                    </ul>
                </div>
            </div>
        </div>
        );
      }
    });
</code>```

Nothing is happening however, with the {this.props.showBulkActions ? 'show' : 'hidden'}. Am I doing anything wrong here?

答:
Reference to @split fire answer, we can update it with template literals, which is more readable,For reference Checkout javascript template literal</p>

```<code><div className={`btn-group pull-right ${this.props.showBulkActions ? 'show' : 'hidden'}`}>
</code>```

Body:
I want to conditionally show and hide this button group depending on what is passed in from the parent component which looks like this:

    <TopicNav showBulkActions={this.__hasMultipleSelected} />

    __hasMultipleSelected: function() {
      return false; //return true or false depending on data
    }

    var TopicNav = React.createClass({
    render: function() {
    return (

                    <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                      Bulk Actions
                    </button>

Merge into New Session

Add to Existing Session

Delete

        );
      }
    });

Nothing is happening however, with the {this.props.showBulkActions ? 'show' : 'hidden'}. Am I doing anything wrong here?

Body:
Reference to @split fire answer, we can update it with template literals, which is more readable,For reference Checkout javascript template literal

<div className={`btn-group pull-right ${this.props.showBulkActions ? 'show' : 'hidden'}`}>


问:
how to select data of a date which the largest of dates less than a specific date in Mysql
say I have data of multiple date and I just want to select the data of a date which is the maximum of dates smaller than a specific date.

eg.

```<code>id  other_columns date
------------------------
1   ...          2020-01-12
2   ...          2019-12-31
3   ...          2019-12-31
4   ...          2019-11-01
5   ...          2019-11-01
6   ...          2018-12-21
</code>```

for above case, if the condition is smaller than '2020-01-01', row 2 and 3 will be selected.
Since row 2 and row 3 have date just smaller than '2020-01-01'.

while if condition is smaller than '2019-12-31', then row 4 and row 5 will be selected.

I would like to see the most optimized query.
Thanks

答:
Here are four alternatives:

```<code>SELECT m1.*
FROM mytable m1
JOIN (SELECT MAX(date) AS maxdate
      FROM mytable
      WHERE date < '2020-01-01') m2 ON m2.maxdate = m1.date
;
SELECT *
FROM mytable
WHERE date = (SELECT MAX(date)
              FROM mytable
              WHERE date < '2020-01-01')
;
SELECT *
FROM mytable m1
WHERE m1.date < '2020-01-01'
  AND NOT EXISTS (SELECT *
                  FROM mytable m2
                  WHERE m2.date > m1.date AND m2.date < '2020-01-01')
;
SELECT m1.*
FROM mytable m1
LEFT JOIN mytable m2 ON m2.date > m1.date AND m2.date < '2020-01-01'
WHERE m1.date < '2020-01-01' AND m2.id IS NULL
</code>```

All give the same output for your sample data:

```<code>id  other_columns   date
2   ...             2019-12-31
3   ...             2019-12-31
</code>```

Demo on SQLFiddle

Body:
say I have data of multiple date and I just want to select the data of a date which is the maximum of dates smaller than a specific date.

eg.

id  other_columns date
------------------------
1   ...          2020-01-12
2   ...          2019-12-31
3   ...          2019-12-31
4   ...          2019-11-01
5   ...          2019-11-01
6   ...          2018-12-21

for above case, if the condition is smaller than '2020-01-01', row 2 and 3 will be selected.
Since row 2 and row 3 have date just smaller than '2020-01-01'.

while if condition is smaller than '2019-12-31', then row 4 and row 5 will be selected.

I would like to see the most optimized query.
Thanks

Body:
Here are four alternatives:

SELECT m1.*
FROM mytable m1
JOIN (SELECT MAX(date) AS maxdate
      FROM mytable
      WHERE date < '2020-01-01') m2 ON m2.maxdate = m1.date
;
SELECT *
FROM mytable
WHERE date = (SELECT MAX(date)
              FROM mytable
              WHERE date < '2020-01-01')
;
SELECT *
FROM mytable m1
WHERE m1.date < '2020-01-01'
  AND NOT EXISTS (SELECT *
                  FROM mytable m2
                  WHERE m2.date > m1.date AND m2.date < '2020-01-01')
;
SELECT m1.*
FROM mytable m1
LEFT JOIN mytable m2 ON m2.date > m1.date AND m2.date < '2020-01-01'
WHERE m1.date < '2020-01-01' AND m2.id IS NULL

All give the same output for your sample data:

id  other_columns   date
2   ...             2019-12-31
3   ...             2019-12-31

Demo on SQLFiddle


问:
mini.css modal dialog size
On the docs page of mini.css https://minicss.org/docs#modal-dialogs , there's a modal dialog example. It works, and everything's fine, just the size (width to be precise) of the dialog seems to be constant, regardless of the screen size. It's very short, even on quite wide screens. Is there a way to make it wider (e.g. to take 70% of available space)?

Perhaps the problem is trivial, yet I'm not a CSS expert. I've checked the size of div elements, and they are set to 100%. Just the modal part is rendered so small.

答:
It is using a media query , Override that media query.

```<code>media screen and (min-width: 320px)
.card {
     max-width: 70%; //try !important tag if does not work without it.
}
</code>```

Or probably define your own media queries.

Title: mini.css modal dialog size

Body:
It is using a media query , Override that media query.

media screen and (min-width: 320px)
.card {
     max-width: 70%; //try !important tag if does not work without it.
}

Or probably define your own media queries.


问:
which method of fragment is used to load image from fire base?
```<code>databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange( DataSnapshot dataSnapshot) {
                Glide.with(get Context()).load(dataSnapshot.get Value(String.class)).into(profImage);
            }

            @Override
            public void onCancelled(DatabaseError databaseError){

            }
        });
</code>```

答:
Override the onActivityCreated method of fragment and place it in that method

```<code>    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

          databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange( DataSnapshot dataSnapshot) {
                Glide.with(get Context()).load(dataSnapshot.get Value(String.class)).into(profImage);
            }

            @Override
            public void onCancelled(DatabaseError databaseError){

            }
        });
    }
</code>```

Body:
Override the onActivityCreated method of fragment and place it in that method

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

          databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange( DataSnapshot dataSnapshot) {
                Glide.with(get Context()).load(dataSnapshot.get Value(String.class)).into(profImage);
            }

            @Override
            public void onCancelled(DatabaseError databaseError){

            }
        });
    }


问:
How do I import an SQL file using the command line in MySQL?
I have a .sql file with an export from phpMyAdmin. I want to import it into a different server using the command line.

I have a Windows Server 2008 R2 installation. I placed the .sql file on the C drive, and I tried this command

```<code>database_name < file.sql
</code>```

It is not working. I get syntax errors.

How can I import this file without a problem?

Do I need to create a database first?

答:
For exporting a database:

```<code>mysqldump -u username -p database_name > file.sql
</code>```

For importing a database:

```<code>mysql -u username -p database_name < file.sql
</code>```

Body:
I have a .sql file with an export from phpMyAdmin. I want to import it into a different server using the command line.

I have a Windows Server 2008 R2 installation. I placed the .sql file on the C drive, and I tried this command

database_name < file.sql

It is not working. I get syntax errors.

How can I import this file without a problem?

Do I need to create a database first?

Body:
For exporting a database:

mysqldump -u username -p database_name > file.sql

For importing a database:

mysql -u username -p database_name < file.sql


问:
How can I make this construction simpler, like with classes or functions in python?
```<code>print(
    "1. Engine block \n"
    "2. Pistons \n"
    "3. Crankshaft \n"
    "4. Camshaft \n"
    "5. Cylinder head \n"
    "6. Connecting Rod \n"
)

part = int(input("Choose an engine part to show you details about it: "))

if part == 1:
    print("Engine block")
elif part == 2:
    print("Pistons")
elif part == 3:
    print("Crankshaft")
</code>```

I have 26 statements like these and I wonder if I can make it simpler with classes,

functions, lists or something I can't find a way??

答: You can create a class with Question and answer. Also add function in the class to check if the input is same as the Answer and return the result accordingly. You can use the regular expression to fetch the value of right answer from the Question text.</p>

Body:
print(
    "1. Engine block \n"
    "2. Pistons \n"
    "3. Crankshaft \n"
    "4. Camshaft \n"
    "5. Cylinder head \n"
    "6. Connecting Rod \n"
)

part = int(input("Choose an engine part to show you details about it: "))

if part == 1:
    print("Engine block")
elif part == 2:
    print("Pistons")
elif part == 3:
    print("Crankshaft")

I have 26 statements like these and I wonder if I can make it simpler with classes,

functions, lists or something I can't find a way??


问:
Changing an array code to a vector
So I have been trying to look all over, but can't seem to find a whole lot on what exactly needs to be changed in order to convert an array to vector.  Or rather, I suppose I just don't know what exactly to search for.

The array is this:

```<code>public class Member{

 private int id;
 private String name;
 private String[] books = new String[5];
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String[] getBooks(){
     return books;
 }

 public void setBooks(String[] pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books[x] + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String[] args) {
    String[] list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books[i] = list[i];
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books[x] = list[i];
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}
</code>```

Now, I have been trying to convert it, but to be honest, I don't know what I am doing.

```<code>import java.util.Vector;

public class Member{

 private int id;
 private String name;
 private Vector<String> books = new Vector<String>(5);
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String getBooks(){
     return books;
 }

 public void setBooks(String pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books<x> + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String args) {
    String list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books<i> = list<i>;
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books<x> = list<i>;
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}
</code>```

Any help would be greatly appreciated.

答:
You can use Arrays.asList to convert an array to a list. Vector is a List but I suspect all you need is a list. It's a good idea to program to the List interface rather than a concrete class such as Vector.

```<code>List<String> list = Arrays.asList(array)
</code>```

Title: Changing an array code to a vector

Body:
So I have been trying to look all over, but can't seem to find a whole lot on what exactly needs to be changed in order to convert an array to vector.  Or rather, I suppose I just don't know what exactly to search for.

The array is this:

public class Member{

 private int id;
 private String name;
 private String[] books = new String[5];
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String[] getBooks(){
     return books;
 }

 public void setBooks(String[] pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books[x] + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String[] args) {
    String[] list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books[i] = list[i];
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books[x] = list[i];
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}

Now, I have been trying to convert it, but to be honest, I don't know what I am doing.

import java.util.Vector;

public class Member{

 private int id;
 private String name;
 private Vector<String> books = new Vector<String>(5);
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String getBooks(){
     return books;
 }

 public void setBooks(String pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books<x> + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String args) {
    String list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books = list;
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books<x> = list;
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}

Any help would be greatly appreciated.

Body:
You can use Arrays.asList to convert an array to a list. Vector is a List but I suspect all you need is a list. It's a good idea to program to the List interface rather than a concrete class such as Vector.

List<String> list = Arrays.asList(array)


问:
Azure Blob Storage: Mocking CloudBlobContainer
I am trying to unittest a class which uploads files to Azure Blob Storage. The uploading method takes CloudBlobContainer as input. When calling _storageContainer.Object.GetBlockBlobReference(), a System.NullReferenceException is thrown. Can anyone help me mocking this?

Unittest code:

```<code>[TestClass()]
public class BlobStorageServiceUploadUnitTest
{
    private static BlobStorageService _service;
    private static Mock<CloudBlobContainer> _storageContainer;
    private static List<FileType> _extensions;
    private static int _maxSize;

    [ClassInitialize]
    public static void Setup_Service(TestContext context)
    {
        _extensions = new List<FileType> { FileType.Image };
        _maxSize = 2048;

        _storageContainer = new Mock<CloudBlobContainer>();

        _service = new BlobStorageService(new Mock<BEntitiesContainer>().Object, _storageContainer.Object);
    }

    [TestMethod()]
    public void When_FileIsDeleted()
    {
        var file = CreateMockFile("test.jpg", 500000);
        var blob = _storageContainer.Object.GetBlockBlobReference("deleteTest.jpg");
        blob.UploadFromStream(file.Object.InputStream);

        _service.DeleteFromStorage("deleteTest.jpg");

        var blobs = _storageContainer.Object.ListBlobs();
        Assert.AreEqual(0, blobs.Count());
    }

    public Mock<HttpPostedFileBase> CreateMockFile(string fileName, int sizeInBytes)
    {
        var file = new Mock<HttpPostedFileBase>();
        var stream = new MemoryStream();
        var bmp = new Bitmap(1, 1);
        var graphics = Graphics.FromImage(bmp);
        graphics.FillRectangle(Brushes.Black, 0, 0, 1, 1);
        bmp.Save(stream, ImageFormat.Jpeg);

        file.Setup(pf => pf.InputStream).Returns(stream);
        file.Setup(f => f.FileName).Returns(fileName);
        file.Setup(f => f.ContentLength).Returns(sizeInBytes);

        return file;
    }
}
</code>```

Tested class:

```<code>public class BlobStorageService : BaseRepository<User>
{
    private CloudBlobContainer _storageContainer;

    public BlobStorageService(BEntitiesContainer context, CloudBlobContainer storageContainer) : base(context)
    {
        Context = context;
        _storageContainer = storageContainer;
    }

    public void DeleteFromStorage(string fileName)
    {
        _storageContainer.GetBlockBlobReference(fileName).DeleteIfExists();
    }
}
</code>```

答:
Only one thing you can do is to move CloudBlobContainer operation to the separate service with the abstract implementation. In this case you will be able to mock the service and not to touch the Azure classes at all.

For example:

```<code>public interface IAzureServiceWrapper
{
    CloudBlockBlob GetBlockBlobReference(CloudBlobContainer storageContainer, string fileName);
}

public class AzureServiceWrapper : IAzureServiceWrapper
{
    public CloudBlockBlob GetBlockBlobReference(CloudBlobContainer storageContainer, string fileName)
    {
         storageContainer.GetBlockBlobReference(fileName).DeleteIfExists();
    }
}
</code>```

In this case it will be very easy to mock the AzureServiceWrapper and this solution will solve all the problems with Azure classes using in unit tests. You just need to use AzureServiceWrapper in BlobStorageService instead of CloudBlobContainer.

Body:
I am trying to unittest a class which uploads files to Azure Blob Storage. The uploading method takes CloudBlobContainer as input. When calling _storageContainer.Object.GetBlockBlobReference(), a System.NullReferenceException is thrown. Can anyone help me mocking this?

Unittest code:

[TestClass()]
public class BlobStorageServiceUploadUnitTest
{
    private static BlobStorageService _service;
    private static Mock<CloudBlobContainer> _storageContainer;
    private static List<FileType> _extensions;
    private static int _maxSize;

    [ClassInitialize]
    public static void Setup_Service(TestContext context)
    {
        _extensions = new List<FileType> { FileType.Image };
        _maxSize = 2048;

        _storageContainer = new Mock<CloudBlobContainer>();

        _service = new BlobStorageService(new Mock<BEntitiesContainer>().Object, _storageContainer.Object);
    }

    [TestMethod()]
    public void When_FileIsDeleted()
    {
        var file = CreateMockFile("test.jpg", 500000);
        var blob = _storageContainer.Object.GetBlockBlobReference("deleteTest.jpg");
        blob.UploadFromStream(file.Object.InputStream);

        _service.DeleteFromStorage("deleteTest.jpg");

        var blobs = _storageContainer.Object.ListBlobs();
        Assert.AreEqual(0, blobs.Count());
    }

    public Mock<HttpPostedFileBase> CreateMockFile(string fileName, int sizeInBytes)
    {
        var file = new Mock<HttpPostedFileBase>();
        var stream = new MemoryStream();
        var bmp = new Bitmap(1, 1);
        var graphics = Graphics.FromImage(bmp);
        graphics.FillRectangle(Brushes.Black, 0, 0, 1, 1);
        bmp.Save(stream, ImageFormat.Jpeg);

        file.Setup(pf => pf.InputStream).Returns(stream);
        file.Setup(f => f.FileName).Returns(fileName);
        file.Setup(f => f.ContentLength).Returns(sizeInBytes);

        return file;
    }
}

Tested class:

public class BlobStorageService : BaseRepository<User>
{
    private CloudBlobContainer _storageContainer;

    public BlobStorageService(BEntitiesContainer context, CloudBlobContainer storageContainer) : base(context)
    {
        Context = context;
        _storageContainer = storageContainer;
    }

    public void DeleteFromStorage(string fileName)
    {
        _storageContainer.GetBlockBlobReference(fileName).DeleteIfExists();
    }
}

Body:
Only one thing you can do is to move CloudBlobContainer operation to the separate service with the abstract implementation. In this case you will be able to mock the service and not to touch the Azure classes at all.

For example:

public interface IAzureServiceWrapper
{
    CloudBlockBlob GetBlockBlobReference(CloudBlobContainer storageContainer, string fileName);
}

public class AzureServiceWrapper : IAzureServiceWrapper
{
    public CloudBlockBlob GetBlockBlobReference(CloudBlobContainer storageContainer, string fileName)
    {
         storageContainer.GetBlockBlobReference(fileName).DeleteIfExists();
    }
}

In this case it will be very easy to mock the AzureServiceWrapper and this solution will solve all the problems with Azure classes using in unit tests. You just need to use AzureServiceWrapper in BlobStorageService instead of CloudBlobContainer.


问:
Why is Azure AD B2C restricting the use of the 'for' attribute in custom UIs?
Does anyone know why the sanitizerPolicy applied by B2C does not have the for attribute listed within the allowedAttributes list or if it's possible to modify the policy? I cannot think of any real vulnerability with allowing use of that attribute but instead it's stripped by the HTML sanitization of the HTML retrieved from the custom UI source. There is very little documentation to be found on the sanitizerPolicy.

The sanitizerPolicy is complex property contained within the SETTINGS JavaScript object which is injected by the Expression framework (so B2C itself) into the B2C UI and used when loading remote content (e.g. custom UI HTML and CSS) for a specific content definition. The injected settings are then applied by JavaScript functions (e.g. sanitizeHTML) which are also injected by default by the Expression Framework. The functions and settings are used to restrict the HTML being served by the remote source (via the LoadUri property of the ContentDefinition in the Expression Framework). There is little or no documentation on this so no useful links can be provided

The current allowedAttribute array within the sanitizerPolicy is as follows:
['id', 'class', 'href', 'name', 'data-*', 'aria-*', 'type', 'lang', 'src', 'sizes', 'role', 'placeholder', 'title', 'width', 'height', 'style']

Context: My use case is that I would like to have a password policy toggle purely in CSS which makes use of a hidden checkbox and a label bound to the checkbox using the for attribute but alas no binding as the forattribute is stripped from the label element by the sanizterPolicy upon rendering my custom ui.

There is a closed GitHub issue relating to a request to add proper documentation on this functionality. The location of that documentation is unknown nor is any link to other open tasks to delivery same provided.

答: I just heard back from Azure support engineer to confirm that the ‘for’ attribute is not supported in customizing UIs under Azure B2C scenarios. Currently they have indicated that a better documentation regarding this behavior is needed for now.</p>