问:
If cell in a range has value "x" copy and paste a range of cells into a different sheet
I am not a programmer by trade but I am trying to automate a small portion of a report I use every day out of curiosity and self interest. Basically, we receive and manually enter contact information (name, e-mail, phone number, etc.) and mark select groups that a person is interested in joining. We then copy and paste that contact information entered into a different sheet for each group.

I want to have a macro that checks the specific columns for each interest group for a "x" and if it finds that value copy and paste the contact information collected to the specific interest groups worksheet. People are able to select multiple interest groups and their contact information is added to each separate interest group spreadsheet.

Report columns look as follows:

```<code>Group 1 Group 2 Group 3 Name Organization Phone E-mail  Notes

Row Contact Information looks similar to:
  x  x John ABC Inc. 000-000-0000 john.smith@fake.com  Call me ASAP!
</code>```

The macro checks the column I have marked interest in Group 1 in and if it finds "x" then it copies the full range to the Group 1 worksheet.

I want it to be able to check multiple columns (i.e. Group 1, 2, 3) for "x" and then copy and paste the information to the right of those columns to the appropriate sheet for the group. If they have interest in multiple groups, their contact info should be copied to each specific worksheet.\

Do I need to have separate counters for each group worksheet and is there a way to write a if then statement that checks for x in each of the columns and then runs the appropriate code to copy and paste into that group?

```<code>Sub Update()

    Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet
    Dim Target1 As Worksheet
    Dim Target2 As Worksheet
    Dim Target3 As Worksheet

    Set Source = ActiveWorkbook.Worksheets("Interest Group Tracking")
    Set Target1 = ActiveWorkbook.Worksheets("Group 1")

    j = 1   'Start copying to row 1 in target sheet
    For Each c In Source.Range("A1:A1000") 'not sure if there is a way to not set a limit for the range
        If c = "x" Then
            Source.Rows(c.Row).Copy Target1.Rows(j + 1)
            j = j + 1
            End If
    Next c

End Sub
</code>```

No errors besides the occasional syntax but don't really know how to structure the loop for checking for each group. I am continuing to research and test things I find and will update if I need to.

答:
I changed the main piece of logic at the end but this should work. Instead of copy and pasting, I just made the range in the group1 sheet equal to the row's range. I also use the last used row.  </p>

```<code>Sub Update()
Dim c As Range
Dim j As Integer
Dim k As Integer
Dim Source As Worksheet
Dim Target1 As Worksheet
Dim Target2 As Worksheet
Dim Target3 As Worksheet
Dim curSheet As Worksheet
Dim lastRow, lastRow1, lastRow2, lastRow3, lastCol As Long
Dim group1, group2, group3, curGroup As Long

Set Source = ActiveWorkbook.Worksheets("Interest Group Tracking")
Set Target1 = ActiveWorkbook.Worksheets("Group 1")
Set Target2 = ActiveWorkbook.Worksheets("Group 2")
Set Target3 = ActiveWorkbook.Worksheets("Group 3")

j = 1
group1 = 1
group2 = 1
group3 = 1
With Source
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
lastRow1 = .Cells(.Rows.Count, 1).End(xlUp).Row
lastRow2 = .Cells(.Rows.Count, 2).End(xlUp).Row
lastRow3 = .Cells(.Rows.Count, 3).End(xlUp).Row

    If lastRow1 > lastRow2 And lastRow1 > lastRow3 Then
    lastRow = lastRow1
End If
If lastRow2 > lastRow1 And lastRow2 > lastRow3 Then
    lastRow = lastRow2
End If
If lastRow3 > lastRow1 And lastRow3 > lastRow2 Then
    lastRow = lastRow3
End If

For j = 1 To lastRow
    For k = 1 To 3
        If .Cells(j, k) = "x" Then
           Set curSheet = ActiveWorkbook.Sheets("Group" & " " & k)
           If k = 1 Then
                curGroup = group1
           ElseIf k = 2 Then
                curGroup = group2
           ElseIf k = 3 Then
                curGroup = group3
           Else
                GoTo line1
           End If
           curSheet.Range(curSheet.Cells(curGroup, 1), curSheet.Cells(curGroup, lastCol)).Value = .Range(.Cells(j, 1), .Cells(j, lastCol)).Value
        End If
           If k = 1 Then
                group1 = group1 + 1
           ElseIf k = 2 Then
                group2 = group2 + 1
           ElseIf k = 3 Then
                group3 = group3 + 1
           End If
 line1:
    Next k
Next j
End With
 End Sub
</code>```

Body:
I am not a programmer by trade but I am trying to automate a small portion of a report I use every day out of curiosity and self interest. Basically, we receive and manually enter contact information (name, e-mail, phone number, etc.) and mark select groups that a person is interested in joining. We then copy and paste that contact information entered into a different sheet for each group.

I want to have a macro that checks the specific columns for each interest group for a "x" and if it finds that value copy and paste the contact information collected to the specific interest groups worksheet. People are able to select multiple interest groups and their contact information is added to each separate interest group spreadsheet.

Report columns look as follows:

Group 1 Group 2 Group 3 Name Organization Phone E-mail  Notes

Row Contact Information looks similar to:
  x  x John ABC Inc. 000-000-0000 john.smith@fake.com  Call me ASAP!

The macro checks the column I have marked interest in Group 1 in and if it finds "x" then it copies the full range to the Group 1 worksheet.

I want it to be able to check multiple columns (i.e. Group 1, 2, 3) for "x" and then copy and paste the information to the right of those columns to the appropriate sheet for the group. If they have interest in multiple groups, their contact info should be copied to each specific worksheet.\

Do I need to have separate counters for each group worksheet and is there a way to write a if then statement that checks for x in each of the columns and then runs the appropriate code to copy and paste into that group?

Sub Update()

    Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet
    Dim Target1 As Worksheet
    Dim Target2 As Worksheet
    Dim Target3 As Worksheet

    Set Source = ActiveWorkbook.Worksheets("Interest Group Tracking")
    Set Target1 = ActiveWorkbook.Worksheets("Group 1")

    j = 1   'Start copying to row 1 in target sheet
    For Each c In Source.Range("A1:A1000") 'not sure if there is a way to not set a limit for the range
        If c = "x" Then
            Source.Rows(c.Row).Copy Target1.Rows(j + 1)
            j = j + 1
            End If
    Next c

End Sub

No errors besides the occasional syntax but don't really know how to structure the loop for checking for each group. I am continuing to research and test things I find and will update if I need to.

Body:
I changed the main piece of logic at the end but this should work. Instead of copy and pasting, I just made the range in the group1 sheet equal to the row's range. I also use the last used row.

Sub Update()
Dim c As Range
Dim j As Integer
Dim k As Integer
Dim Source As Worksheet
Dim Target1 As Worksheet
Dim Target2 As Worksheet
Dim Target3 As Worksheet
Dim curSheet As Worksheet
Dim lastRow, lastRow1, lastRow2, lastRow3, lastCol As Long
Dim group1, group2, group3, curGroup As Long

Set Source = ActiveWorkbook.Worksheets("Interest Group Tracking")
Set Target1 = ActiveWorkbook.Worksheets("Group 1")
Set Target2 = ActiveWorkbook.Worksheets("Group 2")
Set Target3 = ActiveWorkbook.Worksheets("Group 3")

j = 1
group1 = 1
group2 = 1
group3 = 1
With Source
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
lastRow1 = .Cells(.Rows.Count, 1).End(xlUp).Row
lastRow2 = .Cells(.Rows.Count, 2).End(xlUp).Row
lastRow3 = .Cells(.Rows.Count, 3).End(xlUp).Row

    If lastRow1 > lastRow2 And lastRow1 > lastRow3 Then
    lastRow = lastRow1
End If
If lastRow2 > lastRow1 And lastRow2 > lastRow3 Then
    lastRow = lastRow2
End If
If lastRow3 > lastRow1 And lastRow3 > lastRow2 Then
    lastRow = lastRow3
End If

For j = 1 To lastRow
    For k = 1 To 3
        If .Cells(j, k) = "x" Then
           Set curSheet = ActiveWorkbook.Sheets("Group" & " " & k)
           If k = 1 Then
                curGroup = group1
           ElseIf k = 2 Then
                curGroup = group2
           ElseIf k = 3 Then
                curGroup = group3
           Else
                GoTo line1
           End If
           curSheet.Range(curSheet.Cells(curGroup, 1), curSheet.Cells(curGroup, lastCol)).Value = .Range(.Cells(j, 1), .Cells(j, lastCol)).Value
        End If
           If k = 1 Then
                group1 = group1 + 1
           ElseIf k = 2 Then
                group2 = group2 + 1
           ElseIf k = 3 Then
                group3 = group3 + 1
           End If
 line1:
    Next k
Next j
End With
 End Sub


来源: stackexchange

问:
django QueryDict only returns the last value of a list
Using django 1.8, I'm observing something strange.
Here is my javascript:

```<code>function form_submit(){
  var form = $('#form1_id');
  request = $.post($(this).attr('action'), form.serialize(), function(response){
     if(response.indexOf('Success') >= 0){
        alert(response);
     }
  },'text')
  .fail(function() {
    alert("Failed to save!");
  });
  return false;
}
</code>```

and here are the parameters displayed in views.py

```<code>print request.POST
<QueryDict: {u'form_4606-name': [u''], u'form_4606-parents': [u'4603', u'2231', u'2234']}>
</code>```

but I cannot extract the parents:

```<code>print request.POST['form_4606-parents']
2234
</code>```

Why is it just giving me the last value?
I think there is something wrong with the serialization, but I just cannot figure out how to resolve this.

答:
The function below converts a QueryDict object to a python dictionary. It's a slight modification of Django's QueryDict.dict() method. But unlike that method, it keeps lists that have two or more items as lists.

```<code>def querydict_to_dict(query_dict):
    data = {}
    for key in query_dict.keys():
        v = query_dict.getlist(key)
        if len(v) == 1:
            v = v[0]
        data[key] = v
    return data
</code>```

Usage:

