问:
Loop through Rows with multiple IF ANDs with an array as values
I have an worksheet that has 3 columns A-C of text.

I want to write a VBA script to loop through each row and if (in each row) col a = (text 1 or text 2) AND col b = (Text5 or text 6 or text 7 or text 8) AND col c = (Text20 or Text 22) put a yes in column D

I was thinking of putting my text values to search for in multiple arrays:

```<code>Dim Search1 As Variant
Dim Search2 as Variant
Dim Search3 as Variant

Search1 = Array("Cat", "Dog")
Search2 = Array("Red", "Brown", "Blue")
Search2 = Array("House", "Condo")
</code>```

Then do a loop through the rows:

Dim i As Long
For i = 1 To rg.Rows.Count

Where I'm stuck is the search logic:

```<code>Application.CountIFs(Cells(i,1),Search1, Cells(i,2), Search2, Cells(i,3), Search4)) > 0 then
sh.Cells(i, "F").Value = "yes"
i = i + 1
End if
Next i
</code>```

So something like:

```<code>A    B       C      D
Dog    Brown House  Y       A=(Dog or Cat) AND  B=(Brown or Blue or Red)  AND C =( House or Condo)
Bird   Blue  House
Cat    Brown Condo  Y
Cat    Pink  Condo
Cat    Blue  House  Y
Horse  Red   Condo
Cat    Green House
Dog    Pink  Condo
Horse  Blue  House
</code>```

I hope this make sense...I'm really looking for how to do the countIF(Range, Array, Range,Array, Rang, Array) for each row.

Thank you!

答:
Triple Match

```<code>Option Explicit

Sub TripleMatch()

    ' Define constants.
    Const SheetName As String = "Sheet1"
    Const Cols As String = "A:C"
    Const FirstRow As Long = 2
    Const TargetColumn As Long = 4
    Const StringValue As String = "Yes"
    Dim Search(2) As Variant
    Search(0) = Array("Cat", "Dog")
    Search(1) = Array("Red", "Brown", "Blue")
    Search(2) = Array("House", "Condo")

    ' Write values of Source Range to Source Array.
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets(SheetName)
    Dim FirstColumn As Long
    FirstColumn = ws.Columns(Cols).Column
    Dim rng As Range
    Set rng = ws.Columns(FirstColumn).Find("*", , xlValues, , , xlPrevious)
    If rng Is Nothing Then Exit Sub
    If rng.Row < FirstRow Then Exit Sub
    Dim Source As Variant
    Source = Intersect(ws.Range(ws.Cells(FirstRow, FirstColumn), rng) _
      .EntireRow.Rows, ws.Columns(Cols))

    ' Check Source Array and write to Target Array.
    Dim Target As Variant
    ReDim Target(1 To UBound(Source), 1 To 1)
    Dim i As Long, j As Long
    For i = 1 To UBound(Source)
        GoSub CheckValue
    Next i

    ' Write values of Target Array to Target Range.
    ws.Cells(FirstRow, TargetColumn).Resize(UBound(Target)).Value = Target

    ' Inform user.
    MsgBox "TripleMatch finished successfully.", vbInformation, "Success"

    Exit Sub

CheckValue:
    For j = 1 To UBound(Source, 2)
        If IsError(Application.Match(Source(i, j), Search(j - 1), 0)) Then
            Return
        End If
    Next j
    Target(i, 1) = StringValue
    Return

End Sub
</code>```

Body:
I have an worksheet that has 3 columns A-C of text.

I want to write a VBA script to loop through each row and if (in each row) col a = (text 1 or text 2) AND col b = (Text5 or text 6 or text 7 or text 8) AND col c = (Text20 or Text 22) put a yes in column D

I was thinking of putting my text values to search for in multiple arrays:

Dim Search1 As Variant
Dim Search2 as Variant
Dim Search3 as Variant

Search1 = Array("Cat", "Dog")
Search2 = Array("Red", "Brown", "Blue")
Search2 = Array("House", "Condo")

Then do a loop through the rows:

Dim i As Long
For i = 1 To rg.Rows.Count

Where I'm stuck is the search logic:

Application.CountIFs(Cells(i,1),Search1, Cells(i,2), Search2, Cells(i,3), Search4)) > 0 then
sh.Cells(i, "F").Value = "yes"
i = i + 1
End if
Next i

So something like:

A    B       C      D
Dog    Brown House  Y       A=(Dog or Cat) AND  B=(Brown or Blue or Red)  AND C =( House or Condo)
Bird   Blue  House
Cat    Brown Condo  Y
Cat    Pink  Condo
Cat    Blue  House  Y
Horse  Red   Condo
Cat    Green House
Dog    Pink  Condo
Horse  Blue  House

I hope this make sense...I'm really looking for how to do the countIF(Range, Array, Range,Array, Rang, Array) for each row.

Thank you!

Body:
Triple Match

Option Explicit

Sub TripleMatch()

    ' Define constants.
    Const SheetName As String = "Sheet1"
    Const Cols As String = "A:C"
    Const FirstRow As Long = 2
    Const TargetColumn As Long = 4
    Const StringValue As String = "Yes"
    Dim Search(2) As Variant
    Search(0) = Array("Cat", "Dog")
    Search(1) = Array("Red", "Brown", "Blue")
    Search(2) = Array("House", "Condo")

    ' Write values of Source Range to Source Array.
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets(SheetName)
    Dim FirstColumn As Long
    FirstColumn = ws.Columns(Cols).Column
    Dim rng As Range
    Set rng = ws.Columns(FirstColumn).Find("*", , xlValues, , , xlPrevious)
    If rng Is Nothing Then Exit Sub
    If rng.Row < FirstRow Then Exit Sub
    Dim Source As Variant
    Source = Intersect(ws.Range(ws.Cells(FirstRow, FirstColumn), rng) _
      .EntireRow.Rows, ws.Columns(Cols))

    ' Check Source Array and write to Target Array.
    Dim Target As Variant
    ReDim Target(1 To UBound(Source), 1 To 1)
    Dim i As Long, j As Long
    For i = 1 To UBound(Source)
        GoSub CheckValue
    Next i

    ' Write values of Target Array to Target Range.
    ws.Cells(FirstRow, TargetColumn).Resize(UBound(Target)).Value = Target

    ' Inform user.
    MsgBox "TripleMatch finished successfully.", vbInformation, "Success"

    Exit Sub

CheckValue:
    For j = 1 To UBound(Source, 2)
        If IsError(Application.Match(Source(i, j), Search(j - 1), 0)) Then
            Return
        End If
    Next j
    Target(i, 1) = StringValue
    Return

End Sub


来源: stackexchange

问:
How do you initialize variables inside function scope and avoid global scope?
I have in the global space a variable set as follows:

```<code>let hoverMessageLock = 0;
</code>```

This allows the function below to operate how I want. Its function is to add a message upon button hover and then delete said message and replace it with a new message upon another hover.

The issue I'm having is I would like to NOT use the global space for variables and instead put it inside the function itself. However the function itself is getting called over and over again per each hover event, so if I set hoverMessageLock = 0 in the function scope, it just keeps getting set to 0 over and over again. Therefor my switch statement doesn't work as intended as when its in the global scope.

I know in other programming languages that utilizes classes, you can set variables in the class scope and then alter them in the same way you would global scope inside your functions. Is there a way to do this as well here in Javascript?

```<code>let macroManager = {
    hoverMessage: function(message, style = "hovertext noTextSelect"){
        switch (hoverMessageLock){
            case 0:
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                hoverMessageLock = 1;
                break;
            case 1:
                uiManager.messageDirector.removeMessage();
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                break;
        }
    },
}
</code>```

答:
```<code>class macroManger{
  constructor(){
     this.hoverMessageLock = 0;
  }
  hoverMessage(message, style = "hovertext noTextSelect"){
    switch (this.hoverMessageLock) {
        case 0:
          uiManager.messageDirector.addMessage("" + message + "", 0, 0, style);
          this.hoverMessageLock = 1;
          break;
        case 1:
          uiManager.messageDirector.removeMessage();
          uiManager.messageDirector.addMessage("" + message + "", 0, 0, style);
          break;
      }
  }
}

macroManger1 = new macroManger();
macroManger1.hoverMessage(...);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have in the global space a variable set as follows:

let hoverMessageLock = 0;

This allows the function below to operate how I want. Its function is to add a message upon button hover and then delete said message and replace it with a new message upon another hover.

The issue I'm having is I would like to NOT use the global space for variables and instead put it inside the function itself. However the function itself is getting called over and over again per each hover event, so if I set hoverMessageLock = 0 in the function scope, it just keeps getting set to 0 over and over again. Therefor my switch statement doesn't work as intended as when its in the global scope.

I know in other programming languages that utilizes classes, you can set variables in the class scope and then alter them in the same way you would global scope inside your functions. Is there a way to do this as well here in Javascript?

let macroManager = {
    hoverMessage: function(message, style = "hovertext noTextSelect"){
        switch (hoverMessageLock){
            case 0:
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                hoverMessageLock = 1;
                break;
            case 1:
                uiManager.messageDirector.removeMessage();
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                break;
        }
    },
}


问:
How to implement pagination in RecyclerView on scroll
Recyclerview comes with its own scroll listener which has the following methods :

```<code>void onScrollStateChanged(RecyclerView recyclerView, int newState)
</code>```

Callback method to be invoked when RecyclerView's scroll state changes.

```<code>void onScrolled(RecyclerView recyclerView, int dx, int dy)
</code>```

Callback method to be invoked when the RecyclerView has been scrolled.

Is there any way to trigger loader to load more data when scroll reaches end of the list?

I have implemented this way:

```<code>@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    GenerItem generItem=generItems.get(i);
    Log.d("TAG","position "+i);
    if(i==generItems.size()-1)
    ((GenerSearchActivity)mContext).onScroll(i);
    viewHolder.bindValues(generItem);
}
</code>```

Here onScroll() in Activity, will trigger the loader to load more data. What is the best way please suggest.

答:
Make Next Call at the end of scroll

There are essentially 3 steps.

Notify when the list is scrolled

Make REST call (for NEXT page)

Add the result in the old list + Notify DataSet change

CALLBACK

But first, we need a Callback which would work as a bridge between RecyclerView.Adapter and Activity

```<code>public interface PaginationCallBack{
     public void oadNextPage();
}
</code>```

Implement this callback in Your Activity

```<code>class YourActivity extends AppCompatActivity implements PaginationCallBack{

     int pageNum = 1;

     @Override
     public void loadNextPage(){
           // Your implementation
     }
}
</code>```

Initialize Callback in RecyclerView.Adapter

```<code>class YourAdapter extends RecyclerView.Adapter{

     private PaginationCallBack paginationCallBack;

     public YourAdapter(PaginationCallBack paginationCallBack) {
        this.paginationCallBack = paginationCallBack;
     }

}
</code>```

STEP 1
Add a condition in onBindViewHolder method and notify with a Callback.

```<code>@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewholder, int position) {

    if(position+1==images.size()){
        paginationCallBack.loadNextPage();  // Callback
    }

}
</code>```

Step 2: Call NEXT Page

getImages(++pageNum)  // YOUR REST method which page number

```<code>@Override
public void loadNextPage(){
    getImages(++pageNumber) // REST call with next Page
}
</code>```

Step 3 Add the result in old list and notify datasetChanged

```<code>public void getImages(int pageNum){

      List<Images> newResults = //RESTCALL
      imageList.addAll(newResults);
      adapter.updateDataSet(imageList)

}
</code>```

Where is updateDataSet(imageList) method?

Write this method inside RecyclerView.Adapter

```<code> public void updateDataSet(List<GalleryMedia> newImages){

    if(newImages!=null){
        images = newImages;
    }

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

Full Code

RecyclerView Pagination

Result:

Body:
Recyclerview comes with its own scroll listener which has the following methods :

void onScrollStateChanged(RecyclerView recyclerView, int newState)

Callback method to be invoked when RecyclerView's scroll state changes.

void onScrolled(RecyclerView recyclerView, int dx, int dy)

Callback method to be invoked when the RecyclerView has been scrolled.

Is there any way to trigger loader to load more data when scroll reaches end of the list?

I have implemented this way:

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    GenerItem generItem=generItems.get(i);
    Log.d("TAG","position "+i);
    if(i==generItems.size()-1)
    ((GenerSearchActivity)mContext).onScroll(i);
    viewHolder.bindValues(generItem);
}

