问:
How to fix invalid prop 'color' suplied to 'icon'?
I’m setting up a new component with an icon from the "react-native-vector-icons" and I got a yellow warning.

This is for a new feature of the icon

```<code>Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                // HERE IS THE PROBLEM //
            return <SSIcon name={'home'} size={20} color={focused ? GStyle.GREEN : Color(GStyle.BLACK).alpha(.45)} />

            },

        }
    },
</code>```

I expect for no yellow warning

答:
in your application's root index.js add this line:

```<code>console.disableYellowBox = true;
</code>```

Body:
I’m setting up a new component with an icon from the "react-native-vector-icons" and I got a yellow warning.

This is for a new feature of the icon

Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                // HERE IS THE PROBLEM //
            return <SSIcon name={'home'} size={20} color={focused ? GStyle.GREEN : Color(GStyle.BLACK).alpha(.45)} />

            },

        }
    },

I expect for no yellow warning

Body:
in your application's root index.js add this line:

console.disableYellowBox = true;


来源: stackexchange

问:
Is there a way to define a Dynamic Table comprised of entries that have NOT been touched by an event recently?
I'm new to Flink and I'm trying to use it to have a bunch of live views of my application. At least one of the dynamic views I'd like to build would be to show entries that have not met an SLA -- or essentially expired -- and the condition for this would be a simple timestamp comparison. So I would basically want an entry to show up in my dynamic table if it has NOT been touched by an event recently. In playing around with Flink 1.6 (constrained to this due to AWS Kinesis) in a dev environment, I'm not seeing that Flink is re-evaluating a condition unless an event touches that entry.

I've got my dev environment plugged into a Kinesis stream that's sending in live access log events from a web server. This isn't my real use case but it was an easy one to begin testing with. I've written a simple table query that pulls in a request path, its last access time, and computes a boolean flag to indicate whether it hasn't been accessed in the last minute. I'm debugging this via a retract stream connected to PrintSinkFunction so all updates/deletes are printed to my console.

tEnv.registerDataStream("AccessLogs", accessLogs, "username, status, request, responseSize, referrer, userAgent, requestTime, ActionTime.rowtime");

Table paths = tEnv.sqlQuery("SELECT request AS path, MAX(requestTime) as lastTime, CASE WHEN MAX(requestTime) < CURRENT_TIMESTAMP - INTERVAL '1' MINUTE THEN 1 ELSE 0 END AS expired FROM AccessLogs GROUP BY request");

DataStream<Tuple2<Boolean, Row>> retractStream = tEnv.toRetractStream(paths, Row.class);
retractStream .addSink(new PrintSinkFunction<>());
```

<p>I expect that when I access a page, an Add event is sent to this stream. Then if I wait 1 minute (do nothing), the CASE statement in my table will evaluate to 1, so I should see a Delete and then Add event with that flag set.</p>

<p>What I actually see is that nothing happens until I load that page again. The Delete event actually has the flag set, while the Add event that immediate follows that has it cleared again (as it should since it's no longer "expired).</p>

```// add/delete, path, lastAccess, expired
(true,/mypage,2019-05-20 20:02:48.0,0) // first page load, add event
(false,/mypage,2019-05-20 20:02:48.0,1) // second load > 2 mins later, remove event for the entry with expired flag set
(true,/mypage,2019-05-20 20:05:01.0,0) // second load, add event
```

Edit: The most useful tip I've come across in my searching is to create a ProcessFunction. I think this is something I could make work with my dynamic tables (in some cases I'd end up with intermediate streams to look at computed dates), but hopefully it doesn't have to come to that.

I've gotten the ProcessFunction approach to work but it required a lot more tinkering than I initially thought it would:

I had to add a field to my POJO that changes in the onTimer() method (could be a date or a version that you simply bump each time)

I had to register this field as part of the dynamic table

I had to use this field in my query in order for the query to get re-evaluated and change the boolean flag (even though I don't actually use the new field). I just added it as part of my SELECT clause.

答:
Your approach looks promising but a comparison with a moving "now" timestamp is not supported by Flink's Table API / SQL (yet).

I would solve this in two steps.

register the dynamic table in upsert mode, i.e., a table that is upserted per key (request in your case) based on a version timestamp (requestTime in your case). The resulting dynamic table would hold the latest row for every request.

Have a query with a simple filter predicate like yours that compares the version timestamp of the rows of the dynamic (upsert) table and filters out all rows that have timestamps which are too close to now.

Unfortunately, neither of both features (upsert conversions and comparisons against the moving "now" timestamp) are available in Flink, yet. There is some ongoing work for upsert table conversions though.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Flink and I'm trying to use it to have a bunch of live views of my application. At least one of the dynamic views I'd like to build would be to show entries that have not met an SLA -- or essentially expired -- and the condition for this would be a simple timestamp comparison. So I would basically want an entry to show up in my dynamic table if it has NOT been touched by an event recently. In playing around with Flink 1.6 (constrained to this due to AWS Kinesis) in a dev environment, I'm not seeing that Flink is re-evaluating a condition unless an event touches that entry.

I've got my dev environment plugged into a Kinesis stream that's sending in live access log events from a web server. This isn't my real use case but it was an easy one to begin testing with. I've written a simple table query that pulls in a request path, its last access time, and computes a boolean flag to indicate whether it hasn't been accessed in the last minute. I'm debugging this via a retract stream connected to PrintSinkFunction so all updates/deletes are printed to my console.

tEnv.registerDataStream("AccessLogs", accessLogs, "username, status, request, responseSize, referrer, userAgent, requestTime, ActionTime.rowtime");

Table paths = tEnv.sqlQuery("SELECT request AS path, MAX(requestTime) as lastTime, CASE WHEN MAX(requestTime) < CURRENT_TIMESTAMP - INTERVAL '1' MINUTE THEN 1 ELSE 0 END AS expired FROM AccessLogs GROUP BY request");

DataStream<Tuple2<Boolean, Row>> retractStream = tEnv.toRetractStream(paths, Row.class);
retractStream .addSink(new PrintSinkFunction<>());

I expect that when I access a page, an Add event is sent to this stream. Then if I wait 1 minute (do nothing), the CASE statement in my table will evaluate to 1, so I should see a Delete and then Add event with that flag set.

What I actually see is that nothing happens until I load that page again. The Delete event actually has the flag set, while the Add event that immediate follows that has it cleared again (as it should since it's no longer "expired).

// add/delete, path, lastAccess, expired
(true,/mypage,2019-05-20 20:02:48.0,0) // first page load, add event
(false,/mypage,2019-05-20 20:02:48.0,1) // second load > 2 mins later, remove event for the entry with expired flag set
(true,/mypage,2019-05-20 20:05:01.0,0) // second load, add event

Edit: The most useful tip I've come across in my searching is to create a ProcessFunction. I think this is something I could make work with my dynamic tables (in some cases I'd end up with intermediate streams to look at computed dates), but hopefully it doesn't have to come to that.

I've gotten the ProcessFunction approach to work but it required a lot more tinkering than I initially thought it would:

I had to add a field to my POJO that changes in the onTimer() method (could be a date or a version that you simply bump each time)

I had to register this field as part of the dynamic table

I had to use this field in my query in order for the query to get re-evaluated and change the boolean flag (even though I don't actually use the new field). I just added it as part of my SELECT clause.


问:
Creating a range for a field from internal table using RTTS
I want to create a function/custom class method that takes in 2 parameters:

1) IM_ITAB type ANY TABLE

2) IM_COMPONENT type STRING

and returns 1 parameter:

1) EX_RANGE type PIQ_SELOPT_T

So, algorithm is like this:

First of all, we check if the column with a component name at all exists

Then, we check that internal table is not empty.

Then, we loop through internal table assigning component and filling range table. Code is below.

```<code>METHODS compose_range_from_itab
    IMPORTING
      IM_ITAB      type ANY TABLE
      IM_COMPONENT type STRING
    EXPORTING
      EX_RANGE     type PIQ_SELOPT_T.
...
METHOD compose_range_from_itab.

  DATA: lo_obj   TYPE REF TO cl_abap_tabledescr,
        wa_range TYPE selopt,
        lt_range TYPE piq_selopt_t.

  FIELD-SYMBOLS: <fs_line> TYPE ANY,
                 <fs_component> TYPE ANY.

  lo_obj ?= cl_abap_typedescr=>describe_by_data( p_data = im_itab ).

  READ TABLE lo_obj->key TRANSPORTING NO FIELDS WITH KEY name = im_component.

  IF sy-subrc IS INITIAL.

    IF LINES( im_itab ) GT 0.

      LOOP AT im_itab ASSIGNING <fs_line>.

        ASSIGN COMPONENT im_component OF STRUCTURE <fs_line> TO <fs_component>.

        wa_range-sign = 'I'.
        wa_range-option = 'EQ'.
        wa_range-low = <fs_component>.

        APPEND wa_range TO lt_range.

      ENDLOOP.

      SORT lt_range BY low.
      DELETE ADJACENT DUPLICATES FROM lt_range COMPARING low.

      ex_range[] = lt_range[].

    ENDIF.

  ENDIF.

ENDMETHOD.
</code>```

But I want to improve the method further. If the imported internal table has, let's say, 255 columns, then it will take longer to loop through such table. But I need only one column to compose the range.

So I want to get components of internal table, then choose only one component, create a new line type containing only that component, then create internal table with that line type and copy.

Here is the pseudo code corresponding to what I want to achieve:

```<code>append corresponding fields of im_itab into new_line_type_internal_table.
</code>```

How can I "cut out" one component and create a new line type using RTTS?

答:
Surprisingly, this variant turned out to be faster:

```<code>CLASS-METHODS make_range_variant_2
  IMPORTING
    sample        TYPE table_type
    column        TYPE string
  RETURNING
    VALUE(result) TYPE range_type.

METHOD make_range_variant_2.

  TYPES:
    BEGIN OF narrow_structure_type,
      content TYPE char32,
    END OF narrow_structure_type.

  TYPES narrow_table_type TYPE STANDARD TABLE OF narrow_structure_type WITH EMPTY KEY.

  DATA narrow_table TYPE narrow_table_type.

  DATA(mapping) =
    VALUE cl_abap_corresponding=>mapping_table_value(
      ( kind = cl_abap_corresponding=>mapping_component srcname = column dstname = 'CONTENT' ) ).

  DATA(mover) =
    cl_abap_corresponding=>create_with_value(
      source      = sample
      destination = narrow_table
      mapping     = mapping ).

  mover->execute(
    EXPORTING
      source      = sample
    CHANGING
      destination = narrow_table ).

  LOOP AT narrow_table ASSIGNING FIELD-SYMBOL(<row>).

    INSERT VALUE #(
        sign   = 'I'
        option = 'EQ'
        low    = <row>-content )
      INTO TABLE result.

  ENDLOOP.