```<code>data = querydict_to_dict(request.POST)

# Or

data = querydict_to_dict(request.GET)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using django 1.8, I'm observing something strange.
Here is my javascript:

function form_submit(){
  var form = $('#form1_id');
  request = $.post($(this).attr('action'), form.serialize(), function(response){
     if(response.indexOf('Success') >= 0){
        alert(response);
     }
  },'text')
  .fail(function() {
    alert("Failed to save!");
  });
  return false;
}

and here are the parameters displayed in views.py

print request.POST
<QueryDict: {u'form_4606-name': [u''], u'form_4606-parents': [u'4603', u'2231', u'2234']}>

but I cannot extract the parents:

print request.POST['form_4606-parents']
2234

Why is it just giving me the last value?
I think there is something wrong with the serialization, but I just cannot figure out how to resolve this.

Body:
The function below converts a QueryDict object to a python dictionary. It's a slight modification of Django's QueryDict.dict() method. But unlike that method, it keeps lists that have two or more items as lists.

def querydict_to_dict(query_dict):
    data = {}
    for key in query_dict.keys():
        v = query_dict.getlist(key)
        if len(v) == 1:
            v = v[0]
        data[key] = v
    return data

Usage:

data = querydict_to_dict(request.POST)

# Or

data = querydict_to_dict(request.GET)

ContentLicense: CC BY-SA 4.0


问:
Using Java, how is this charAt(); turn a string into an int?
I'm a beginner at Java and I'm trying to understand and explain to myself how this for loop is working. The instructions say it's converting the numeric Unicode equivalent for each letter in each word by using loops.

Based on my understanding the for loop goes through the entire word using the .length() and then stores it as int i, which gets carried down into the parenthesis of i of the charAt. CharAt returns each character in the word and then the int converts it into an int that is stored as finalInt.

So my question is where does unicode number comes from? How does it know that it's unicode?

```<code>String word1;
int finalInt;

for (int i = 0; i < word1.length(); i++) {
    finalInt = (int) word1.charAt(i);

        }
</code>```

答:
Java Character is based on Unicode

Character information is based on the Unicode Standard, version 6.0.0.

https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html

Besides, char and int can convert each other. please refer to : Convert int to char in java

Body:
I'm a beginner at Java and I'm trying to understand and explain to myself how this for loop is working. The instructions say it's converting the numeric Unicode equivalent for each letter in each word by using loops.

Based on my understanding the for loop goes through the entire word using the .length() and then stores it as int i, which gets carried down into the parenthesis of i of the charAt. CharAt returns each character in the word and then the int converts it into an int that is stored as finalInt.

So my question is where does unicode number comes from? How does it know that it's unicode?

String word1;
int finalInt;

for (int i = 0; i < word1.length(); i++) {
    finalInt = (int) word1.charAt(i);

        }


问:
How to serve files larger than 32 MB from GCS using GAE and Python 3
I'm serving some files from GCS through a GAE application (using flask), recently I hit the 32 MB limit. It should according to the documentation be possible to serve files from GCS that are larger than 32 MB, but I can't find the correct python3 apis.

Response limits
  Dynamic responses are limited to 32MB. If a script handler generates a response larger than this limit, the server sends back an empty response with a 500 Internal Server Error status code. This limitation does not apply to responses that serve data from the Blobstore or Cloud Storage.

I've found the blobstore API which can serve files from GCS, but unfortunately that library is deprecated and not python3 compatible. This is what I think the code would have looked like in that approach

```<code>blobstore_filename = '/gs/{}/{}'.format(CLOUD_STORAGE_BUCKET, path)
blob_key = blobstore.create_gs_key(blobstore_filename)

response = Response("This should be overriden by App Enginge")
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['X-AppEngine-BlobKey'] = blob_key
return response
</code>```

I think in PHP there is a specific API method that does exactly what I need
CloudStorageTools#serve

I've seen some suggestions for similar problems to use Signed URLs but that seems more like a work-around rather than an actual solution to the problem.

I had expected to find a method to serve content from GCS, I don't know if my search skills are failing me or the method I need doesn't exist for the python3 environment.

答:
There are two options in order to serve files:

1.-You can use a resumable uploads to upload objects to your bucket.You only need to use the signed URL in the initial POST request.

2.-You can create a policy document (policy document defines what a user (with or without a Google account) can upload with a form POST, and provides authorization to ensure that the form can upload files into the target bucket) and use regular HTML forms to do the upload.

Please let me know your thoughts and how it goes.

Body:
I'm serving some files from GCS through a GAE application (using flask), recently I hit the 32 MB limit. It should according to the documentation be possible to serve files from GCS that are larger than 32 MB, but I can't find the correct python3 apis.

Response limits
  Dynamic responses are limited to 32MB. If a script handler generates a response larger than this limit, the server sends back an empty response with a 500 Internal Server Error status code. This limitation does not apply to responses that serve data from the Blobstore or Cloud Storage.

I've found the blobstore API which can serve files from GCS, but unfortunately that library is deprecated and not python3 compatible. This is what I think the code would have looked like in that approach

blobstore_filename = '/gs/{}/{}'.format(CLOUD_STORAGE_BUCKET, path)
blob_key = blobstore.create_gs_key(blobstore_filename)

response = Response("This should be overriden by App Enginge")
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['X-AppEngine-BlobKey'] = blob_key
return response

I think in PHP there is a specific API method that does exactly what I need
CloudStorageTools#serve

I've seen some suggestions for similar problems to use Signed URLs but that seems more like a work-around rather than an actual solution to the problem.

I had expected to find a method to serve content from GCS, I don't know if my search skills are failing me or the method I need doesn't exist for the python3 environment.


问:
How to import data from one sheet to another
I have two different work sheets in excel with the same headings in in all the row 1 cells(a1 = id, b1 = name, c1 = price). My question is, is there a way to import data(like the name) from 1 worksheet to the other where the "id" is the same in both worksheets.

```<code>eg.
sheet 1                             sheet2
ID      Name       Price            ID        Name        Price
xyz     Bag        20               abc                     15
abc     jacket     15               xyz                     20
</code>```

So is there a way to add the "Name" in sheet 1 the "Name" in sheet 2 where the "ID" in sheet 1 = "ID" in sheet 2?

Without coping and pasting of course
Thanks

答:
VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".

External Reference

To reference a cell of the same Workbook use the following pattern:

```<code><Sheetname>!<Cell>
</code>```

Example:

```<code>Table1!A1
</code>```

To reference a cell of a different Workbook use this pattern:

```<code>[<Workbook_name>]<Sheetname>!<Cell>
</code>```

Example:

```<code>[MyWorkbook]Table1!A1
</code>```

Body:
I have two different work sheets in excel with the same headings in in all the row 1 cells(a1 = id, b1 = name, c1 = price). My question is, is there a way to import data(like the name) from 1 worksheet to the other where the "id" is the same in both worksheets.

eg.
sheet 1                             sheet2
ID      Name       Price            ID        Name        Price
xyz     Bag        20               abc                     15
abc     jacket     15               xyz                     20

So is there a way to add the "Name" in sheet 1 the "Name" in sheet 2 where the "ID" in sheet 1 = "ID" in sheet 2?

Without coping and pasting of course
Thanks

Body:
VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1


问:
R6034 An application has made an attempt to load the C runtime library incorrectly
I am running a python 2.7 code (containing GPy and GPyOpt, python implementation of gaussian process and Bayesian optimization) from Matlab on Anaconda 64bit on Windows 10 and I am facing with the following error:

warning in stationary: failed to import cython module: falling back to
  numpy Error using stationary>_gradients_X_cython (line 323) Python
  Error: NameError: global name 'stationary_cython' is not defined

When I run the code in python I do not have any problem, but the problem comes when I call the script from MATLAB (I have run the code from MATLAB a few months ago without any problem.)

I have to mention, recently for some reasons, I have downgraded the numpy to Numpy=1.11.0. That's because Matlab has a bug with the latest version of Numpy.

Also I am facing with the following window:
An application has made an attempt to load the C runtime library ...

Q: Could you please help me to resolve the issue?

```<code>    Python Error: NameError: global name 'stationary_cython' is not defined

    Error in stationary>gradients_X (line 236)
            return self._gradients_X_cython(dL_dK, X, X2)

    Error in kernel_slice_operations>wrap (line 118)
            ret = s.handle_return_array(f(self, dL_dK, s.X, s.X2))

    Error in prod>gradients_X (line 80)
            target += self.parts[0].gradients_X(dL_dK*self.parts[1].K(X,
    X2), X, X2)

   Error in kernel_slice_operations>wrap (line 118)
            ret = s.handle_return_array(f(self, dL_dK, s.X, s.X2))

   Error in gp>predictive_gradients (line 337)
            mean_jac[:,:,i] =
   kern.gradients_X(self.posterior.woodbury_vector[:,i:i+1].T, Xnew,
   self._predictive_variable)

   Error in gpmodel>predict_withGradients (line 113)
        dmdx, dvdx = self.model.predictive_gradients(X)

   Error in EI>_compute_acq_withGradients (line 47)
        m, s, dmdx, dsdx = self.model.predict_withGradients(x)

   Error in base>acquisition_function_withGradients (line 46)
        f_acqu,df_acqu = self._compute_acq_withGradients(x)
   Error in LP>d_acquisition_function (line 128)
            _, grad_acq_x = self.acq.acquisition_function_withGradients(x)

Error in LP>acquisition_function_withGradients (line 139)
        aqu_x_grad = self.d_acquisition_function(x)

Error in acquisition_optimizer>fp_dfp (line 165)
            fp_xx , dfp_xx = f_df(xx)

Error in optimizer>_f_df (line 60)
                return f(x), f_df(x)[1][0]

Error in optimize>__call__ (line 63)
        fg = self.fun(x, *args)

Error in optimize>function_wrapper (line 289)
        return function(*(wrapper_args + args))

Error in lbfgsb>func_and_grad (line 278)
            f = fun(x, *args)

Error in lbfgsb>_minimize_lbfgsb (line 330)
                f, g = func_and_grad(x)

Error in lbfgsb>fmin_l_bfgs_b (line 193)
                           **opts)

Error in optimizer>optimize (line 64)
            res = scipy.optimize.fmin_l_bfgs_b(_f_df, x0=x0, bounds=self.space.get_bounds(), maxiter=self.maxiter)

Error in acquisition_optimizer>optimize (line 177)
                x_min, f_min = self.optimizer.optimize(x0, f =fp, df=None, f_df=fp_dfp)