Here onScroll() in Activity, will trigger the loader to load more data. What is the best way please suggest.

Body:
Make Next Call at the end of scroll

There are essentially 3 steps.

Notify when the list is scrolled

Make REST call (for NEXT page)

Add the result in the old list + Notify DataSet change

CALLBACK

But first, we need a Callback which would work as a bridge between RecyclerView.Adapter and Activity

public interface PaginationCallBack{
     public void oadNextPage();
}

Implement this callback in Your Activity

class YourActivity extends AppCompatActivity implements PaginationCallBack{

     int pageNum = 1;

     @Override
     public void loadNextPage(){
           // Your implementation
     }
}

Initialize Callback in RecyclerView.Adapter

class YourAdapter extends RecyclerView.Adapter{

     private PaginationCallBack paginationCallBack;

     public YourAdapter(PaginationCallBack paginationCallBack) {
        this.paginationCallBack = paginationCallBack;
     }

}

STEP 1
Add a condition in onBindViewHolder method and notify with a Callback.

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewholder, int position) {

    if(position+1==images.size()){
        paginationCallBack.loadNextPage();  // Callback
    }

}

Step 2: Call NEXT Page

getImages(++pageNum)  // YOUR REST method which page number

@Override
public void loadNextPage(){
    getImages(++pageNumber) // REST call with next Page
}

Step 3 Add the result in old list and notify datasetChanged

public void getImages(int pageNum){

      List<Images> newResults = //RESTCALL
      imageList.addAll(newResults);
      adapter.updateDataSet(imageList)

}

Where is updateDataSet(imageList) method?

Write this method inside RecyclerView.Adapter

 public void updateDataSet(List<GalleryMedia> newImages){

    if(newImages!=null){
        images = newImages;
    }

    notifyDataSetChanged();
}

Full Code

RecyclerView Pagination

Result:


问:
How to read in parallel multiple chunks from the same connection in R?
I have a .bz2 file and I want to read it and do some processing. The file cannot be loaded in memory. I want to do some computations on the chunks I read and I they can be performed independently of one another and therefore I thought I would try to do it in parallel.
I tried the following:

```<code>library(parallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)
con = file("myfile.bz2", "r")

parLapply(cl, con,
          function(x)
            print(head(read.csv(x, nrows = 100, stringsAsFactors = F, header = F, colClasses = "character", fill = F), 16)))
## Doesn't work Error in checkForRemoteErrors(val) :
  one node produced an error: 'file' must be a character string or connection

parLapply(cl, list(con, con, con),
          function(x)
            print(head(read.csv(x, nrows = 100, stringsAsFactors = F, header = F, colClasses = "character", fill = F), 16)))
## Doesn't work Error in checkForRemoteErrors(val) :
  3 nodes produced errors; first error: invalid connection
</code>```

Can this somehow work?
Also any other recommendation as to how to go about it would be really helpful, as I am new to the world of parallel processing.

答:
You cannot and must not use connections from one R process in another R process - connections are unique to the R session where they are created.

Internally, they are just integer indices and there is very little in R that protects you from mistakenly trying to use them in other R processes.  If your want to know for details, see https://github.com/HenrikBengtsson/Wishlist-for-R/issues/81.

FWIW, if you use the future framework for parallelization and set R option future.globals.onReference to "error", then it protects you against this mistake (https://cran.r-project.org/web/packages/future/vignettes/future-4-non-exportable-objects.html).  For example,

library(future.apply)
options(future.globals.onReference = "error")

library(parallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)

cat("Hello world\n", file = bzfile("myfile.bz2", open="wb"))
con <- file("myfile.bz2", "r")

y <- future_lapply(list(con, con, con), FUN = function(x) {
  data <- read.csv(x, nrows = 100, stringsAsFactors = FALSE, header = FALSE, colClasses = "character", fill = FALSE)
  print(head(data), 16)
})
Error: Detected a non-exportable reference ('externalptr') in one of the globals (<unknown>) used in the future expression
```

Body:
I have a .bz2 file and I want to read it and do some processing. The file cannot be loaded in memory. I want to do some computations on the chunks I read and I they can be performed independently of one another and therefore I thought I would try to do it in parallel.
I tried the following:

library(parallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)
con = file("myfile.bz2", "r")

parLapply(cl, con,
          function(x)
            print(head(read.csv(x, nrows = 100, stringsAsFactors = F, header = F, colClasses = "character", fill = F), 16)))
## Doesn't work Error in checkForRemoteErrors(val) :
  one node produced an error: 'file' must be a character string or connection

parLapply(cl, list(con, con, con),
          function(x)
            print(head(read.csv(x, nrows = 100, stringsAsFactors = F, header = F, colClasses = "character", fill = F), 16)))
## Doesn't work Error in checkForRemoteErrors(val) :
  3 nodes produced errors; first error: invalid connection

Can this somehow work?
Also any other recommendation as to how to go about it would be really helpful, as I am new to the world of parallel processing.


问:
How to see the dataframe in the console (equivalent of .show() for structured streaming)?
I'm trying to see what's coming in as my DataFrame..

here is the spark code

```<code>from pyspark.sql import SparkSession
import pyspark.sql.functions as psf
import logging
import time

spark = SparkSession \
    .builder \
    .appName("Console Example") \
    .getOrCreate()

logging.info("started to listen to the host..")

lines = spark \
    .readStream \
    .format("socket") \
    .option("host", "127.0.0.1") \
    .option("port", 9999) \
    .load()

data = lines.selectExpr("CAST(value AS STRING)")
query1 = data.writeStream.format("console").start()
time.sleep(10)
query1.awaitTermination()
</code>```

I am getting the progress reports but obviously the input rows are 0 for each trigger..

```<code>2019-08-19 23:45:45 INFO  MicroBatchExecution:54 - Streaming query made progress: {
  "id" : "a4b26eaf-1032-4083-9e42-a9f2f0426eb7",
  "runId" : "35c2b82a-191d-4998-9c98-17b24f5e3e9d",
  "name" : null,
  "timestamp" : "2019-08-20T06:45:45.458Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "inputRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 0
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: 127.0.0.1, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "inputRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "org.apache.spark.sql.execution.streaming.ConsoleSinkProvider@5f3e6f3"
  }
}
</code>```

My TCP server is spitting some stuff out and I can see it in the console too - but i just want to make sure if my spark job is receiving anything by printing out but difficult to do so.

This is my TCP server code.

```<code>import socket
import sys
import csv
import time

port = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', port))
server_socket.listen(5)
connection_socket, addr = server_socket.accept()

file_path = "/Users/Downloads/youtube-new/USvideos.csv"
row_count = sum(1 for row in file_path)

with open(file_path, "r") as f:
    reader = csv.reader(f, delimiter="\t")
    while True:
        for i, line in enumerate(reader):
            try:
                print(line)
                data = line[0].encode('utf-8')
                connection_socket.send(data)
                time.sleep(2)
                if (row_count == i-1):
                    break
            except IndexError:
                print("Index error")
                server_socket.close()

server_socket.close()
</code>```

I can see the line is getting printed out so I can at least say that this has accepted connection at localhost:9999 which is the host & port I'm using for spark job as well.

this is one of the data..

```<code>['8mhTWqWlQzU,17.15.11,"Wearing Online Dollar Store Makeup For A Week","Safiya Nygaard",22,2017-11-11T01:19:33.000Z,"wearing online dollar store makeup for a week"|"online dollar store makeup"|"dollar store makeup"|"daiso"|"shopmissa makeup"|"shopmissa haul"|"dollar store makeup haul"|"dollar store"|"shopmissa"|"foundation"|"concealer"|"eye primer"|"eyebrow pencil"|"eyeliner"|"bronzer"|"contour"|"face powder"|"lipstick"|"$1"|"$1 makeup"|"safiya makeup"|"safiya dollar store"|"safiya nygaard"|"safiya"|"safiya and tyler",2922523,119348,1161,6736,https://i.ytimg.com/vi/8mhTWqWlQzU/default.jpg,False,False,False,"I found this online dollar store called ShopMissA that sells all their makeup products for $1 and decided I had to try it out! So I replaced my entire everyday makeup routine with $1 makeup products, including foundation, concealer, eye primer, eyebrow pencil, eyeliner, bronzer, contour, face powder, and lipstick. What do you think? Would you try this?\\n\\nThis video is NOT sponsored!\\n\\nSafiya\'s Nextbeat: https://nextbeat.co/u/safiya\\nIG: https://www.instagram.com/safiyany/\\nTwitter: https://twitter.com/safiyajn\\nFacebook: https://www.facebook.com/safnygaard/\\n\\nAssistant Editor: Claire Wiley\\n\\nMUSIC\\nMind The Gap\\nvia Audio Network\\n\\nSFX\\nvia AudioBlocks"']
</code>```

Everything in the bracket (notice I'm actually sending data[0])

答:
```<code>from pyspark.sql import SparkSession
import pyspark.sql.functions as psf
import logging
import time

