问:
Drawing fast lines in pygame
I'm trying to draw fast lines using pygame that aren't rendered directly to the screen.  I've got a Python list as large as the number of pixels for the desired resolution, and store integer values corresponding to the number of times that pixel was hit by the line algorithm.  Using this, a 2D heat map is built up, so rather than drawing a flat pixel value, pixel values are incremented based on the number of times a line runs through it, and "hot" pixels get brighter colours.

The reason for doing it this way is that we don't know in advance how many of these lines are going to get drawn, and what the maximum number of times any given pixel is going to be hit.  Since we'd like to scale the output so that each rendering has the correct maximum and minimum RGB values, we can't just draw to the screen.

Is there a better way to draw these lines than a relatively naive Bresenham's algorithm?  Here's the critical part of the drawLine function:

```<code>  # before the loop, to save repeated multiplications
  xm = []
  for i in range(resolution[0]):
    xm.append(i * resolution[0])

  # inside of drawLine, index into the f list, of size resolution[0] * resolution[1]
  for x in range(x0, x1 + 1):
    if steep:
      idx = y + xm[x]
      f[idx] += 1
    else:
      idx = x + xm[y]
      f[idx] += 1
</code>```

The end result is scaled and drawn to the screen based on the maximum value inside of f.  For example, if the maximum value is 1000, then you can assume the RGB value of each of the pixels is (f[i] * 255) / 1000.

The profile information says that runtime is dominated by the index lookups into f.  I've used previous questions here to prove that these basic lists are faster than numpy arrays or arrays in Python, but for drawing lines like this, it still seems like there's room to improve.

What's a good and fast method for drawing an unknown number of lines to the screen, knowing that you'll be scaling the output in the end to render to the screen?  Is there a good way to get rid of the index overhead?

答:
Try Cython or something similar. (If you do, I would be interested in knowing if/how much that helped)