ENDMETHOD.
</code>```

CL_ABAP_CORRESPONDING delegates to a kernel function for the structure-to-structure move, which apparently is faster than the ABAP-native ASSIGN COMPONENT [...] OF STRUCTURE [...] TO FIELD-SYMBOL [...]. The actual loop then seems to be faster because it uses fixed-name assignments.

Maybe somebody could verify.

Body:
I want to create a function/custom class method that takes in 2 parameters:

1) IM_ITAB type ANY TABLE

2) IM_COMPONENT type STRING

and returns 1 parameter:

1) EX_RANGE type PIQ_SELOPT_T

So, algorithm is like this:

First of all, we check if the column with a component name at all exists

Then, we check that internal table is not empty.

Then, we loop through internal table assigning component and filling range table. Code is below.

METHODS compose_range_from_itab
    IMPORTING
      IM_ITAB      type ANY TABLE
      IM_COMPONENT type STRING
    EXPORTING
      EX_RANGE     type PIQ_SELOPT_T.
...
METHOD compose_range_from_itab.

  DATA: lo_obj   TYPE REF TO cl_abap_tabledescr,
        wa_range TYPE selopt,
        lt_range TYPE piq_selopt_t.

  FIELD-SYMBOLS: <fs_line> TYPE ANY,
                 <fs_component> TYPE ANY.

  lo_obj ?= cl_abap_typedescr=>describe_by_data( p_data = im_itab ).

  READ TABLE lo_obj->key TRANSPORTING NO FIELDS WITH KEY name = im_component.

  IF sy-subrc IS INITIAL.

    IF LINES( im_itab ) GT 0.

      LOOP AT im_itab ASSIGNING <fs_line>.

        ASSIGN COMPONENT im_component OF STRUCTURE <fs_line> TO <fs_component>.

        wa_range-sign = 'I'.
        wa_range-option = 'EQ'.
        wa_range-low = <fs_component>.

        APPEND wa_range TO lt_range.

      ENDLOOP.

      SORT lt_range BY low.
      DELETE ADJACENT DUPLICATES FROM lt_range COMPARING low.

      ex_range[] = lt_range[].

    ENDIF.

  ENDIF.

ENDMETHOD.

But I want to improve the method further. If the imported internal table has, let's say, 255 columns, then it will take longer to loop through such table. But I need only one column to compose the range.

So I want to get components of internal table, then choose only one component, create a new line type containing only that component, then create internal table with that line type and copy.

Here is the pseudo code corresponding to what I want to achieve:

append corresponding fields of im_itab into new_line_type_internal_table.

How can I "cut out" one component and create a new line type using RTTS?

Body:
Surprisingly, this variant turned out to be faster:

CLASS-METHODS make_range_variant_2
  IMPORTING
    sample        TYPE table_type
    column        TYPE string
  RETURNING
    VALUE(result) TYPE range_type.

METHOD make_range_variant_2.

  TYPES:
    BEGIN OF narrow_structure_type,
      content TYPE char32,
    END OF narrow_structure_type.

  TYPES narrow_table_type TYPE STANDARD TABLE OF narrow_structure_type WITH EMPTY KEY.

  DATA narrow_table TYPE narrow_table_type.

  DATA(mapping) =
    VALUE cl_abap_corresponding=>mapping_table_value(
      ( kind = cl_abap_corresponding=>mapping_component srcname = column dstname = 'CONTENT' ) ).

  DATA(mover) =
    cl_abap_corresponding=>create_with_value(
      source      = sample
      destination = narrow_table
      mapping     = mapping ).

  mover->execute(
    EXPORTING
      source      = sample
    CHANGING
      destination = narrow_table ).

  LOOP AT narrow_table ASSIGNING FIELD-SYMBOL(<row>).

    INSERT VALUE #(
        sign   = 'I'
        option = 'EQ'
        low    = <row>-content )
      INTO TABLE result.

  ENDLOOP.

ENDMETHOD.

CL_ABAP_CORRESPONDING delegates to a kernel function for the structure-to-structure move, which apparently is faster than the ABAP-native ASSIGN COMPONENT [...] OF STRUCTURE [...] TO FIELD-SYMBOL [...]. The actual loop then seems to be faster because it uses fixed-name assignments.

Maybe somebody could verify.


问:
Is there any best way to implement Encryption in Flex 3
we have one application where we are pulling some confidential information from one of the product design tools. So we have used HTTPS as the channel and also we are encrypting the Request Parameters and Some data before we sent it to Web Services. So, Everything seems OK.

But when we gave the application for Security auditing they found we have hard coded the encryption key in source code. They have used Sothink SWF Decompiler to look into my SWF file. They caught the key and raised concern over it.

We have developed this application using Flex 3(SDK 3.4). Is there any best way to use Secret key without being hard coded in source code. If anybody come across this kind of problem, please let me know.

Anyone, please suggest me the best way to use the secret keys in SourceCode without being Hard coded.

Here is my sample code:

```<code>var currentResult:String = "";
        var strDataToEncrypt:String = "";
        var kdata:ByteArray;

        var todayDate:Date = new Date();

        kdata = Hex.toArray(Hex.fromString("secretKey here"));
        strDataToEncrypt =username.toUpperCase() + "#$#" + password + "#$#"  + todayDate.getTime().toString();
        var data:ByteArray;
        data = Hex.toArray(Hex.fromString(strDataToEncrypt))
        var name:String = "des3-ecb";
        var pad:IPad = new PKCS5;
        var mode:ICipher = Crypto.getCipher(name, kdata, pad);
        pad.setBlockSize(mode.getBlockSize());
        mode.encrypt(data);
        currentResult = Base64.encodeByteArray(data);
        var token:String = currentResult;
</code>```

答:
don't send your data as url parameters. send it with a post request.

if that's not possible you could try implementing a scheme with a public key. but be careful, chances are high that you implement something wrong which leads to even bigger security problems.

ContentLicense: CC BY-SA 3.0

Body:
we have one application where we are pulling some confidential information from one of the product design tools. So we have used HTTPS as the channel and also we are encrypting the Request Parameters and Some data before we sent it to Web Services. So, Everything seems OK.

But when we gave the application for Security auditing they found we have hard coded the encryption key in source code. They have used Sothink SWF Decompiler to look into my SWF file. They caught the key and raised concern over it.

We have developed this application using Flex 3(SDK 3.4). Is there any best way to use Secret key without being hard coded in source code. If anybody come across this kind of problem, please let me know.

Anyone, please suggest me the best way to use the secret keys in SourceCode without being Hard coded.

Here is my sample code:

var currentResult:String = "";
        var strDataToEncrypt:String = "";
        var kdata:ByteArray;

        var todayDate:Date = new Date();

        kdata = Hex.toArray(Hex.fromString("secretKey here"));
        strDataToEncrypt =username.toUpperCase() + "#$#" + password + "#$#"  + todayDate.getTime().toString();
        var data:ByteArray;
        data = Hex.toArray(Hex.fromString(strDataToEncrypt))
        var name:String = "des3-ecb";
        var pad:IPad = new PKCS5;
        var mode:ICipher = Crypto.getCipher(name, kdata, pad);
        pad.setBlockSize(mode.getBlockSize());
        mode.encrypt(data);
        currentResult = Base64.encodeByteArray(data);
        var token:String = currentResult;


问:
Copying local production build for to production server
Our angular application build size is around 38MB (size of dist directory), and source-map's build size is 1.6MB. Our AWS instance configuration is:

Ram: 4GB.

OS: Ubuntu.

 But when we build it on the server for production, CPU usage reaches 100%, sometimes it takes 1/2hr to complete the build, sometimes it can even fail. We have two possible option for this problem:

1. While creating the production build, we set the AOT and build optimizer to false. However, it will affect our application performance during runtime.

2. We are thinking of building the production build locally from our system, then copy the build to the server (it will be done through CI/CD tools). However, developers will be using a different OS. Some will be using Windows, some will be using Linux or Mac.

1. Will there be any issue with such an approach?

2. Is there any better way to solve such a problem?

答:
Your application production build should not be 38MB.
You HAVE TO set the build optimizer to true, it will reduce a lot your build size.

It looks like you have some performances issues, and it will be hard to build your application in a CI Platform (GitlabCI, CircleCI, etc) because they limit the build time or the performances.

Before, you should really fix theses performances issues.
If you still have performances problems with build, you can change node memory limit :
./node_modules/.bin/ng build --prod --max-old-space-size

You can find more informations, directly on the Angular Documentation : https://angular.io/guide/deployment


问:
How much request is free with geocoding api?
I want to get the address from latitude/longitude using Google Geocoding API. For that, I want to know, how many no of hit can be done with a free account?

Bellow link showing the 2,500 requests per 24 hour period free.

Google Geocoding API, free?

Kindly clear me, it is still free hit exist with Google Geocoding API or not.
If no, then how many hits are free with this API?

答:
Google has changed their billing policy a while ago you should consult Usage and billing

Pay-As-You-Go Pricing

The Geocoding API uses a pay-as-you-go pricing model.

How usage and billing work under the pay-as-you-go model

The Google Maps Platform APIs are billed by SKU.

Usage is tracked for each Product SKU, and an API may have more than one Product SKU.

Cost is calculated by: SKU Usage x Price per each use.

For each billing account, for qualifying Google Maps Platform SKUs, a $200 USD Google 1. Maps Platform credit is available each month, and automatically applied to the qualifying SKUs.

See guide to understanding billing for more information.

Pricing for the Geocoding API

Under the pay-as-you-go pricing model, requests for the Geocoding API are billed using the SKU for Geocoding.

When you create a new account and connect a credit card to it you will be given $300 credit that you can use to test your application before you bring it live.


问:
Botium isn't working following the tutorial
I'm setting up Botium testing freamework to run some tests against my watson based chatbot, I'm encountering Error: WATSON_USER capability required, I'm follwoing the tutorial available here https://chatbotsmagazine.com/10-minutes-codeless-test-automation-for-ibm-watson-chatbots-d71eac9626d7

As part of the error message, it's also suggesting me to use API key, I'm not sure how to get one.

```<code>botium-cli emulator --config ./botium.json
Error: WATSON_USER capability required (or use WATSON_APIKEY)
    at BotiumConnectorWatson.Validate (/usr/local/lib/node_modules/botium-cli/node_modules/botium-connector-watson/dist/botium-connector-watson-cjs.js:60:55)
    at Validate.Validate.then (/usr/local/lib/node_modules/botium-cli/node_modules/botium-core/src/containers/PluginConnectorContainer.js:72:66)