spark = SparkSession \
    .builder \
    .appName("Console Example") \
    .getOrCreate()

logging.info("started to listen to the host..")

lines = spark \
    .readStream \
    .format("socket") \
    .option("host", "127.0.0.1") \
    .option("port", 9999) \
    .load()

data = lines.selectExpr("CAST(value AS STRING)")
query1 = data.writeStream.queryName("counting").format("memory").outputMode("append").start()
for x in range(5):
  spark.sql("select * from counting").show()
  time.sleep(10)
</code>```

Try this, it will show you data just as the method show() does in spark Sql. It will show you 5 sets of data, as we are looping five times.

Body:
I'm trying to see what's coming in as my DataFrame..

here is the spark code

from pyspark.sql import SparkSession
import pyspark.sql.functions as psf
import logging
import time

spark = SparkSession \
    .builder \
    .appName("Console Example") \
    .getOrCreate()

logging.info("started to listen to the host..")

lines = spark \
    .readStream \
    .format("socket") \
    .option("host", "127.0.0.1") \
    .option("port", 9999) \
    .load()

data = lines.selectExpr("CAST(value AS STRING)")
query1 = data.writeStream.format("console").start()
time.sleep(10)
query1.awaitTermination()

I am getting the progress reports but obviously the input rows are 0 for each trigger..

2019-08-19 23:45:45 INFO  MicroBatchExecution:54 - Streaming query made progress: {
  "id" : "a4b26eaf-1032-4083-9e42-a9f2f0426eb7",
  "runId" : "35c2b82a-191d-4998-9c98-17b24f5e3e9d",
  "name" : null,
  "timestamp" : "2019-08-20T06:45:45.458Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "inputRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 0
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: 127.0.0.1, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "inputRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "org.apache.spark.sql.execution.streaming.ConsoleSinkProvider@5f3e6f3"
  }
}

My TCP server is spitting some stuff out and I can see it in the console too - but i just want to make sure if my spark job is receiving anything by printing out but difficult to do so.

This is my TCP server code.

import socket
import sys
import csv
import time

port = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', port))
server_socket.listen(5)
connection_socket, addr = server_socket.accept()

file_path = "/Users/Downloads/youtube-new/USvideos.csv"
row_count = sum(1 for row in file_path)

with open(file_path, "r") as f:
    reader = csv.reader(f, delimiter="\t")
    while True:
        for i, line in enumerate(reader):
            try:
                print(line)
                data = line[0].encode('utf-8')
                connection_socket.send(data)
                time.sleep(2)
                if (row_count == i-1):
                    break
            except IndexError:
                print("Index error")
                server_socket.close()

server_socket.close()

I can see the line is getting printed out so I can at least say that this has accepted connection at localhost:9999 which is the host & port I'm using for spark job as well.

this is one of the data..

['8mhTWqWlQzU,17.15.11,"Wearing Online Dollar Store Makeup For A Week","Safiya Nygaard",22,2017-11-11T01:19:33.000Z,"wearing online dollar store makeup for a week"|"online dollar store makeup"|"dollar store makeup"|"daiso"|"shopmissa makeup"|"shopmissa haul"|"dollar store makeup haul"|"dollar store"|"shopmissa"|"foundation"|"concealer"|"eye primer"|"eyebrow pencil"|"eyeliner"|"bronzer"|"contour"|"face powder"|"lipstick"|"$1"|"$1 makeup"|"safiya makeup"|"safiya dollar store"|"safiya nygaard"|"safiya"|"safiya and tyler",2922523,119348,1161,6736,https://i.ytimg.com/vi/8mhTWqWlQzU/default.jpg,False,False,False,"I found this online dollar store called ShopMissA that sells all their makeup products for $1 and decided I had to try it out! So I replaced my entire everyday makeup routine with $1 makeup products, including foundation, concealer, eye primer, eyebrow pencil, eyeliner, bronzer, contour, face powder, and lipstick. What do you think? Would you try this?\\n\\nThis video is NOT sponsored!\\n\\nSafiya\'s Nextbeat: https://nextbeat.co/u/safiya\\nIG: https://www.instagram.com/safiyany/\\nTwitter: https://twitter.com/safiyajn\\nFacebook: https://www.facebook.com/safnygaard/\\n\\nAssistant Editor: Claire Wiley\\n\\nMUSIC\\nMind The Gap\\nvia Audio Network\\n\\nSFX\\nvia AudioBlocks"']

Everything in the bracket (notice I'm actually sending data[0])

Body:
from pyspark.sql import SparkSession
import pyspark.sql.functions as psf
import logging
import time

spark = SparkSession \
    .builder \
    .appName("Console Example") \
    .getOrCreate()

logging.info("started to listen to the host..")

lines = spark \
    .readStream \
    .format("socket") \
    .option("host", "127.0.0.1") \
    .option("port", 9999) \
    .load()

data = lines.selectExpr("CAST(value AS STRING)")
query1 = data.writeStream.queryName("counting").format("memory").outputMode("append").start()
for x in range(5):
  spark.sql("select * from counting").show()
  time.sleep(10)

Try this, it will show you data just as the method show() does in spark Sql. It will show you 5 sets of data, as we are looping five times.


问:
nx.node_connectivity and nx.minimum_node_cut arent' matching up
This returns 1:

```<code>nx.node_connectivity(G_sc,97,38)
</code>```

but,
nx.minimum_node_cut(G_sc, 97, 38) returns an empty list. Why?

答:
By checking on a sample graph, a possible explanation is likely to be as shown here. Take for instance:

```<code>G = nx.from_edgelist([[1,4], [1,3], [4,3], [4,5], [1,2], [2,5]])
nx.draw(G, with_labels=True, node_color='lightgreen')
</code>```

If we take say, nodes 3 and 5:

```<code>nx.node_connectivity(G,3,5)
# 2
nx.minimum_node_cut(G, 3,5)
# {2, 4}
</code>```

Everything seems as expected, since as mentioned in the docs in nx.minimum_node_cut, this is a set of nodes of minimum cardinality that disconnects G.

Though if we try on 4 and 5 for instance:

```<code>nx.node_connectivity(G,4,5)
# 2
nx.minimum_node_cut(G, 4,5)
#{}
</code>```

We get an empty set as a result of nx.minimum_node_cut, even though it is clear that we'd need to remove two paths to disconnect them, as specified by nx.node_connectivity.

The explanation seems to be that in the case where both source and target nodes specified in nx.minimum_node_cut are adjacent, the returned subset does not consider any other paths, since the solution excludes the trivial answer of removing the edge connecting both adjacent nodes.
So it is likely that this is what is happening in your actual case.

Body:
This returns 1:

nx.node_connectivity(G_sc,97,38)

but,
nx.minimum_node_cut(G_sc, 97, 38) returns an empty list. Why?

Body:
By checking on a sample graph, a possible explanation is likely to be as shown here. Take for instance:

G = nx.from_edgelist([[1,4], [1,3], [4,3], [4,5], [1,2], [2,5]])
nx.draw(G, with_labels=True, node_color='lightgreen')

If we take say, nodes 3 and 5:

nx.node_connectivity(G,3,5)
# 2
nx.minimum_node_cut(G, 3,5)
# {2, 4}

Everything seems as expected, since as mentioned in the docs in nx.minimum_node_cut, this is a set of nodes of minimum cardinality that disconnects G.

Though if we try on 4 and 5 for instance:

nx.node_connectivity(G,4,5)
# 2
nx.minimum_node_cut(G, 4,5)
#{}

We get an empty set as a result of nx.minimum_node_cut, even though it is clear that we'd need to remove two paths to disconnect them, as specified by nx.node_connectivity.

The explanation seems to be that in the case where both source and target nodes specified in nx.minimum_node_cut are adjacent, the returned subset does not consider any other paths, since the solution excludes the trivial answer of removing the edge connecting both adjacent nodes.
So it is likely that this is what is happening in your actual case.


问:
Error: reCAPTCHA placeholder element must be an element or
I am using firebase phone auth with invisible ReCaptcha. I have set captcha property size to invisible and also used id of HTML button.

But every time user enters mobile number I am getting the following error

Error: reCAPTCHA placeholder element must be an element or id

EDIT This error is occurring when I hide the sign-in-button which has set with ReCaptcha (in my case button with id="send").

Any idea why this is happening?

I am not getting what went wrong.

Thank you in advance
.html

```<code><div>

        <ion-label > Enter your mobile number </ion-label>

        <ion-item>
         +91 |     <ion-input type="tel" [formControl] = "mobile_no" ></ion-input>

        </ion-item>
        <ion-button id="send" [disabled] = "mobile_no.invalid" (click)="send( mobile_no.value)">Continue</ion-button>
      </div>

<ion-button (click) ="verify(otpArray)">Submit</ion-button> // submit otp. otpArray contains otp
</code>```

.ts

```<code>send(mobile_no){

    let mobile = '+91' + mobile_no
    console.log(mobile)

    const appVerifier = new firebase.auth.RecaptchaVerifier('send', {
       'size': 'invisible',
     });

    this.response.linkWithPhoneNumber( mobile, appVerifier).then(data => { // response contains response after Gmail login

      if(data){

        console.log(this.result)
      }
    }).catch(err => {
      console.log(err)
    })

   }

   verify(otp){

    console.log(otp)

    this.code = otp.first + otp.second + otp.third + otp.fourth + otp.fifth + otp.sixth
    console.log(this.code)

     this.result.confirm(this.code).then(result => {
       var user = result.user;
       console.log(result)
     }).catch(function (err) {console.log(err)} )

   }