Cython is a programming language to
  simplify writing C and C++ extension
  modules for the CPython Python
  runtime. Strictly speaking, Cython
  syntax is a superset of Python syntax
  additionally supporting: Direct
  calling of C functions, or C++
  functions/methods, from Cython code.
  Strong typing of Cython variables,
  classes, and class attributes as C
  types. Cython compiles to C or C++
  code rather than Python, and the
  result is used as a Python Extension
  Module or as a stand-alone application
  embedding the CPython runtime.
  (http://en.wikipedia.org/wiki/Cython)

Title: Drawing fast lines in pygame

Body:
I'm trying to draw fast lines using pygame that aren't rendered directly to the screen.  I've got a Python list as large as the number of pixels for the desired resolution, and store integer values corresponding to the number of times that pixel was hit by the line algorithm.  Using this, a 2D heat map is built up, so rather than drawing a flat pixel value, pixel values are incremented based on the number of times a line runs through it, and "hot" pixels get brighter colours.

The reason for doing it this way is that we don't know in advance how many of these lines are going to get drawn, and what the maximum number of times any given pixel is going to be hit.  Since we'd like to scale the output so that each rendering has the correct maximum and minimum RGB values, we can't just draw to the screen.

Is there a better way to draw these lines than a relatively naive Bresenham's algorithm?  Here's the critical part of the drawLine function:

  # before the loop, to save repeated multiplications
  xm = []
  for i in range(resolution[0]):
    xm.append(i * resolution[0])

  # inside of drawLine, index into the f list, of size resolution[0] * resolution[1]
  for x in range(x0, x1 + 1):
    if steep:
      idx = y + xm[x]
      f[idx] += 1
    else:
      idx = x + xm[y]
      f[idx] += 1

The end result is scaled and drawn to the screen based on the maximum value inside of f.  For example, if the maximum value is 1000, then you can assume the RGB value of each of the pixels is (f[i] * 255) / 1000.

The profile information says that runtime is dominated by the index lookups into f.  I've used previous questions here to prove that these basic lists are faster than numpy arrays or arrays in Python, but for drawing lines like this, it still seems like there's room to improve.

What's a good and fast method for drawing an unknown number of lines to the screen, knowing that you'll be scaling the output in the end to render to the screen?  Is there a good way to get rid of the index overhead?


来源: stackexchange

问:
Golang unit testing python function
I have an API handler in Golang that calls a python function. How can I mock the response from the python function to avoid dependence of that function running correctly to test the Golang function?</p>

答:
You could wrap your function into a new moc function:

```<code>func CallPythonFunctionMoc() Result {
    var res Result
    var err error
    res, err = CallPythonFunction()
    if err != nil {
        res = "Moc value"
    }
    return res
</code>```

Edit:

If you do NOT actually want to call the python function just return the moc-value:

```<code>func CallPythonFunctionMoc() Result {
    res := "Moc value"
    return res
</code>```

ContentLicense: CC BY-SA 3.0

Title: Golang unit testing python function

Body:
You could wrap your function into a new moc function:

func CallPythonFunctionMoc() Result {
    var res Result
    var err error
    res, err = CallPythonFunction()
    if err != nil {
        res = "Moc value"
    }
    return res

Edit:

If you do NOT actually want to call the python function just return the moc-value:

func CallPythonFunctionMoc() Result {
    res := "Moc value"
    return res


问:
Excel VBA to filter 2 columns
Is it possible that it will filter 2 columns? Like it will filter country and date (which are less than today's date) or if possible it will filter only the highlighted cell on the second filter. Thank you. Btw, I'm using Ron de Bruin codes, copyrights to him.

Example of what I'm looking:sample excel

```<code>Sub Send_Row_Or_Rows_2()

Dim OutApp As Object
Dim OutMail As Object
Dim rng As Range
Dim Ash As Worksheet
Dim Cws As Worksheet
Dim Rcount As Long
Dim Rnum As Long
Dim FilterRange As Range
Dim FieldNum As Integer

On Error GoTo cleanup
Set OutApp = CreateObject("Outlook.Application")

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

'Set filter sheet, you can also use Sheets("MySheet")
Set Ash = ActiveSheet

'Set filter range and filter column (column with e-mail addresses)
Set FilterRange = Ash.Range("A1:H" & Ash.Rows.Count)
FieldNum = 3 'Filter column = B because the filter range start in column A

'Add a worksheet for the unique list and copy the unique list in A1
Set Cws = Worksheets.Add
FilterRange.Columns(FieldNum).AdvancedFilter _
        Action:=xlFilterCopy, _
        CopyToRange:=Cws.Range("A1"), _
        CriteriaRange:="", Unique:=True

'Count of the unique values + the header cell
Rcount = Application.WorksheetFunction.CountA(Cws.Columns(1))

'If there are unique values start the loop
If Rcount >= 2 Then
    For Rnum = 2 To Rcount

        'Filter the FilterRange on the FieldNum column
        FilterRange.AutoFilter Field:=FieldNum, _
                               Criteria1:=Cws.Cells(Rnum, 1).Value

        'If the unique value is a mail addres create a mail
        'If Cws.Cells(Rnum, 1).Value Like "?*@?*.?*" Then

            With Ash.AutoFilter.Range
                On Error Resume Next
                Set rng = .SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
            End With

            Set OutMail = OutApp.CreateItem(0)

            On Error Resume Next
            With OutMail
                .To = Cws.Cells(Rnum, 1).Offest(0, 1).Value
                .Subject = "Test mail"
                .HTMLBody = RangetoHTML(rng)
                .Display  'Or use Send
            End With
            On Error GoTo 0

            Set OutMail = Nothing

        'Close AutoFilter
        Ash.AutoFilterMode = False

    Next Rnum
End If
</code>```

答:
When you filter once using

```<code>FilterRange.AutoFilter Field:=FieldNum, _
                           Criteria1:=Cws.Cells(Rnum, 1).Value
</code>```

all you have to do to filter it further is write another analogous statement after that:

```<code>FilterRange.AutoFilter Field:=FieldNum2, _
                           Criteria1:= 'your criteria
</code>```

If you do so, it will be filtered on both chosen columns. Same goes for three, four, or multiple other filters on the same dataset.

Title: Excel VBA to filter 2 columns

Body:
Is it possible that it will filter 2 columns? Like it will filter country and date (which are less than today's date) or if possible it will filter only the highlighted cell on the second filter. Thank you. Btw, I'm using Ron de Bruin codes, copyrights to him.

Example of what I'm looking:sample excel

Sub Send_Row_Or_Rows_2()

Dim OutApp As Object
Dim OutMail As Object
Dim rng As Range
Dim Ash As Worksheet
Dim Cws As Worksheet
Dim Rcount As Long
Dim Rnum As Long
Dim FilterRange As Range
Dim FieldNum As Integer

On Error GoTo cleanup
Set OutApp = CreateObject("Outlook.Application")

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

'Set filter sheet, you can also use Sheets("MySheet")
Set Ash = ActiveSheet

'Set filter range and filter column (column with e-mail addresses)
Set FilterRange = Ash.Range("A1:H" & Ash.Rows.Count)
FieldNum = 3 'Filter column = B because the filter range start in column A

'Add a worksheet for the unique list and copy the unique list in A1
Set Cws = Worksheets.Add
FilterRange.Columns(FieldNum).AdvancedFilter _
        Action:=xlFilterCopy, _
        CopyToRange:=Cws.Range("A1"), _
        CriteriaRange:="", Unique:=True

'Count of the unique values + the header cell
Rcount = Application.WorksheetFunction.CountA(Cws.Columns(1))

'If there are unique values start the loop
If Rcount >= 2 Then
    For Rnum = 2 To Rcount

        'Filter the FilterRange on the FieldNum column
        FilterRange.AutoFilter Field:=FieldNum, _
                               Criteria1:=Cws.Cells(Rnum, 1).Value

        'If the unique value is a mail addres create a mail
        'If Cws.Cells(Rnum, 1).Value Like "?*@?*.?*" Then

            With Ash.AutoFilter.Range
                On Error Resume Next
                Set rng = .SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
            End With

            Set OutMail = OutApp.CreateItem(0)

            On Error Resume Next
            With OutMail
                .To = Cws.Cells(Rnum, 1).Offest(0, 1).Value
                .Subject = "Test mail"
                .HTMLBody = RangetoHTML(rng)
                .Display  'Or use Send
            End With
            On Error GoTo 0

            Set OutMail = Nothing

        'Close AutoFilter
        Ash.AutoFilterMode = False

    Next Rnum
End If

Body:
When you filter once using

FilterRange.AutoFilter Field:=FieldNum, _
                           Criteria1:=Cws.Cells(Rnum, 1).Value

all you have to do to filter it further is write another analogous statement after that:

FilterRange.AutoFilter Field:=FieldNum2, _
                           Criteria1:= 'your criteria

If you do so, it will be filtered on both chosen columns. Same goes for three, four, or multiple other filters on the same dataset.


问:
Mongo Partial Compound Unique Index | Not Used In Query
I am facing a strange issue. I have a partial, compound, unique index with defination:

createIndex({a: 1, b:1, c: 1}, {unique:1, partialFilterExpression: {c: {$type: "string"}}})

Now when I perform a query this index is never used as per the explain plan. Even though there are document(s) matching the query.

Chaning same index to sparse instead of partial fixes the above issue, but sparse, compound, unique indexes have following issue:
dealing-with-mongodb-unique-sparse-compound-indexes

答:
As noted in the query coverage documentation for partial indexes:

MongoDB will not use the partial index for a query or sort operation if using the index results in an incomplete result set.

To use the partial index, a query must contain the filter expression (or a modified filter expression that specifies a subset of the filter expression) as part of its query condition.

In your set up you create a partial index filtering on {c: {$type: "string"}}.

Your query conditions are {a:"1", b:"p", c:"2"}, or a query shape of three equality comparisons ({a: eq, b: eq, c: eq}). Since this query shape does not include a $type filter on c,  the query planner has to consider that queries fitting the shape should match values of any data type and the partial index is not a viable candidate for complete results.

Some example queries that would use your partial index (tested with MongoDB 3.4.5):

```<code>// Search on {a, b} with c criteria matching the index filter
db.mydb.find({a:"1", b:"p", c: { $type: "string" } })

// Search on {a,b,c} and use $and to include the type of c
db.mydb.find({a:"1", b:"p", $and: [{ c: "2"} , {c: { $type: "string" }}]})
</code>```

Body:
As noted in the query coverage documentation for partial indexes:

MongoDB will not use the partial index for a query or sort operation if using the index results in an incomplete result set.

To use the partial index, a query must contain the filter expression (or a modified filter expression that specifies a subset of the filter expression) as part of its query condition.

In your set up you create a partial index filtering on {c: {$type: "string"}}.

Your query conditions are {a:"1", b:"p", c:"2"}, or a query shape of three equality comparisons ({a: eq, b: eq, c: eq}). Since this query shape does not include a $type filter on c,  the query planner has to consider that queries fitting the shape should match values of any data type and the partial index is not a viable candidate for complete results.

Some example queries that would use your partial index (tested with MongoDB 3.4.5):

// Search on {a, b} with c criteria matching the index filter
db.mydb.find({a:"1", b:"p", c: { $type: "string" } })

// Search on {a,b,c} and use $and to include the type of c
db.mydb.find({a:"1", b:"p", $and: [{ c: "2"} , {c: { $type: "string" }}]})


问:
What are the differences between JSONiq and XQuery 3.1?
Both JSONiq and XQuery 3.1 extend XQuery 3.0 with support for JSON.

How do they differ?

答:
Overall motivation

XQuery 3.1 was designed with the goal to support additional data structures (maps, arrays) in memory. These structures are mapped to JSON for input and output. XQuery 3.1 has been a W3C recommendation since March 2017.

JSONiq was designed with the goal of querying and updating JSON in settings such as document stores. It was also designed by members of the XML Query working group (disclaimer: I am one of them) while investigating various possibilities to support JSON. While it is not an official recommendation, it is stable and public.

Data model

Both XQuery 3.1 and JSONiq extend the data model with objects and arrays, but do so in different ways, motivated by their distinct focuses. Overall, XQuery 3.1 has a more generic data model, while JSONiq restricts it to mirror JSON.

In JSONiq, object keys must be strings. In XQuery 3.1, they can be any atomic value.

In JSONiq, values in objects and arrays must be single items, in particular, arrays are homomorphic to sequences even though they are distinct. In XQuery 3.1, values in object and arrays can be sequences of items.

In JSONiq, nulls are represented with a dedicated atomic type. In XQuery 3.1, they are represented with empty sequences (which are accepted values in the data model).

In XQuery 3.1, values are not copied with populating an array or map, which supports among others building indices on XML nodes. In JSONiq, copies are made similarly to XML constructors, to ensure a strict tree semantics.

Construction

The syntax for constructing objects and arrays in JSONiq is a superset of JSON.

```<code>{ "foo" : [ 1 to 10 ] }
</code>```

In XQuery 3.1, it is similar to computed XML node constructors:

```<code>map { "foo" : array { 1 to 10 } }
</code>```

XQuery 3.1 has an alternate syntax for arrays in which commas delimite the slots for the values, to nest sequences:

```<code>[ 1, (1 to 10), 11 ]
</code>```

Navigation

XQuery 3.1 uses function calls to perform lookups in objects and arrays:

```<code>let $map := map { "foo" : "bar" }
return $map("foo")

let $array := array { 1, 2, 3 }
return $array(2)
</code>```

It also uses ? as a shortcut for unquoted names and integers:

```<code>let $map := map { "foo" : "bar" }
return $map?foo

let $array := array { 1, 2, 3 }
return $array?2

let $array := array { 1, 2, 3 }
return $array?*
</code>```

JSONiq (the core language) uses dots and square brackets

```<code>let $map := { "foo" : "bar" }
return $map.foo

let $array := [ 1, 2, 3 ]
return $array[[2]]

let $array := [ 1, 2, 3 ]
return $array[]
</code>```

(JSONiq also exists as an extension to XQuery that also overloads the function call syntax).

Body:
Overall motivation

XQuery 3.1 was designed with the goal to support additional data structures (maps, arrays) in memory. These structures are mapped to JSON for input and output. XQuery 3.1 has been a W3C recommendation since March 2017.

JSONiq was designed with the goal of querying and updating JSON in settings such as document stores. It was also designed by members of the XML Query working group (disclaimer: I am one of them) while investigating various possibilities to support JSON. While it is not an official recommendation, it is stable and public.

Data model

Both XQuery 3.1 and JSONiq extend the data model with objects and arrays, but do so in different ways, motivated by their distinct focuses. Overall, XQuery 3.1 has a more generic data model, while JSONiq restricts it to mirror JSON.

In JSONiq, object keys must be strings. In XQuery 3.1, they can be any atomic value.

In JSONiq, values in objects and arrays must be single items, in particular, arrays are homomorphic to sequences even though they are distinct. In XQuery 3.1, values in object and arrays can be sequences of items.

In JSONiq, nulls are represented with a dedicated atomic type. In XQuery 3.1, they are represented with empty sequences (which are accepted values in the data model).

In XQuery 3.1, values are not copied with populating an array or map, which supports among others building indices on XML nodes. In JSONiq, copies are made similarly to XML constructors, to ensure a strict tree semantics.

Construction

The syntax for constructing objects and arrays in JSONiq is a superset of JSON.

{ "foo" : [ 1 to 10 ] }

In XQuery 3.1, it is similar to computed XML node constructors:

map { "foo" : array { 1 to 10 } }

XQuery 3.1 has an alternate syntax for arrays in which commas delimite the slots for the values, to nest sequences:

[ 1, (1 to 10), 11 ]

Navigation

XQuery 3.1 uses function calls to perform lookups in objects and arrays:

let $map := map { "foo" : "bar" }
return $map("foo")

let $array := array { 1, 2, 3 }
return $array(2)

It also uses ? as a shortcut for unquoted names and integers:

let $map := map { "foo" : "bar" }
return $map?foo

let $array := array { 1, 2, 3 }
return $array?2

let $array := array { 1, 2, 3 }
return $array?*

JSONiq (the core language) uses dots and square brackets

let $map := { "foo" : "bar" }
return $map.foo

let $array := [ 1, 2, 3 ]
return $array[[2]]

let $array := [ 1, 2, 3 ]
return $array[]

(JSONiq also exists as an extension to XQuery that also overloads the function call syntax).


问:
I am using FCM.how can i display notification tittle in alert dialogue or custom Toast when app is in foreground rather than on status bar?
Right now i am using this when app is in foreground it gives me status on status bar now i want alert dialogue r custom popup for notification when appp is in foreground</p>

```<code>    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            try
            {
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", title);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
                NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.imgpsh_fullsize)
                        .setContentTitle(title);
                NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
                manager.notify(0, builder.build());

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
</code>```

答:
In your FCM class where you are getting the Notification add this

```<code>                 if (Activity.isVisible) {
                    Intent intent = new Intent("notification");
                    //you can pass data using bundle here
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
                }
</code>```

Activity is the name of your Activity and isVisible is the boolean
  value. You need to set the isVisible value to true when the activity is in foreground else set it to false.

In your Activity add the below code

```<code>/**
     * Broadcast Receiver for updating the notification count when a notification is received
     */
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                       //Add Dialog code here

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

 @Override
    public void onResume() {
        super.onResume();
        isVisible = true;
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver, new IntentFilter("notification"));

    }

 @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }
</code>```

Try this and let me know if this work for you.

P.S. : This code is of Fragment you can convert it accordingly with respect to your Activity

Body:
Right now i am using this when app is in foreground it gives me status on status bar now i want alert dialogue r custom popup for notification when appp is in foreground

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            try
            {
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", title);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
                NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.imgpsh_fullsize)
                        .setContentTitle(title);
                NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
                manager.notify(0, builder.build());

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

Body:
In your FCM class where you are getting the Notification add this

                 if (Activity.isVisible) {
                    Intent intent = new Intent("notification");
                    //you can pass data using bundle here
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
                }

Activity is the name of your Activity and isVisible is the boolean
  value. You need to set the isVisible value to true when the activity is in foreground else set it to false.

In your Activity add the below code

/**
     * Broadcast Receiver for updating the notification count when a notification is received
     */
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                       //Add Dialog code here

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

 @Override
    public void onResume() {
        super.onResume();
        isVisible = true;
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver, new IntentFilter("notification"));

    }

 @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
        isVisible = false;
    }

Try this and let me know if this work for you.

P.S. : This code is of Fragment you can convert it accordingly with respect to your Activity


问:
Kafka bootstrap.servers config value as subset of brokers
For kafka bootstrap.servers config one should provide all the broker details.

If not, how does kafka producer/consumer will resolve all brokers available?

If yes, Do producer/consumer needs restart after adding a node?

答:
The bootstrap.servers config is mandatory for producer and consumer and it must have one broker host:port at least in order to allow producer/consumer to connect to the cluster and then getting all the other metadata (where topics are, who are the leaders and so on).

If you add a node, you don't need to restart producer/consumer but of course the current configuration will be stale. I mean ...
If you have a cluster with broker1 and broker2 and you put them into the bootstrap.servers config then producer/consumer connect to the cluster.
Let's imagine that you add broker3 and some new topics/partitions are deployed there. Your producer/consumer will be able to write/read to/from these new topics/partitions because information about them (so that they are on broker3) will be available through asking metadata to broker1 or broker2.

Of course if you shutdown broker1 and broker2 and your cluster will be just made of broker3, you'll have to restart producer/consumer with the bootstrap.servers config with just broker3.

The bootstrap.servers config is just (as the name implies) a configuration used on starting; then each client will be able to connect directly to a broker (for reading/writing topic/partitions there) even if such broker isn't in the bootstrap.servers config.


问:
How to find url which caused redirection from my redirected page?
Here is a sample url. Say like,

```<code>https://example.com/test/<item_id>
</code>```

which lands in the servlet Test.java from where it is redirected to a jsp page say error.jsp when error occurs

Now all I need from my jsp page is to get the source url (https://example.com/test/) which caused this redirection. How should i get it?

Any help would be most welcome ! Thanks in advance :-)

答:
javax.servlet.forward.request_uri helped me to get uri

```<code>String requestUri = request.getAttribute("javax.servlet.forward.request_uri").toString();
String sourceUrl = <domain_url> + requestUri;
</code>```

Allows me to get entire url. Here I know base domain name hence I could get the entire url. But when it is redirected from some external site I'm not sure how to handle it.

Body:
Here is a sample url. Say like,

https://example.com/test/<item_id>

which lands in the servlet Test.java from where it is redirected to a jsp page say error.jsp when error occurs

Now all I need from my jsp page is to get the source url (https://example.com/test/) which caused this redirection. How should i get it?

Any help would be most welcome ! Thanks in advance :-)

Body:
javax.servlet.forward.request_uri helped me to get uri

String requestUri = request.getAttribute("javax.servlet.forward.request_uri").toString();
String sourceUrl = <domain_url> + requestUri;

Allows me to get entire url. Here I know base domain name hence I could get the entire url. But when it is redirected from some external site I'm not sure how to handle it.


问:
how to insert variable's value in SQlite Database in Qt cpp
i am using Qt and i have written c++ code,i have already connected with sqlite database.i want to insert name in database

```<code>std::string name="Hello";
qry.prepare( "INSERT INTO s_no (Name,Status) VALUES ('name','1' )");
if( !qry.exec() )
    qDebug() << qry.lastError();
else
    qDebug( "Inserted!" );
</code>```

but in db i am finding name only , not hello;

please help me..thank you so much in advance

答:
C++ and SQL are two different programming languages, and execute in different environments. This means that C++ objects are not visible in SQL.

In theory, it would be possible to construct the string containing the SQL command so that the value of the name variable is inserted directly into it:

```<code>qry.prepare("INSERT INTO s_no (Name,Status) VALUES('" + name + "', '1')");  // don't do this
</code>```

However, this will blow up if the name contains a quote. Escaping quotes would be possible with additional code, but a better way of getting variable values into an SQL query is to use parameters:

```<code>qry.prepare("INSERT INTO s_no (Name,Status) VALUES(?, '1')");
qry.bindValue(0, name);
</code>```

(This is the only sensible way of using blob values in a query.)

Body:
i am using Qt and i have written c++ code,i have already connected with sqlite database.i want to insert name in database

std::string name="Hello";
qry.prepare( "INSERT INTO s_no (Name,Status) VALUES ('name','1' )");
if( !qry.exec() )
    qDebug() << qry.lastError();
else
    qDebug( "Inserted!" );

but in db i am finding name only , not hello;

please help me..thank you so much in advance

Body:
C++ and SQL are two different programming languages, and execute in different environments. This means that C++ objects are not visible in SQL.

In theory, it would be possible to construct the string containing the SQL command so that the value of the name variable is inserted directly into it:

qry.prepare("INSERT INTO s_no (Name,Status) VALUES('" + name + "', '1')");  // don't do this

However, this will blow up if the name contains a quote. Escaping quotes would be possible with additional code, but a better way of getting variable values into an SQL query is to use parameters:

qry.prepare("INSERT INTO s_no (Name,Status) VALUES(?, '1')");
qry.bindValue(0, name);

(This is the only sensible way of using blob values in a query.)


问:
Smooth expanding UIView animation in Swift
Aim:

How can I animate a UIView that I want to expand to fill the whole screen. The UIView needs to expand in smooth, even and balance way while it animates.

I have one red square positioned on screen, starts small then expands to fit the screen. (Image 1.)

```<code>let subview = UIView()
subview.backgroundColor = .red
subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
self.view.addSubview(subview)
</code>```

Question:

In Swift 2 and Swift 3, using an animateWithDuration, how do I
  animate the the red square UIView expanding in a balanced and even
  manner in all directions to fill the whole screen?

```<code>UIView.animateWithDuration(1.0, delay: 0, options: nil, animations: {

    ?????

}, completion: nil)
</code>```

Image 1:

答:
It looks like you need to play with scale.

```<code>class ViewController: UIViewController {

var subview:UIView!

@IBOutlet weak var animateButton:UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    subview = UIView()
    subview.backgroundColor = .red
    subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
    self.view.addSubview(subview)

    self.view.bringSubview(toFront: animateButton)
}

@IBAction func animateButtonPressed(sender:UIButton) {
    if(sender.tag == 0) {

        let screenCenter = CGPoint(x:UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
        let subviewCenter = self.view.convert(self.subview.center, to: self.view)
        let offset = UIOffset(horizontal: screenCenter.x-subviewCenter.x, vertical: screenCenter.y-subviewCenter.y)

        let widthScale = UIScreen.main.bounds.size.width/subview.frame.size.width
        let heightScale = UIScreen.main.bounds.size.height/subview.frame.size.height
        UIView.animate(withDuration: 1.0, animations: {
            let scaleTransform = CGAffineTransform(scaleX: widthScale, y: heightScale)
            let translateTransform = CGAffineTransform(translationX: offset.horizontal, y: offset.vertical)
            self.subview.transform = scaleTransform.concatenating(translateTransform)
        }, completion: { (finished) in
            sender.tag = 1;
        })

    } else {
        UIView.animate(withDuration: 1.0, animations: {
            self.subview.transform = CGAffineTransform.identity
        }, completion: { (finished) in
            sender.tag = 0;
        })
    }
}
}
</code>```

Body:
Aim:

How can I animate a UIView that I want to expand to fill the whole screen. The UIView needs to expand in smooth, even and balance way while it animates.

I have one red square positioned on screen, starts small then expands to fit the screen. (Image 1.)

let subview = UIView()
subview.backgroundColor = .red
subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
self.view.addSubview(subview)

Question:

In Swift 2 and Swift 3, using an animateWithDuration, how do I
  animate the the red square UIView expanding in a balanced and even
  manner in all directions to fill the whole screen?

UIView.animateWithDuration(1.0, delay: 0, options: nil, animations: {

    ?????

}, completion: nil)

Image 1:

Body:
It looks like you need to play with scale.

class ViewController: UIViewController {

var subview:UIView!

@IBOutlet weak var animateButton:UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    subview = UIView()
    subview.backgroundColor = .red
    subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
    self.view.addSubview(subview)

    self.view.bringSubview(toFront: animateButton)
}

@IBAction func animateButtonPressed(sender:UIButton) {
    if(sender.tag == 0) {

        let screenCenter = CGPoint(x:UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
        let subviewCenter = self.view.convert(self.subview.center, to: self.view)
        let offset = UIOffset(horizontal: screenCenter.x-subviewCenter.x, vertical: screenCenter.y-subviewCenter.y)

        let widthScale = UIScreen.main.bounds.size.width/subview.frame.size.width
        let heightScale = UIScreen.main.bounds.size.height/subview.frame.size.height
        UIView.animate(withDuration: 1.0, animations: {
            let scaleTransform = CGAffineTransform(scaleX: widthScale, y: heightScale)
            let translateTransform = CGAffineTransform(translationX: offset.horizontal, y: offset.vertical)
            self.subview.transform = scaleTransform.concatenating(translateTransform)
        }, completion: { (finished) in
            sender.tag = 1;
        })

    } else {
        UIView.animate(withDuration: 1.0, animations: {
            self.subview.transform = CGAffineTransform.identity
        }, completion: { (finished) in
            sender.tag = 0;
        })
    }
}
}


问:
How can I print a list of characters in a string using a for loop?
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

```<code>string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}
</code>```

I know this code is not correct. Can anyone help me out?

答:
If you really want to pass alpha as string then use exapme 1 other wise pass char value it will more easy:

Example 1:

```<code>string alpha = "A";
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(Convert.ToChar(alpha) + i));
}
</code>```

Example 2:

```<code>char alpha = 'A';
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(alpha + i));
}
</code>```

Body:
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}

I know this code is not correct. Can anyone help me out?

Body:
If you really want to pass alpha as string then use exapme 1 other wise pass char value it will more easy:

Example 1:

string alpha = "A";
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(Convert.ToChar(alpha) + i));
}