Error in base>optimize (line 59)
            out = self.optimizer.optimize(f=self.acquisition_function, f_df=self.acquisition_function_withGradients)[0]

Error in batch_local_penalization>compute_batch (line 34)
        X_batch = self.acquisition.optimize()

Error in bo>_compute_next_evaluations (line 186)
        return self.evaluator.compute_batch()

Error in bo>run_optimization (line 108)
            self.suggested_sample = self._compute_next_evaluations()

Error in bayesian_optimization>run_optimization (line 458)
        super(BayesianOptimization, self).run_optimization(max_iter = max_iter, max_time = max_time,  eps = eps,
        verbosity=verbosity, save_models_parameters = save_models_parameters, report_file = report_file, evaluations_file=
        evaluations_file, models_file=models_file)

Error in bayesian_optimization>__init__ (line 244)
        self.run_optimization(max_iter=0,verbosity=self.verbosity)

Error in BatchBO>BAYESOPT2 (line 37)
                                                 acquisition_weight = 2)
</code>```

答:
Did you install paramz first?
Or did you try installing gcc and gmp in Anaconda?

If your problem goes away when using a Linear Kernel, it seems dependency issues arise due to the Python Package Manager Anaconda.

Source:
https://github.com/SheffieldML/GPy/issues/458

Body:
I am running a python 2.7 code (containing GPy and GPyOpt, python implementation of gaussian process and Bayesian optimization) from Matlab on Anaconda 64bit on Windows 10 and I am facing with the following error:

warning in stationary: failed to import cython module: falling back to
  numpy Error using stationary>_gradients_X_cython (line 323) Python
  Error: NameError: global name 'stationary_cython' is not defined

When I run the code in python I do not have any problem, but the problem comes when I call the script from MATLAB (I have run the code from MATLAB a few months ago without any problem.)

I have to mention, recently for some reasons, I have downgraded the numpy to Numpy=1.11.0. That's because Matlab has a bug with the latest version of Numpy.

Also I am facing with the following window:
An application has made an attempt to load the C runtime library ...

Q: Could you please help me to resolve the issue?

    Python Error: NameError: global name 'stationary_cython' is not defined

    Error in stationary>gradients_X (line 236)
            return self._gradients_X_cython(dL_dK, X, X2)

    Error in kernel_slice_operations>wrap (line 118)
            ret = s.handle_return_array(f(self, dL_dK, s.X, s.X2))

    Error in prod>gradients_X (line 80)
            target += self.parts[0].gradients_X(dL_dK*self.parts[1].K(X,
    X2), X, X2)

   Error in kernel_slice_operations>wrap (line 118)
            ret = s.handle_return_array(f(self, dL_dK, s.X, s.X2))

   Error in gp>predictive_gradients (line 337)
            mean_jac[:,:,i] =
   kern.gradients_X(self.posterior.woodbury_vector[:,i:i+1].T, Xnew,
   self._predictive_variable)

   Error in gpmodel>predict_withGradients (line 113)
        dmdx, dvdx = self.model.predictive_gradients(X)

   Error in EI>_compute_acq_withGradients (line 47)
        m, s, dmdx, dsdx = self.model.predict_withGradients(x)

   Error in base>acquisition_function_withGradients (line 46)
        f_acqu,df_acqu = self._compute_acq_withGradients(x)
   Error in LP>d_acquisition_function (line 128)
            _, grad_acq_x = self.acq.acquisition_function_withGradients(x)

Error in LP>acquisition_function_withGradients (line 139)
        aqu_x_grad = self.d_acquisition_function(x)

Error in acquisition_optimizer>fp_dfp (line 165)
            fp_xx , dfp_xx = f_df(xx)

Error in optimizer>_f_df (line 60)
                return f(x), f_df(x)[1][0]

Error in optimize>__call__ (line 63)
        fg = self.fun(x, *args)

Error in optimize>function_wrapper (line 289)
        return function(*(wrapper_args + args))

Error in lbfgsb>func_and_grad (line 278)
            f = fun(x, *args)

Error in lbfgsb>_minimize_lbfgsb (line 330)
                f, g = func_and_grad(x)

Error in lbfgsb>fmin_l_bfgs_b (line 193)
                           **opts)

Error in optimizer>optimize (line 64)
            res = scipy.optimize.fmin_l_bfgs_b(_f_df, x0=x0, bounds=self.space.get_bounds(), maxiter=self.maxiter)

Error in acquisition_optimizer>optimize (line 177)
                x_min, f_min = self.optimizer.optimize(x0, f =fp, df=None, f_df=fp_dfp)

Error in base>optimize (line 59)
            out = self.optimizer.optimize(f=self.acquisition_function, f_df=self.acquisition_function_withGradients)[0]

Error in batch_local_penalization>compute_batch (line 34)
        X_batch = self.acquisition.optimize()

Error in bo>_compute_next_evaluations (line 186)
        return self.evaluator.compute_batch()

Error in bo>run_optimization (line 108)
            self.suggested_sample = self._compute_next_evaluations()

Error in bayesian_optimization>run_optimization (line 458)
        super(BayesianOptimization, self).run_optimization(max_iter = max_iter, max_time = max_time,  eps = eps,
        verbosity=verbosity, save_models_parameters = save_models_parameters, report_file = report_file, evaluations_file=
        evaluations_file, models_file=models_file)

Error in bayesian_optimization>__init__ (line 244)
        self.run_optimization(max_iter=0,verbosity=self.verbosity)

Error in BatchBO>BAYESOPT2 (line 37)
                                                 acquisition_weight = 2)


问:
Can I create a NuGet package (or other package) with legacy dll's that are not on a .NET Framework?
We have a bunch of legacy dll's (basically could be anything, some are old fortran, some .NET) and we want to move them to Azure Artifacts.  Can I create NuGet packages from these legacy dll's that are not based on .NET (like the Fortran ones) by themselves.

I've already tried creating the NuGet packages, but I get warnings on my dependencies because it looks like they are trying to load the packages on a .NET framework.  Is the only real workaround here to build a .NET say class library or something, then reference the dll through that, and create a NuGet package with that library and just add the legacy dll's as references?

答:
I assume what you mean is that your managed code is usng DllImport attributes to call native code, which in the .NET ecosystem is called Platform Invoke, or P/Invoke. I mention this because if you googled terms around P/Invoke and nuget you probably would have had better luck finding existint stack overflow questions, blog posts and so on. For this reason it's useful to try to find out the official or commonly used names of the features you use, so you know what to search for. Unfortunately I don't think the NuGet team has any docs on this scenario at the moment.

SDK style projects support the runtime\ directory in the package, although I think that's somewhat undocumented as well. I don't know about traditional projects using PackageReference (PR), but packages.config (PC) definately does not support runtimes\. For PC projects, the package author typically (always?) includes build targets to copy the native assemblies after build. In the package, the native dlls are elsewhere, often the author puts them in the build directory next to the targets, but I think I've also seen the targets copy from the runtime directory so that the package supports both PC and SDK style projects.

I suggest you try to think of some commonly used native libraries that have .NET bindings and see how the package works (nupkg is just a zip renamed). My guesses would be sqlite or curl, or how asp.net core's kestrel web server bundles libuv (or did in earlier versions if it no longer does). I'm on vacation at the moment, so don't have the motivation to dig deep myself.


问:
How to verify port connectivity between two unix hosts?
I am creating one bash script which can automate the process of checking the connectivity between two unix hosts. Need to check whether specific port is open from one host to other. hosts don't have NCAT(due to some constraint) so have to use Telnet only.

Code works fine if telnet connection is successful however takes more then 2 minutes if telnet fails. I need telnet to exit within 2 secs if it is not connecting. Trying to find a way to force the telnet command to exit even if it fails.

I have created couple of scripts which can read source file and run below command from there to telnet the destination servers.

Below code will be executed on the server from where telnet connectivity needs to be tested.

```<code>#!/usr/bin/bash
>/wastmp/$1.txt
echo "********************************************************************" >>/wastmp/$1.txt
echo "Checking Telnet connection from "$1 >>/wastmp/$1.txt
echo "********************************************************************" >>/wastmp/$1.txt
while read target;
do
x=$(sleep 3 | telnet `echo  $target | awk 'BEGIN { FS=":" } { print $1 }'` ` echo  $target | awk 'BEGIN { FS=":" } { print $2 }
'` | grep -i connected | awk  {'print $1'})
if [[ "$x"  ==  "Connected" ]];
  then
   echo $target"=Success" >>/wastmp/$1.txt
  else
   echo $target"=Fail, please check server & port">>/wastmp/$1.txt
fi
done </wastmp/target_server
</code>```

Expected result:
host1:port=Fail, please check server & port
host2:port=Fail, please check server & port
.
.
.

hostn:port=Success

答:
You need to send telnet a exit. Another reason it lags is that pipe line of redundant awk commands.

This is how i would write the x variable:

```<code>x=$(echo exit 0 | telnet $target 2>/dev/null | grep -o "Connected")
</code>```

The condition could also be shortened to:

```<code>echo exit 0 | telnet $target 2>/dev/null | grep -o "Connected" 1>/dev/null && echo "Success" >>/wastmp/$1.txt  || echo "Failed" >>/wastmp/$1.txt
</code>```

Body:
I am creating one bash script which can automate the process of checking the connectivity between two unix hosts. Need to check whether specific port is open from one host to other. hosts don't have NCAT(due to some constraint) so have to use Telnet only.

Code works fine if telnet connection is successful however takes more then 2 minutes if telnet fails. I need telnet to exit within 2 secs if it is not connecting. Trying to find a way to force the telnet command to exit even if it fails.

I have created couple of scripts which can read source file and run below command from there to telnet the destination servers.

Below code will be executed on the server from where telnet connectivity needs to be tested.

#!/usr/bin/bash
>/wastmp/$1.txt
echo "********************************************************************" >>/wastmp/$1.txt
echo "Checking Telnet connection from "$1 >>/wastmp/$1.txt
echo "********************************************************************" >>/wastmp/$1.txt
while read target;
do
x=$(sleep 3 | telnet `echo  $target | awk 'BEGIN { FS=":" } { print $1 }'` ` echo  $target | awk 'BEGIN { FS=":" } { print $2 }
'` | grep -i connected | awk  {'print $1'})
if [[ "$x"  ==  "Connected" ]];
  then
   echo $target"=Success" >>/wastmp/$1.txt
  else
   echo $target"=Fail, please check server & port">>/wastmp/$1.txt