</code>```

答:
Apparently you are at some point hiding a block with id = "send". But you do it too soon. Transfer id = "send" hiding logic to an explanation</p>

```<code>window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
  'size': 'invisible',
  'callback': (response) => {
    hiddenButtonBlock(); // Here
  }
});
</code>```

Body:
I am using firebase phone auth with invisible ReCaptcha. I have set captcha property size to invisible and also used id of HTML button.

But every time user enters mobile number I am getting the following error

Error: reCAPTCHA placeholder element must be an element or id

EDIT This error is occurring when I hide the sign-in-button which has set with ReCaptcha (in my case button with id="send").

Any idea why this is happening?

I am not getting what went wrong.

Thank you in advance
.html

        <ion-label > Enter your mobile number </ion-label>

        <ion-item>
         +91 |     <ion-input type="tel" [formControl] = "mobile_no" ></ion-input>

        </ion-item>
        <ion-button id="send" [disabled] = "mobile_no.invalid" (click)="send( mobile_no.value)">Continue</ion-button>

<ion-button (click) ="verify(otpArray)">Submit</ion-button> // submit otp. otpArray contains otp

.ts

send(mobile_no){

    let mobile = '+91' + mobile_no
    console.log(mobile)

    const appVerifier = new firebase.auth.RecaptchaVerifier('send', {
       'size': 'invisible',
     });

    this.response.linkWithPhoneNumber( mobile, appVerifier).then(data => { // response contains response after Gmail login

      if(data){

        console.log(this.result)
      }
    }).catch(err => {
      console.log(err)
    })

   }

   verify(otp){

    console.log(otp)

    this.code = otp.first + otp.second + otp.third + otp.fourth + otp.fifth + otp.sixth
    console.log(this.code)

     this.result.confirm(this.code).then(result => {
       var user = result.user;
       console.log(result)
     }).catch(function (err) {console.log(err)} )

   }

Body:
Apparently you are at some point hiding a block with id = "send". But you do it too soon. Transfer id = "send" hiding logic to an explanation

window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
  'size': 'invisible',
  'callback': (response) => {
    hiddenButtonBlock(); // Here
  }
});


问:
How to send 'Application Version' with client side application insights using javascript?
We can send 'application version' property with every insight in c# like in this tutorial by adding a initializer.

```<code>    class AppVersionTelemetryInitializer : Microsoft.ApplicationInsights.Extensibility.ITelemetryInitializer
{
    public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
    {
        telemetry.Context.Component.Version = ApplicationInsightsHelper.ApplicationVersion;
    }
}
</code>```

https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions/

How can I do this with javascript?

答:
If you are using the @microsoft/applicationinsights-web SDK (for client-side Javascript), you can set the application version in this way:

const appInsights = new ApplicationInsights(...);
appInsights.loadAppInsights();  // important, otherwise the `application` object is missing
appInsights.context.application.ver = "YOUR_VERSION_HERE";
```

This way, you'll be able to drill down into metrics by application version in the dashboards.

ContentLicense: CC BY-SA 3.0

Body:
We can send 'application version' property with every insight in c# like in this tutorial by adding a initializer.

    class AppVersionTelemetryInitializer : Microsoft.ApplicationInsights.Extensibility.ITelemetryInitializer
{
    public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
    {
        telemetry.Context.Component.Version = ApplicationInsightsHelper.ApplicationVersion;
    }
}

https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions/

How can I do this with javascript?

Body:
If you are using the @microsoft/applicationinsights-web SDK (for client-side Javascript), you can set the application version in this way:

const appInsights = new ApplicationInsights(...);
appInsights.loadAppInsights();  // important, otherwise the `application` object is missing
appInsights.context.application.ver = "YOUR_VERSION_HERE";

This way, you'll be able to drill down into metrics by application version in the dashboards.


问:
Using jQuery in table to display single cell contents of selected row outside of table
This is essentially my table inside of a loop:

```<code><table id="tblMyTable">
  <tr>
     <td><%= attachment.Name %></td>
     <td><%= attachment.Description %></td>
     <td>
        <a id="clickPreview" href="#">Preview</a>
        <div id="divAttachmentContents" style="display:none;"> <%= attachment.ContentsAsHtml %>
        </div>
     </td>
   </tr>
</table>
</code>```

From this I get multiple rows with data.  I want to have a preview button on the end of the row, the last column, that will 'preview' the contents in a div further down the page.
I assumed I should render out the content to a hidden cell to make it appear quickly.

I need to know how to tell jQuery the row I'm on - and to fetch the text of the last cell.

The gist of what I need is:

```<code>    $('#clickPreview').click(function () {
        var newContent = $('#divAttachmentContents').text();
        $('#divAttachmentPreview').html(newContent);
    });
</code>```

But that only works on the first row.
I may have to do something like

```<code><div id="<%= "divAttachmentContents_" + attachment.Id %>" style="display:none;"> <%= attachment.ContentsAsHtml %> </div>
</code>```

But I'm not sure.  This may be similar to This question Any assistance would be greatly appreciated!

答:
You can assign a class for the anchor. That will make the job easier. For e.g.

```<code>$('.clickPreviewClass').click(function () {
    var newContent =$(this).next("div").text();
    $('#divAttachmentPreview').html(newContent);
});
</code>```

assuming clickPreviewClass is the name of the class you give your anchor.

Body:
This is essentially my table inside of a loop:

     <%= attachment.Name %>
     <%= attachment.Description %>

        Preview

 <%= attachment.ContentsAsHtml %>

From this I get multiple rows with data.  I want to have a preview button on the end of the row, the last column, that will 'preview' the contents in a div further down the page.
I assumed I should render out the content to a hidden cell to make it appear quickly.

I need to know how to tell jQuery the row I'm on - and to fetch the text of the last cell.

The gist of what I need is:

    $('#clickPreview').click(function () {
        var newContent = $('#divAttachmentContents').text();
        $('#divAttachmentPreview').html(newContent);
    });

But that only works on the first row.
I may have to do something like

<div id="<%= "divAttachmentContents_" + attachment.Id %>" style="display:none;"> <%= attachment.ContentsAsHtml %>

But I'm not sure.  This may be similar to This question Any assistance would be greatly appreciated!

Body:
You can assign a class for the anchor. That will make the job easier. For e.g.

$('.clickPreviewClass').click(function () {
    var newContent =$(this).next("div").text();
    $('#divAttachmentPreview').html(newContent);
});

assuming clickPreviewClass is the name of the class you give your anchor.


问:
How to detect the input device if mouse and touchpad are both enabled
I already have a WH_MOUSE_LL hook in my application, but need a different behavior for Mouse and Touchpad.

I know about Raw Input API, but have no idea how to use it with hooks :(

Any suggestions?

答: You could use Raw Input to register for devices that you are interested to receive input from if you want to receive input for only the Touchpad,  the Mouse, or both. You just need to register to receive input from the devices of your interest using the RegisterRawInputDevices function. this Microsoft docs example explains how to do this for a mouse and keyboard. Listening for Touchpad input would require a similar approach. you would use page 0x0D and usage 0x05. As for using this API with hooks, the AbsoluteTouchEx repository could provide some guidance on how to do this.</p>

ContentLicense: CC BY-SA 2.5


问:
"Value of ContainerControlledLifetimeManager can only be set once" when using an open-generic singleton registration
I'm using the Unity.Container NuGet package 5.11 and I want to register an open-generic type such that each concrete type is a singleton.

Background: I'm working in an old-school ASP.NET WebForms application and I've made a crude reimplementation of Microsoft.Extensions.Logging like so:

```<code>// `ILogger` is implemented elsewhere. Specifically I wrote an implementation using Serilog.
public interface ILogger
{
    void Log( LogLevel level, String messageTemplate, params Object[] args );
}

// Unlike `ILogger`, this `ILogger<TSourceContext>` is not implemented by the code elsewhere (that uses Serilog, described above).
// Instead, it's only implemented by the internal class below:
public interface ILogger<TSourceContext> : ILogger
{
}

internal class LoggerWithSourceContext<TSourceContext> : ILogger<TSourceContext>
{
    private readonly ILogger realLogger;

    internal LoggerWithSourceContext( ILoggerFactory factory )
    {
        if( factory == null ) throw new ArgumentNullException(nameof(factory));
        this.realLogger = factory.CreateLogger( sourceContext: typeof(TSourceContext).FullName );
    }

    public void Log( LogLevel level, String messageTemplate, params Object[] args )
    {
        this.realLogger.Log( level, messageTemplate, args );
    }
}

// This is implemented elsewhere in my Serilog code.
public interface ILoggerFactory
{
    ILogger CreateLogger( String sourceContext );
}
</code>```

This is registered in my root Unity container like so:

```<code>IUnityContainer rootContainer = ...
rootContainer
    .RegisterSingleton<ILoggerFactory,MySerilogLoggerFactory>()
    .RegisterSingleton( from: typeof(ILogger<>), to: typeof(LoggerWithSourceContext<>);
</code>```

When this is used, the first time an ILogger<T> is resolved it works fine - however the second time an ILogger<T> is resolved it fails with this error:

InvalidOperationException

  ContainerControlledLifetimeManager can only be set once

I was able to work-around it by changing the registration from a Singleton to a Transient registration using RegisterType, but I'd like it to use a Singleton registration to mitigate the risks of a memory or resource leak:

```<code>IUnityContainer rootContainer = ...
rootContainer
    .RegisterSingleton<ILoggerFactory,MySerilogLoggerFactory>()
    .RegisterType( from: typeof(ILogger<>), to: typeof(LoggerWithSourceContext<>);
</code>```

Full stack trace:

```<code>ContainerControlledLifetimeManager can only be set once
-2146233079
System.InvalidOperationException
   at Unity.Lifetime.ContainerControlledLifetimeManager.<>c.<SetValue>b__7_0(Object o, ILifetimeContainer c) in C:\projects\unity\Abstractions\src\Lifetime\Managers\ContainerControlledLifetimeManager.cs:line 70
   at Unity.Lifetime.ContainerControlledLifetimeManager.SetValue(Object newValue, ILifetimeContainer container) in C:\projects\unity\Abstractions\src\Lifetime\Managers\ContainerControlledLifetimeManager.cs:line 70
   at Unity.Strategies.LifetimeStrategy.PostBuildUp(BuilderContext& context) in C:\projects\unity\Container\src\Strategies\LifetimeStrategy.cs:line 86
   at Unity.UnityContainer.<>c.<.ctor>b__41_3(BuilderStrategy[] chain, BuilderContext& context) in C:\projects\unity\Container\src\UnityContainer.Resolution.cs:line 431
   at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration) in C:\projects\unity\Container\src\Builder\Context\BuilderContext.cs:line 177
   at Unity.Builder.BuilderContext.Resolve(Type type, String name) in C:\projects\unity\Container\src\Builder\Context\BuilderContext.cs:line 67
   at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value) in C:\projects\unity\Container\src\Builder\Context\BuilderContext.cs:line 217
   at Unity.Processors.ConstructorProcessor.<>c__DisplayClass16_0.<GetResolverDelegate>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Constructor\ConstructorResolution.cs:line 77
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Abstracts\MemberProcessor.cs:line 162
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Abstracts\MemberProcessor.cs:line 162
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Abstracts\MemberProcessor.cs:line 162
   at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context) in C:\projects\unity\Container\src\Strategies\BuildPlanStrategy.cs:line 88
   at Unity.UnityContainer.<>c.<.ctor>b__41_2(BuilderContext& context) in C:\projects\unity\Container\src\UnityContainer.Resolution.cs:line 363
   at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides) in C:\projects\unity\Container\src\UnityContainer.IUnityContainer.cs:line 244
</code>```

答: Now in latest unity version 5.11.7 this problem fixed</p>

Body:
I'm using the Unity.Container NuGet package 5.11 and I want to register an open-generic type such that each concrete type is a singleton.

Background: I'm working in an old-school ASP.NET WebForms application and I've made a crude reimplementation of Microsoft.Extensions.Logging like so:

// `ILogger` is implemented elsewhere. Specifically I wrote an implementation using Serilog.
public interface ILogger
{
    void Log( LogLevel level, String messageTemplate, params Object[] args );
}

// Unlike `ILogger`, this `ILogger<TSourceContext>` is not implemented by the code elsewhere (that uses Serilog, described above).
// Instead, it's only implemented by the internal class below:
public interface ILogger<TSourceContext> : ILogger
{
}

internal class LoggerWithSourceContext<TSourceContext> : ILogger<TSourceContext>
{
    private readonly ILogger realLogger;

    internal LoggerWithSourceContext( ILoggerFactory factory )
    {
        if( factory == null ) throw new ArgumentNullException(nameof(factory));
        this.realLogger = factory.CreateLogger( sourceContext: typeof(TSourceContext).FullName );
    }

    public void Log( LogLevel level, String messageTemplate, params Object[] args )
    {
        this.realLogger.Log( level, messageTemplate, args );
    }
}

// This is implemented elsewhere in my Serilog code.
public interface ILoggerFactory
{
    ILogger CreateLogger( String sourceContext );
}

This is registered in my root Unity container like so:

IUnityContainer rootContainer = ...
rootContainer
    .RegisterSingleton<ILoggerFactory,MySerilogLoggerFactory>()
    .RegisterSingleton( from: typeof(ILogger<>), to: typeof(LoggerWithSourceContext<>);

When this is used, the first time an ILogger<T> is resolved it works fine - however the second time an ILogger<T> is resolved it fails with this error:

InvalidOperationException

  ContainerControlledLifetimeManager can only be set once

I was able to work-around it by changing the registration from a Singleton to a Transient registration using RegisterType, but I'd like it to use a Singleton registration to mitigate the risks of a memory or resource leak:

IUnityContainer rootContainer = ...
rootContainer
    .RegisterSingleton<ILoggerFactory,MySerilogLoggerFactory>()
    .RegisterType( from: typeof(ILogger<>), to: typeof(LoggerWithSourceContext<>);

Full stack trace:

ContainerControlledLifetimeManager can only be set once
-2146233079
System.InvalidOperationException
   at Unity.Lifetime.ContainerControlledLifetimeManager.<>c.<SetValue>b__7_0(Object o, ILifetimeContainer c) in C:\projects\unity\Abstractions\src\Lifetime\Managers\ContainerControlledLifetimeManager.cs:line 70
   at Unity.Lifetime.ContainerControlledLifetimeManager.SetValue(Object newValue, ILifetimeContainer container) in C:\projects\unity\Abstractions\src\Lifetime\Managers\ContainerControlledLifetimeManager.cs:line 70
   at Unity.Strategies.LifetimeStrategy.PostBuildUp(BuilderContext& context) in C:\projects\unity\Container\src\Strategies\LifetimeStrategy.cs:line 86
   at Unity.UnityContainer.<>c.<.ctor>b__41_3(BuilderStrategy[] chain, BuilderContext& context) in C:\projects\unity\Container\src\UnityContainer.Resolution.cs:line 431
   at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration) in C:\projects\unity\Container\src\Builder\Context\BuilderContext.cs:line 177
   at Unity.Builder.BuilderContext.Resolve(Type type, String name) in C:\projects\unity\Container\src\Builder\Context\BuilderContext.cs:line 67
   at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value) in C:\projects\unity\Container\src\Builder\Context\BuilderContext.cs:line 217
   at Unity.Processors.ConstructorProcessor.<>c__DisplayClass16_0.<GetResolverDelegate>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Constructor\ConstructorResolution.cs:line 77
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Abstracts\MemberProcessor.cs:line 162
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Abstracts\MemberProcessor.cs:line 162
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c) in C:\projects\unity\Container\src\Processors\Abstracts\MemberProcessor.cs:line 162
   at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context) in C:\projects\unity\Container\src\Strategies\BuildPlanStrategy.cs:line 88
   at Unity.UnityContainer.<>c.<.ctor>b__41_2(BuilderContext& context) in C:\projects\unity\Container\src\UnityContainer.Resolution.cs:line 363
   at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides) in C:\projects\unity\Container\src\UnityContainer.IUnityContainer.cs:line 244