Example 2:

char alpha = 'A';
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(alpha + i));
}


问:
SharePoint site hierarchy for company intranet - multiple sites or sub-sites with one root?
I'm the IT Manager at a mid-size manufacturing company.  We are getting our feet wet with SharePoint - so far we're got one blog in production use> It's the CEO's.

We have use cases for a couple of list-based "applications" with some simple workflow that will be implemented by one of our developers.  We also want to give our users (at least the more tech-savvy ones) the ability to create and work with their own departmental sites.

We're concerned, however, that we might be starting something that could quickly get out of control if it's widely adopted (which would be a good thing).  Since we don't really understand all the architectural trade-offs, we could end up with massive amounts of user data in a structure that bites us down the road.

Our biggest question is whether to have multiple sites for each use vs. a single root site from which everything else descends.  Multiple sites would give us flexibility to make changes or develop new features without creating problems for all the users.  However, multiple sites might be harder to back-up, search, and maintain user profiles/security.  A single massive site seems to reverse the cost/benefits.

I'd appreciate any insight on the one vs. many trade-offs, or links to resources that discuss it.  Links to general SharePoint "enterprise best practices" (sorry) would also be appreciated.

Thanks.

答:
However, multiple sites might be harder
  to back-up, search, and maintain user
  profiles/security. A single massive
  site seems to reverse the
  cost/benefits.