fi
done </wastmp/target_server

Expected result:
host1:port=Fail, please check server & port
host2:port=Fail, please check server & port
.
.
.

hostn:port=Success

Body:
You need to send telnet a exit. Another reason it lags is that pipe line of redundant awk commands.

This is how i would write the x variable:

x=$(echo exit 0 | telnet $target 2>/dev/null | grep -o "Connected")

The condition could also be shortened to:

echo exit 0 | telnet $target 2>/dev/null | grep -o "Connected" 1>/dev/null && echo "Success" >>/wastmp/$1.txt  || echo "Failed" >>/wastmp/$1.txt


问:
return dict items from a python function
Is there a way for a function to return just the key value pairs in Python without the dict itself?

return {"_meta": {"hostvars": {}}, "group":Tags}

returns

```<code>{
  "_meta": {
    "hostvars": {}
  },
  "group": {
    "Env_Prod": [
      "1.1.1.1"
    ],
    "Logstash": [
      "2.2.2.2"
    ] } }

#Trying to have it return.
{
  "_meta": {
    "hostvars": {}
  },
    "Env_Prod": [
      "1.1.1.1"
    ],
    "Logstash": [
      "2.2.2.2"
    ] }
</code>```

答:
If I have understood it correctly, Tags is a dict, and you want to merge it into your other dict, so:

d1 = {"_meta": {"hostvars": {}}}
return {**d1, **Tags}
```

Tell me if it worked.

Body:
Is there a way for a function to return just the key value pairs in Python without the dict itself?

return {"_meta": {"hostvars": {}}, "group":Tags}

returns

{
  "_meta": {
    "hostvars": {}
  },
  "group": {
    "Env_Prod": [
      "1.1.1.1"
    ],
    "Logstash": [
      "2.2.2.2"
    ] } }

#Trying to have it return.
{
  "_meta": {
    "hostvars": {}
  },
    "Env_Prod": [
      "1.1.1.1"
    ],
    "Logstash": [
      "2.2.2.2"
    ] }

Body:
If I have understood it correctly, Tags is a dict, and you want to merge it into your other dict, so:

d1 = {"_meta": {"hostvars": {}}}
return {**d1, **Tags}

Tell me if it worked.


问:
How to get rid of display corruption during horizontal scroll in WPF4 DataGrid with grouping?
I'm trying to create a datagrid with grouping and I'm getting display corruption (blank areas) during horizontal scrolling. The issue appears only when there is a GroupStyle.ContainerStyle defined. The datagrid should contain 200 rows or more to reproduce the problem.

UPDATE2:
Related Microsoft Connect feedback.

UPDATE:
Microsoft guy at social.msdn.com pointed out that adding grouping turns off datagrid virtualization. Possibly that's the root of the problem. I removed grouping from my sample and set VirtualizingStackPanel.IsVirtualizing to false and got exactly the same kind of corruption.

Code to reproduce the problem:

```<code><DataGrid ItemsSource="{Binding Source={StaticResource ResourceKey=cvsGoods}}"
          CanUserAddRows="False" CanUserReorderColumns="False"
          CanUserDeleteRows="False" CanUserResizeRows="False"
          CanUserSortColumns="False" AutoGenerateColumns="True">
    <DataGrid.GroupStyle>
        <GroupStyle>
            <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type GroupItem}">
                                <ItemsPresenter  />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </DataGrid.GroupStyle>
</DataGrid>
</code>```

After several horizontal scrolls to the right and back to the left blank areas appear on the left side. I tried it on WinXP and Win7.

The question is: how to get rid of that bug? Is there any workaround? Any suggestions?

Screenshot illustrating the problem:

答:
We once faced the same issue (but not the same cause) i.e. the datagrid will have blank areas just before the first column of some of the rows. The way we solved (a hack) it at that time was by disabling the rowheader (don't know how it solved the problem but did figure out that the blank areas were actually rowheaders).

We disabled (correct word would be made it size-zero) the rowheader by setting the width to zero, something like the code below:

```<code><wpftk:DataGrid>
...
...
<wpftk:DataGrid.RowHeaderStyle>
    <Style  TargetType="wpftk:DataGridRowHeader" >
        <Setter Property="Width" Value="0" />
        <Setter Property="MaxWidth" Value="0" />
    </Style>
</wpftk:DataGrid.RowHeaderStyle>
...
...
</wpftk:DataGrid>
</code>```

Let me know if it works in your case.

One more thing we noticed that if we either disable the virtualization or rowheaderstyle, it would solve our problem. We went for disabling the rowheader as we didn't need it.

Body:
I'm trying to create a datagrid with grouping and I'm getting display corruption (blank areas) during horizontal scrolling. The issue appears only when there is a GroupStyle.ContainerStyle defined. The datagrid should contain 200 rows or more to reproduce the problem.

UPDATE2:
Related Microsoft Connect feedback.

UPDATE:
Microsoft guy at social.msdn.com pointed out that adding grouping turns off datagrid virtualization. Possibly that's the root of the problem. I removed grouping from my sample and set VirtualizingStackPanel.IsVirtualizing to false and got exactly the same kind of corruption.

Code to reproduce the problem:

<DataGrid ItemsSource="{Binding Source={StaticResource ResourceKey=cvsGoods}}"
          CanUserAddRows="False" CanUserReorderColumns="False"
          CanUserDeleteRows="False" CanUserResizeRows="False"
          CanUserSortColumns="False" AutoGenerateColumns="True">
    <DataGrid.GroupStyle>
        <GroupStyle>
            <GroupStyle.ContainerStyle>

            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </DataGrid.GroupStyle>
</DataGrid>

After several horizontal scrolls to the right and back to the left blank areas appear on the left side. I tried it on WinXP and Win7.

The question is: how to get rid of that bug? Is there any workaround? Any suggestions?

Screenshot illustrating the problem:

Body:
We once faced the same issue (but not the same cause) i.e. the datagrid will have blank areas just before the first column of some of the rows. The way we solved (a hack) it at that time was by disabling the rowheader (don't know how it solved the problem but did figure out that the blank areas were actually rowheaders).

We disabled (correct word would be made it size-zero) the rowheader by setting the width to zero, something like the code below:

<wpftk:DataGrid>
...
...
<wpftk:DataGrid.RowHeaderStyle>
    <Style  TargetType="wpftk:DataGridRowHeader" >
        <Setter Property="Width" Value="0" />
        <Setter Property="MaxWidth" Value="0" />
    </Style>
</wpftk:DataGrid.RowHeaderStyle>
...
...
</wpftk:DataGrid>

Let me know if it works in your case.

One more thing we noticed that if we either disable the virtualization or rowheaderstyle, it would solve our problem. We went for disabling the rowheader as we didn't need it.


问:
c++ code won't run on Visual Studios due to errors but no errors are shown
I have written a simple program to output different temperature units using conversions given. When I run the code on Visual Studios, it won't run due to build errors but no errors are shown. I have seen similar questions asked but couldn't really see any answer that solved my issue. I was also wondering whether I should be declaring the variables before or after the main function.</p>

```<code>#include <iostream>

using namespace std;

int fahrenheit, i=0;
float celsius, absolute_value;

main() {
    cout.width(20);
    cout << "Fahrenheit" << "Celsius" << "Absolute value\n";
    for (i = 0; i = 15; i += 1) {
        fahrenheit = i * 20;
        celsius = ((fahrenheit - 30) * 5) / 9;
        absolute_value = celsius + 273.15;
        cout.width(20); /*each item in next output will have width of at least 20*/
        cout << fahrenheit << celsius << absolute_value;
    }
    system("pause");
    return 0;
}
</code>```

答:
```<code>#include <iostream>