</code>```

My config looks like:

{
    "botium": {
        "Capabilities": {
            "PROJECTNAME": "****",
            "CONTAINERMODE": "watson",
            "WATSONCONVERSATION_USER": "*****",
            "WATSONCONVERSATION_PASSWORD": "*****",
            "WATSONCONVERSATION_WORKSPACE_ID": "****",
            "WATSONCONVERSATION_USE_INTENT": false
        }
    }
}
```

答:
The capability names in Botium have changed a while ago, you can find documentation on the valid capabilities for the Botium Watson Connector on Github: https://github.com/codeforequity-at/botium-connector-watson

I updated the article you mentioned with the new capability names. The botium.json should look like this (see article):

Body:
I'm setting up Botium testing freamework to run some tests against my watson based chatbot, I'm encountering Error: WATSON_USER capability required, I'm follwoing the tutorial available here https://chatbotsmagazine.com/10-minutes-codeless-test-automation-for-ibm-watson-chatbots-d71eac9626d7

As part of the error message, it's also suggesting me to use API key, I'm not sure how to get one.

botium-cli emulator --config ./botium.json
Error: WATSON_USER capability required (or use WATSON_APIKEY)
    at BotiumConnectorWatson.Validate (/usr/local/lib/node_modules/botium-cli/node_modules/botium-connector-watson/dist/botium-connector-watson-cjs.js:60:55)
    at Validate.Validate.then (/usr/local/lib/node_modules/botium-cli/node_modules/botium-core/src/containers/PluginConnectorContainer.js:72:66)

My config looks like:

{
    "botium": {
        "Capabilities": {
            "PROJECTNAME": "****",
            "CONTAINERMODE": "watson",
            "WATSONCONVERSATION_USER": "*****",
            "WATSONCONVERSATION_PASSWORD": "*****",
            "WATSONCONVERSATION_WORKSPACE_ID": "****",
            "WATSONCONVERSATION_USE_INTENT": false
        }
    }
}


问:
Oracle query to filter and sort table based on values in child table
I am using Oracle 11g, and I have tables with data and structure as follows:

```<code>TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 2 | Jane   | 40  |
 3 | Agatha | 45  |
-------------------

TABLE2_CHILD
==============================================
CID | Name       | Age | Class | House | PID |
----------------------------------------------
 1 | John        | 7  |    3   | Red   |  1  |
 2 | Marie       | 5  |    1   | Yellow|  2  |
 3 | Petra       | 6  |    2   | Green |  3  |
 4 | Taylor      | 8  |    4   | Blue  |  2  |
 5 | Lean        | 9  |    5   | Red   |  2  |
 6 | Justin      | 7  |    3   | Yellow|  3  |
 7 | Arianna     | 5  |    1   | Blue  |  3  |
 8 | Brendon     | 6  |    2   | Green |  3  |
 9 | Shawn       | 7  |    3   | Red   |  1  |
----------------------------------------------
</code>```

For a single condition, the query is simple:

```<code>SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7);
</code>```

which will result in the following result:

```<code>TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 3 | Agatha | 45  |
-------------------
</code>```

However, if I want to fetch the list of parents whose children are of age=7 and belong to house='GREEN', if I write a query as below:

```<code>SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7 AND house='GREEN');
</code>```

I would get no results.

I am expecting the result to be :

```<code>TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 3 | Agatha | 45  |
-------------------
</code>```

since Agatha has a child belonging to age=7, and a child belonging to house='GREEN'.

I was able to come up with a solution for a similar data structure using Java streams. I am trying to do the same using Oracle SQL.

```<code>List<Parent> filteredParents = parents.stream()
                .filter(parent -> parent.getChildren().stream()
                        .anyMatch(child -> child.getAge().equals("7")) && parent.getChildren().stream()
                        .anyMatch(child -> child.getHouse().equalsIgnoreCase("Green")))
                .collect(Collectors.toList());

</code>```

I am expecting the query to give me a result where the conditions could match any of the children. Because, the filtering is happening at the Parent level.

Any help would be great. Thanks!

答:
You can do it with EXISTS:

```<code>SELECT t.*
FROM TABLE1_PARENT t
WHERE t.PID IN (
  SELECT PID FROM TABLE2_CHILD WHERE AGE=7
) AND EXISTS (
  SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND House = 'Green'
)
</code>```

The problem with your query is that it tries to apply both conditions in the same row inside TABLE2_CHILD. But this is not what you want.

You want the parent ids for which children rows have AGE = 7 and there is a row inside TABLE2_CHILD with House = 'Green'.

You could use EXISTS for both conditions, which may be more efficient:

```<code>SELECT t.*
FROM TABLE1_PARENT t
WHERE EXISTS (
  SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND AGE=7
) AND EXISTS (
  SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND House = 'Green'
)
</code>```

or with conditional aggregation by grouping the child table by PID:

```<code>SELECT * FROM TABLE1_PARENT
WHERE PID IN (
  SELECT PID
  FROM TABLE2_CHILD
  GROUP BY PID
  HAVING
    SUM(CASE WHEN Age = 7 THEN 1 ELSE 0 END) > 0
    AND
    SUM(CASE WHEN House = 'Green' THEN 1 ELSE 0 END) > 0
)
</code>```

Body:
I am using Oracle 11g, and I have tables with data and structure as follows:

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 2 | Jane   | 40  |
 3 | Agatha | 45  |
-------------------

TABLE2_CHILD
==============================================
CID | Name       | Age | Class | House | PID |
----------------------------------------------
 1 | John        | 7  |    3   | Red   |  1  |
 2 | Marie       | 5  |    1   | Yellow|  2  |
 3 | Petra       | 6  |    2   | Green |  3  |
 4 | Taylor      | 8  |    4   | Blue  |  2  |
 5 | Lean        | 9  |    5   | Red   |  2  |
 6 | Justin      | 7  |    3   | Yellow|  3  |
 7 | Arianna     | 5  |    1   | Blue  |  3  |
 8 | Brendon     | 6  |    2   | Green |  3  |
 9 | Shawn       | 7  |    3   | Red   |  1  |
----------------------------------------------

For a single condition, the query is simple:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7);

which will result in the following result:

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 3 | Agatha | 45  |
-------------------

However, if I want to fetch the list of parents whose children are of age=7 and belong to house='GREEN', if I write a query as below:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7 AND house='GREEN');

I would get no results.

I am expecting the result to be :

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 3 | Agatha | 45  |
-------------------

since Agatha has a child belonging to age=7, and a child belonging to house='GREEN'.

I was able to come up with a solution for a similar data structure using Java streams. I am trying to do the same using Oracle SQL.

List<Parent> filteredParents = parents.stream()
                .filter(parent -> parent.getChildren().stream()
                        .anyMatch(child -> child.getAge().equals("7")) && parent.getChildren().stream()
                        .anyMatch(child -> child.getHouse().equalsIgnoreCase("Green")))
                .collect(Collectors.toList());

I am expecting the query to give me a result where the conditions could match any of the children. Because, the filtering is happening at the Parent level.

Any help would be great. Thanks!

Body:
You can do it with EXISTS:

SELECT t.*
FROM TABLE1_PARENT t
WHERE t.PID IN (
  SELECT PID FROM TABLE2_CHILD WHERE AGE=7
) AND EXISTS (
  SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND House = 'Green'
)

The problem with your query is that it tries to apply both conditions in the same row inside TABLE2_CHILD. But this is not what you want.

You want the parent ids for which children rows have AGE = 7 and there is a row inside TABLE2_CHILD with House = 'Green'.

You could use EXISTS for both conditions, which may be more efficient:

SELECT t.*
FROM TABLE1_PARENT t
WHERE EXISTS (
  SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND AGE=7
) AND EXISTS (
  SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND House = 'Green'
)

or with conditional aggregation by grouping the child table by PID:

SELECT * FROM TABLE1_PARENT
WHERE PID IN (
  SELECT PID
  FROM TABLE2_CHILD
  GROUP BY PID
  HAVING
    SUM(CASE WHEN Age = 7 THEN 1 ELSE 0 END) > 0
    AND
    SUM(CASE WHEN House = 'Green' THEN 1 ELSE 0 END) > 0
)


问:
Is there any way to specify that multiple versions of a dependency are valid for my library?
I am using a library that breaks depending on which other crates  I am using. The way around is to downgrade a few dependencies and keep a local version of the library.

It works if I put MyLibraryDep = {version = "*"} in my Cargo.toml. Since Cargo will then fix dependencies automatically, but crates.io doesn't allow for that.

Example:

If using MyLibrary, and LibraryA I have to use MyLibraryDep v0.1.0 in MyLibrary

If using MyLibrary, and LibraryB I have to use MyLibraryDep v0.2.0 in MyLibrary

答:
As specified in the Cargo book, you can use inequality requirements and multiple requirements combined to form a range of valid versions.

```<code>MyLibraryDep = {version = ">=0.1.0, <=0.2.0"}
</code>```

Such a requirement will also allow Cargo to choose the appropriate version and should be allowed by crates.io.

Body:
As specified in the Cargo book, you can use inequality requirements and multiple requirements combined to form a range of valid versions.

MyLibraryDep = {version = ">=0.1.0, <=0.2.0"}

Such a requirement will also allow Cargo to choose the appropriate version and should be allowed by crates.io.


问:
Find questions with multiple tags (AND, not OR)
How can I find questions that are tagged with multiple tags, for example, BOTH regex AND python?

I've found answers on meta about using the browser to search multiple tags, but this question is specific to the SEDE: https://data.stackexchange.com

In the table Posts, the column Tags are stored as ncharv(250) and tags are appended to the string (not stored as array). In the browser, it looks like this

I only need the question (and answer) text for some text mining, so I had tried going direct to the Posts table:

pseudo_sql

select * from Posts where Tags in (tag_list)

this returns tag1 OR tag2

select * from Posts p1 inner join Posts p2 ON p1.Tags in (tag1) AND p2.Tags in (tag2)

I've also tried a larger query based on this popular query.

答:
For multiple tags, one inefficient way to use SEDE is multiple LIKE statements