I would consider this as incorrect. First we need to clarify when we say multiple sites, do we mean multiple site collections or multiple sites - they are two entirely different things.

Now even if they are multiple different site collections, in SQL database, they are just one database, since the database is created as web application level and not site level.

That was regarding backup.

Coming to search and user profiles, again your assumption is wrong. Search and User Profiles are Shared SErvices and they work fine as long as they reside in single Shared Services Provider. Both are farm level services.

A single massive site is (if you really mean site here not site collection) is a complete no-no and a bad design.

I would recommend having multiple site collections (something like Overall department in your company like HR, Finance , IT) and then have subistes under it. This way you have one database in SQL to manage and still you can scale by adding content database to existing web application.

Again here, I assume that you are creating your topology at company level. If this is at some lower level it needs to be refined.

Read some articles on taxonomy and site architecture on Technet before going ahead with any one.

```<code>Planning worksheets for SharePoint Server 2010
http://technet.microsoft.com/en-us/library/cc262451.aspx

Plan sites and site collections
http://technet.microsoft.com/en-us/library/cc263267.aspx

Sites and site collections overview
http://technet.microsoft.com/en-us/library/cc262410.aspx

Plan site navigation
http://technet.microsoft.com/en-us/library/cc262951.aspx
</code>```

ContentLicense: CC BY-SA 2.5

Body:
However, multiple sites might be harder
  to back-up, search, and maintain user
  profiles/security. A single massive
  site seems to reverse the
  cost/benefits.

I would consider this as incorrect. First we need to clarify when we say multiple sites, do we mean multiple site collections or multiple sites - they are two entirely different things.

Now even if they are multiple different site collections, in SQL database, they are just one database, since the database is created as web application level and not site level.

That was regarding backup.

Coming to search and user profiles, again your assumption is wrong. Search and User Profiles are Shared SErvices and they work fine as long as they reside in single Shared Services Provider. Both are farm level services.

A single massive site is (if you really mean site here not site collection) is a complete no-no and a bad design.

I would recommend having multiple site collections (something like Overall department in your company like HR, Finance , IT) and then have subistes under it. This way you have one database in SQL to manage and still you can scale by adding content database to existing web application.

Again here, I assume that you are creating your topology at company level. If this is at some lower level it needs to be refined.

Read some articles on taxonomy and site architecture on Technet before going ahead with any one.

Planning worksheets for SharePoint Server 2010
http://technet.microsoft.com/en-us/library/cc262451.aspx

Plan sites and site collections
http://technet.microsoft.com/en-us/library/cc263267.aspx

Sites and site collections overview
http://technet.microsoft.com/en-us/library/cc262410.aspx

Plan site navigation
http://technet.microsoft.com/en-us/library/cc262951.aspx


问:
Display:none to image if class
I use the code above to display pdf icon before each pdf file to download.

```<code>a[href*="pdf"]::before {
    content: url('../gfx/pdficon.png');
    display: inline-block;
    vertical-align: middle;
    padding-right: 5px;
}
</code>```

I have problem when the icon appear with objects like img, at which I do not want this icon.
I came up with the idea to create a class "nopdf" to add to images to be without this icon.

How can I apply it in css? I guess that is enough to "display:none", but how to construct a rule css in this case?

EDIT: Problem is only when I link (href) to image. Then before image I see pdf icon.

答:
```<code>a.nopdf::before {
  display: none !important;
}
</code>```

or you just extend your existing rule like so:

```<code>a[href*="pdf"]:not( .nopdf )::before {
    content: url('../gfx/pdficon.png');
    display: inline-block;
    vertical-align: middle;
    padding-right: 5px;
}
</code>```

Title: Display:none to image if class

Body:
I use the code above to display pdf icon before each pdf file to download.

a[href*="pdf"]::before {
    content: url('../gfx/pdficon.png');
    display: inline-block;
    vertical-align: middle;
    padding-right: 5px;
}

I have problem when the icon appear with objects like img, at which I do not want this icon.
I came up with the idea to create a class "nopdf" to add to images to be without this icon.

How can I apply it in css? I guess that is enough to "display:none", but how to construct a rule css in this case?

EDIT: Problem is only when I link (href) to image. Then before image I see pdf icon.

Body:
a.nopdf::before {
  display: none !important;
}

or you just extend your existing rule like so:

a[href*="pdf"]:not( .nopdf )::before {
    content: url('../gfx/pdficon.png');
    display: inline-block;
    vertical-align: middle;
    padding-right: 5px;
}


问:
Redirect internally to index.php
I'm trying to redirect all the /docs/* requests to /docs/ so that index.php can handle it.

```<code>RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} ^/docs/[a-z]+
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^docs/(.*)$ /docs/ [L,QSA]
</code>```

But the above .htaccess configuration throws the following error.

Request exceeded the limit of 10 internal redirects due to probable configuration error.