int main() {
    std::cout << "Fahrenheit\t" << "Celsius\t\t" << "Absolute value\n";
    for (int i = 0; i <= 15; i++)
    {
        const int fahrenheit = i * 20;
        const float celsius = ((fahrenheit - 32.0) * 5) / 9;
        const float absolute_value = celsius + 273.15;
        std::cout << fahrenheit << "\t\t" << celsius << "\t\t"<< absolute_value << "\n";
    }
    system("pause");
    return 0;
}
</code>```

Issues fixed:

main must return int

loop had assignement instead of comparison

variables should not be global

using namespace std; should be avoided

formula for fahrenheit to celsius was wrong

celsius was calculated with interger arithmetic despite being float

const correctness

cosmetic: formatted output with tabs

Body:
I have written a simple program to output different temperature units using conversions given. When I run the code on Visual Studios, it won't run due to build errors but no errors are shown. I have seen similar questions asked but couldn't really see any answer that solved my issue. I was also wondering whether I should be declaring the variables before or after the main function.

#include <iostream>

using namespace std;

int fahrenheit, i=0;
float celsius, absolute_value;

main() {
    cout.width(20);
    cout << "Fahrenheit" << "Celsius" << "Absolute value\n";
    for (i = 0; i = 15; i += 1) {
        fahrenheit = i * 20;
        celsius = ((fahrenheit - 30) * 5) / 9;
        absolute_value = celsius + 273.15;
        cout.width(20); /*each item in next output will have width of at least 20*/
        cout << fahrenheit << celsius << absolute_value;
    }
    system("pause");
    return 0;
}

Body:
#include <iostream>

int main() {
    std::cout << "Fahrenheit\t" << "Celsius\t\t" << "Absolute value\n";
    for (int i = 0; i <= 15; i++)
    {
        const int fahrenheit = i * 20;
        const float celsius = ((fahrenheit - 32.0) * 5) / 9;
        const float absolute_value = celsius + 273.15;
        std::cout << fahrenheit << "\t\t" << celsius << "\t\t"<< absolute_value << "\n";
    }
    system("pause");
    return 0;
}

Issues fixed:

main must return int

loop had assignement instead of comparison

variables should not be global

using namespace std; should be avoided

formula for fahrenheit to celsius was wrong

celsius was calculated with interger arithmetic despite being float

const correctness

cosmetic: formatted output with tabs


问:
How get git commit hash by it number (--count)
I get a position of commit by command

```<code>git rev-list HEAD --count
</code>```

For example, output is 1164. I want checkout to this commit number. How can I do this? I think, need get hash of this commit and checkout to commit by it hash.

答:
Here's another solution:

```<code>git rev-list HEAD --reverse | nl | grep <your build number>
</code>```

git rev-list HEAD --reverse prints out all the commit hashes from oldest to newest. nl prefixes each line with a line number (effectively the count). And finally, good ol' grep filters to just the line you want.

You could further refine this to just the commit hash with awk:

```<code>git rev-list HEAD --reverse | nl | grep <your build number> | awk '{print $2}'
</code>```

or take it to the next level with a git alias:

```<code>git config --global alias.build-number '!f() { git rev-list HEAD --reverse | nl | grep $1 | awk '"'"'{print $2}'"'"'; }; f'
</code>```

Alias usage:

```<code>git build-number <your build number>
</code>```

That quoting madness in the git config command above is explained here: https://stackoverflow.com/a/1250279/320737

Body:
I get a position of commit by command

git rev-list HEAD --count

For example, output is 1164. I want checkout to this commit number. How can I do this? I think, need get hash of this commit and checkout to commit by it hash.

Body:
Here's another solution:

git rev-list HEAD --reverse | nl | grep <your build number>

git rev-list HEAD --reverse prints out all the commit hashes from oldest to newest. nl prefixes each line with a line number (effectively the count). And finally, good ol' grep filters to just the line you want.

You could further refine this to just the commit hash with awk:

git rev-list HEAD --reverse | nl | grep <your build number> | awk '{print $2}'

or take it to the next level with a git alias:

git config --global alias.build-number '!f() { git rev-list HEAD --reverse | nl | grep $1 | awk '"'"'{print $2}'"'"'; }; f'

Alias usage:

git build-number <your build number>

That quoting madness in the git config command above is explained here: https://stackoverflow.com/a/1250279/320737


问:
Any way to "cast" units in CSS?
I'm trying to change element rotation in CSS with the respect to screen width. Something like:

transform: rotate(calc(30deg / 100vw / 1000px));

Apparently, length arithmetic returns <length>, and dividing degrees on length is illegal. On the other hand calc(30deg / 2) works fine. Is there any CSS trick to "cast" length to <number>? I'd rather avoid JavaScript at the moment.

答:
It seems, no.

https://drafts.csswg.org/css-values-3/#calc-notation

If compatible, the type resolves as described below (the following ignores precedence rules on the operators for simplicity):

At + or -, check that both sides have the same type, or that one side is a  and the other is an <integer>. If both sides are the same type, resolve to that type. If one side is a <number> and the other is an <integer>, resolve to <number>.

At *, check that at least one side is <number>. If both sides are <integer>, resolve to <integer>. Otherwise, resolve to the type of the other side.

At /, check that the right side is <number>. If the left side is <integer>, resolve to <number>. Otherwise, resolve to the type of the left side.

Note: Algebraic simplifications do not affect the validity of the calc() expression or its resolved type. For example, calc(5px - 5px + 10s) and calc(0 * 5px + 10s) are both invalid due to the attempt to add a length and a time.

Also, https://www.w3.org/TR/css-values-4/#calc-type-checking

Title: Any way to "cast" units in CSS?


问:
Which library is the best in php for making async requests
I have a lot of data, which I want to transfer to Logz.io.

Basically, the project is written in Laravel and I want to create an event manager  which will do all the job of logging info to  Logz.io. I need an advice about which library h is better to use , something like guzzle curl, which can help me to send logs info to logz.io in the  background. I mean, I don't want to wait until the request with data for logz.io will finish.

Thank you.

答:
Well, as far as I know, there are two approaches that you could take:

1) Using Laravel's queue system to send your logs later. For this you'd have to enable a worker or a supervisor process to send them on the background.

2) There's this package by the people at spatie - spatie/async which is a wrapper around PHP's PCNTL extension and allows excecuting php code in separate threads.

I hope I could help you, even if a little.


问:
Spring WebClient unsupported Content-Type
I am starting to use Spring WebClient to send requests to external services.
One of those services, not under my control, responds in Json, but has the Content-Type "text" in the response headers.

```<code>status: 200
server: nginx/1.12.2
date: Tue, 13 Nov 2018 01:48:23 GMT
content-type: text
</code>```

This makes the WebClient fail with the following exception when I call either bodyToMono(String.class) or toEntity(String.class):

```<code>Caused by: org.springframework.util.InvalidMimeTypeException: Invalid mime type "text": does not contain '/'
</code>```

I am trying to see my options here, and I see none.
I am not able to change the header on the fly (I saw this post: Reactive WebClient GET Request with text/html response but it does not work)
I am not able to make WebClient accept a mime-type that has no /.

Can anybody help?

答:
As a consumer, I am able to receive a String response at my Java Client using Spring WebClient for a content type: text/javascript provided by the producer.

If you are the producer of the service that sends the content-type as text, it is recommended to have it send content type in proper format.

Eg: application/json,
    application/pdf,
    text/javascript

Body:
I am starting to use Spring WebClient to send requests to external services.
One of those services, not under my control, responds in Json, but has the Content-Type "text" in the response headers.

status: 200
server: nginx/1.12.2
date: Tue, 13 Nov 2018 01:48:23 GMT
content-type: text

This makes the WebClient fail with the following exception when I call either bodyToMono(String.class) or toEntity(String.class):

Caused by: org.springframework.util.InvalidMimeTypeException: Invalid mime type "text": does not contain '/'

I am trying to see my options here, and I see none.
I am not able to change the header on the fly (I saw this post: Reactive WebClient GET Request with text/html response but it does not work)
I am not able to make WebClient accept a mime-type that has no /.

Can anybody help?


问:
Web service File Stream to Byte[] to FileStream to pdf failing C#
I am trying to create a web service that returns a pdf file as a byte[] and then the app that consumes it grabs the byte[] and saves it as a pdf file and then opens it. The file fails to open at the end.

Here is the Web Service that returns a byte[]

[WebMethod]
public byte[] XXXX(int fileID)
{
    try
    {
        using (EntitiesModel dbContext = new EntitiesModel())
        {
            string fileFullPath = .....
            .......
            if (fileFullNamePath != null)
            {
                FileStream fileStream = new FileStream(fileFullNamePath, FileMode.Open, System.IO.FileAccess.Read);
                int len = fileStream.Length.ToInt();
                Byte[] documentContents = new byte[len];
                fileStream.Read(documentContents, 0, len);
                fileStream.Close();
                return documentContents;
```

<p>Then it is called from an <strong>app</strong> with the following code</p>

<pre class="lang-cs prettyprint-override"><code>string soap = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>" +
              "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
              "<soap:Body>" +
              "<XXXX xmlns=\"http://tempuri.org/\">" +
              "<fileID>XXXXX</fileID>" +
              "</XXXX>" +
              "</soap:Body>" +
              "</soap:Envelope>";
string localhostContext = @"http://localhost:3381/";
string webserviceAddress = @"XXXX/XXXX/XXXXX.asmx";
string url = localhostContext + webserviceAddress ;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "text/xml";
request.ContentLength = soap.Length;
request.Timeout = 20000;
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
    using (StreamWriter streamWriter = new StreamWriter(stream))
    {
        streamWriter.Write(soap);               }
    }
}
byte[] bytes;
try
{
    WebResponse response = request.GetResponse();
    bytes = ReadFully(response.GetResponseStream());
}
catch (Exception exception)
{
    throw;
}

private byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream memoryStream = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            memoryStream.Position = 0;
            memoryStream.Write(buffer, 0, read);
        }
        return memoryStream.ToArray();
    }
}

FileStream objfilestream =
                new FileStream(fileName, FileMode.Create,FileAccess.ReadWrite);