```<code>SELECT TOP 10
 *
FROM Posts
WHERE Tags LIKE ('%python%')
AND Tags LIKE ('%regex%')
</code>```

This will get you also similar tags, for example, python-3.x.

To get only those tags and no fuzzy matching, use

```<code>%<python>%
</code>```

permalink

Body:
For multiple tags, one inefficient way to use SEDE is multiple LIKE statements

SELECT TOP 10
 *
FROM Posts
WHERE Tags LIKE ('%python%')
AND Tags LIKE ('%regex%')

This will get you also similar tags, for example, python-3.x.

To get only those tags and no fuzzy matching, use

%<python>%

permalink


问:
OpenCL: can I do simultaneous "read" operations?
I have an OpenCL buffer created with the read and write flag. Can I access the same memory address simultaneously? say, calling enqueueReadBuffer and a kernel that doesn't modify the contents out-of-order without waitlists, or two calls to kernels that only read from the buffer.</p>

答:
Yes, you can do so. Create 2 queues, then call clEnqueieReadBuffer and clEnqueueNDRangeKernel on the different queue.

It ultimately depends on weather the device and driver supports executing different queues at the same time. Most GPUs can while embedded devices may or may not.


问:
How to determine what AMIs are available for a selected AZ
I am currently using cloud formation to launch the following AMI image: ami-0d28e5e0f13248294

However I have been told that the instance type (m5.large) is not supported in my requested Availability Zone (ap-southeast-2a).

How can I find a similar AMI that is supported in ap-southeast-2a. I have tried using the 'launch EC2 instance' in the console but I don't get any information about the availability zones I can use for ap-southeast-2a for my required instance type.

答:
AMI's provide information required to launch the instance. An AMI is registered in a region and not in an availability zone.

You can search the list of AMI's in the given region by the following command

```<code>aws ec2 describe-images --owners self amazon --filters "Name=root-device-type,Values=ebs"
</code>```

Body:
AMI's provide information required to launch the instance. An AMI is registered in a region and not in an availability zone.

You can search the list of AMI's in the given region by the following command

aws ec2 describe-images --owners self amazon --filters "Name=root-device-type,Values=ebs"


问:
Allow RabbitMQ and Pika maintain the conection always open
I've a Python script which reads stuff from a stream, and when a new string gets readed, it pushes its content (a string) to a RabbitMQ queue.

The thing is that the stream might not send messages in 1, 2 or 9h or so, so I would like to have the RabbitMQ connection always open.

The problem is that when I create the conection and the channel:

```<code>self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials))
channel = self.connection.channel()
channel.exchange_declare(exchange=self.exchange_name, exchange_type='fanout')
</code>```

... and if after an hour a message arrives, I get this error:

```<code>  File "/usr/local/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/var/opt/rabbitmq-agent.py", line 34, in push_to_queue
    raise Exception("Error sending the message to the queue: " + format(e))
Exception: Error sending the message to the queue: Send message to publisher error: Channel allocation requires an open connection: <SelectConnection CLOSED socket=None params=<ConnectionParameters host=x port=xvirtual_host=/ ssl=False>>
</code>```

Which I suppose is that the connection has been closed between the rabbitmq server and client.

How can I avoid this? I would like to have a "please, keep the connection alive always". Maybe setting a super-big heartbeat in the connection parameters of Pika? Something like this:

```<code>self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials, heartbeat=6000))
</code>```

Any other cooler solutions would be highly appreciated.

Thanks in advance

答:
I would suggest you check connection every time before sending message and if the connection is closed then simply reconnect.</p>

```<code>if not self.connection or self.connection.is_closed:
    self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials))
    channel = self.connection.channel()
    channel.exchange_declare(exchange=self.exchange_name, exchange_type='fanout')
</code>```

Body:
I've a Python script which reads stuff from a stream, and when a new string gets readed, it pushes its content (a string) to a RabbitMQ queue.

The thing is that the stream might not send messages in 1, 2 or 9h or so, so I would like to have the RabbitMQ connection always open.

The problem is that when I create the conection and the channel:

self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials))
channel = self.connection.channel()
channel.exchange_declare(exchange=self.exchange_name, exchange_type='fanout')

... and if after an hour a message arrives, I get this error:

  File "/usr/local/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/var/opt/rabbitmq-agent.py", line 34, in push_to_queue
    raise Exception("Error sending the message to the queue: " + format(e))
Exception: Error sending the message to the queue: Send message to publisher error: Channel allocation requires an open connection: <SelectConnection CLOSED socket=None params=<ConnectionParameters host=x port=xvirtual_host=/ ssl=False>>

Which I suppose is that the connection has been closed between the rabbitmq server and client.

How can I avoid this? I would like to have a "please, keep the connection alive always". Maybe setting a super-big heartbeat in the connection parameters of Pika? Something like this:

self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials, heartbeat=6000))

Any other cooler solutions would be highly appreciated.

Thanks in advance

Body:
I would suggest you check connection every time before sending message and if the connection is closed then simply reconnect.

if not self.connection or self.connection.is_closed:
    self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials))
    channel = self.connection.channel()
    channel.exchange_declare(exchange=self.exchange_name, exchange_type='fanout')


问:
Splitting a string and inserting the parts in the correct columns inside a table
I am trying to build a fact table with sql server. It currently looks like this:

```<code>[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL
</code>```

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

```<code>[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4
</code>```

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

答:
Try This

```<code>IF OBJECT_ID('tempdb..#temp')IS NOT NULL
DROP TABLE #temp

CREATE TABLE #temp (
            [Item] INT,
            [Variant Descr.] VARCHAR(100),
            [Variant Order] VARCHAR(100) ,
            [Dim_Colour] VARCHAR(100),
            [Dim_Size]INT ,
            [Dim_Style]  VARCHAR(100)
            )

INSERT INTO  #temp
SELECT 01,'NAVY/44' ,'COLOUR/SIZE' ,NULL,NULL,NULL UNION ALL
SELECT 02,'BLACK/S4','COLOUR/STYLE',NULL,NULL,NULL

SELECT * FROM #temp

UPDATE o
SET     o.[Dim_Colour]  = dt.Dim_Colour,
        o.Dim_Size = dt.Dim_Size,
        o.Dim_Style = dt.Dim_Style
FROM #temp o
INNER JOIN
(

SELECT [Item],  [Variant Descr.], [Variant Order] ,
            SUBSTRING([Variant Descr.],0,CHARINDEX('/',[Variant Descr.])) AS [Dim_Colour]
           ,CASE WHEN ISNUMERIC(SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))) = 1 AND [Variant Order] = 'COLOUR/SIZE'
                  THEN SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))
                  ELSE NULL END AS [Dim_Size]
           ,CASE WHEN ISNUMERIC(SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))) <> 1 AND [Variant Order] ='COLOUR/STYLE'
                  THEN SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))
                  ELSE NULL END AS [Dim_Style]
      FROM  #temp i
)dt ON dt.[Item] = o.[Item]

SELECT * FROM  #temp
</code>```

Result

```<code>Item    Variant Descr.  Variant Order       Dim_Colour  Dim_Size    Dim_Style
------------------------------------------------------------------------------
1       NAVY/44         COLOUR/SIZE            NAVY         44        NULL
2       BLACK/S4        COLOUR/STYLE           BLACK       NULL       S4
</code>```

Body:
I am trying to build a fact table with sql server. It currently looks like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

Body:
Try This

IF OBJECT_ID('tempdb..#temp')IS NOT NULL
DROP TABLE #temp

CREATE TABLE #temp (
            [Item] INT,
            [Variant Descr.] VARCHAR(100),
            [Variant Order] VARCHAR(100) ,
            [Dim_Colour] VARCHAR(100),
            [Dim_Size]INT ,
            [Dim_Style]  VARCHAR(100)
            )

INSERT INTO  #temp
SELECT 01,'NAVY/44' ,'COLOUR/SIZE' ,NULL,NULL,NULL UNION ALL
SELECT 02,'BLACK/S4','COLOUR/STYLE',NULL,NULL,NULL

SELECT * FROM #temp

UPDATE o
SET     o.[Dim_Colour]  = dt.Dim_Colour,
        o.Dim_Size = dt.Dim_Size,
        o.Dim_Style = dt.Dim_Style
FROM #temp o
INNER JOIN
(

SELECT [Item],  [Variant Descr.], [Variant Order] ,
            SUBSTRING([Variant Descr.],0,CHARINDEX('/',[Variant Descr.])) AS [Dim_Colour]
           ,CASE WHEN ISNUMERIC(SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))) = 1 AND [Variant Order] = 'COLOUR/SIZE'
                  THEN SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))
                  ELSE NULL END AS [Dim_Size]
           ,CASE WHEN ISNUMERIC(SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))) <> 1 AND [Variant Order] ='COLOUR/STYLE'
                  THEN SUBSTRING([Variant Descr.],CHARINDEX('/',[Variant Descr.])+1,LEN ([Variant Descr.]))
                  ELSE NULL END AS [Dim_Style]
      FROM  #temp i
)dt ON dt.[Item] = o.[Item]

SELECT * FROM  #temp

Result

Item    Variant Descr.  Variant Order       Dim_Colour  Dim_Size    Dim_Style
------------------------------------------------------------------------------
1       NAVY/44         COLOUR/SIZE            NAVY         44        NULL
2       BLACK/S4        COLOUR/STYLE           BLACK       NULL       S4


问:
How to remove duplicate items from an array with multiple criteria?
Objective: I have to delete object from array which has same title, vicinity, coordinate.latitude and coordinate.longitude

```<code>    class Place {
        var placeID: String?
        var title: String?
        var vicinity: String?
        var detailsUrl: String?
        var openingHours: OpeningHours?
        var position: [Double]

        var coordinate: CLLocationCoordinate2D {
          return CLLocationCoordinate2DMake(position.first ?? 0, position.last ?? 0)
    }
</code>```

One way i have tried that -

```<code>extension Array {
    func removingDuplicates <T: Hashable>(byKey key: (Element) -> T) -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(key(value)).inserted {
                result.append(value)
            }
        }
        return result
    }
}

let array = list.removingDuplicates(byKey: { "\($0.coordinate.latitude)" + "\($0.coordinate.longitude)" + ($0.title ?? " ") + ($0.vicinity ?? " ") })
</code>```

But i really don't like above solution. What is the most appropriate way to handle it ?

答:
Add Equatable to the Place class