答:
Try the below one:</p>

```<code>RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} ^/docs/[a-z]+
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^docs/(.*)$ /docs/index.php/$0 [L,QSA]
</code>```

Title: Redirect internally to index.php

Body:
I'm trying to redirect all the /docs/* requests to /docs/ so that index.php can handle it.

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} ^/docs/[a-z]+
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^docs/(.*)$ /docs/ [L,QSA]

But the above .htaccess configuration throws the following error.

Request exceeded the limit of 10 internal redirects due to probable configuration error.

Body:
Try the below one:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} ^/docs/[a-z]+
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^docs/(.*)$ /docs/index.php/$0 [L,QSA]


问:
WORDPRESS Audio Player not loading when the content is loaded through Ajax, MediaElement.js no applied
I'm creating a wordpress theme.
When I load the content using ajax it doesn't apply MediaElements.js to my audio player, so the audio isn't display. I think this is because the MediaElement.js is loaded with wp-footer(), and this new audio is added to the DOM after, and it's not recognized for MediaElement.js.

The same happend with local videos.

How can I resolve this?

答:
I have found that this solves most cases:

You first need to make sure the mediaelement.js scripts are being loaded on all pages (ie even the ones that don't contain media).

functions.php (or similar)

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style( 'wp-mediaelement' );
}, 100);
```

<p>Then it should simply be a case of calling this in your JS once your AJAX content has been injected to the page</p>

<p>main.js (or wherever)</p>

<pre class="lang-js prettyprint-override"><code>$( window.wp.mediaelement.initialize );
</code>```

Body:
I have found that this solves most cases:

You first need to make sure the mediaelement.js scripts are being loaded on all pages (ie even the ones that don't contain media).

functions.php (or similar)

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style( 'wp-mediaelement' );
}, 100);

Then it should simply be a case of calling this in your JS once your AJAX content has been injected to the page

main.js (or wherever)

$( window.wp.mediaelement.initialize );


问:
Executing PHP via command line
I want to be able to execute PHP via command line with a $_GET variable.  I understand I can do this with exec, but I'd like to understand more of the security risk and what things I should look out for.  The parameter I want to pass is a MySQL auto_incremented ID returned from MySQL, so I'm not concerned with user input.  But by merely allowing this to happen what things should be considered in regards to security?

The script will accept an order ID and send the customer an email invoice.  This allows me to perform this function from multiple sections of the site only maintaining the code in 1 location.

答:
For cmdline scripts $argv is the answer. But you can indeed inject $_GET variables as well. Just pre-define the QUERY_STRING environment variable accordingly:

```<code>putenv("QUERY_STRING=id=$id");
exec("php script.php");
</code>```

Regarding security, cmdline php scripts could be more worriesome on shared hosting servers if they initiate administrative actions. But there is not much you can do about that. Keep strictly cmdline scripts out of the document_root, and apply file or directory permission if anyhow possible.

Title: Executing PHP via command line

Body:
For cmdline scripts $argv is the answer. But you can indeed inject $_GET variables as well. Just pre-define the QUERY_STRING environment variable accordingly:

putenv("QUERY_STRING=id=$id");
exec("php script.php");

Regarding security, cmdline php scripts could be more worriesome on shared hosting servers if they initiate administrative actions. But there is not much you can do about that. Keep strictly cmdline scripts out of the document_root, and apply file or directory permission if anyhow possible.


问:
C++ Using for loops when you don't know when the iteration would end
So I have this code for c++ (not c++11)

```<code>#include <iostream>

using namespace std;

int calcTrip (string s) {
    int ans = 1;
    for (int i = 0; i < sizeof(s); i++) {
        char c = s[i];
        ans = ((ans*(c - 'A' + 1)) );
    }
    return ans;

}
int main() {

    string a1, a2;
    cin >> a1 >> a2;
    cout << calcTrip(a1) << endl;
    if (calcTrip(a1) != calcTrip(a2)) {
        cout << "STAY" << endl;
    }
    else {
        cout << "GO" << endl;
    }

}
</code>```

For my for loop in the variable i in calctrip, if I do i<sizeof(s) I get i is less than 32 because a string has a size of 32. Since string s is a user input, how do I make i less than the number of characters in a user input, s.

P.S And I know how to do this in c++ 11, but for class, I need to know how to do it in c++ 98

答:
To iterate over an std::string (or over the any of Standard Containers) in C++98, you can use iterators too:

```<code>for(std::string::iterator it = s.begin(); it != s.end(); ++it) {
    char c = *it;
    ans = ((ans * (c - 'A' + 1)));
}
</code>```

The range-based for loop is a C++11 feature, but iterators aren't. Another option is to use a simple for loop as follows:

```<code>for(int i = 0; i < s.size(); i++) {
    char c = s[i];
    ans = ((ans * (c - 'A' + 1)));
}
</code>```

The std::string::size returns the number of characters in the std::string.

Body:
So I have this code for c++ (not c++11)

#include <iostream>

using namespace std;

int calcTrip (string s) {
    int ans = 1;
    for (int i = 0; i < sizeof(s); i++) {
        char c = s[i];
        ans = ((ans*(c - 'A' + 1)) );
    }
    return ans;

}
int main() {

    string a1, a2;
    cin >> a1 >> a2;
    cout << calcTrip(a1) << endl;
    if (calcTrip(a1) != calcTrip(a2)) {
        cout << "STAY" << endl;
    }
    else {
        cout << "GO" << endl;
    }

}

For my for loop in the variable i in calctrip, if I do i<sizeof(s) I get i is less than 32 because a string has a size of 32. Since string s is a user input, how do I make i less than the number of characters in a user input, s.

P.S And I know how to do this in c++ 11, but for class, I need to know how to do it in c++ 98

Body:
To iterate over an std::string (or over the any of Standard Containers) in C++98, you can use iterators too:

for(std::string::iterator it = s.begin(); it != s.end(); ++it) {
    char c = *it;
    ans = ((ans * (c - 'A' + 1)));
}

The range-based for loop is a C++11 feature, but iterators aren't. Another option is to use a simple for loop as follows:

for(int i = 0; i < s.size(); i++) {
    char c = s[i];
    ans = ((ans * (c - 'A' + 1)));
}

The std::string::size returns the number of characters in the std::string.


问:
AngularJS : Can't able to access scope inside call back function
Below function is being called from directive link function. My problem is, I cant able to access scope inside then function

```<code>function workerInit(scope) {
        var data = scope.vm.graphData;
        graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
            postWorkerResponse(response);
            //scope is not defined
        })

        nodesinQueue.push(data.node[0].id)
    }
</code>```

My factory code

```<code>app.factory("graphViewService",['$q',function($q){

    var graphViewService = {};
    var worker = new Worker('./app/modules/common/graphViewWorker.js');
    var defer = $q.defer();
    worker.addEventListener('message', function(e) {
    defer.resolve(e.data);
    }, false);

    return {
        send : function(data){
            defer = $q.defer();
            worker.postMessage(data); // Send data to our worker.
            return defer.promise;
        }
    };

}])
</code>```

My Directive Code(removed unnecessary function def from original)

```<code>    (function () {
    var app = angular.module('sureApp');
    app.directive('graphView', function ($rootScope, graphViewService) {

        var controller = function () {
            var vm = this;
            //controller code
        };

        var linkFunction = function (scope, elem, attrs) {
            var el = angular.element(elem);
            var graph = graphInit(scope, scope.vm.graphData.node[0]);
            nodes = new vis.DataSet(graph.nodeList);
            edges = new vis.DataSet(graph.edgeList);
            var container = el.find('#network')[0];
            var data = {
                nodes: nodes,
                edges: edges
            };
            network = new vis.Network(container, data, networkOptions());
            networkEvents(network, scope);
            new detailWindow(el, scope);
        }

        function graphInit(scope, node) {
            var nodeList = [];
            var edgeList = [];
            workerInit(scope);
            scope.vm.graphChips = [];
            scope.vm.graphChips.push(node.currentEntity);
            nodeList.push(updateNodeStructure(node, lIcons));
            return {
                nodeList: nodeList,
                edgeList: edgeList
            }
        }

        function workerInit(scope) {
            var data = scope.vm.graphData;
            WorkerData.url = data.url;
            WorkerData.requestHeaders = requestConfig.headers;
            graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
                postWorkerResponse(response);
                //scope is not defined
            })

            nodesinQueue.push(data.node[0].id)
            console.time("test");
        }

        function WorkerData(id, level, currentEntity){
            this.url = WorkerData.url
            this.requestHeaders = WorkerData.requestHeaders;
            this.id = id;
            this.level = level;
            this.currentEntity = currentEntity;
        }

        //removed other function def

        return {
            restrict: 'E',
            scope: {
                graphData: '=',
                detailedView: '=',
                mainEntity: '='
            },
            link: linkFunction,
            controller: controller,
            controllerAs: 'vm',
            bindToController: true,
            templateUrl: './app/modules/common/graphView.html'
        };
    })
}());
</code>```

Can anyone help me on this?

答:
Check by adding apply function</p>