问:
keras :model.predict returns array with the wrong shape
I am having issue with the shape of the output of model.predict.

Lets condiser the following simple dummy model:

```<code>import numpy as np
import pandas as pd
import tensorflow as tf
import string
from tensorflow.keras import layers

###Creating pseudo data
a = pd.DataFrame(np.random.randn(1000, 10), columns = [i for i in string.ascii_lowercase[:10]])

### Splitting data between train and test set
train = a.sample(frac=0.75, random_state=0)
test = a.drop(train.index)

### Creating features columns
f = []
for c in a.columns:
    if c == 'j':
        continue
    x = tf.feature_column.numeric_column(c)
    f.append(x)

l = layers.DenseFeatures(f)

### Creating model
model = tf.keras.models.Sequential()
model.add(l)
model.add(tf.keras.layers.Dense(
    units = 64,
    activation = 'relu',
    name = 'hidden1'
    )
)
model.add(tf.keras.layers.Dense(
    units = 128,
    activation = 'relu',
    name = 'hidden2'
    )
)

### Prepping training data for input in the model
features = {name : np.array(value) for name, value in train.items()}
label = np.array(features.pop('j'))

lr = 0.001
batch_size = 40
epochs = 40

model.compile(optimizer = tf.keras.optimizers.RMSprop(lr = lr),
    loss = 'mean_squared_error',
    metrics = [tf.keras.metrics.MeanSquaredError()])

model.fit(x=features, y=label, batch_size = batch_size, epochs = epochs, shuffle = True)

features_predict = {name : np.array(value) for name, value in test.items()}
label_predict = np.array(features_predict.pop('j'))

p = model.predict(x=features_predict)
</code>```

now if I inspect p:

```<code>p.shape
</code>```