```<code>class Place: Equatable {
    static func == (lhs: Place, rhs: Place) -> Bool {
        return lhs.title == rhs.title && lhs.vicinity == rhs.vicinity &&
            lhs.coordinate.latitude == rhs.coordinate.latitude && lhs.coordinate.longitude == rhs.coordinate.longitude
    }
    //...
}
</code>```

And filter the array elements with the place/places to delete

```<code>var list = [Place]()
//Delete multiple places
let placesToDelete = [Place]()
let result = list.removeAll { placesToDelete.contains($0) }
//Delete one place
let placeToDelete = Place()
let result = list.removeAll { $0 == placeToDelete }
</code>```

Body:
Objective: I have to delete object from array which has same title, vicinity, coordinate.latitude and coordinate.longitude

    class Place {
        var placeID: String?
        var title: String?
        var vicinity: String?
        var detailsUrl: String?
        var openingHours: OpeningHours?
        var position: [Double]

        var coordinate: CLLocationCoordinate2D {
          return CLLocationCoordinate2DMake(position.first ?? 0, position.last ?? 0)
    }

One way i have tried that -

extension Array {
    func removingDuplicates <T: Hashable>(byKey key: (Element) -> T) -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(key(value)).inserted {
                result.append(value)
            }
        }
        return result
    }
}

let array = list.removingDuplicates(byKey: { "\($0.coordinate.latitude)" + "\($0.coordinate.longitude)" + ($0.title ?? " ") + ($0.vicinity ?? " ") })

But i really don't like above solution. What is the most appropriate way to handle it ?

Body:
Add Equatable to the Place class

class Place: Equatable {
    static func == (lhs: Place, rhs: Place) -> Bool {
        return lhs.title == rhs.title && lhs.vicinity == rhs.vicinity &&
            lhs.coordinate.latitude == rhs.coordinate.latitude && lhs.coordinate.longitude == rhs.coordinate.longitude
    }
    //...
}

And filter the array elements with the place/places to delete

var list = [Place]()
//Delete multiple places
let placesToDelete = [Place]()
let result = list.removeAll { placesToDelete.contains($0) }
//Delete one place
let placeToDelete = Place()
let result = list.removeAll { $0 == placeToDelete }


问:
regex to extract a text
regex to find the text

```<code>string = '<a href="/naruto/700">Naruto 700</a> : Naruto Uzumaki!!</td>'
</code>```

output that i desire

```<code>[("/naruto/700", "Naruto 700", "Naruto Uzumaki!!")]
</code>```

regex i am using re.compile(r'"(.*?)">(.*?)<*:(.*?)<')

result i am getting [('/naruto/700', 'Naruto 700 ', ' Naruto Uzumaki!!')]

i don't want to iterate over it again to split it

how can i remove  tag here.

thanks

Title: regex to extract a text

Body:
regex to find the text

string = 'Naruto 700 : Naruto Uzumaki!!	'

output that i desire

[("/naruto/700", "Naruto 700", "Naruto Uzumaki!!")]

regex i am using re.compile(r'"(.*?)">(.*?)<*:(.*?)<')

result i am getting [('/naruto/700', 'Naruto 700 ', ' Naruto Uzumaki!!')]

i don't want to iterate over it again to split it

how can i remove  tag here.

thanks

Body:
Just using

r'\<a href\=\"(.*?)\"\>(.*?)\<\/a\> \: (.*?)\<\/td\>'

Demo: https://regex101.com/r/TyGKaQ/1


问:
How to define IF clause within WHERE condition in SQL?
I'm trying a simple if statement within where condition in SQL. I don't want CASE statement since it is very simple.

Example:

```<code>CREATE PROCEDURE [dbo].[usp_GetStatus]
    @siteId INT,

    ........
    FROM sites
    WHERE StartDate = @reportMonth
      AND..
      AND ...
      AND IF(@siteId > 0) sites.SiteId = @siteId
    ........
</code>```

I would like to define simple as above.

My siteId parameter can be 0 or greater than that, if user passes a integer value. I want to omit my AND condition if siteId parameter is 0.

答:
I would rather suggest</p>

```<code>CREATE PROCEDURE [dbo].[usp_GetStatus]
    @siteId INT,

    ........
    FROM sites
    WHERE StartDate = @reportMonth
      AND..
      AND ...
      AND
sites.SiteId = case when @siteId > 0 then @siteId else sites.SiteId end
</code>```

Body:
I'm trying a simple if statement within where condition in SQL. I don't want CASE statement since it is very simple.

Example:

CREATE PROCEDURE [dbo].[usp_GetStatus]
    @siteId INT,

    ........
    FROM sites
    WHERE StartDate = @reportMonth
      AND..
      AND ...
      AND IF(@siteId > 0) sites.SiteId = @siteId
    ........

I would like to define simple as above.

My siteId parameter can be 0 or greater than that, if user passes a integer value. I want to omit my AND condition if siteId parameter is 0.

Body:
I would rather suggest

CREATE PROCEDURE [dbo].[usp_GetStatus]
    @siteId INT,

    ........
    FROM sites
    WHERE StartDate = @reportMonth
      AND..
      AND ...
      AND
sites.SiteId = case when @siteId > 0 then @siteId else sites.SiteId end


问:
Appropriate SecureRandom method for API token for use in URL?
I am aware that SecureRandom (ruby on rails) offers multiple methods for generating tokens

Is there some method that is designed for urls?

e.g.

```<code>SecureRandom.hex(32)
</code>```

```<code>SecureRandom.base64(20)
</code>```

etc

The main reason I ask is to ensure I don't accidentally generate tokens with characters that are illegal in urls. Ultimately I need to generate tokens of the same length that are safe in urls

答:
```<code>SecureRandom.urlsafe_base64
</code>```

Documentation here

Body:
I am aware that SecureRandom (ruby on rails) offers multiple methods for generating tokens

Is there some method that is designed for urls?

e.g.

SecureRandom.hex(32)

SecureRandom.base64(20)

etc

The main reason I ask is to ensure I don't accidentally generate tokens with characters that are illegal in urls. Ultimately I need to generate tokens of the same length that are safe in urls

Body:
SecureRandom.urlsafe_base64

Documentation here


问:
Attemping to parallelize a nested loop in Scala
I am comparing 2 dataframes in scala/spark using a nested loop and an external jar.

```<code>for (nrow <- dfm.rdd.collect) {
  var mid = nrow.mkString(",").split(",")(0)
  var mfname = nrow.mkString(",").split(",")(1)
  var mlname = nrow.mkString(",").split(",")(2)
  var mlssn = nrow.mkString(",").split(",")(3)

  for (drow <- dfn.rdd.collect) {
    var nid = drow.mkString(",").split(",")(0)
    var nfname = drow.mkString(",").split(",")(1)
    var nlname = drow.mkString(",").split(",")(2)
    var nlssn = drow.mkString(",").split(",")(3)

    val fNameArray = Array(mfname,nfname)
    val lNameArray = Array (mlname,nlname)
    val ssnArray = Array (mlssn,nlssn)

    val fnamescore = Main.resultSet(fNameArray)
    val lnamescore = Main.resultSet(lNameArray)
    val ssnscore =  Main.resultSet(ssnArray)

    val overallscore = (fnamescore +lnamescore +ssnscore) /3

    if(overallscore >= .95) {
       println("MeditechID:".concat(mid)
         .concat(" MeditechFname:").concat(mfname)
         .concat(" MeditechLname:").concat(mlname)
         .concat(" MeditechSSN:").concat(mlssn)
         .concat(" NextGenID:").concat(nid)
         .concat(" NextGenFname:").concat(nfname)
         .concat(" NextGenLname:").concat(nlname)
         .concat(" NextGenSSN:").concat(nlssn)
         .concat(" FnameScore:").concat(fnamescore.toString)
         .concat(" LNameScore:").concat(lnamescore.toString)
         .concat(" SSNScore:").concat(ssnscore.toString)
         .concat(" OverallScore:").concat(overallscore.toString))
    }
  }
}
</code>```

What I'm hoping to do is add some parallelism to the outer loop so that I can create a threadpool of 5 and pull 5 records from the collection of the outerloop and compare them to the collection of the inner loop, rather than doing this serially. So the outcome would be I can specify the number of threads, have 5 records from the outerloop's collection processing at any given time against the collection in the inner loop. How would I go about doing this?

答:
Let's start by analyzing what you are doing. You collect the data of dfm to the driver. Then, for each element you collect the data from dfn, transform it and compute a score for each pair of elements.

That's problematic in many ways. First even without considering parallel computing, the transformations on the elements of dfn are made as many times as dfm as elements. Also, you collect the data of dfn for every row of dfm. That's a lot of network communications (between the driver and the executors).

If you want to use spark to parallelize you computations, you need to use the API (RDD , SQL or Datasets). You seem to want to use RDDs to perform a cartesian product (this is O(N*M) so be careful, it may take a while).

Let's start by transforming the data before the Cartesian product to avoid performing them more than once per element. Also, for clarity, let's define a case class to contain your data and a function that transform your dataframes into RDDs of that case class.

case class X(id : String, fname : String, lname : String, lssn : String)
def toRDDofX(df : DataFrame) = {
    df.rdd.map(row => {
        // using pattern matching to convert the array to the case class X
        row.mkString(",").split(",") match {
            case Array(a, b, c, d) => X(a, b, c, d)
        }
    })
}
```

<p>Then, I use <code>filter</code> to keep only the tuples whose score is more than <code>.95</code> but you could use <code>map</code>, <code>foreach</code>... depending on what you intend to do.</p>

<pre class="lang-scala prettyprint-override"><code>val rddn = toRDDofX(dfn)
val rddm = toRDDofX(dfm)
rddn.cartesian(rddm).filter{ case (xn, xm) => {
    val fNameArray = Array(xm.fname,xn.fname)
    val lNameArray = Array(xm.lname,xn.lname)
    val ssnArray = Array(xm.lssn,xn.lssn)

    val fnamescore = Main.resultSet(fNameArray)
    val lnamescore = Main.resultSet(lNameArray)
    val ssnscore =  Main.resultSet(ssnArray)

    val overallscore = (fnamescore +lnamescore +ssnscore) /3
    // and then, let's say we filter by score
    overallscore > .95
}}
</code>```

Body:
I am comparing 2 dataframes in scala/spark using a nested loop and an external jar.