```<code>function workerInit(scope) {
    var data = scope.vm.graphData;
    graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
        scope.$apply(function () {
          postWorkerResponse(response);
          //Check here able to access scope
        });
    });
    nodesinQueue.push(data.node[0].id)
}
</code>```

Body:
Below function is being called from directive link function. My problem is, I cant able to access scope inside then function

function workerInit(scope) {
        var data = scope.vm.graphData;
        graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
            postWorkerResponse(response);
            //scope is not defined
        })

        nodesinQueue.push(data.node[0].id)
    }

My factory code

app.factory("graphViewService",['$q',function($q){

    var graphViewService = {};
    var worker = new Worker('./app/modules/common/graphViewWorker.js');
    var defer = $q.defer();
    worker.addEventListener('message', function(e) {
    defer.resolve(e.data);
    }, false);

    return {
        send : function(data){
            defer = $q.defer();
            worker.postMessage(data); // Send data to our worker.
            return defer.promise;
        }
    };

}])

My Directive Code(removed unnecessary function def from original)

    (function () {
    var app = angular.module('sureApp');
    app.directive('graphView', function ($rootScope, graphViewService) {

        var controller = function () {
            var vm = this;
            //controller code
        };

        var linkFunction = function (scope, elem, attrs) {
            var el = angular.element(elem);
            var graph = graphInit(scope, scope.vm.graphData.node[0]);
            nodes = new vis.DataSet(graph.nodeList);
            edges = new vis.DataSet(graph.edgeList);
            var container = el.find('#network')[0];
            var data = {
                nodes: nodes,
                edges: edges
            };
            network = new vis.Network(container, data, networkOptions());
            networkEvents(network, scope);
            new detailWindow(el, scope);
        }

        function graphInit(scope, node) {
            var nodeList = [];
            var edgeList = [];
            workerInit(scope);
            scope.vm.graphChips = [];
            scope.vm.graphChips.push(node.currentEntity);
            nodeList.push(updateNodeStructure(node, lIcons));
            return {
                nodeList: nodeList,
                edgeList: edgeList
            }
        }

        function workerInit(scope) {
            var data = scope.vm.graphData;
            WorkerData.url = data.url;
            WorkerData.requestHeaders = requestConfig.headers;
            graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
                postWorkerResponse(response);
                //scope is not defined
            })

            nodesinQueue.push(data.node[0].id)
            console.time("test");
        }

        function WorkerData(id, level, currentEntity){
            this.url = WorkerData.url
            this.requestHeaders = WorkerData.requestHeaders;
            this.id = id;
            this.level = level;
            this.currentEntity = currentEntity;
        }

        //removed other function def

        return {
            restrict: 'E',
            scope: {
                graphData: '=',
                detailedView: '=',
                mainEntity: '='
            },
            link: linkFunction,
            controller: controller,
            controllerAs: 'vm',
            bindToController: true,
            templateUrl: './app/modules/common/graphView.html'
        };
    })
}());

Can anyone help me on this?

Body:
Check by adding apply function

function workerInit(scope) {
    var data = scope.vm.graphData;
    graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
        scope.$apply(function () {
          postWorkerResponse(response);
          //Check here able to access scope
        });
    });
    nodesinQueue.push(data.node[0].id)
}


问:
String pattern delimiter
I have this code:

```<code>string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = @"\s?(\d+)([-])(\d+)";
</code>```

And I would like to know if there is any way to put the delimiter in the pattern instead of the ([-]) ?

答:
Additionaly I would use Regex.Escape to escape the delimiter.

```<code>$@"\s?(\d+)([{Regex.Escape(delimiter)}])(\d+)";
</code>```

For example if the delimiter is . it needs to be changed into \. because . is a special regex character which matches any character. The same goas for other characters.

Title: String pattern delimiter

Body:
I have this code:

string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = @"\s?(\d+)([-])(\d+)";

And I would like to know if there is any way to put the delimiter in the pattern instead of the ([-]) ?

Body:
Additionaly I would use Regex.Escape to escape the delimiter.

$@"\s?(\d+)([{Regex.Escape(delimiter)}])(\d+)";

For example if the delimiter is . it needs to be changed into \. because . is a special regex character which matches any character. The same goas for other characters.


问:
Pass data to User Control ASP.NET MVC
I have a user control which shows list of latest announcements. This user control would be used in almost 90% of my pages. Now my concern is how to pass data to this user control for latest announcements.

My first approach is to make a base controller and in Initialise method I pass data to user control via ViewBag/ViewData. All my other controllers derive from this base controller. This looks nice but my concern is that it may become an overkill for some simple solution existing already out there. Also I would need to make sure that no controller ever fiddles with my Viewdata/Viewbag data meant for my usercontrol.

Please let me know if this is correct way of proceeding ahead or there exists some better solution.

Thanks

答: You should use RenderAction in this kind of scenario, so that you do not have bother to pass the required data in each action method of your controllers.</p>

Title: Pass data to User Control ASP.NET MVC


问:
Should not allow the space in password field?
Need to show error message whenever i enter space in password input field using ng-pattern.</p>

答:
Use of regEx - /^\S*$/ does not allow space anywhere in the string.

```<code><form name="myForm">
   <input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
   <div data-ng-show="myForm.passInpt.$error.pattern" >White Space not allowed</div>
</form>
</code>```

DEMO:

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <form name="myForm">
    <input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
    <div data-ng-show="myForm.passInpt.$error.pattern">White Space not allowed</div>
  </form>
</body></code>```

Body:
Use of regEx - /^\S*$/ does not allow space anywhere in the string.

<form name="myForm">
   <input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
   <div data-ng-show="myForm.passInpt.$error.pattern" >White Space not allowed</div>
</form>

DEMO:

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <form name="myForm">
    <input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
    <div data-ng-show="myForm.passInpt.$error.pattern">White Space not allowed</div>
  </form>
</body>


问:
Separate numeric inside string variable using patindex
I have here a short problem.

i have a value like this

1/11
11/1
11/11
111/1
111/11

i'm trying to separate those value and put them into numeric variable.
let say for example i have numericvar1 and numericvar2

so in the 1st string numericvar1 will contain 1 and numericvar2 will contain 11

and so on.

i've tried it like this

```<code>SET @numericvar1= LEFT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder ))
SET @numericvar2= REPLACE(RIGHT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder )),'/','')
</code>```

in this code if the first number before / is in 2 digit i got the correct output. But if the first number is in 1 digit and the next number is in 2 digit like 1/11 i got the wrong output. something like this var1 = 1 and var2 = 1

did something wrong in my code? or it is not possible? please help me.

答:
Can you try something like this?</p>

```<code>DECLARE @STRNUMHOLDER VARCHAR(20)
SET @STRNUMHOLDER='111/1'
DECLARE @pos INT
SET @pos = CHARINDEX('/', @STRNUMHOLDER)
SELECT @STRNUMHOLDER AS ORIG, LEFT(@STRNUMHOLDER, @pos-1) AS NUM1, SUBSTRING(@STRNUMHOLDER, @pos+1,99) AS NUM2
</code>```

Body:
I have here a short problem.

i have a value like this

1/11
11/1
11/11
111/1
111/11

i'm trying to separate those value and put them into numeric variable.
let say for example i have numericvar1 and numericvar2

so in the 1st string numericvar1 will contain 1 and numericvar2 will contain 11

and so on.

i've tried it like this

SET @numericvar1= LEFT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder ))
SET @numericvar2= REPLACE(RIGHT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder )),'/','')

in this code if the first number before / is in 2 digit i got the correct output. But if the first number is in 1 digit and the next number is in 2 digit like 1/11 i got the wrong output. something like this var1 = 1 and var2 = 1

did something wrong in my code? or it is not possible? please help me.

Body:
Can you try something like this?

DECLARE @STRNUMHOLDER VARCHAR(20)
SET @STRNUMHOLDER='111/1'
DECLARE @pos INT
SET @pos = CHARINDEX('/', @STRNUMHOLDER)
SELECT @STRNUMHOLDER AS ORIG, LEFT(@STRNUMHOLDER, @pos-1) AS NUM1, SUBSTRING(@STRNUMHOLDER, @pos+1,99) AS NUM2


问:
Regular Expression - 12/22
I want to validate credit card expiration date something like that  Which allows me to input valid current year to future

var regex = /^((0[1-9])|(1[0-2]))\/(0[1-3]|1[0-9])$/

console.log('12/17', regex.test('12/17'))
console.log('12/22', regex.test('12/22'))
console.log('12/25', regex.test('12/25'))
console.log('00/18', regex.test('00/18'))
console.log('01/38', regex.test('01/38'))```

Thank you in advance

Title: Regular Expression - 12/22

Body:
I want to validate credit card expiration date something like that  Which allows me to input valid current year to future

var regex = /^((0[1-9])|(1[0-2]))\/(0[1-3]|1[0-9])$/

console.log('12/17', regex.test('12/17'))
console.log('12/22', regex.test('12/22'))
console.log('12/25', regex.test('12/25'))
console.log('00/18', regex.test('00/18'))
console.log('01/38', regex.test('01/38'))