objfilestream.Write(bytes, 0, bytes.Length);
objfilestream.Close();
var process = Process.Start(fileName);
</code>```

The code runs fine and creates a pdf and then tries to open that pdf. But the file can not be opened. Adobe Acrobat gives the error

```<code>Adobe Acrobat Reader could not open XXX.pdf because it is either not a
supported file type or because the file has been damaged (for example, it
was sent as an email attachment and wasn't correctly decoded).
</code>```

Because I am not getting an error in the code I am at a loss to know where the error is that is not creating the proper file.

There was an issue with the Stream variable called input was not giving length so I used Jon Skeet's suggestion here Stackoverflow:Creating a byte array from a stream

```<code>new byte[16*1024];
</code>```

rather than

```<code>new byte[input.length]
</code>```

答:
There were three things wrong.

```<code>memoryStream.Position = 0;
</code>```

in the while loop was problematic so I removed it.

Secondly when reading the stream. What it returned was the SOAP XMl message with the encoded base64 string in the the XXXXResult XML tag. So I had to extract that.

Finally I had to use

```<code>byte[] fileResultBytes  = Convert.FromBase64String(resultString);
</code>```

to get the byte[] from the resultString extracted from the SOAP message. In the test SOAP message, that can be generated locally, it tells you the type of this result string. I missed that initially.

Thanks to VC.One and CodeCaster for their correct suggestions.

Body:
I am trying to create a web service that returns a pdf file as a byte[] and then the app that consumes it grabs the byte[] and saves it as a pdf file and then opens it. The file fails to open at the end.

Here is the Web Service that returns a byte[]

[WebMethod]
public byte[] XXXX(int fileID)
{
    try
    {
        using (EntitiesModel dbContext = new EntitiesModel())
        {
            string fileFullPath = .....
            .......
            if (fileFullNamePath != null)
            {
                FileStream fileStream = new FileStream(fileFullNamePath, FileMode.Open, System.IO.FileAccess.Read);
                int len = fileStream.Length.ToInt();
                Byte[] documentContents = new byte[len];
                fileStream.Read(documentContents, 0, len);
                fileStream.Close();
                return documentContents;

Then it is called from an app with the following code

string soap = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>" +
              "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
              "<soap:Body>" +
              "<XXXX xmlns=\"http://tempuri.org/\">" +
              "<fileID>XXXXX</fileID>" +
              "</XXXX>" +
              "</soap:Body>" +
              "</soap:Envelope>";
string localhostContext = @"http://localhost:3381/";
string webserviceAddress = @"XXXX/XXXX/XXXXX.asmx";
string url = localhostContext + webserviceAddress ;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "text/xml";
request.ContentLength = soap.Length;
request.Timeout = 20000;
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
    using (StreamWriter streamWriter = new StreamWriter(stream))
    {
        streamWriter.Write(soap);               }
    }
}
byte[] bytes;
try
{
    WebResponse response = request.GetResponse();
    bytes = ReadFully(response.GetResponseStream());
}
catch (Exception exception)
{
    throw;
}

private byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream memoryStream = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            memoryStream.Position = 0;
            memoryStream.Write(buffer, 0, read);
        }
        return memoryStream.ToArray();
    }
}

FileStream objfilestream =
                new FileStream(fileName, FileMode.Create,FileAccess.ReadWrite);
objfilestream.Write(bytes, 0, bytes.Length);
objfilestream.Close();
var process = Process.Start(fileName);

The code runs fine and creates a pdf and then tries to open that pdf. But the file can not be opened. Adobe Acrobat gives the error

Adobe Acrobat Reader could not open XXX.pdf because it is either not a
supported file type or because the file has been damaged (for example, it
was sent as an email attachment and wasn't correctly decoded).

Because I am not getting an error in the code I am at a loss to know where the error is that is not creating the proper file.

There was an issue with the Stream variable called input was not giving length so I used Jon Skeet's suggestion here Stackoverflow:Creating a byte array from a stream

new byte[16*1024];

rather than

new byte[input.length]

Body:
There were three things wrong.

memoryStream.Position = 0;

in the while loop was problematic so I removed it.

Secondly when reading the stream. What it returned was the SOAP XMl message with the encoded base64 string in the the XXXXResult XML tag. So I had to extract that.

Finally I had to use

byte[] fileResultBytes  = Convert.FromBase64String(resultString);

to get the byte[] from the resultString extracted from the SOAP message. In the test SOAP message, that can be generated locally, it tells you the type of this result string. I missed that initially.

Thanks to VC.One and CodeCaster for their correct suggestions.


问:
How can i create an object when having @ManyToOne linking between tables
I have 2 classes - Person and Team.
One person can be in only one team, but one team can have many people (person objects). The problem is that both Person and Team need the other class objects to create themselves.

Classes:

```<code>@Entity
@Table(name = "Team")
public class Team {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Column(name = "teamName", nullable = false)
    private String teamName;

    @OneToMany(mappedBy = "myTeam", fetch = FetchType.LAZY)
    private Set <Person> setOfMembers = new HashSet<Person>();

    public Team(int id, String teamName, Set <Person> setOfMembers) {
            //usual code (don't want to waste so much space)
    }
    ... other irrelevant fields ...
}

@Entity
@Table(name = "Person")
public class Person{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false)
    private int id;

    @Column(name = "teamID", nullable = false)
    private int teamID;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teamID", referencedColumnName = "id")
    private Team myTeam;

    public Person(int id, int teamID, Team myTeam) {
        //usual code
    }
    ... other irrelevant fields ...
}
</code>```

Now in the main file, i'm trying to create a new object:

```<code>Team t1 = new Team(1,"Nights Watch", <and here i need Person Object, so i
do something as follows:> new Person(1,1, <and here i need Team object>));
</code>```

so it goes recurrent, without end.
I want to add some records to the database, but i don't know how.

Actually I need there the Set of Person Objects, but still, i don't know how

答:
Why do you need all your teammates during the initialization of the Team class ?

Just do a constructor without the Person argument, and then do a method like:

public void addTeamMember(Person person) {
   setOfMembers.add(person);
}
```

Then, you can create the Team, create the Person and finally add the Person to the Team.

Body:
I have 2 classes - Person and Team.
One person can be in only one team, but one team can have many people (person objects). The problem is that both Person and Team need the other class objects to create themselves.

Classes:

@Entity
@Table(name = "Team")
public class Team {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Column(name = "teamName", nullable = false)
    private String teamName;

    @OneToMany(mappedBy = "myTeam", fetch = FetchType.LAZY)
    private Set <Person> setOfMembers = new HashSet<Person>();

    public Team(int id, String teamName, Set <Person> setOfMembers) {
            //usual code (don't want to waste so much space)
    }
    ... other irrelevant fields ...
}

@Entity
@Table(name = "Person")
public class Person{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false)
    private int id;

    @Column(name = "teamID", nullable = false)
    private int teamID;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teamID", referencedColumnName = "id")
    private Team myTeam;

    public Person(int id, int teamID, Team myTeam) {
        //usual code
    }
    ... other irrelevant fields ...
}

Now in the main file, i'm trying to create a new object:

Team t1 = new Team(1,"Nights Watch", <and here i need Person Object, so i
do something as follows:> new Person(1,1, <and here i need Team object>));

so it goes recurrent, without end.
I want to add some records to the database, but i don't know how.

Actually I need there the Set of Person Objects, but still, i don't know how

Body:
Why do you need all your teammates during the initialization of the Team class ?

Just do a constructor without the Person argument, and then do a method like:

public void addTeamMember(Person person) {
   setOfMembers.add(person);
}

Then, you can create the Team, create the Person and finally add the Person to the Team.


问:
GSON: encode map of objects and preserve type when decoding
I have a class like:

```<code>public class MyClass {
    private final Map<Property, Object> properties;
}
</code>```

where Property is an enum.

Let's say that properties contains 2 elements, one whose value is a Double and one whose value is a class instance having only one attribute called ownerName. When I serialise this class I get the following string:

```<code>{"properties":{"NAME":{"ownerName":"MyBucket"},"DIVISOR":33.0}}
</code>```

The problem is that when I tried to obtain a MyClass instance from the string above, the value for NAME property will be a Map instead of an instance of the class having ownerName attribute. I tried to write a custom serializer/deserializer but I was not able to do that only for NAME property. Any ideas?

答:
You need to write custom deserialiser for the whole Map. Custom deserialiser could look like below:

```<code>class PropertyJsonDeserializer implements JsonDeserializer<Map<Property, Object>>, JsonSerializer<Map<Property, Object>> {

    @Override
    public Map<Property, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!json.isJsonObject()) {
            return Collections.emptyMap();
        }

        JsonObject root = json.getAsJsonObject();
        Map<Property, Object> result = new LinkedHashMap<>();
        root.entrySet().forEach(entry -> {
            Property property = Property.valueOf(entry.getKey());
            switch (property) {
                case DIVISOR:
                    result.put(property, entry.getValue().getAsDouble());
                    break;
                case NAME:
                    Object owner = context.deserialize(entry.getValue(), Owner.class);
                    result.put(property, owner);
            }
        });
        return result;
    }

    @Override
    public JsonElement serialize(Map<Property, Object> src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(src, Map.class);
    }
}
</code>```

Example usage:

```<code>import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.JsonAdapter;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        Map<Property, Object> properties = new EnumMap<>(Property.class);
        properties.put(Property.DIVISOR, new BigDecimal("33.0"));
        properties.put(Property.NAME, new Owner());

        MyClass myClass = new MyClass(properties);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(myClass);
        System.out.println(json);

        myClass = gson.fromJson(json, MyClass.class);
        System.out.println(myClass);
    }
}

class MyClass {

    @JsonAdapter(PropertyJsonDeserializer.class)
    private final Map<Property, Object> properties;

    public MyClass(Map<Property, Object> properties) {
        this.properties = properties;
    }

    // getters, setters, toString
}

class Owner {
    private String ownerName = "MyBucket";

    // getters, setters, toString
}

enum Property {
    NAME, DIVISOR
}
</code>```

Above code prints:

```<code>{
  "properties": {
    "NAME": {
      "ownerName": "MyBucket"
    },
    "DIVISOR": 33.0
  }
}

MyClass{properties={NAME=Owner{ownerName='MyBucket'}, DIVISOR=33.0}}
</code>```

Body:
I have a class like:

public class MyClass {
    private final Map<Property, Object> properties;
}

where Property is an enum.

Let's say that properties contains 2 elements, one whose value is a Double and one whose value is a class instance having only one attribute called ownerName. When I serialise this class I get the following string:

{"properties":{"NAME":{"ownerName":"MyBucket"},"DIVISOR":33.0}}

The problem is that when I tried to obtain a MyClass instance from the string above, the value for NAME property will be a Map instead of an instance of the class having ownerName attribute. I tried to write a custom serializer/deserializer but I was not able to do that only for NAME property. Any ideas?

Body:
You need to write custom deserialiser for the whole Map. Custom deserialiser could look like below:

class PropertyJsonDeserializer implements JsonDeserializer<Map<Property, Object>>, JsonSerializer<Map<Property, Object>> {

    @Override
    public Map<Property, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!json.isJsonObject()) {
            return Collections.emptyMap();
        }

        JsonObject root = json.getAsJsonObject();
        Map<Property, Object> result = new LinkedHashMap<>();
        root.entrySet().forEach(entry -> {
            Property property = Property.valueOf(entry.getKey());
            switch (property) {
                case DIVISOR:
                    result.put(property, entry.getValue().getAsDouble());
                    break;
                case NAME:
                    Object owner = context.deserialize(entry.getValue(), Owner.class);
                    result.put(property, owner);
            }
        });
        return result;
    }

    @Override
    public JsonElement serialize(Map<Property, Object> src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(src, Map.class);
    }
}

Example usage:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.JsonAdapter;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        Map<Property, Object> properties = new EnumMap<>(Property.class);
        properties.put(Property.DIVISOR, new BigDecimal("33.0"));
        properties.put(Property.NAME, new Owner());

        MyClass myClass = new MyClass(properties);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(myClass);
        System.out.println(json);

        myClass = gson.fromJson(json, MyClass.class);
        System.out.println(myClass);
    }
}

class MyClass {

    @JsonAdapter(PropertyJsonDeserializer.class)
    private final Map<Property, Object> properties;

    public MyClass(Map<Property, Object> properties) {
        this.properties = properties;
    }

    // getters, setters, toString
}

class Owner {
    private String ownerName = "MyBucket";

    // getters, setters, toString
}

enum Property {
    NAME, DIVISOR
}

Above code prints:

{
  "properties": {
    "NAME": {
      "ownerName": "MyBucket"
    },
    "DIVISOR": 33.0
  }
}

MyClass{properties={NAME=Owner{ownerName='MyBucket'}, DIVISOR=33.0}}


问:
How to get values from #result-set-1 in SimpleJdbcCall
When executing SimpleJdbcCall, I get two parameters #result-set-1, #update-count-1