for (nrow <- dfm.rdd.collect) {
  var mid = nrow.mkString(",").split(",")(0)
  var mfname = nrow.mkString(",").split(",")(1)
  var mlname = nrow.mkString(",").split(",")(2)
  var mlssn = nrow.mkString(",").split(",")(3)

  for (drow <- dfn.rdd.collect) {
    var nid = drow.mkString(",").split(",")(0)
    var nfname = drow.mkString(",").split(",")(1)
    var nlname = drow.mkString(",").split(",")(2)
    var nlssn = drow.mkString(",").split(",")(3)

    val fNameArray = Array(mfname,nfname)
    val lNameArray = Array (mlname,nlname)
    val ssnArray = Array (mlssn,nlssn)

    val fnamescore = Main.resultSet(fNameArray)
    val lnamescore = Main.resultSet(lNameArray)
    val ssnscore =  Main.resultSet(ssnArray)

    val overallscore = (fnamescore +lnamescore +ssnscore) /3

    if(overallscore >= .95) {
       println("MeditechID:".concat(mid)
         .concat(" MeditechFname:").concat(mfname)
         .concat(" MeditechLname:").concat(mlname)
         .concat(" MeditechSSN:").concat(mlssn)
         .concat(" NextGenID:").concat(nid)
         .concat(" NextGenFname:").concat(nfname)
         .concat(" NextGenLname:").concat(nlname)
         .concat(" NextGenSSN:").concat(nlssn)
         .concat(" FnameScore:").concat(fnamescore.toString)
         .concat(" LNameScore:").concat(lnamescore.toString)
         .concat(" SSNScore:").concat(ssnscore.toString)
         .concat(" OverallScore:").concat(overallscore.toString))
    }
  }
}

What I'm hoping to do is add some parallelism to the outer loop so that I can create a threadpool of 5 and pull 5 records from the collection of the outerloop and compare them to the collection of the inner loop, rather than doing this serially. So the outcome would be I can specify the number of threads, have 5 records from the outerloop's collection processing at any given time against the collection in the inner loop. How would I go about doing this?

Body:
Let's start by analyzing what you are doing. You collect the data of dfm to the driver. Then, for each element you collect the data from dfn, transform it and compute a score for each pair of elements.

That's problematic in many ways. First even without considering parallel computing, the transformations on the elements of dfn are made as many times as dfm as elements. Also, you collect the data of dfn for every row of dfm. That's a lot of network communications (between the driver and the executors).

If you want to use spark to parallelize you computations, you need to use the API (RDD , SQL or Datasets). You seem to want to use RDDs to perform a cartesian product (this is O(N*M) so be careful, it may take a while).

Let's start by transforming the data before the Cartesian product to avoid performing them more than once per element. Also, for clarity, let's define a case class to contain your data and a function that transform your dataframes into RDDs of that case class.

case class X(id : String, fname : String, lname : String, lssn : String)
def toRDDofX(df : DataFrame) = {
    df.rdd.map(row => {
        // using pattern matching to convert the array to the case class X
        row.mkString(",").split(",") match {
            case Array(a, b, c, d) => X(a, b, c, d)
        }
    })
}

Then, I use filter to keep only the tuples whose score is more than .95 but you could use map, foreach... depending on what you intend to do.

val rddn = toRDDofX(dfn)
val rddm = toRDDofX(dfm)
rddn.cartesian(rddm).filter{ case (xn, xm) => {
    val fNameArray = Array(xm.fname,xn.fname)
    val lNameArray = Array(xm.lname,xn.lname)
    val ssnArray = Array(xm.lssn,xn.lssn)

    val fnamescore = Main.resultSet(fNameArray)
    val lnamescore = Main.resultSet(lNameArray)
    val ssnscore =  Main.resultSet(ssnArray)

    val overallscore = (fnamescore +lnamescore +ssnscore) /3
    // and then, let's say we filter by score
    overallscore > .95
}}


问:
Shared settings in .NET Core?
I have 3 files named appsettings.[int/stg/prod].json  in my asp.net core app:

```<code>{
    "EmailForFailedNonCrucial":
    {
        "Email": "royin...",
        "Subject": "...",
        "Body": "...",
        "ConnectionString": "Staging-Connection-String"
    },
    "Servers": [
    {
        "Name": "aaa",
        "Services": [
            ...
        ]
    },
    {
        "Name": "bbb",
        "Services": [
            ...
        ]
    }]
}
</code>```

Each section has a corresponded section in C# class. (for IOptions).

I have 3 versions of that file, for each environemnt :

I can use it via :

```<code> public static IConfigurationRoot ConfigureConfiguration()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($@"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

        }
</code>```

But the only thing that should be different across environments is the ConnectionString.

The Servers section is the same for all environments.

Question:

It seems odd to duplicate the Servers across all 3 files.

How can I accomplish (inheritance?) specifying it once, and have only EmailForFailedNonCrucial per environment?

答:
Configuration settings in .NET Core are treated as values in a key/value dictionary. Values from multiple providers are all merged together, with newer values replacing the older ones. The file names have no special significance, only the order of the calls matters.

This is explained in Essential .NET - Configuration in .NET Core and Configuration in ASP.NET Core. Despite the name, the configuration library is available for Full Framework applications too.

Settings are converted to key/value pairs when loading. This file's contents :

```<code>{
  "section0": {
    "key0": "value",
    "key1": "value"
  },
  "section1": {
    "key0": "value",
    "key1": "value"
  }
}
</code>```

Are flattened into just 4 pairs, whose keys are :

```<code>- section0:key0
- section0:key1
- section1:key0
- section1:key1
</code>```

Another file or provider can override a previous setting if it produces the same key. SomeotherFile.json could replace section1:key0 by specifying a new value just for that key :

```<code>{
  "section1": {
    "key0": "value",
  }
}
</code>```

There's no need to duplicate settings.

You can specify different settings per environment by putting all common settings in one file, and reading environment-specific settings from another file or provider.

```<code>var envSpecificFile=...
return new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile(envSpecificFile, optional: true)
            .AddEnvironmentVariables()
            .Build();
</code>```

Using appsettings.prod.json is just a convention. Reading a specific environment variable to determine the environment is just a convention as well.

The common convention for ASP.NET Core projects is to use the ASPNETCORE_ENVIRONMENT environment variable :

```<code>var env=Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var envSpecificFile = $"appsettings.{env}.json";
</code>```

The environment could just as easily come from a command-line argument. This would allow testing different configurations on a QA server, eg :

```<code>string env;
if(args.Length>0)
{
    env=args[0];
}
else
{
    env=Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
}
</code>```

The settings don't need to come from a JSON file, they could easily come from a dictionary, a database or a centralized configuration service.

For example:

```<code>  var dictSettings = new Dictionary<string, string>()
  {
      ["section0:key1"] = args[1],
  };
</code>```

Can be used to override the section0:key1 value :

```<code>return new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env}.json", optional: true)
            .AddInMemoryCollection(dictSettings)
            .AddEnvironmentVariables()
            .Build();
</code>```

That example is a bit contrived. Dictionaries are typically used to provide defaults so they're typically added before other providers.

```<code>.AddInMemoryCollection(defaultSettings)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true)
.AddEnvironmentVariables()
</code>```

Title: Shared settings in .NET Core?

Body:
I have 3 files named appsettings.[int/stg/prod].json  in my asp.net core app:

{
    "EmailForFailedNonCrucial":
    {
        "Email": "royin...",
        "Subject": "...",
        "Body": "...",
        "ConnectionString": "Staging-Connection-String"
    },
    "Servers": [
    {
        "Name": "aaa",
        "Services": [
            ...
        ]
    },
    {
        "Name": "bbb",
        "Services": [
            ...
        ]
    }]
}

Each section has a corresponded section in C# class. (for IOptions).

I have 3 versions of that file, for each environemnt :

I can use it via :

 public static IConfigurationRoot ConfigureConfiguration()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($@"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

        }

But the only thing that should be different across environments is the ConnectionString.

The Servers section is the same for all environments.

Question:

It seems odd to duplicate the Servers across all 3 files.

How can I accomplish (inheritance?) specifying it once, and have only EmailForFailedNonCrucial per environment?

Body:
Configuration settings in .NET Core are treated as values in a key/value dictionary. Values from multiple providers are all merged together, with newer values replacing the older ones. The file names have no special significance, only the order of the calls matters.

This is explained in Essential .NET - Configuration in .NET Core and Configuration in ASP.NET Core. Despite the name, the configuration library is available for Full Framework applications too.

Settings are converted to key/value pairs when loading. This file's contents :

{
  "section0": {
    "key0": "value",
    "key1": "value"
  },
  "section1": {
    "key0": "value",
    "key1": "value"
  }
}

Are flattened into just 4 pairs, whose keys are :

- section0:key0
- section0:key1
- section1:key0
- section1:key1

Another file or provider can override a previous setting if it produces the same key. SomeotherFile.json could replace section1:key0 by specifying a new value just for that key :

{
  "section1": {
    "key0": "value",
  }
}

There's no need to duplicate settings.

You can specify different settings per environment by putting all common settings in one file, and reading environment-specific settings from another file or provider.

var envSpecificFile=...
return new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile(envSpecificFile, optional: true)
            .AddEnvironmentVariables()
            .Build();

Using appsettings.prod.json is just a convention. Reading a specific environment variable to determine the environment is just a convention as well.

The common convention for ASP.NET Core projects is to use the ASPNETCORE_ENVIRONMENT environment variable :

var env=Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var envSpecificFile = $"appsettings.{env}.json";

The environment could just as easily come from a command-line argument. This would allow testing different configurations on a QA server, eg :

string env;
if(args.Length>0)
{
    env=args[0];
}
else
{
    env=Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
}

The settings don't need to come from a JSON file, they could easily come from a dictionary, a database or a centralized configuration service.

For example:

  var dictSettings = new Dictionary<string, string>()
  {
      ["section0:key1"] = args[1],
  };

Can be used to override the section0:key1 value :

return new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env}.json", optional: true)
            .AddInMemoryCollection(dictSettings)
            .AddEnvironmentVariables()
            .Build();

That example is a bit contrived. Dictionaries are typically used to provide defaults so they're typically added before other providers.

.AddInMemoryCollection(defaultSettings)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true)
.AddEnvironmentVariables()


问:
What other get method characters can be used? aside from question mark?
the normal get:
http://localhost/get.php?id=2&get=row

can it be done like this?

http://localhost/get.php&id=2&get=row

or in other way.

When a user make a parameter to my site like

http://test.com/?url=http://localhost/sample/

or what if it contains a "?id=234"

so the new url is http://test.com/?url=http://localhost/smaple?id=1234

it creates now a 2 question mark.