Thank you in advance

Body:
You can try that:

^(0[1-9]|1[0-2])\/(1[7-9]|[2-9]\d)$

var regex = /^(0[1-9]|1[0-2])\/(1[7-9]|[2-9]\d)$/g

console.log('12/25', regex.test('12/25'))
console.log('13/25', regex.test('13/25'))
console.log('01/18', regex.test('01/18'))
console.log('00/18', regex.test('00/18'))
console.log('01/18', regex.test('01/38'))
console.log('01/31', regex.test('01/38'))


问:
Java Jdk Installer won't start after UAC notification
Problem installing java jdk-8u131-windows-x64. Tried disabling firewall & antivirus....After clicking YES on the UAC Notification nothing happens...it even does not give any errors.</p>

答:
Try to execute jdk as administrator  ]
         or
Try to execute jdk in compatible mode as window 7
         or
If any of the above doesn't work either your jdk is corrupted  or your any other program is stopping to install java. So for that download a fresh new jdk and try to install
else
Run windows in safe mode and then install

I m sure that any of the above method will work surely


问:
Swift iOS: Set Gradient Background To A UITextView?
I'm trying to apply gradient background to a UITextView object, not sure if it's possible because I get white background instead.

Here is my UIView extension:

```<code>extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}
</code>```

Here where I assign gradient to the text view:

```<code>        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt
</code>```

Here are the colors in the Constants class:

```<code>    struct Colors{
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}
</code>```

I always get white background when using the gradient method. Appreciate any suggestions.

答:
Please check your code Output

Hi Folk try like that hope you helps,

```<code>    let titleStr = "Hi How are you ?"
    let detailStr = "HI How UR preparation..."
    gradientTextview.translatesAutoresizingMaskIntoConstraints = false
    gradientTextview.bottomAnchor.constraint(equalTo:self.view.bottomAnchor).isActive = true
    gradientTextview.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -8).isActive = true
    gradientTextview.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 8).isActive = true
    gradientTextview.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.5).isActive = true

    gradientTextview.setGradient(startColor: UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1), endColor: UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1))

    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont (name: "HelveticaNeue-Bold", size: 20)! , NSForegroundColorAttributeName: UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont (name: "HelveticaNeue-Bold", size: 18)! , NSForegroundColorAttributeName:UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.characters.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    gradientTextview.attributedText = attributedTxt
</code>```

===============================================================

```<code>extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}
</code>```

NOTE:-

instead of view you can add self.gradientTextview also...

Body:
I'm trying to apply gradient background to a UITextView object, not sure if it's possible because I get white background instead.

Here is my UIView extension:

extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}

Here where I assign gradient to the text view:

        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt

Here are the colors in the Constants class:

    struct Colors{
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}

I always get white background when using the gradient method. Appreciate any suggestions.

Body:
Please check your code Output

Hi Folk try like that hope you helps,

    let titleStr = "Hi How are you ?"
    let detailStr = "HI How UR preparation..."
    gradientTextview.translatesAutoresizingMaskIntoConstraints = false
    gradientTextview.bottomAnchor.constraint(equalTo:self.view.bottomAnchor).isActive = true
    gradientTextview.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -8).isActive = true
    gradientTextview.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 8).isActive = true
    gradientTextview.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.5).isActive = true

    gradientTextview.setGradient(startColor: UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1), endColor: UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1))

    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont (name: "HelveticaNeue-Bold", size: 20)! , NSForegroundColorAttributeName: UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont (name: "HelveticaNeue-Bold", size: 18)! , NSForegroundColorAttributeName:UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.characters.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    gradientTextview.attributedText = attributedTxt

===============================================================

extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}

NOTE:-

instead of view you can add self.gradientTextview also...


问:
Error using Windows Handle Selelnium
Below is the code that I wrote where i am using windows handle to validate the url new window being opened after clicking on a link into new page.

```<code>package pages;

import java.io.IOException;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import appSetup_Maven.test.BaseClass;

public class HelpCenter extends BaseClass {

    @Test
    public void Kb() throws IOException {
        Login();
        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a")).click();

        Object[] handle = driver.getWindowHandles().toArray();

        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[4]/a")).click();
        driver.switchTo().window((String) handle[0]);
        String URL = driver.getCurrentUrl();
        System.out.println(URL);
        Assert.assertEquals(URL, "https://preprod.xyz.com/home");
        driver.switchTo().window((String) handle[1]);
        driver.getTitle();
        Assert.assertEquals(URL, "https://kb.xyz.com/");
    }

}
</code>```

However the above code is not working at it fails and gives the below error -

```<code>java.lang.ArrayIndexOutOfBoundsException: 1
    at pages.HelpCenter.Kb(HelpCenter.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:744)
    at org.testng.TestRunner.run(TestRunner.java:602)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
</code>```

答:
As a Test Engineer, my first point is getting to know the meaning of error and caused it. It can be easily debugged using the traceback that the IDE provides. You should refer to the documentation, and then try to apply logic why it failed.

Now, if I see your code, the exception that comes it ArrayIndexOutOfBoundsException. As per the documentation from Oracle, this is what they say about ArrayIndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

And, then your traceback, suggests, this is at line 25

```<code>     at pages.HelpCenter.Kb(HelpCenter.java:25)
</code>```

which indicates to this piece of code

```<code>     driver.switchTo().window((String) handle[1]);
</code>```

The array that you created doesn't has element at index 1, and so it throws this error.

The reasons may include -

You're not giving enough time for WebDriver to recognise the window. I would suggest adding a Wait after you click on the web element, before switching to the window.

Using an Object array to get the windows. You are getting an array of Objects, and then converting this back to String? Why is that? Unless there is an need to be converted to Objects, I don't think you need an array of Objects. You can simply use String for the window handles itself. Try to simplify your code.

You can use something like

```<code>      String parentWindowHandler = driver.getWindowHandle();
      String subWindowHandler = null;

      Set<String> handles = driver.getWindowHandles();
      Iterator<String> iterator = handles.iterator();
      while (iterator.hasNext())
     {
      subWindowHandler = iterator.next();
      driver.switchTo().window(subWindowHandler);

       System.out.println(subWindowHandler);
      }

      driver.switchTo().window(parentWindowHandler);
</code>```

Here is an excellent post on IndexOutOfBoundsException.

Title: Error using Windows Handle Selelnium

Body:
Below is the code that I wrote where i am using windows handle to validate the url new window being opened after clicking on a link into new page.

package pages;

import java.io.IOException;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import appSetup_Maven.test.BaseClass;

public class HelpCenter extends BaseClass {

    @Test
    public void Kb() throws IOException {
        Login();
        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a")).click();

        Object[] handle = driver.getWindowHandles().toArray();

        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[4]/a")).click();
        driver.switchTo().window((String) handle[0]);
        String URL = driver.getCurrentUrl();
        System.out.println(URL);
        Assert.assertEquals(URL, "https://preprod.xyz.com/home");
        driver.switchTo().window((String) handle[1]);
        driver.getTitle();
        Assert.assertEquals(URL, "https://kb.xyz.com/");
    }

}

However the above code is not working at it fails and gives the below error -

java.lang.ArrayIndexOutOfBoundsException: 1
    at pages.HelpCenter.Kb(HelpCenter.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:744)
    at org.testng.TestRunner.run(TestRunner.java:602)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)

Body:
As a Test Engineer, my first point is getting to know the meaning of error and caused it. It can be easily debugged using the traceback that the IDE provides. You should refer to the documentation, and then try to apply logic why it failed.

Now, if I see your code, the exception that comes it ArrayIndexOutOfBoundsException. As per the documentation from Oracle, this is what they say about ArrayIndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

And, then your traceback, suggests, this is at line 25

     at pages.HelpCenter.Kb(HelpCenter.java:25)

which indicates to this piece of code

     driver.switchTo().window((String) handle[1]);

The array that you created doesn't has element at index 1, and so it throws this error.

The reasons may include -

You're not giving enough time for WebDriver to recognise the window. I would suggest adding a Wait after you click on the web element, before switching to the window.

Using an Object array to get the windows. You are getting an array of Objects, and then converting this back to String? Why is that? Unless there is an need to be converted to Objects, I don't think you need an array of Objects. You can simply use String for the window handles itself. Try to simplify your code.

You can use something like

      String parentWindowHandler = driver.getWindowHandle();
      String subWindowHandler = null;

      Set<String> handles = driver.getWindowHandles();
      Iterator<String> iterator = handles.iterator();
      while (iterator.hasNext())
     {
      subWindowHandler = iterator.next();
      driver.switchTo().window(subWindowHandler);

       System.out.println(subWindowHandler);
      }

      driver.switchTo().window(parentWindowHandler);

Here is an excellent post on IndexOutOfBoundsException.


问:
elm-css: What happened to mixins in elm-css 9.0?
My code broke when I upgraded from elm-css 8.x to 9.0. It looks like mixins are no longer in the documentation. What happened to them, or what were mixins replaced with?</p>

答:
It seems Mixins were replaced with Styles. You can compose Styles to make other Styles (which essentially is what mixins are for in preprocessors like Sass or Less)