```<code>MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("name", "something");
Map<String, Object> resultFromProcedure = cstmt.execute(parameterSource);
</code>```

#result-set-1 have variables

```<code>[{
 id = 123,
 name = "something",
 accountnumber = 123456,
 balance = 789999
}]
</code>```

Everything is fine until I tried to access

```<code>resultFromProcedure.get("accountnumber")
</code>```

Which getting null. The Question is how to access the values in #result-set-1

答:
As there could be more than one result set, SimpleJdbcCall returns an object in the arraylist within another map marked as "#result-set-1". To access the values in it, try the following:</p>

```<code>ArrayList arrayList = new ArrayList();
arrayList = (ArrayList) resultFromProcedure.get("#result-set-1");
Map resultMap = (Map) arrayList.get(0);

System.out.println("Account Number: " + resultMap.get("accountnumber"));
</code>```

Body:
When executing SimpleJdbcCall, I get two parameters #result-set-1, #update-count-1

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("name", "something");
Map<String, Object> resultFromProcedure = cstmt.execute(parameterSource);

#result-set-1 have variables

[{
 id = 123,
 name = "something",
 accountnumber = 123456,
 balance = 789999
}]

Everything is fine until I tried to access

resultFromProcedure.get("accountnumber")

Which getting null. The Question is how to access the values in #result-set-1

Body:
As there could be more than one result set, SimpleJdbcCall returns an object in the arraylist within another map marked as "#result-set-1". To access the values in it, try the following:

ArrayList arrayList = new ArrayList();
arrayList = (ArrayList) resultFromProcedure.get("#result-set-1");
Map resultMap = (Map) arrayList.get(0);

System.out.println("Account Number: " + resultMap.get("accountnumber"));


问:
Is there a way to store a file in a React state?
I'm working on a project where I need to store an image in my components state, so that I can send the file and accompanying data to a different component that uploads the data to my Firebase Database and the image to my Firestore.

I've tried doing it by setting the state the normal way, using a functions that is called when an image is submitted. But the state in which I want to pass on the file remains empty.

The initial state:

```<code>state = {
    title: '',
    description: '',
    date: '',
    ticket: '',
    price: '',
    image: []
}
</code>```

The input:

```<code><input type="file" id="image" accept="image/*" onChange={this.handleChangeImage} />
</code>```

The function that is supposed to handle my problem:

```<code>handleChangeImage = (e) => {
    const file = e.target.files[0];
    this.setState({
        [e.target.id]: file
    });
}
</code>```

If I console log the variable "file" I get the file, but console logging state.image will just show me an empty array.

答:
Try changing your handle function to this:</p>

```<code>handleChangeImage = (e) => {
  const file = e.target.files[0];
  const newImages = [...this.state.image];
  newImages.push(file);
  this.setState({
    image: newImages
  });
}
</code>```

Body:
I'm working on a project where I need to store an image in my components state, so that I can send the file and accompanying data to a different component that uploads the data to my Firebase Database and the image to my Firestore.

I've tried doing it by setting the state the normal way, using a functions that is called when an image is submitted. But the state in which I want to pass on the file remains empty.

The initial state:

state = {
    title: '',
    description: '',
    date: '',
    ticket: '',
    price: '',
    image: []
}

The input:

<input type="file" id="image" accept="image/*" onChange={this.handleChangeImage} />

The function that is supposed to handle my problem:

handleChangeImage = (e) => {
    const file = e.target.files[0];
    this.setState({
        [e.target.id]: file
    });
}

If I console log the variable "file" I get the file, but console logging state.image will just show me an empty array.

Body:
Try changing your handle function to this:

handleChangeImage = (e) => {
  const file = e.target.files[0];
  const newImages = [...this.state.image];
  newImages.push(file);
  this.setState({
    image: newImages
  });
}


问:
How do I use BeautifulSoup4 to get ALL text before
 tag into a pandas data frame
I'm trying to extract postcode and suburbs of sydney as dataframe by scraping a website

I've located the corresponding tag in beautifulsup but am not able to finish the process

import requests
from bs4 import BeautifulSoup

url = 'https://data.mongabay.com/igapo/australia/postcodes/sydney-numeric.html'
res = requests.get(url)
soup = BeautifulSoup(res.text,'html5lib')

table = soup.find_all('table')[10]

rows = table.find_all('td')[2]

for br in rows.find_all("br"):
    br.replace_with("\n")

parsedText = rows.get_text()

```

<p>I'm expecting a dataframe such as:</p>

<pre class="lang-py prettyprint-override"><code>postcode suburbs
2000 Australia Square Post Office
2000 Circular Quay
2000 Clarence Street Post Office
...
</code>```

thank you for your help

答:
A somewhat verbose method. bs4 4.7.1</p>

```<code>import requests
import pandas as pd

url = 'https://data.mongabay.com/igapo/australia/postcodes/sydney-numeric.html'
r = requests.get(url, headers = {'User-Agent' : 'Mozilla/5.0'})
soup = bs(r.content, 'lxml')
codes = []
names = []

for line in soup.select_one('h1:contains("Postal codes") ~ font [size="2"]').text.split('\n'):
    if line[:4]:
        codes.append(line[:4]), names.append(line[5:])
df = pd.DataFrame(list(zip(codes, names)), columns = ['code', 'name'])

</code>```

Title: How do I use BeautifulSoup4 to get ALL text before <br> tag into a pandas data frame

Body:
I'm trying to extract postcode and suburbs of sydney as dataframe by scraping a website

I've located the corresponding tag in beautifulsup but am not able to finish the process

import requests
from bs4 import BeautifulSoup

url = 'https://data.mongabay.com/igapo/australia/postcodes/sydney-numeric.html'
res = requests.get(url)
soup = BeautifulSoup(res.text,'html5lib')

table = soup.find_all('table')[10]

rows = table.find_all('td')[2]

for br in rows.find_all("br"):
    br.replace_with("\n")

parsedText = rows.get_text()

I'm expecting a dataframe such as:

postcode suburbs
2000 Australia Square Post Office
2000 Circular Quay
2000 Clarence Street Post Office
...

thank you for your help

Body:
A somewhat verbose method. bs4 4.7.1

import requests
import pandas as pd

url = 'https://data.mongabay.com/igapo/australia/postcodes/sydney-numeric.html'
r = requests.get(url, headers = {'User-Agent' : 'Mozilla/5.0'})
soup = bs(r.content, 'lxml')
codes = []
names = []

for line in soup.select_one('h1:contains("Postal codes") ~ font [size="2"]').text.split('\n'):
    if line[:4]:
        codes.append(line[:4]), names.append(line[5:])
df = pd.DataFrame(list(zip(codes, names)), columns = ['code', 'name'])


问:
PHP URL Rewriting for the link
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       document.location="delete_row.php";
       return false;
     }
</script>
</head>

<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th> </th>
<?php
while($row = mysql_fetch_array($result))
  {?>
  <tr>
  <td><?php echo $row['name'];?></td>
  <td><?php echo $row['age'];?></td>
  <td><a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete</a></td>
  </tr>
  <?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>
</code>```

This is the PHP part with file name delete_row.php

```<code><?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>
</code>```

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

答:
How will the page then know what row to delete? You'll have to send some sort of identifier across to it. If you mean, after it's deleted, get the id to hide again, you can do that with a redirect by using:

header('Location: urlOfPageWithoutQueryString');

Title: PHP URL Rewriting for the link

Body:
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>

Name
Age

<?php
while($row = mysql_fetch_array($result))
  {?>

  <?php echo $row['name'];?>
  <?php echo $row['age'];?>
  <a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete

  <?php } ?>

<?php
mysql_close($con);
?>

This is the PHP part with file name delete_row.php

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13


问:
Extracting Files between two dates which has been saved with dates
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

```<code>import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)
</code>```

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

答:
What about this

```<code>start_date = "05-01-2019"
end_date = "04-02-2019"

all_csv_files = [x for x in os.listdir(file_path) if x.endswith('.csv')]
correct_date_files = [x for x in all_csv_files
                      if x >= start_date + "-Sales.csv" and x <= end_date + "-Sales.csv"]
df = pd.concat([pd.read_csv(f) for f in correct_date_files], sort=False)
</code>```

You basically just list all .csv files in your directory and only take the ones between the chosen dates.

Body:
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

Body:
What about this

start_date = "05-01-2019"
end_date = "04-02-2019"

all_csv_files = [x for x in os.listdir(file_path) if x.endswith('.csv')]
correct_date_files = [x for x in all_csv_files
                      if x >= start_date + "-Sales.csv" and x <= end_date + "-Sales.csv"]
df = pd.concat([pd.read_csv(f) for f in correct_date_files], sort=False)

You basically just list all .csv files in your directory and only take the ones between the chosen dates.


问:
Loop through entire array while excluding an item
I have an array of items that I'd like to loop through and apply some code to, excluding one item (the clicked-on item).  I've tried using splice but I don't want to remove the array item, just skip over it.  In this case, I'm trying to remove a CSS class for each item, except the excluded one.

I've tried a few methods, using splice for one which isn't what I need.  I've also tried something like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... } but can't seem to get that to work.

```<code>   var array = ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(array[i] is the excluded one){
               skip over}
    else { $(items[i]).removeClass('class');
    }
</code>```

No error messages, just not working as expected.

答:
Elegant way in functional programming:</p>

```<code>const array = ["item1", "item2", "item3"];

// item to ignore
const ignore = "item2";

// use filter to keep only items which are not ignored
const newarray = array.filter((e)=> { return e !== ignore } );