答:
What you want to do is not possible, at least not using & and ? as separator characters. They have a defined meaning in a URL and cannot be used beyond that meaning. Repeating the characters will result in an invalid URL. It will probably work in most browsers but it's bad practice.

Consider sticking with the classical ?param=value&param2=value2 notation. Why do you want to change that in the first place? Is there a specific reason?

If you really want to do this, and are fine with some other character to separate the parameters from each other, you can use one of these two methods.

PATH_INFO

If the AcceptPathInfo setting is enabled on your Apache server (it usually is), you can address your URL like this:

```<code>http://localhost/get.php/id=2/get=row
</code>```

this will call get.php. The id=2/get=row part will be available in the $_SERVER["PATH_INFO"] variable for you to split.

mod_rewrite

Alternatively, you could use mod_rewrite to map a URL according to a pre-defined pattern, like this:

```<code>http://localhost/2/row
</code>```

Here is a question dealing with how to use mod_rewrite; there are many more on Stack Overflow.

Body:
What you want to do is not possible, at least not using & and ? as separator characters. They have a defined meaning in a URL and cannot be used beyond that meaning. Repeating the characters will result in an invalid URL. It will probably work in most browsers but it's bad practice.

Consider sticking with the classical ?param=value&param2=value2 notation. Why do you want to change that in the first place? Is there a specific reason?

If you really want to do this, and are fine with some other character to separate the parameters from each other, you can use one of these two methods.

PATH_INFO

If the AcceptPathInfo setting is enabled on your Apache server (it usually is), you can address your URL like this:

http://localhost/get.php/id=2/get=row

this will call get.php. The id=2/get=row part will be available in the $_SERVER["PATH_INFO"] variable for you to split.

mod_rewrite

Alternatively, you could use mod_rewrite to map a URL according to a pre-defined pattern, like this:

http://localhost/2/row

Here is a question dealing with how to use mod_rewrite; there are many more on Stack Overflow.


问:
Cannot access or assign login username variable - mysql - php
I cannot find a way to access the username I used to log in with on my php web form.

I have had a look at these posts but I think my case varies slightly as they both declare the username variable at the top. I simply log in using a sql query.

Here is the login script

<?php
$uname=$_POST['uname'];
$password=$_POST['password'];
session_start();

$con=mysqli_connect("localhost","root","g7trj98o6fyr5","login");//mysqli("localhost","username of database","password of database","database name")
$result=mysqli_query($con,"SELECT * FROM `login_info` WHERE `uname`='$uname' && `password`='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
    echo "Login success";
    $_SESSION['log']=1;
    header("refresh:2;url=welcome.php");

}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}
?>
```

<p>I'm expecting to be able to do a if check using the currently logged in user to differentiate them from all other users online.</p>

<p>I have this if check which should only put the edit button next to the user who is logged in.</p>

<pre class="lang-php prettyprint-override"><code>while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['uname'] . "</td>";
echo "<td>" . $row['clickrate'] . "</td>";
if($logedInUsername == $row['uname'])
    echo "<td>" . $row['yourword'] . " edit</td>";
else
    echo "<td>" . $row['yourword'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</code>```

welcome.php (where the if statement is)

<?php

function add_ant(&$connection)
{
    mysqli_query($connection, "UPDATE `login_info` SET `clickrate`=`clickrate`+'1' WHERE `uname`='rvbvakama' && `password`='pass'");
}

session_start();

if(isset($_SESSION['log']))
{

$_SESSION['uname'] = $_POST['uname'];

echo "";
$con=mysqli_connect("localhost","root","pass","login"); //mysqli("localhost","username of database","password of database","database name")

if(array_key_exists('add',$_POST))
{
   add_ant($con);
}

$result = mysqli_query($con,"SELECT * FROM login_info");
if (!$result)
{
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

echo "

username
clickrate
yourword

";

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($logedInUsername == $_SESSION['uname'])
    echo "" . $row['yourword'] . " edit	";
else
    echo "" . $row['yourword'] . "	";
echo "
";
}
echo "
";
?>

<!DOCTYPE html>

<title></title>

Add ants

<button type='button' name="add">ADD</button>

logout

<?php
}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}

?>
```

Thanks.

答:
in login.php after login success execute this
$_SESSION['uname'] = $_POST['uname'];

in welcome.php execute this
$logedInUsername = $_SESSION['uname'];

Now the currently logged in username is stored in $logedInUsername for use in welcome.php, this is because SESSION is a global var in php and can be accessed from anywhere.

The while loop and if statement in it should now look like this:

```<code>while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['uname'] . "</td>";
echo "<td>" . $row['clickrate'] . "</td>";
if($row['uname'] == $logedInUsername)
    echo "<td>" . $row['yourword'] . "<a href='edityourword.php?edit=$row[yourword]'> edit</a></td>";
else
    echo "<td>" . $row['yourword'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</code>```

Body:
I cannot find a way to access the username I used to log in with on my php web form.

I have had a look at these posts but I think my case varies slightly as they both declare the username variable at the top. I simply log in using a sql query.

Here is the login script

<?php
$uname=$_POST['uname'];
$password=$_POST['password'];
session_start();

$con=mysqli_connect("localhost","root","g7trj98o6fyr5","login");//mysqli("localhost","username of database","password of database","database name")
$result=mysqli_query($con,"SELECT * FROM `login_info` WHERE `uname`='$uname' && `password`='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
    echo "Login success";
    $_SESSION['log']=1;
    header("refresh:2;url=welcome.php");

}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}
?>

I'm expecting to be able to do a if check using the currently logged in user to differentiate them from all other users online.

I have this if check which should only put the edit button next to the user who is logged in.

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($logedInUsername == $row['uname'])
    echo "" . $row['yourword'] . " edit	";
else
    echo "" . $row['yourword'] . "	";
echo "
";
}
echo "
";
?>

welcome.php (where the if statement is)

<?php

function add_ant(&$connection)
{
    mysqli_query($connection, "UPDATE `login_info` SET `clickrate`=`clickrate`+'1' WHERE `uname`='rvbvakama' && `password`='pass'");
}

session_start();

if(isset($_SESSION['log']))
{

$_SESSION['uname'] = $_POST['uname'];

echo "";
$con=mysqli_connect("localhost","root","pass","login"); //mysqli("localhost","username of database","password of database","database name")

if(array_key_exists('add',$_POST))
{
   add_ant($con);
}

$result = mysqli_query($con,"SELECT * FROM login_info");
if (!$result)
{
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

echo "

username
clickrate
yourword

";

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($logedInUsername == $_SESSION['uname'])
    echo "" . $row['yourword'] . " edit	";
else
    echo "" . $row['yourword'] . "	";
echo "
";
}
echo "
";
?>

<!DOCTYPE html>

<title></title>

Add ants

<button type='button' name="add">ADD</button>

logout

<?php
}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}

?>

Thanks.

Body:
in login.php after login success execute this
$_SESSION['uname'] = $_POST['uname'];

in welcome.php execute this
$logedInUsername = $_SESSION['uname'];

Now the currently logged in username is stored in $logedInUsername for use in welcome.php, this is because SESSION is a global var in php and can be accessed from anywhere.

The while loop and if statement in it should now look like this:

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['uname'] . "</td>";
echo "<td>" . $row['clickrate'] . "</td>";
if($row['uname'] == $logedInUsername)
    echo "<td>" . $row['yourword'] . "<a href='edityourword.php?edit=$row[yourword]'> edit</a></td>";
else
    echo "<td>" . $row['yourword'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>


答:
If you want to get the parent who have a child with age = 7, and the same child belongs to house=GREEN, use the query you already wrote:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD IF AGE=7 AND house='GREEN');

If you want to get the parent whose children either has age=7 or house=GREEN or both, use

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD IF AGE=7 OR house='GREEN');

Title: Oracle query to filter and sort table based on values in child table

Body:
I am using Oracle 11g, and I have tables with data and structure as follows:

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 2 | Jane   | 40  |
 3 | Agatha | 45  |
-------------------

TABLE2_CHILD
==============================================
CID | Name       | Age | Class | House | PID |
----------------------------------------------
 1 | John        | 7  |    3   | Red   |  1  |
 2 | Marie       | 5  |    1   | Yellow|  2  |
 3 | Petra       | 6  |    2   | Green |  3  |
 4 | Taylor      | 8  |    4   | Blue  |  2  |
 5 | Lean        | 9  |    5   | Red   |  2  |
 6 | Justin      | 7  |    3   | Yellow|  3  |
 7 | Arianna     | 5  |    1   | Blue  |  3  |
 8 | Brendon     | 6  |    2   | Green |  3  |
 9 | Shawn       | 7  |    3   | Red   |  1  |
----------------------------------------------

For a single condition, the query is simple:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7);

which will result in the following result:

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 3 | Agatha | 45  |
-------------------

However, if I want to fetch the list of parents whose children are of age=7 and belong to house='GREEN', if I write a query as below:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7 AND house='GREEN');

I would get no results.

I am expecting the result to be :

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 3 | Agatha | 45  |
-------------------

since Agatha has a child belonging to age=7, and a child belonging to house='GREEN'.

I was able to come up with a solution for a similar data structure using Java streams. I am trying to do the same using Oracle SQL.

List<Parent> filteredParents = parents.stream()
                .filter(parent -> parent.getChildren().stream()
                        .anyMatch(child -> child.getAge().equals("7")) && parent.getChildren().stream()
                        .anyMatch(child -> child.getHouse().equalsIgnoreCase("Green")))
                .collect(Collectors.toList());

I am expecting the query to give me a result where the conditions could match any of the children. Because, the filtering is happening at the Parent level.

Any help would be great. Thanks!


问:
Apache Spark - Connection refused for worker
Hi I was new to apache spark and i was trying to learn it

While creating a new standalone cluster I met with this error.

I started my master and it is active in port 7077, i can see that in the ui (port 8080)

While startting the server using the command

```<code> ./bin/spark-class org.apache.spark.deploy.worker.Worker spark://192.168.0.56:7077
</code>```

I am meeting with a connection refused error

```<code>14/07/22 13:18:30 ERROR EndpointWriter: AssociationError [akka.tcp://sparkWorker@node-        physical:55124] -> [akka.tcp://sparkMaster@192.168.0.56:7077]: Error [Association failed     with [akka.tcp://sparkMaster@192.168.0.56:7077]] [
akka.remote.EndpointAssociationException: Association failed with [akka.tcp://sparkMaster@192.168.0.56:7077]
Caused by: akka.remote.transport.netty.NettyTransport$$anonfun$associate$1$$anon$2:     Connection refused: /192.168.0.56:7077
</code>```

Please help me with the error i am sruck here for a long time.

I hope the information is enough. Please help

答: For Windows: spark-class org.apache.spark.deploy.master.Master -h [Interface IP to bind to]</p>

Body:
Hi I was new to apache spark and i was trying to learn it

While creating a new standalone cluster I met with this error.

I started my master and it is active in port 7077, i can see that in the ui (port 8080)

While startting the server using the command

 ./bin/spark-class org.apache.spark.deploy.worker.Worker spark://192.168.0.56:7077

I am meeting with a connection refused error

14/07/22 13:18:30 ERROR EndpointWriter: AssociationError [akka.tcp://sparkWorker@node-        physical:55124] -> [akka.tcp://sparkMaster@192.168.0.56:7077]: Error [Association failed     with [akka.tcp://sparkMaster@192.168.0.56:7077]] [
akka.remote.EndpointAssociationException: Association failed with [akka.tcp://sparkMaster@192.168.0.56:7077]
Caused by: akka.remote.transport.netty.NettyTransport$$anonfun$associate$1$$anon$2:     Connection refused: /192.168.0.56:7077

Please help me with the error i am sruck here for a long time.

I hope the information is enough. Please help


问:
How do inset numpy array to fit in my model?
I have created a model of input_shape(28,28,3) and I have a numpy array of data that I need to fit in the model of shape(28500, 784).

Can anyone help me fit the training data into my model?

```<code>model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28,28,3)))