This Elm code ...

```<code>greenOnHover : Mixin
greenOnHover =
   mixin
        [ hover [ color (rgb 0 0 122) ]
        ]
</code>```

should be replaced with

```<code>greenOnHover : Style
greenOnHover =
    batch
        [ hover [ color (rgb 0 0 122) ]
        ]
</code>```

There is some information in this pull request

Body:
It seems Mixins were replaced with Styles. You can compose Styles to make other Styles (which essentially is what mixins are for in preprocessors like Sass or Less)

This Elm code ...

greenOnHover : Mixin
greenOnHover =
   mixin
        [ hover [ color (rgb 0 0 122) ]
        ]

should be replaced with

greenOnHover : Style
greenOnHover =
    batch
        [ hover [ color (rgb 0 0 122) ]
        ]

There is some information in this pull request


问:
Best-First search in Boost Graph Library
I am starting to work with boost graph library. I need a best-first search, which I could implement using astar_search by having zero costs. (Please correct me if I'm wrong.)

However, I wonder if there is another possibility of doing this? If the costs are not considered, the algorithm should be slightly more efficient.

EDIT: Sorry for the unclear description. I am actually implementing a potential field search, so I don't have any costs/weights associated with the edges but rather need to do a steepest-descent-search (which can overcome local minima).

Thanks for any hints!

答:
You could definitely use A* to tackle this; you'd need h(x) to be 0 though, not g(x). A* rates nodes based on F which is defined by

```<code>F(n) = g(n) + h(n).

TotalCost = PathCost + Heuristic.
</code>```

g(n) = Path cost, the distance from the initial to the current state

h(n) = Heuristic, the estimation of cost from current state to end state.

From Wikipedia:

Dijkstra's algorithm, as another
  example of a best-first search
  algorithm, can be viewed as a special
  case of A* where h(x) = 0 for all x.

Body:
You could definitely use A* to tackle this; you'd need h(x) to be 0 though, not g(x). A* rates nodes based on F which is defined by

F(n) = g(n) + h(n).

TotalCost = PathCost + Heuristic.

g(n) = Path cost, the distance from the initial to the current state

h(n) = Heuristic, the estimation of cost from current state to end state.

From Wikipedia:

Dijkstra's algorithm, as another
  example of a best-first search
  algorithm, can be viewed as a special
  case of A* where h(x) = 0 for all x.


问:
React router loading route on every page
```<code><HashRouter>
        <div>
          <Route path={"/"} component={Home} />
          <Route path={"/component"} component={AnotherComp} />
          <Route path={"*"} component={NotFound} />
        </div>
      </HashRouter>
</code>```

Basically I have this code. and what I want is that when you go to just / it will render the home page but then adding a path will go to that page. However, I have 2 problems. Firstly, for some reason the home page is rendered on every page but with the content of the path page too. so / gives me home (this is correct). /component renders the AnotherComp component AND the home page. I just want it to render the single component. Another problem is that my * route is also rendering on all pages.
how can I get it so home only renders on /, and * only renders when the path is not known?

答:
Try adding exact to the route.

```<code><Route exact path={"/"} component={Home} />
</code>```

If you want a route that gets a hit on any unknown url you can use a switch statement.

```<code><HashRouter>
    <div>
        <Switch>
            <Route exact path={"/"} component={Home} />
            <Route exact path={"/component"} component={AnotherComp} />
            <Route path={"*"} component={NotFound} />
        </Switch>
    </div>
</HashRouter>
</code>```

Body:
<HashRouter>

          <Route path={"/"} component={Home} />
          <Route path={"/component"} component={AnotherComp} />
          <Route path={"*"} component={NotFound} />

      </HashRouter>

Basically I have this code. and what I want is that when you go to just / it will render the home page but then adding a path will go to that page. However, I have 2 problems. Firstly, for some reason the home page is rendered on every page but with the content of the path page too. so / gives me home (this is correct). /component renders the AnotherComp component AND the home page. I just want it to render the single component. Another problem is that my * route is also rendering on all pages.
how can I get it so home only renders on /, and * only renders when the path is not known?

Body:
Try adding exact to the route.

<Route exact path={"/"} component={Home} />

If you want a route that gets a hit on any unknown url you can use a switch statement.

<HashRouter>
    <div>
        <Switch>
            <Route exact path={"/"} component={Home} />
            <Route exact path={"/component"} component={AnotherComp} />
            <Route path={"*"} component={NotFound} />
        </Switch>
    </div>
</HashRouter>


问:
Find word in List and Delete it
I need find a Word in list of char and delete it from that.

The predicate ocurre([List],[Word],[CleanList]).

```<code>[List] is a list of elements for example [a,b,c,d].
[Word] contains in a list the word that I must find in List for example [b,c]
[CleanList] return List with out Word (in the example [a,d])
</code>```

The Program is:

```<code>ocurre([X|LS],[X|P],Aux):- ocurre(LS,P,Aux),!.
ocurre([X|LS],[Y|P],Aux):- concatenar(Aux,[X],Aux2),
                           ocurre(LS,[Y|P],Aux2).
ocurre([],[],Aux):-!.
ocurre([],P,Aux):-!.
ocurre(LS,[],[Aux|LS]):-!.

concatenar([],X,X):-!.
concatenar([X|Y],R,[X|M]):- concatenar(Y,R,M).
</code>```

So, when I consult ocurre([a,b,c,d] , [b,c] , L). My program return L=[] and It must return L=[a,d]. I don't know what it's wrong. I appreciate your help

答:
a library(lists) based alternative:</p>

```<code>?- [user].
ocurre(List,Word,CleanList) :-
|:       append([Left,Word,Right], List),
|:       append(Left,Right,CleanList).
|:
|: ^Dtrue.

?- ocurre([a,b,c,d] , [b,c] , L).
L = [a, d] ;
false.
</code>```

Title: Find word in List and Delete it

Body:
I need find a Word in list of char and delete it from that.

The predicate ocurre([List],[Word],[CleanList]).

[List] is a list of elements for example [a,b,c,d].
[Word] contains in a list the word that I must find in List for example [b,c]
[CleanList] return List with out Word (in the example [a,d])

The Program is:

ocurre([X|LS],[X|P],Aux):- ocurre(LS,P,Aux),!.
ocurre([X|LS],[Y|P],Aux):- concatenar(Aux,[X],Aux2),
                           ocurre(LS,[Y|P],Aux2).
ocurre([],[],Aux):-!.
ocurre([],P,Aux):-!.
ocurre(LS,[],[Aux|LS]):-!.

concatenar([],X,X):-!.
concatenar([X|Y],R,[X|M]):- concatenar(Y,R,M).

So, when I consult ocurre([a,b,c,d] , [b,c] , L). My program return L=[] and It must return L=[a,d]. I don't know what it's wrong. I appreciate your help

Body:
a library(lists) based alternative:

?- [user].
ocurre(List,Word,CleanList) :-
|:       append([Left,Word,Right], List),
|:       append(Left,Right,CleanList).
|:
|: ^Dtrue.

?- ocurre([a,b,c,d] , [b,c] , L).
L = [a, d] ;
false.


答:
If you are in your project folder then your command will be

```<code>./darknet detector test cfg/voc.data cfg/yolo-voc.cfg yolo-voc.weights data/dog.jpg
</code>```

I hope this helps...
Check your .weights file name

Title: Testing using YOLO version 2

Body:
I get the following error while running yolo v2. Yolo and tiny yolo works fine. Any leads will be appreciated

./darknet detector test ./cfg/voc.data ./cfg/yolo-voc.cfg ./yolo-     voc.weights data/dog.jpg
layer filters size input output
0 conv 32 3 x 3 / 1 416 x 416 x 3 -> 416 x 416 x 32
1 max 2 x 2 / 2 416 x 416 x 32 -> 208 x 208 x 32
2 conv 64 3 x 3 / 1 208 x 208 x 32 -> 208 x 208 x 64
3 max 2 x 2 / 2 208 x 208 x 64 -> 104 x 104 x 64
4 conv 128 3 x 3 / 1 104 x 104 x 64 -> 104 x 104 x 128
5 conv 64 1 x 1 / 1 104 x 104 x 128 -> 104 x 104 x 64
6 conv 128 3 x 3 / 1 104 x 104 x 64 -> 104 x 104 x 128
7 max 2 x 2 / 2 104 x 104 x 128 -> 52 x 52 x 128
8 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256
9 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128
10 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256
11 max 2 x 2 / 2 52 x 52 x 256 -> 26 x 26 x 256
12 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512
13 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256
14 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512
15 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256
16 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512
17 max 2 x 2 / 2 26 x 26 x 512 -> 13 x 13 x 512
18 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024
19 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512
20 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024
21 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512
22 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024
23 conv 1024 3 x 3 / 1 13 x 13 x1024 -> 13 x 13 x1024
24 Killed

Body:
If you are in your project folder then your command will be

./darknet detector test cfg/voc.data cfg/yolo-voc.cfg yolo-voc.weights data/dog.jpg

I hope this helps...
Check your .weights file name