it returns (250, 128) (where obviously i would expect to predict the j value and be of shape (250,1)

What am I doing wrong ?

答: The last layer of your model is a Dense layer with 128 units. It is supposed to return a tensor with dimensions [batch_size, 128]. So everything is as expected. You should change the number of units to 1 if you want to have an output with a single value per sample instead.</p>

Body:
I am having issue with the shape of the output of model.predict.

Lets condiser the following simple dummy model:

import numpy as np
import pandas as pd
import tensorflow as tf
import string
from tensorflow.keras import layers

###Creating pseudo data
a = pd.DataFrame(np.random.randn(1000, 10), columns = [i for i in string.ascii_lowercase[:10]])

### Splitting data between train and test set
train = a.sample(frac=0.75, random_state=0)
test = a.drop(train.index)

### Creating features columns
f = []
for c in a.columns:
    if c == 'j':
        continue
    x = tf.feature_column.numeric_column(c)
    f.append(x)

l = layers.DenseFeatures(f)

### Creating model
model = tf.keras.models.Sequential()
model.add(l)
model.add(tf.keras.layers.Dense(
    units = 64,
    activation = 'relu',
    name = 'hidden1'
    )
)
model.add(tf.keras.layers.Dense(
    units = 128,
    activation = 'relu',
    name = 'hidden2'
    )
)

### Prepping training data for input in the model
features = {name : np.array(value) for name, value in train.items()}
label = np.array(features.pop('j'))

lr = 0.001
batch_size = 40
epochs = 40

model.compile(optimizer = tf.keras.optimizers.RMSprop(lr = lr),
    loss = 'mean_squared_error',
    metrics = [tf.keras.metrics.MeanSquaredError()])

model.fit(x=features, y=label, batch_size = batch_size, epochs = epochs, shuffle = True)

features_predict = {name : np.array(value) for name, value in test.items()}
label_predict = np.array(features_predict.pop('j'))

p = model.predict(x=features_predict)

now if I inspect p:

p.shape

it returns (250, 128) (where obviously i would expect to predict the j value and be of shape (250,1)

What am I doing wrong ?


问:
Escape single quote URL query parameter in Jersey / Jackson
Long story, I need to protect some legacy code against SQL injection. Prepared statements not an option.

API are first handled by Jersey and the JSON Object deserialisation is Jackon

So, one thing I'd like is to escape all the occurrences of '. So when Jackson / Jersey deserialises the query parameter from the API, anytime it sees a ' it will replace it with a ''  Is this possible?

答:
Have you tried using a custom string deserializer?</p>

```<code>public class CustomStringDeserializer extends StdScalarDeserializer<String> {
    protected CustomStringDeserializer() {
        super(String.class);
    }

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        String originalValue = parser.getValueAsString();
        String escapedValue = null;
        if (originalValue != null) {
            escapedValue = originalValue.replace("'", "''");
        }
        return escapedValue;
    }
}
</code>```

Body:
Have you tried using a custom string deserializer?

public class CustomStringDeserializer extends StdScalarDeserializer<String> {
    protected CustomStringDeserializer() {
        super(String.class);
    }

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        String originalValue = parser.getValueAsString();
        String escapedValue = null;
        if (originalValue != null) {
            escapedValue = originalValue.replace("'", "''");
        }
        return escapedValue;
    }
}


问:
Passing data as JSON from PHP to Python
Php code for running python script with json data:

```<code>$output = shell_exec("python php_test.py " . base64_encode(json_encode($process_data)) . " 2>&1");
</code>```

Python code for decoding json:

```<code>jdata = json.loads(base64.b64decode(sys.argv[1]))
</code>```

This is how $process_data looks like:

```<code>array (size=15)
  0 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik amaçlarına giriş", "en":"Introduction to Security Goals."}' (length=78)
  1 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografinin Matematiği.", "en":"Mathematics of Cryptography."}' (length=73)
  2 =>
    array (size=1)
      'konu' => string '{"tr":"Geleneksel Simetrik Anahtarlı Şifreler.", "en":"Traditional Symmetric Key Ciphers."}' (length=93)
  3 =>
    array (size=1)
      'konu' => string '{"tr":"Cebirsel Yapılar.", "en":"Algebraic Structures."}' (length=57)
  4 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelere Giriş.", "en":"Introduction to Modern Symmetric Key Ciphers."}' (length=108)
  5 =>
    array (size=1)
      'konu' => string '{"tr":"Gelişmiş Şifreleme Standardı.", "en":"Advanced Encryption Standard."}' (length=80)
  6 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelerle Şifreleme.", "en":"Encipherment Using Modern Symmetric-Key Ciphers."}' (length=116)
  7 =>
    array (size=1)
      'konu' => string '{"tr":"Stream Ciphers", "en":"Akan Şifreleme Yöntemleri."}' (length=60)
  8 =>
    array (size=1)
      'konu' => string '{"tr":"Ara Sınav", "en":"Midterm Exam"}' (length=40)
  9 =>
    array (size=1)
      'konu' => string '{"tr":"Doğrusal ve Diferansiyel Kriptanaliz.", "en":"Linear and DifferentialCryptanalysis."}' (length=93)
  10 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografik Özet Fonsiyonları.", "en":"Cryptographic Hash Functions."}' (length=80)
  11 =>
    array (size=1)
      'konu' => string '{"tr":"Asimetrik Kriptoloji", "en":"Asymmetric Cryptography"}' (length=61)
  12 =>
    array (size=1)
      'konu' => string '{"tr":"Protokollar, Tcp/Ip Protokol ve Hizmetlerinde Güvenlik", "en":"Protocols, Security in Tcp/Ip Networks"}' (length=111)
  13 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik Duvarları ve Sanal Özel Ağlar", "en":"Firewall and Virtual Private Networking"}' (length=99)
  14 =>
    array (size=1)
      'konu' => string '{"tr":"Saldırı Tespit Sistemleri", "en":"Intrusion Detection Systems"}' (length=72)
</code>```

I'm getting a decoder error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in
  position 33: character maps to < undefined>

When I remove base64_encode, I get "Expecting ',' delimiter" error instead.

I'm guessing it is caused by the double-quotes. How can I escape them?

答:
Change character encoding for MS windows console to utf-8 by entering the following command

chcp 65001

Now run your script again.

Title: Passing data as JSON from PHP to Python

Body:
Php code for running python script with json data:

$output = shell_exec("python php_test.py " . base64_encode(json_encode($process_data)) . " 2>&1");

Python code for decoding json:

jdata = json.loads(base64.b64decode(sys.argv[1]))

This is how $process_data looks like:

array (size=15)
  0 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik amaçlarına giriş", "en":"Introduction to Security Goals."}' (length=78)
  1 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografinin Matematiği.", "en":"Mathematics of Cryptography."}' (length=73)
  2 =>
    array (size=1)
      'konu' => string '{"tr":"Geleneksel Simetrik Anahtarlı Şifreler.", "en":"Traditional Symmetric Key Ciphers."}' (length=93)
  3 =>
    array (size=1)
      'konu' => string '{"tr":"Cebirsel Yapılar.", "en":"Algebraic Structures."}' (length=57)
  4 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelere Giriş.", "en":"Introduction to Modern Symmetric Key Ciphers."}' (length=108)
  5 =>
    array (size=1)
      'konu' => string '{"tr":"Gelişmiş Şifreleme Standardı.", "en":"Advanced Encryption Standard."}' (length=80)
  6 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelerle Şifreleme.", "en":"Encipherment Using Modern Symmetric-Key Ciphers."}' (length=116)
  7 =>
    array (size=1)
      'konu' => string '{"tr":"Stream Ciphers", "en":"Akan Şifreleme Yöntemleri."}' (length=60)
  8 =>
    array (size=1)
      'konu' => string '{"tr":"Ara Sınav", "en":"Midterm Exam"}' (length=40)
  9 =>
    array (size=1)
      'konu' => string '{"tr":"Doğrusal ve Diferansiyel Kriptanaliz.", "en":"Linear and DifferentialCryptanalysis."}' (length=93)
  10 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografik Özet Fonsiyonları.", "en":"Cryptographic Hash Functions."}' (length=80)
  11 =>
    array (size=1)
      'konu' => string '{"tr":"Asimetrik Kriptoloji", "en":"Asymmetric Cryptography"}' (length=61)
  12 =>
    array (size=1)
      'konu' => string '{"tr":"Protokollar, Tcp/Ip Protokol ve Hizmetlerinde Güvenlik", "en":"Protocols, Security in Tcp/Ip Networks"}' (length=111)
  13 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik Duvarları ve Sanal Özel Ağlar", "en":"Firewall and Virtual Private Networking"}' (length=99)
  14 =>
    array (size=1)
      'konu' => string '{"tr":"Saldırı Tespit Sistemleri", "en":"Intrusion Detection Systems"}' (length=72)

I'm getting a decoder error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in
  position 33: character maps to < undefined>

When I remove base64_encode, I get "Expecting ',' delimiter" error instead.

I'm guessing it is caused by the double-quotes. How can I escape them?


问:
Convert PNG to JP2 loss of quality
I am converting a png file to jp2 format using imagemagick and even though I am configuring it to have quality 100, it still loses quality but only on the transparent gradient background and the borders of my image.

Command used in console:

```<code>magick input_image.png -quality 100 output_image.jp2
</code>```

Below are only part of the input image and the output image where you can clearly see the loss of quality

I haven't found anything on imagemagick that explains this quality loss or what config could fix it.

*I have successfully used a third party site to convert my png to jp2 format and there was no loss of quality.

答:
This works fine for me on IM 7.0.10.16 Q16 Mac OSX Sierra with OpenJPEG 2.3.1. (You need OpenJPEG 2.1 or higher)

```<code>magick img.png -quality 0 img.jp2
</code>```

See https://imagemagick.org/script/jp2.php, but change "magick convert" to just "magick"

Title: Convert PNG to JP2 loss of quality

Body:
I am converting a png file to jp2 format using imagemagick and even though I am configuring it to have quality 100, it still loses quality but only on the transparent gradient background and the borders of my image.

Command used in console:

magick input_image.png -quality 100 output_image.jp2

Below are only part of the input image and the output image where you can clearly see the loss of quality

I haven't found anything on imagemagick that explains this quality loss or what config could fix it.

*I have successfully used a third party site to convert my png to jp2 format and there was no loss of quality.

Body:
This works fine for me on IM 7.0.10.16 Q16 Mac OSX Sierra with OpenJPEG 2.3.1. (You need OpenJPEG 2.1 or higher)

magick img.png -quality 0 img.jp2

See https://imagemagick.org/script/jp2.php, but change "magick convert" to just "magick"


问:
Why won't my setblock command which summons a chest put the items inside I told it too?
So I am making a Minecraft command with /setblock. It is supposed to put a 32K diamond sword in the first slot, and a 32K diamond axe on the second slot. Here is my command (it's ver big):

```<code>setblock ~ ~1 ~ chest{Items:[{id:"diamond_sword",slot:0,Count:1,tag:{Enchantments:[{id:"bane_of_arthropods",lvl:32768},{id:"fire_aspect",lvl:32768},{id:"knockback",lvl:32768},{id:"mending",lvl:32768},{id:"sharpness",lvl:32768},{id:"smite",lvl:32768},{id:"sweeping_edge",lvl:32768},{id:"unbreaking",lvl:32768}]}},{id:"diamond_axe",slot:1,Count:1,tag:{Enchantments:[{id:"bane_of_arthropods",lvl:32768},{id:"efficiency",lvl:32768},{id:"mending",lvl:32768},{id:"sharpness",lvl:32768},{id:"silk_touch",lvl:32768},{id:"smite",lvl:32768},{id:"unbreaking",lvl:32768}]}}]} replace
</code>```

This however, only puts the 32K axe in the first slot, not the 32K sword in the first, and the 32K axe in the second. Please help!

答:
You need a "b" after the slot number.  Try the following:

```<code>setblock ~ ~1 ~ minecraft:chest{Items:[{Slot:0b,id:"minecraft:diamond_sword",Count:1b,tag:{Enchantments:[{lvl:32768,id:"bane_of_arthropods"},{lvl:32768,id:"fire_aspect"},{lvl:32768,id:"knockback"},{lvl:32768,id:"mending"},{lvl:32768,id:"sharpness"},{lvl:32768,id:"smite"},{lvl:32768,id:"sweeping_edge"},{lvl:32768,id:"unbreaking"}]}},{Slot:1b,id:"minecraft:diamond_axe",Count:1b,tag:{Enchantments:[{lvl:32768,id:"bane_of_arthropods"},{lvl:32768,id:"efficiency"},{lvl:32768,id:"mending"},{lvl:32768,id:"sharpness"},{lvl:32768,id:"silk_touch"},{lvl:32768,id:"smite"},{lvl:32768,id:"unbreaking"}]}}]}
</code>```

Also consider posting on gaming.stackexchange.com in the future.

Body:
So I am making a Minecraft command with /setblock. It is supposed to put a 32K diamond sword in the first slot, and a 32K diamond axe on the second slot. Here is my command (it's ver big):

setblock ~ ~1 ~ chest{Items:[{id:"diamond_sword",slot:0,Count:1,tag:{Enchantments:[{id:"bane_of_arthropods",lvl:32768},{id:"fire_aspect",lvl:32768},{id:"knockback",lvl:32768},{id:"mending",lvl:32768},{id:"sharpness",lvl:32768},{id:"smite",lvl:32768},{id:"sweeping_edge",lvl:32768},{id:"unbreaking",lvl:32768}]}},{id:"diamond_axe",slot:1,Count:1,tag:{Enchantments:[{id:"bane_of_arthropods",lvl:32768},{id:"efficiency",lvl:32768},{id:"mending",lvl:32768},{id:"sharpness",lvl:32768},{id:"silk_touch",lvl:32768},{id:"smite",lvl:32768},{id:"unbreaking",lvl:32768}]}}]} replace

This however, only puts the 32K axe in the first slot, not the 32K sword in the first, and the 32K axe in the second. Please help!

Body:
You need a "b" after the slot number.  Try the following:

setblock ~ ~1 ~ minecraft:chest{Items:[{Slot:0b,id:"minecraft:diamond_sword",Count:1b,tag:{Enchantments:[{lvl:32768,id:"bane_of_arthropods"},{lvl:32768,id:"fire_aspect"},{lvl:32768,id:"knockback"},{lvl:32768,id:"mending"},{lvl:32768,id:"sharpness"},{lvl:32768,id:"smite"},{lvl:32768,id:"sweeping_edge"},{lvl:32768,id:"unbreaking"}]}},{Slot:1b,id:"minecraft:diamond_axe",Count:1b,tag:{Enchantments:[{lvl:32768,id:"bane_of_arthropods"},{lvl:32768,id:"efficiency"},{lvl:32768,id:"mending"},{lvl:32768,id:"sharpness"},{lvl:32768,id:"silk_touch"},{lvl:32768,id:"smite"},{lvl:32768,id:"unbreaking"}]}}]}

Also consider posting on gaming.stackexchange.com in the future.


问:
How to get timestamp of last Friday using JavaScript?
I have to get the timestamp of last Friday, but I am not sure how can I get timestamp using weekday. Can someone please help?

What I trying to get is difference between last Friday and Today.

```<code>var now = new Date();
var time = now.getTime();
var fridayTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 13, 30, 00);
var timeDiff = time - fridayTime;
</code>```

I know I have not written the correct code for "fridayTime", but not sure what is the correct code.

答:
```<code>function lastFriday(){
  var date = new Date();
  date.setDate(date.getDate()-date.getDay()-2);
  return date;
}
</code>```

Body:
I have to get the timestamp of last Friday, but I am not sure how can I get timestamp using weekday. Can someone please help?

What I trying to get is difference between last Friday and Today.

var now = new Date();
var time = now.getTime();
var fridayTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 13, 30, 00);
var timeDiff = time - fridayTime;

I know I have not written the correct code for "fridayTime", but not sure what is the correct code.


问:
SQL injection login bypass
I am preparing SQL injection vulnerable page to test skills, here is my code:

```<code><?php
    echo "<center><h1>Login Bypass</h1></center>";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "<center>".$query_string."</center><br/>";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "<center>SUCCESS</center><br/>";
    else echo "<center>ACCESS DENIED</center><br/>";
    echo "<center>".$row['email']."</center><br/>";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />
</head>

<body>
    <center>
    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>
    </center>
</body>

</html>
</code>```

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

```<code>$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
</code>```

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

```<code>SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '
</code>```

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

答: Probably you did not close your C-style comment cleanly, so you have managed a syntax error in your comment.  Use a double-dash -- comment.

Title: SQL injection login bypass

Body:
I am preparing SQL injection vulnerable page to test skills, here is my code:

<?php
    echo "
Login Bypass
";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "".$query_string."
";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "SUCCESS
";
    else echo "ACCESS DENIED
";
    echo "".$row['email']."
";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />

    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?


问:
Copy specific cell to a specific column
Cell E8 and E6 are dependent dropdown lists and they are working.

If I select Tool in cell E8, than cell E6 gives a list of all the tools.

If I select Equipment in cell E8, than cell E6 gives me all the equipment.

The range of this dependent dropdown list comes from columns K to M.

Now I want to add automatically more names do my dependent dropdown list.

If E8 = "Tool" then copy the name that is in cell E6 to last row of column "L"

If E8 = "Equipment" then copy the name that is in cell E6 to last row of column "K"

Same with if E8 = "Car"

答:
```<code>Private Sub Move()
Dim row, column As Integer
Dim ws As Worksheet
Set ws = ActiveSheet

'Determine Column
Select Case ws.Cells(8, 5).Value

    Case "Equipment"
        column = 11
    Case "Tool"
        column = 12
    Case "Car"
        column = 13

End Select

If column = 0 Then
    Exit Sub
End If

'Determine row
row = ws.Cells(Rows.Count, column).End(xlUp).row + 1

'Put value in cell
ws.Cells(row, column).Value = ws.Cells(6, 5).Value

End Sub
</code>```

Title: Copy specific cell to a specific column


问:
Pandas: Conditional Rolling window by another column element?
I have a dataframe with dates, id's and values.

For example:

```<code>date        id        value
2016-08-28   A          1
2016-08-28   B          1
2016-08-29   C          2
2016-09-02   B          0
2016-09-03   A          3
2016-09-06   C          1
2017-01-15   B          2
2017-01-18   C          3
2017-01-18   A          2
</code>```

I want to apply a rolling mean by element, stating one after, so that the result would be like:

```<code>date        id        value    rolling_mean
2016-08-28   A          1           NaN
2016-08-28   B          1           NaN
2016-08-29   C          2           NaN
2016-09-02   B          0           0.5
2016-09-03   A          3           2.0
2016-09-06   C          1           1.5
2017-01-15   B          2           1.0
2017-01-18   C          3           2.0
2017-01-18   A          2           2.5
</code>```

The closest I've come to this was:

```<code>grouped = df.groupby(["id", "value"])
df["rolling_mean"] = grouped["value"].shift(1).rolling(window = 2).mean()
</code>```

But this gives me the wrong values back, as it keeps the order with the remaining elements.

Any ideia?

Thank you in advance,

Body:
I have a dataframe with dates, id's and values.

For example:

date        id        value
2016-08-28   A          1
2016-08-28   B          1
2016-08-29   C          2
2016-09-02   B          0
2016-09-03   A          3
2016-09-06   C          1
2017-01-15   B          2
2017-01-18   C          3
2017-01-18   A          2

I want to apply a rolling mean by element, stating one after, so that the result would be like:

date        id        value    rolling_mean
2016-08-28   A          1           NaN
2016-08-28   B          1           NaN
2016-08-29   C          2           NaN
2016-09-02   B          0           0.5
2016-09-03   A          3           2.0
2016-09-06   C          1           1.5
2017-01-15   B          2           1.0
2017-01-18   C          3           2.0
2017-01-18   A          2           2.5

The closest I've come to this was:

grouped = df.groupby(["id", "value"])
df["rolling_mean"] = grouped["value"].shift(1).rolling(window = 2).mean()

But this gives me the wrong values back, as it keeps the order with the remaining elements.

Any ideia?

Thank you in advance,

Body:
Fix your code with groupby with id

grouped = df.groupby(["id"])
df['rolling_mean']=grouped["value"].rolling(window = 2).mean().reset_index(level=0,drop=True)
df
Out[67]:
        date id  value  rolling_mean
0 2016-08-28  A      1           NaN
1 2016-08-28  B      1           NaN
2 2016-08-29  C      2           NaN
3 2016-09-02  B      0           0.5
4 2016-09-03  A      3           2.0
5 2016-09-06  C      1           1.5
6 2017-01-15  B      2           1.0
7 2017-01-18  C      3           2.0
8 2017-01-18  A      2           2.5


Title: Pandas: Conditional Rolling window by another column element?

Body:
You can just groupby id and use transform:

df['rolling_mean'] = df.groupby('id')['value'].transform(lambda x: x.rolling(2).mean())

Output:

         date id  value  rolling_mean
0  2016-08-28  A      1           NaN
1  2016-08-28  B      1           NaN
2  2016-08-29  C      2           NaN
3  2016-09-02  B      0           0.5
4  2016-09-03  A      3           2.0
5  2016-09-06  C      1           1.5
6  2017-01-15  B      2           1.0
7  2017-01-18  C      3           2.0
8  2017-01-18  A      2           2.5


问:
how to pass named route parameter with ajax
I need to pass route parameter with ajax but I am using named route method in ajax code.

route I want to go
Route

```<code>Route::post('/edit/{id}', 'ArticleController@updateArticle')->name('updateArticle');
</code>```

Ajax

```<code>var id= $("input[name=editId]").val();
$.ajax({
   type:'POST',
   enctype: 'multipart/form-data',
   url:"{{ route('updateArticle',"id") }}",
   data: formdata,
   contentType: false,
   processData: false,
   success:function(data){
        $('.alert-success').html(data.success).fadeIn('slow');
        $('.alert-success').delay(3000).fadeOut('slow');
   }
});
</code>```

I want to use variable id in ajax URL.

答:
I had the same problem, just change your ajax url with this one.</p>

```<code>var id= $("input[name=editId]").val();
$.ajax({
   type:'POST',
   enctype: 'multipart/form-data',
   url:"{{ route('updateArticle') }}" + '/' + id,
   data: formdata,
   contentType: false,
   processData: false,
   success:function(data){
        $('.alert-success').html(data.success).fadeIn('slow');
        $('.alert-success').delay(3000).fadeOut('slow');
   }
});
</code>```

Body:
I need to pass route parameter with ajax but I am using named route method in ajax code.

route I want to go
Route

Route::post('/edit/{id}', 'ArticleController@updateArticle')->name('updateArticle');

Ajax

var id= $("input[name=editId]").val();
$.ajax({
   type:'POST',
   enctype: 'multipart/form-data',
   url:"{{ route('updateArticle',"id") }}",
   data: formdata,
   contentType: false,
   processData: false,
   success:function(data){
        $('.alert-success').html(data.success).fadeIn('slow');
        $('.alert-success').delay(3000).fadeOut('slow');
   }
});

I want to use variable id in ajax URL.

Body:
I had the same problem, just change your ajax url with this one.

var id= $("input[name=editId]").val();
$.ajax({
   type:'POST',
   enctype: 'multipart/form-data',
   url:"{{ route('updateArticle') }}" + '/' + id,
   data: formdata,
   contentType: false,
   processData: false,
   success:function(data){
        $('.alert-success').html(data.success).fadeIn('slow');
        $('.alert-success').delay(3000).fadeOut('slow');
   }
});


问:
How to make this method more generic
i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.

I have this superclass..

```<code>public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}
</code>```

And i have these 2 subclasses

```<code>public class PromotionalItem extends MyItem {

    private String promotion;

    public String setPromotion(String promotion) {
        this.promotion = promotion;
    }

    public void getPromotion() {
        this.promotion = promotion;
    }

}

public class SellableItem extends MyItem {

    private String quantity;

    public String setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void getQuantity() {
        this.quantity = quantity;
    }

}
</code>```

Now i have a method that i want to make generic, i thought something like this could work...

```<code>public void processItem(MyItem item){
    if(item.getClass().isAssignableFrom(PromotionalItem.class)){
        processPromotionalItem((PromotionalItem)item);
    }
    else{
        processSellableItem((SellableItem)item);
    }
}
</code>```

But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?

答:
Use the instanceof keyword

if(item instanceof PromotionalItem){
    processPromotionalItem((PromotionalItem) item);
} else if(item instanceof SellableItem) {
    processSellableItem((SellableItem) item);
}
```

Make sure you use else if not only else because item might be
  something else other than PromotionalItem and SellableItem if you
  cast it to a class from which it wasn't build from, you will get a ClassCastException

instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.

Title: How to make this method more generic

Body:
i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.

I have this superclass..

public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}

And i have these 2 subclasses

public class PromotionalItem extends MyItem {

    private String promotion;

    public String setPromotion(String promotion) {
        this.promotion = promotion;
    }

    public void getPromotion() {
        this.promotion = promotion;
    }

}

public class SellableItem extends MyItem {

    private String quantity;

    public String setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void getQuantity() {
        this.quantity = quantity;
    }

}

Now i have a method that i want to make generic, i thought something like this could work...

public void processItem(MyItem item){
    if(item.getClass().isAssignableFrom(PromotionalItem.class)){
        processPromotionalItem((PromotionalItem)item);
    }
    else{
        processSellableItem((SellableItem)item);
    }
}

But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?

Body:
Use the instanceof keyword

if(item instanceof PromotionalItem){
    processPromotionalItem((PromotionalItem) item);
} else if(item instanceof SellableItem) {
    processSellableItem((SellableItem) item);
}

Make sure you use else if not only else because item might be
  something else other than PromotionalItem and SellableItem if you
  cast it to a class from which it wasn't build from, you will get a ClassCastException

instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.


问:
Flex applications on Windows Phone 7
I'm evaluating Flex 4.5 for use as a mobile development platform. The demo version of the IDE supports android and promises to support iPhone development in future. There's no mention of Windows Phone 7. Usually, this is the sort of thing that google excels at but in this case, I've come up empty handed. I've found many contradictory reports of Adobe supporting WP7, then not supporting it, then supporting it but not in the initial release. </p>

<p>Has anyone come across any official announcements from Adobe on this? I understand that companies change their priorities and business relationships change so I'm not looking for a crystal ball, I'd just like to see the latest communication from Adobe on this is. </p>

答:
Flex 4.5 can currently be used on Android and iPhone, however WinPhone7 is kind of out of the loop for now.  There has been some demos of it shown, but who knows when Microsoft/Adobe will work together to get Flash out on Internet Explorer mobile or get to having Air on WinPhone7.

I know personally that Adobe is aiming for it, but not sure how much of a priority it is since WinPhone7 is still an underdog in this arena.  My feeling is that it will come, but not just yet.

Title: Flex applications on Windows Phone 7

Body:
I'm evaluating Flex 4.5 for use as a mobile development platform. The demo version of the IDE supports android and promises to support iPhone development in future. There's no mention of Windows Phone 7. Usually, this is the sort of thing that google excels at but in this case, I've come up empty handed. I've found many contradictory reports of Adobe supporting WP7, then not supporting it, then supporting it but not in the initial release.

Has anyone come across any official announcements from Adobe on this? I understand that companies change their priorities and business relationships change so I'm not looking for a crystal ball, I'd just like to see the latest communication from Adobe on this is.


问:
openssl command for encryption/decryption with prime256v1 private key?
I want to encrypt a simply message with an EC private key, specifically, prime256v1 by CMD; and decrypt with the corresponding EC public key.

I have only found references for RSA in the asymmetric cryptographic case or encryption with an ec public key, but i need to use ECDSA algorithm and encrypt with a private key.

答:
Generate a self-signed P-256 certificate and associated private key like this:

```<code>openssl ecparam -name prime256v1 -out p256-params.pem

openssl req -x509 -nodes -days 3650 -newkey  ec:p256-params.pem -keyout p256-key.pem -out p256-cert.pem
</code>```

Encrypt a file like this:

```<code>openssl cms -encrypt -binary -aes-256-cbc -in plaintext.dat -out ciphertext.dat p256-cert.pem
</code>```

Decrypt a file like this:

```<code>openssl cms -decrypt -in ciphertext.dat -out plaintext2.dat -inkey p256-key.pem
</code>```

Sign a file like this:

```<code>openssl cms -sign -binary -in plaintext.dat -out signedtext.dat -inkey p256-key.pem -signer p256-cert.pem -nodetach
</code>```

Verify a signed file like this:

```<code>openssl cms -verify -in signedtext.dat -out plaintext2.dat -CAfile p256-cert.pem
</code>```

Body:
Generate a self-signed P-256 certificate and associated private key like this:

openssl ecparam -name prime256v1 -out p256-params.pem

openssl req -x509 -nodes -days 3650 -newkey  ec:p256-params.pem -keyout p256-key.pem -out p256-cert.pem

Encrypt a file like this:

openssl cms -encrypt -binary -aes-256-cbc -in plaintext.dat -out ciphertext.dat p256-cert.pem

Decrypt a file like this:

openssl cms -decrypt -in ciphertext.dat -out plaintext2.dat -inkey p256-key.pem

Sign a file like this:

openssl cms -sign -binary -in plaintext.dat -out signedtext.dat -inkey p256-key.pem -signer p256-cert.pem -nodetach

Verify a signed file like this:

openssl cms -verify -in signedtext.dat -out plaintext2.dat -CAfile p256-cert.pem


答:
In your case you should use instanceof instead of isAssignableFrom (be careful though, the syntax is different, more on that below).

isAssignableFrom checks if the parameter object can be written to the object the function has been called from. instanceof checks if the left object is from the same class or a subclass of the right class. This will make more sense once you've seen the syntax of instanceof:

```<code>if(item instanceof PromotionalItem){
    processPromotionalItem((PromotionalItem)item);
}

</code>```

So in a nutshell, your logic was just a little off. You were trying to cast from one subclass of your item class to a completely different subclass.

Title: How to make this method more generic

Body:
In your case you should use instanceof instead of isAssignableFrom (be careful though, the syntax is different, more on that below).

isAssignableFrom checks if the parameter object can be written to the object the function has been called from. instanceof checks if the left object is from the same class or a subclass of the right class. This will make more sense once you've seen the syntax of instanceof:

if(item instanceof PromotionalItem){
    processPromotionalItem((PromotionalItem)item);
}

So in a nutshell, your logic was just a little off. You were trying to cast from one subclass of your item class to a completely different subclass.


问:
Internet Explorer redirect on all .Net Core project pages
I'm a .Net Core beginner and look for a solution to protect the application from IE.

I got the following code working in Controller:

```<code>string userAgent = Request.Headers["User-Agent"].ToString();
var flagsIE = new [] {"MSIE", "Trident"};

if(flagsIE.Any(userAgent.Contains)){
    return RedirectToAction("BadBrowser");
}
</code>```

Now if someone is trying to visit the page using IE, they get redirected to an info-page asking them to use a modern browser. Instead of adding this code to every single Controller.cs I would like to add it on project level, so that it get's executed independent from the location within of the project.

And, I know that this can be achieved with _Layout.cshtml, my question is:
Where and how would I implement a function to get it executed for all requested views withing the project without adding it every single request within Controller.

Thank you in advance.

答:
Never do that. Excluding browsers with redirects, is what lead to massive user agent spoofing. Effectively making that AgentId useless. And the way you wrote it, you may get a lot of false-positives.

It is also a bad idea from the early days of the internet, we are hoping to get rid off:
https://en.wikipedia.org/wiki/User_agent#User_agent_spoofing

Body:
I'm a .Net Core beginner and look for a solution to protect the application from IE.

I got the following code working in Controller:

string userAgent = Request.Headers["User-Agent"].ToString();
var flagsIE = new [] {"MSIE", "Trident"};

if(flagsIE.Any(userAgent.Contains)){
    return RedirectToAction("BadBrowser");
}

Now if someone is trying to visit the page using IE, they get redirected to an info-page asking them to use a modern browser. Instead of adding this code to every single Controller.cs I would like to add it on project level, so that it get's executed independent from the location within of the project.

And, I know that this can be achieved with _Layout.cshtml, my question is:
Where and how would I implement a function to get it executed for all requested views withing the project without adding it every single request within Controller.

Thank you in advance.


问:
pytesseract using tesseract 4.0 numbers only not working
Any one tried to get numbers only calling the latest version of tesseract 4.0 in python?

The below worked in 3.05 but still returns characters in 4.0, I tried removing all config files but the digits file and still didn't work; any help would be great:

im is an image of a date, black text white background:

```<code>import pytesseract
im =  imageOfDate
im = pytesseract.image_to_string(im, config='outputbase digits')
print(im)
</code>```

答:
You can specify the numbers in the tessedit_char_whitelist as below as a config option.

```<code>ocr_result = pytesseract.image_to_string(image, lang='eng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')
</code>```

Body:
Any one tried to get numbers only calling the latest version of tesseract 4.0 in python?

The below worked in 3.05 but still returns characters in 4.0, I tried removing all config files but the digits file and still didn't work; any help would be great:

im is an image of a date, black text white background:

import pytesseract
im =  imageOfDate
im = pytesseract.image_to_string(im, config='outputbase digits')
print(im)

Body:
You can specify the numbers in the tessedit_char_whitelist as below as a config option.

ocr_result = pytesseract.image_to_string(image, lang='eng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')


问:
Unable to run flask application as a service with systemd on Centos 7 server
I'm able to run flask app within virtualenv /web_services/flask_api/flask_api like this:

gunicorn --workers=4 --bind=localhost:8000 --log-level=error app:app

But, when I try to run it as a service it's not working. Here's a post that I followed to create a .service config file:

https://blog.miguelgrinberg.com/post/running-a-flask-application-as-a-service-with-systemd

Here's how my web_service.service file looks like:

```<code>[Unit]
Description=Sample web service
After=network.target

[Service]
User=aaa.bbb
WorkingDirectory=/web_services/flask_api/flask_api
ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app
Restart=always

[Install]
WantedBy=multi-user.target
</code>```

After saving this file I did:

```<code>$ sudo systemctl daemon-reload
$ sudo systemctl start web_service
$ sudo systemctl enable web_service
</code>```

systemctl | grep running is not displaying this api.

While checking status of this service, I'm getting this:

```<code>sudo systemctl status web_service
● web_service.service - Sample web service
 Loaded: loaded (/etc/systemd/system/web_service.service; enabled; vendor preset: disabled)
 Active: failed (Result: start-limit) since Mon 2020-06-01 16:15:15 EDT; 13s ago
 Process: 1016 ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app (code=exited, status=1/FAILURE)
 Main PID: 1016 (code=exited, status=1/FAILURE)
</code>```

Don't know what I'm missing here or doing wrong. Any help would be appreciated..

答:
It got solved by changing:

ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app

to

ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error app:app

Body:
I'm able to run flask app within virtualenv /web_services/flask_api/flask_api like this:

gunicorn --workers=4 --bind=localhost:8000 --log-level=error app:app

But, when I try to run it as a service it's not working. Here's a post that I followed to create a .service config file:

https://blog.miguelgrinberg.com/post/running-a-flask-application-as-a-service-with-systemd

Here's how my web_service.service file looks like:

[Unit]
Description=Sample web service
After=network.target

[Service]
User=aaa.bbb
WorkingDirectory=/web_services/flask_api/flask_api
ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app
Restart=always

[Install]
WantedBy=multi-user.target

After saving this file I did:

$ sudo systemctl daemon-reload
$ sudo systemctl start web_service
$ sudo systemctl enable web_service

systemctl | grep running is not displaying this api.

While checking status of this service, I'm getting this:

sudo systemctl status web_service
● web_service.service - Sample web service
 Loaded: loaded (/etc/systemd/system/web_service.service; enabled; vendor preset: disabled)
 Active: failed (Result: start-limit) since Mon 2020-06-01 16:15:15 EDT; 13s ago
 Process: 1016 ExecStart=/web_services/flask_api/flask_api/bin/gunicorn --workers=4 --bind=localhost:8000 --log-level=error web_service:app (code=exited, status=1/FAILURE)
 Main PID: 1016 (code=exited, status=1/FAILURE)

Don't know what I'm missing here or doing wrong. Any help would be appreciated..