x_train.shape
</code>```

output = (28500, 784)

答:
```<code>new_train = []
nchannels = 3
for x in x_train:
  x = np.resize(x, (28, 28, nchannels))
  new_train.append(x)
new_train = np.array(new_train)
</code>```

Body:
I have created a model of input_shape(28,28,3) and I have a numpy array of data that I need to fit in the model of shape(28500, 784).

Can anyone help me fit the training data into my model?

model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28,28,3)))

x_train.shape

output = (28500, 784)


问:
display new Django object with jQuery
I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly?

views.py:

```<code>def add_post(request):
error_msg = u"No POST data sent."
post = Post()
if request.method == "POST":
    #do stuff

return HttpResponse("success")
</code>```

So far I am able to return "success" and save the new Post just fine.

jQuery:

```<code>       $("form#add_post").submit(function() {
       //do stuff
       var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
            if (status == "success") {
                alert("success");
            } else {

            }
        }};

       $.ajax(args);

       return false;

   })
</code>```

Just alerting "success" here, and that works fine. I can see the new Post in the Post List if I refresh the page. Now how do I load the new Post AJAX-ly? Do I have to grab Post's attributes and prepend them to my DIV manually? Is there an easy way to just reload my Post List?

Thank you!

答: Why don't you just return the HTML for the post the in the success return, and use jQuery to append it to where it should go in your page. That's what I usually do in my code, it's quick and easy. For more complex solutions you'd want to return a list of JSON objects perhaps and use a javascript framework like backbone.js</p>

Title: display new Django object with jQuery

Body:
I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly?

views.py:

def add_post(request):
error_msg = u"No POST data sent."
post = Post()
if request.method == "POST":
    #do stuff

return HttpResponse("success")

So far I am able to return "success" and save the new Post just fine.

jQuery:

       $("form#add_post").submit(function() {
       //do stuff
       var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
            if (status == "success") {
                alert("success");
            } else {

            }
        }};

       $.ajax(args);

       return false;

   })

Just alerting "success" here, and that works fine. I can see the new Post in the Post List if I refresh the page. Now how do I load the new Post AJAX-ly? Do I have to grab Post's attributes and prepend them to my DIV manually? Is there an easy way to just reload my Post List?

Thank you!


Title: regex to extract a text

Body:
regex to find the text

string = 'Naruto 700 : Naruto Uzumaki!!	'

output that i desire

[("/naruto/700", "Naruto 700", "Naruto Uzumaki!!")]

regex i am using re.compile(r'"(.*?)">(.*?)<*:(.*?)<')

result i am getting [('/naruto/700', 'Naruto 700 ', ' Naruto Uzumaki!!')]

i don't want to iterate over it again to split it

how can i remove  tag here.

thanks

Body:
use this :

\"(.*?)\">(.*?)<.*:(.*?)<


问:
JS equivalent to Java's Collections.unmodifiableCollection
I often use this strategy to my java code in order to make a Collection read only for the outside world, but avoid big/often clonings:

```<code>public abstract class MyClass {
    List<Long> myIds;

    public Collection<Long> getIds() {
        return Collections.unmodifiableCollection(this.myIds);
    }
}
</code>```

I would like to follow the same pattern in my JS classes. This would make my business logic code much safer and cleaner, since I would be able to controll every change to my lists (push/splice etc) within the class that owns the fields.

At the moment use "private" fields for the lists and get-set functions for accessing them from outside. The only missing link is some equivalent to java's Collections.unmodifiableCollection. Something that would not copy the whole list (such as slice()), and that would not affect the original field (such as Object.freeze()).

Is there such a feature in JS? If not, how could someone achieve a similar effect (custom iterables?)

答:
If you are not limited to use only JS solutions, then you can try immutable.js (https://github.com/immutable-js/immutable-js).

From the docs:

Immutable.js provides many Persistent Immutable data structures including: List, Stack, Map, OrderedMap, Set, OrderedSet and Record

Here is simple example with Immutable.List:

const list1 = Immutable.List([ 1, 2 ]);
const list2 = list1.push(3, 4, 5);
const list3 = list2.unshift(0);
const list4 = list1.concat(list2, list3);

console.log('list1:', list1); // [1,2]
console.log('list2:', list2); // [1,2,3,4,5]
console.log('list3:', list3); // [0,1,2,3,4,5]
console.log('list4:', list4); // [1,2,1,2,3,4,5,0,1,2,3,4,5]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script></code>```

Updated at Mon, 27 May 2019 09:55:43 GMT

Body:
I often use this strategy to my java code in order to make a Collection read only for the outside world, but avoid big/often clonings:

public abstract class MyClass {
    List<Long> myIds;

    public Collection<Long> getIds() {
        return Collections.unmodifiableCollection(this.myIds);
    }
}

I would like to follow the same pattern in my JS classes. This would make my business logic code much safer and cleaner, since I would be able to controll every change to my lists (push/splice etc) within the class that owns the fields.

At the moment use "private" fields for the lists and get-set functions for accessing them from outside. The only missing link is some equivalent to java's Collections.unmodifiableCollection. Something that would not copy the whole list (such as slice()), and that would not affect the original field (such as Object.freeze()).

Is there such a feature in JS? If not, how could someone achieve a similar effect (custom iterables?)

Body:
If you are not limited to use only JS solutions, then you can try immutable.js (https://github.com/immutable-js/immutable-js).

From the docs:

Immutable.js provides many Persistent Immutable data structures including: List, Stack, Map, OrderedMap, Set, OrderedSet and Record

Here is simple example with Immutable.List:

const list1 = Immutable.List([ 1, 2 ]);
const list2 = list1.push(3, 4, 5);
const list3 = list2.unshift(0);
const list4 = list1.concat(list2, list3);

console.log('list1:', list1); // [1,2]
console.log('list2:', list2); // [1,2,3,4,5]
console.log('list3:', list3); // [0,1,2,3,4,5]
console.log('list4:', list4); // [1,2,1,2,3,4,5,0,1,2,3,4,5]

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

Updated at Mon, 27 May 2019 09:55:43 GMT


答:
If you don't want to copy the object, and you want to make sure the original object can't be mutated externally, one option is to return a Proxy which throws when anything tries to mutate:

const handler = {
  get(obj, prop) {
    return obj[prop];
  },
  set() {
    throw new Error('Setting not permitted');
  }
}
class MyClass {
  _myIds = ['foo', 'bar']
  getIds() {
    return new Proxy(this._myIds, handler);
  }
}

const instance = new MyClass();
const ids = instance.getIds();
console.log(ids);
// Error:
// ids[2] = 'baz';
// Error:
// ids.push('baz');```
</div>
</div>
</p>

<p>Of course, <code>instance._myIds</code> is still technically visible - if you want to prevent that, you can use something like a WeakMap to ensure that the private array is truly only visible from inside the class.</p>

<p>But Proxies are a bit slow. You might consider something like Typescript's <code>ReadonlyArray</code> instead - that way, you ensure that the code doesn't contain anything that mutates the array after it's <em>returned</em>, while keeping the actual code fast at runtime:</p>

```private myIds = ['foo', 'bar']
public getIds() {
  return this.myIds as ReadonlyArray<string>;
}
```

Title: JS equivalent to Java's Collections.unmodifiableCollection

Body:
If you don't want to copy the object, and you want to make sure the original object can't be mutated externally, one option is to return a Proxy which throws when anything tries to mutate:

const handler = {
  get(obj, prop) {
    return obj[prop];
  },
  set() {
    throw new Error('Setting not permitted');
  }
}
class MyClass {
  _myIds = ['foo', 'bar']
  getIds() {
    return new Proxy(this._myIds, handler);
  }
}

const instance = new MyClass();
const ids = instance.getIds();
console.log(ids);
// Error:
// ids[2] = 'baz';
// Error:
// ids.push('baz');

Of course, instance._myIds is still technically visible - if you want to prevent that, you can use something like a WeakMap to ensure that the private array is truly only visible from inside the class.

But Proxies are a bit slow. You might consider something like Typescript's ReadonlyArray instead - that way, you ensure that the code doesn't contain anything that mutates the array after it's returned, while keeping the actual code fast at runtime:

private myIds = ['foo', 'bar']
public getIds() {
  return this.myIds as ReadonlyArray<string>;
}


问:
ObjC / iPhone dictionary grep?
I have a large number of strings in my iPhone app containing random combinations of letters, and I'd like to check each of these random strings against a dictionary. I'm looking for a way to grep each string with /usr/share/dict/words and return the result (or number of results) back to my app. Is this possible in an iPhone app?

Edit: Thanks for all the suggestions. Originally I wanted to execute a grep and ideally pipe the results back into my app, but after some more digging and playing around with NSTask it seems its not possible on an iPhone. I ended up loading all the words into a big NSDictionary with this approach:

NSString* allWords = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSASCIIStringEncoding error:NULL];
NSArray* wordArray = [allWords componentsSeparatedByString:@"\n"];

答: Easiest way would be to add the words to a sqlite database and do grep against them using an sql query or NSPredicate

Title: ObjC / iPhone dictionary grep?