// iterate over remaining
newarray.forEach((e)=> { $(e).removeClass("class"); });
</code>```

Body:
I have an array of items that I'd like to loop through and apply some code to, excluding one item (the clicked-on item).  I've tried using splice but I don't want to remove the array item, just skip over it.  In this case, I'm trying to remove a CSS class for each item, except the excluded one.

I've tried a few methods, using splice for one which isn't what I need.  I've also tried something like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... } but can't seem to get that to work.

   var array = ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(array[i] is the excluded one){
               skip over}
    else { $(items[i]).removeClass('class');
    }

No error messages, just not working as expected.

Body:
Elegant way in functional programming:

const array = ["item1", "item2", "item3"];

// item to ignore
const ignore = "item2";

// use filter to keep only items which are not ignored
const newarray = array.filter((e)=> { return e !== ignore } );

// iterate over remaining
newarray.forEach((e)=> { $(e).removeClass("class"); });


问:
Automatically generated title for a TXT file for the ">" command
I'm trying to write a short batch file to monitor the data traffic hourly and write it in TXT files. My problem is that I want to give the TXT files the date and time of their creation as their filename.

I already tried to use the %date% and %time% commands, the "date /t" and "time /t" commands or to generate a file beforehand and access it afterwards, but I'm simply not well-versed enough in batch programming to access this file.

netstat -e > C:\Users\User1\Documents\%date%.%time%.txt
exit

There should be a file with the name of e.g. "20.02.2016 , 12:06:12.txt" , but I'm either getting a &date file or an error in cmd: "The syntax for filename, directory name, or volume label is incorrect.".

答:
```<code>For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set filedate=%%c%%a%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set filetime=%%a%%b)
netstat -e > C:\Users\User1\Documents\%filedate=%.%filetime%.txt exit
</code>```

The first for loop does date /t then is set "/" as a delimiter and reassembles the date without a delimiter.

The second for loop does time /t then using ":" as a delimiter and reassembles the time without a delimiter.

Then we do your netstat command, placing our variables into the filename.

This will not work for all locales, but the general idea is the same. If you live a locale where this solution does not work, then just adapt the code to your own needs. This works for me on my own system, in North America.

Body:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set filedate=%%c%%a%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set filetime=%%a%%b)
netstat -e > C:\Users\User1\Documents\%filedate=%.%filetime%.txt exit

The first for loop does date /t then is set "/" as a delimiter and reassembles the date without a delimiter.

The second for loop does time /t then using ":" as a delimiter and reassembles the time without a delimiter.

Then we do your netstat command, placing our variables into the filename.

This will not work for all locales, but the general idea is the same. If you live a locale where this solution does not work, then just adapt the code to your own needs. This works for me on my own system, in North America.


问:
Problem accessing variable declared in one file in extension file
I  declared a variable in my ViewController.swift file like this:

```<code>struct serials{
    static var snToConnectTo2 = ""
}

class ViewController: UIViewController {
....
}
</code>```

I want to access this variable from my KeyboardViewController.swift file which belongs to an extension of my application that ViewController.swift controls.

I am trying to access the variable like this:

```<code>serials.snToConnectTo2
</code>```

When I try to compile my code I get the following error:

```<code>Use of unresolved identifier 'serials';
</code>```

How do you properly access variables from different files?

答:
first of all you need to declare your struct as public and its properties like the following:

```<code> public struct serials{
 public static var snToConnectTo2 = ""

 public init() {

 }
}
</code>```

second you need to link this file (I mean the file that contain your struct) as described in the following screenshot

then choose your file and add it, and it will work fine with you

Body:
I  declared a variable in my ViewController.swift file like this:

struct serials{
    static var snToConnectTo2 = ""
}

class ViewController: UIViewController {
....
}

I want to access this variable from my KeyboardViewController.swift file which belongs to an extension of my application that ViewController.swift controls.

I am trying to access the variable like this:

serials.snToConnectTo2

When I try to compile my code I get the following error:

Use of unresolved identifier 'serials';

How do you properly access variables from different files?

Body:
first of all you need to declare your struct as public and its properties like the following:

 public struct serials{
 public static var snToConnectTo2 = ""

 public init() {

 }
}

second you need to link this file (I mean the file that contain your struct) as described in the following screenshot

then choose your file and add it, and it will work fine with you


问:
Value of type 'UICollectionViewCell?' has no member 'contentImage'
I have two custom UICollectionViewCells(AddImageCollectionViewCell, ItemCollectionViewCell) which I am loading depending on indexpath. Here is my code for the cellForItemAtIndexpath-

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        var cell :UICollectionViewCell!

        if indexPath.row == 0{
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath) as! AddImageCollectionViewCell
        }
        else{
             cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCollectionViewCell
            cell.contentImage = self.droppedItemList[indexPath.row] //error here
        }
        return cell
    }
</code>```

I am getting the error as "Value of type 'UICollectionViewCell?' has no member 'contentImage'". Why is my cell in the else clause is not cast to "ItemCollectionViewCell" type.

I know, I must be doing something very foolish. I would be really grateful if someone can point me to the right direction.

答:
You are declaring cell as basic type UICollectionViewCell, that's the reason. Return the cells separately

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if indexPath.row == 0 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath) as! AddImageCollectionViewCell
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCollectionViewCell
        cell.contentImage = self.droppedItemList[indexPath.row]
        return cell
    }
}
</code>```

Body:
I have two custom UICollectionViewCells(AddImageCollectionViewCell, ItemCollectionViewCell) which I am loading depending on indexpath. Here is my code for the cellForItemAtIndexpath-

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        var cell :UICollectionViewCell!

        if indexPath.row == 0{
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath) as! AddImageCollectionViewCell
        }
        else{
             cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCollectionViewCell
            cell.contentImage = self.droppedItemList[indexPath.row] //error here
        }
        return cell
    }

I am getting the error as "Value of type 'UICollectionViewCell?' has no member 'contentImage'". Why is my cell in the else clause is not cast to "ItemCollectionViewCell" type.

I know, I must be doing something very foolish. I would be really grateful if someone can point me to the right direction.

Body:
You are declaring cell as basic type UICollectionViewCell, that's the reason. Return the cells separately

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if indexPath.row == 0 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath) as! AddImageCollectionViewCell
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCollectionViewCell
        cell.contentImage = self.droppedItemList[indexPath.row]
        return cell
    }
}


问:
form post not posting hidden field because of action?
I have the following form:

```<code><form name="cart_quantity" action="https://www.example.com/product_info.php?action=add_product" method="post" onsubmit="return validate(); ">
<input type="hidden" name="products_id" value="226" />
<input type="hidden" name="final_sale" value="final_sale" />
</form>
</code>```

The products_id is properly being passed to the shopping cart page. However the final sale value I am trying to add is not.

The form action functions:

```<code>$goto =  shopping_cart.php;
        $parameters = array('action', 'cPath', 'products_id', 'pid');

case 'add_product' :    if (isset($HTTP_POST_VARS['products_id']) && is_numeric($HTTP_POST_VARS['products_id'])) {
    $attributes = isset($HTTP_POST_VARS['id']) ? $HTTP_POST_VARS['id'] : '';

    $cart->add_cart($HTTP_POST_VARS['products_id'], $cart->get_quantity(tep_get_uprid($HTTP_POST_VARS['products_id'], $HTTP_POST_VARS['id'])) + $HTTP_POST_VARS['cart_quantity'], $HTTP_POST_VARS['id']);

}
    tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
    break;
</code>```

I tried changing the action to include the final_sale value (which I didnt think was necessary):

```<code>case 'add_product' :    if (isset($HTTP_POST_VARS['products_id']) && is_numeric($HTTP_POST_VARS['products_id'])) {
            $attributes = isset($HTTP_POST_VARS['id']) ? $HTTP_POST_VARS['id'] : '';
            $final_sale = isset($HTTP_POST_VARS['final_sale']) ? $HTTP_POST_VARS['final_sale'] : '';
            $cart->add_cart($HTTP_POST_VARS['products_id'], $cart->get_quantity(tep_get_uprid($HTTP_POST_VARS['products_id'], $HTTP_POST_VARS['id'])) + $HTTP_POST_VARS['cart_quantity'], $HTTP_POST_VARS['id']);

        }
            tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
            break;
</code>```

This too did not work.

In shopping_cart.php I am just trying to echo the value like so to see if it passes but I am getting nothing:

```<code>echo $_GET['final_sale'];

if (tep_not_null( ($_GET['final_sale']) )) {
    echo "finalsale";

}
</code>```

答:
There are three problems with code samples you provided:

Variable $HTTP_POST_VARS isn't superglobal so to use it you need to declare it using a global keyword.

Also the $HTTP_POST_VARS is depreceted and you should use the $_POST variable insetead. The $_POST is superglobal so you don't need to use the global keyword.

In last code sample you used $_GET variable but form which you created is declared as POST.

To make your code work you need replace all $HTTP_POST_VARS and $_GET variables to $_POST.

Body:
I have the following form:

<form name="cart_quantity" action="https://www.example.com/product_info.php?action=add_product" method="post" onsubmit="return validate(); ">
<input type="hidden" name="products_id" value="226" />
<input type="hidden" name="final_sale" value="final_sale" />
</form>

The products_id is properly being passed to the shopping cart page. However the final sale value I am trying to add is not.

The form action functions:

$goto =  shopping_cart.php;
        $parameters = array('action', 'cPath', 'products_id', 'pid');

case 'add_product' :    if (isset($HTTP_POST_VARS['products_id']) && is_numeric($HTTP_POST_VARS['products_id'])) {
    $attributes = isset($HTTP_POST_VARS['id']) ? $HTTP_POST_VARS['id'] : '';

    $cart->add_cart($HTTP_POST_VARS['products_id'], $cart->get_quantity(tep_get_uprid($HTTP_POST_VARS['products_id'], $HTTP_POST_VARS['id'])) + $HTTP_POST_VARS['cart_quantity'], $HTTP_POST_VARS['id']);

}
    tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
    break;

I tried changing the action to include the final_sale value (which I didnt think was necessary):

case 'add_product' :    if (isset($HTTP_POST_VARS['products_id']) && is_numeric($HTTP_POST_VARS['products_id'])) {
            $attributes = isset($HTTP_POST_VARS['id']) ? $HTTP_POST_VARS['id'] : '';
            $final_sale = isset($HTTP_POST_VARS['final_sale']) ? $HTTP_POST_VARS['final_sale'] : '';
            $cart->add_cart($HTTP_POST_VARS['products_id'], $cart->get_quantity(tep_get_uprid($HTTP_POST_VARS['products_id'], $HTTP_POST_VARS['id'])) + $HTTP_POST_VARS['cart_quantity'], $HTTP_POST_VARS['id']);

        }
            tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
            break;

This too did not work.

In shopping_cart.php I am just trying to echo the value like so to see if it passes but I am getting nothing:

echo $_GET['final_sale'];

if (tep_not_null( ($_GET['final_sale']) )) {
    echo "finalsale";

}