问:
Laravel Eloquent multiple database
I have multiple database connected into my web app.

These are: write and read

I have this eloquent database query:

$users = User::whereIsAdmin(0)->get();

I want this db query to use the read database since by default my app is reading in the write database.

How would I do that?

Thanks!

答:
I looked at the source code of Laravel Eloquent Models, and here:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L303

It says on should be used to change connections.

So:

```<code>User::on("read")->whereIsAdmin(0)->get();
</code>```

Title: Laravel Eloquent multiple database

Body:
I looked at the source code of Laravel Eloquent Models, and here:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L303

It says on should be used to change connections.

So:

User::on("read")->whereIsAdmin(0)->get();


来源: stackexchange

问:
how to get the input value of dynamically generated textboxes?
I have a button to add textarea, but how to retrieve values from the text areas.
I have tried using

```<code>document.getElementById('newutterances').value;
</code>```

but its not working.

Please help, as I am new to JavaScript.

    <input type="button" value="Add Text Area" onClick="addTextArea();">
    <button type="button" onClick="getValue()">Get Value</button>

    ```

答:
With this code snippet below, I get the value of your input field, which you've created, and print it using console.log().

```<code>var button = document.querySelector('button');

button.addEventListener('click', function() {
     var input = document.querySelector('#newutterance input[type="text"]');
     var inputValue = input.value;
     console.log(inputValue);
});
</code>```

  <input type="button" value="Add Text Area" onClick="addTextArea();">
  <button type="button">Get Value</button>

```

ContentLicense: CC BY-SA 3.0

Body:
I have a button to add textarea, but how to retrieve values from the text areas.
I have tried using

document.getElementById('newutterances').value;

but its not working.

Please help, as I am new to JavaScript.

    <input type="button" value="Add Text Area" onClick="addTextArea();">
    <button type="button" onClick="getValue()">Get Value</button>

Body:
With this code snippet below, I get the value of your input field, which you've created, and print it using console.log().

var button = document.querySelector('button');

button.addEventListener('click', function() {
     var input = document.querySelector('#newutterance input[type="text"]');
     var inputValue = input.value;
     console.log(inputValue);
});

<html>

<body>
  <div id="newutterance"></div>
  <input type="button" value="Add Text Area" onClick="addTextArea();">
  <button type="button">Get Value</button>

  <script type="text/javascript">
    function addTextArea() {
      var intTextBox = 0;
      intTextBox++;
      var objNewDiv = document.createElement('div');
      objNewDiv.setAttribute('id', 'div_' + intTextBox);
      objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text" id="tb_' + intTextBox + '" name="tb_"/>';
      document.getElementById('newutterance').appendChild(objNewDiv);

    }
    var button = document.querySelector('button');

    button.addEventListener('click', function() {
      var input = document.querySelector('#newutterance input[type="text"]');
      var inputValue = input.value;
      console.log(inputValue);
    });
  </script>
</body>

</html>


问:
python sort strings with digits at the end
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

```<code>>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']
</code>```

should  put the 1234 one on the end. is there an easy way to do this?

答:
You need a key function. You're willing to specify 3 or 4 digits at the end and I have a feeling that you want them to compare numerically.

```<code>sorted(list_, key=lambda s: (s[:-4], int(s[-4:])) if s[-4] in '0123456789' else (s[:-3], int(s[-3:])))
</code>```

Without the lambda and conditional expression that's

```<code>def key(s):
    if key[-4] in '0123456789':
         return (s[:-4], int(s[-4:]))
    else:
         return (s[:-3], int(s[-3:]))

sorted(list_, key=key)
</code>```

This just takes advantage of the fact that tuples sort by the first element, then the second. So because the key function is called to get a value to compare, the elements will now be compared like the tuples returned by the key function. For example, 'asdfbad123' will compare to  'asd7890' as ('asdfbad', 123) compares to ('asd', 7890). If the last 3 characters of a string aren't in fact digits, you'll get a ValueError which is perfectly appropriate given the fact that you passed it data that doesn't fit the specs it was designed for.

ContentLicense: CC BY-SA 2.5

Body:
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

should  put the 1234 one on the end. is there an easy way to do this?

Body:
You need a key function. You're willing to specify 3 or 4 digits at the end and I have a feeling that you want them to compare numerically.

sorted(list_, key=lambda s: (s[:-4], int(s[-4:])) if s[-4] in '0123456789' else (s[:-3], int(s[-3:])))

Without the lambda and conditional expression that's

def key(s):
    if key[-4] in '0123456789':
         return (s[:-4], int(s[-4:]))
    else:
         return (s[:-3], int(s[-3:]))

sorted(list_, key=key)

This just takes advantage of the fact that tuples sort by the first element, then the second. So because the key function is called to get a value to compare, the elements will now be compared like the tuples returned by the key function. For example, 'asdfbad123' will compare to  'asd7890' as ('asdfbad', 123) compares to ('asd', 7890). If the last 3 characters of a string aren't in fact digits, you'll get a ValueError which is perfectly appropriate given the fact that you passed it data that doesn't fit the specs it was designed for.


问:
ZF Apigility Admin UI set main authentication
I'm trying to create an authentication in ZF Apigility Admin UI, but I haven't found any information regarding this..

The authentication must be only for Admin UI page (http://host/apigility/ui/)

Maybe someone has links to the documentation/guide how to do it?

答:
Didn't find anything about authentication, but you can disable development mode by executing the following command from terminal:
php public/index.php development disable


问:
Write a String to a File in the Assets Folder
I have a .txt file in my Assets folder.
I tried using
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(getAssets().open("---.txt")));

I get an error underlining (getAssets().open("---.txt"))); Saying

OutputStreamWriter(java.io.OutputStream) in OutputStreamWriter cannot be applied to (java.io.InputStream)

I don't know how to write to this file, and I need help. It would also be good if I knew how to erase everything that's already in that file and write in a blank file...(Sorry for being unclear).

I know I can do this using PrintWriter on PC, but I am learning Android now.

答:
The assets folder is read-only, as well as its contents. If you wish to modify and save any modifications in an asset, consider storing a copy in the device storage, using Context.openFileOutput(). Here's an example without exception handling:

// copy the asset to storage

InputStream assetIs = getAssets().open(filename);
OutputStream copyOs = openFileOutput(filename, MODE_PRIVATE);

byte[] buffer = new byte[4096];
int bytesRead;

while ((bytesRead = assetIs.read(buffer)) != -1) {
    copyOs.write(buffer, 0, bytesRead);
}

assetIs.close();
copyOs.close();

// now you can open and modify the copy

copyOs = openFileOutput(filename, MODE_APPEND);

BufferedWriter writer =
        new BufferedWriter(
                new OutputStreamWriter(copyOs));
```


问:
SQLite storage class And retrieval efficiency
Say I have one table, which is a reference table (the table is only been consulted, not update).

for example, the table schema :

```<code>CREATE TABLE countries(
               zip_code INTEGER PRIMARY KEY,
               name TEXT)
</code>```

I want to improve the retrieval speed of data. Now, I'm using index on the namecolumn, but I want to go further...

Change the table schema:

```<code>CREATE TABLE countries(
                   zip_code INT PRIMARY KEY,
                   name CHAR(200))
</code>```

remarque that I've modified the data type of the columns in order to specify a fixed size for each column, hence a fixed size for the entire row.

Is it a correct assumption ? Thinking that fixed size rows are retrievable more quickly than dynamic size rows in SQLite DBMS.

I'm inspiring from other DBMS (MySQL) which retrieve static size rows more quickly than dynamic size rows

答:
I'm fixing this answer to be relevant to SQLite.  It is accepted, so I can't delete it.

I don't think that storing 200 bytes for each name is going to speed your query.  In most databases, all it will do is multiply the volume of data you are storing -- because names are shorter.  In SQLite, it is a no-op.  SQLite stores all character strings as text; it does not pad the values with spaces as other databases do.

I am not intimately familiar with the internals of SQLite.  But databases (including SQLite) store records on data pages.  These are managed by a caching mechanism.  And indexes identify a record by the page it is on.  The entire data page is read in.

In most databases, declaring a column as name(200) would probably waste a lot of space.  It would Increase the size of the record and that has the following effects:

Fewer records can be store on a single page.

A subsequent retrieval is less likely to find the page for the record in the cache.

Reading the entire table is likely to occupy much more memory space.

Reading a row requires reading and processing more bytes.

In SQLite, none of this applies, because SQLite just ignores the length and doesn't pad the value with spaces.

What you want to do isn't a good idea in most databases, and it has no effect in SQLite.  I would recommend avoiding such an approach.  The index should be sufficient.

Body:
Say I have one table, which is a reference table (the table is only been consulted, not update).

for example, the table schema :

CREATE TABLE countries(
               zip_code INTEGER PRIMARY KEY,
               name TEXT)

I want to improve the retrieval speed of data. Now, I'm using index on the namecolumn, but I want to go further...

Change the table schema:

CREATE TABLE countries(
                   zip_code INT PRIMARY KEY,
                   name CHAR(200))

remarque that I've modified the data type of the columns in order to specify a fixed size for each column, hence a fixed size for the entire row.

Is it a correct assumption ? Thinking that fixed size rows are retrievable more quickly than dynamic size rows in SQLite DBMS.

I'm inspiring from other DBMS (MySQL) which retrieve static size rows more quickly than dynamic size rows


问:
rendering millions of voxels using 3D textures with three.js
I am using three.js to render a voxel representation as a set of triangles. I have got it render 5 million triangles comfortably but that seems to be the limit. you can view it online here.

select the Dublin model at resolution 3 to see a lot of triangles being drawn.

I have used every trick to get it this far (buffer geometry, voxel culling, multiple buffers) but I think it has hit the maximum amount that openGL triangles can accomplish.

Large amounts of voxels are normally rendered as a set of images in a 3D texture and while there are several posts on how to hack 2d textures into 3D textures but they seem to have a maximum limit on the texture size.

I have searched for tutorials or examples using this approach but haven't found any. Has anyone used this approach before with three.js

答:
Your scene is render twice, because SSAO need depth texture. You could use WEBGL_depth_texture extension - which have pretty good support - so you just need a single render pass. You can stil fallback to low-perf-double-pass if extension is unavailable.

Your voxel's material is double sided. It's may be on purpose, but it may create a huge overdraw.

In your demo, you use a MeshPhongMaterial and directional lights. It's a needlessly complex material. Your geometries don't have any normals so you can't have any lighting. Try to use a simpler unlit material.

Your goal is to render a huge amount of vertices, so assuming the framerate is bound by vertex shader :

try stuff like https://github.com/GPUOpen-Tools/amd-tootle to preprocess your geometries. Focusing on prefetch vertex cache and vertex cache.

reduce the bandwidth used by your vertex buffers. Since your vertices are aligned on a "grid", you could store vertices position as 3 Shorts instead of 3 floats, reducing your VBO size by 2. You could use a same tricks if you had normals since all normals should be Axis aligned (cubes)

generally reduce the amount of varyings needed by fragment shader

if you need more attributes than just vec3 position, use one single interleaved VBO instead of one per attrib.


问:
combine 8 tables into 1
I've got 8 diffrent tables that looks like this

```<code> date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:30   15    0    6    X
3-4-2017 13:45   12    0    2    X

 date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    Y
</code>```

I want to visualize in Power BI on a map the ID states wher it should be maped. But for this visualisation my data should look like this.

```<code>date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    X
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    X
3-4-2017 13:45   12    0    2    Y
</code>```

I have tested this on a small part but have to be able to do this on 3 to 4 years. I'd rather do this in Excel or BI itself but R is a option.

答:
If these tables live in a database, and you can query them with your PowerBI tool, a simple UNION between queries will do the trick.

Example

```<code>select * from table1
UNION
select * from table2
</code>```

Title: combine 8 tables into 1

Body:
I've got 8 diffrent tables that looks like this

 date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:30   15    0    6    X
3-4-2017 13:45   12    0    2    X

 date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    Y

I want to visualize in Power BI on a map the ID states wher it should be maped. But for this visualisation my data should look like this.

date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    X
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    X
3-4-2017 13:45   12    0    2    Y

I have tested this on a small part but have to be able to do this on 3 to 4 years. I'd rather do this in Excel or BI itself but R is a option.

Body:
If these tables live in a database, and you can query them with your PowerBI tool, a simple UNION between queries will do the trick.

Example

select * from table1
UNION
select * from table2


问:
Dependencies in functions. Two functions working individually but when combined in code are showing error in Shiny
I have 2 separate codes which work individually (Code A and Code B). When I club these codes to create single app, it shows error when both inputs are updated. Not sure where the error is?

Code A

```<code>library(shiny)
dfaa <- data.frame(A = c( 1L, 4L, 0L, 1L),
                   B = c("3","*","*","2"),
                   C = c("4","5","2","*"),
                   D = c("*","9","*","4"),stringsAsFactors = F)
dfbb <- data.frame(variable = c("A","B","C","D"),
                   Value    = c( 2L, 1L, 9L, 0L),stringsAsFactors = F)

dfbb["Drop_Variable"] <- "No"

ui <-  fluidPage(titlePanel("Sample"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("select2", label = h3("Select any other Variable to drop"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     selectInput("select3", label = h3("Yes/No"),
                                 choices = list("Yes", "No"),
                                 selected = "No"),
                     actionButton("applyChanges", "Apply Changes specified in B to A")),
                   mainPanel(
                     h3("Table A"),  dataTableOutput(outputId="tableA"),
                     h3("Table B"),  dataTableOutput(outputId="tableB")
                   )))

server <- function(input, output) {
  rv <- reactiveValues(dfA=dfaa,dfB=dfbb)
  observe({
    # update dfB immediately when the variable or value in the ui changes

    rv$dfB$Drop_Variable[rv$dfB$variable==input$select2] <- input$select3
  })

  observeEvent(input$applyChanges,{
    drop <- as.character(rv$dfB$variable[rv$dfB$Drop_Variable == "Yes"])
    rv$dfA <- rv$dfA[,!(names(rv$dfA) %in% drop)]
  })
  output$tableB <- renderDataTable({ rv$dfB })
  output$tableA <- renderDataTable({ rv$dfA })
}
       shinyApp(ui=ui,server=server)
</code>```

Code B

```<code>library(shiny)
dfaa <- data.frame(A = c( 1L, 4L, 0L, 1L),
                   B = c("3","*","*","2"),
                   C = c("4","5","2","*"),
                   D = c("*","9","*","4"),stringsAsFactors = F)
dfbb <- data.frame(variable = c("A","B","C","D"),
                   Value    = c( 2L, 1L, 9L, 0L),stringsAsFactors = F)

dfbb["Drop_Variable"] <- "No"

ui <-  fluidPage(titlePanel("Sample"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("select", label = h3("Select Variable"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     numericInput("num", label = h3("Replace * in A with"),
                                  value = unique(dfbb$Value)[1]),
                     actionButton("applyChanges", "Apply Changes specified in B to A")),
                   mainPanel(
                     h3("Table A"),  dataTableOutput(outputId="tableA"),
                     h3("Table B"),  dataTableOutput(outputId="tableB")
                   )))

server <- function(input, output) {
  rv <- reactiveValues(dfA=dfaa,dfB=dfbb)
  observe({
    # update dfB immediately when the variable or value in the ui changes
    rv$dfB$Value[rv$dfB$variable==input$select] <- input$num

  })

  observeEvent(input$applyChanges,{
    # Here we apply the changes that were specified
    dfAcol <-as.character(rv$dfB$variable)
    rv$dfA[dfAcol] <-
      Map(function(x, y) replace(x, x=="*", y), rv$dfA[dfAcol], rv$dfB$Value)

  })
  output$tableB <- renderDataTable({ rv$dfB })
  output$tableA <- renderDataTable({ rv$dfA })
}
shinyApp(ui=ui,server=server)
</code>```

Combined Code A and B

```<code>library(shiny)

dfaa <- data.frame(A = c( 1L, 4L, 0L, 1L),
                   B = c("3","*","*","2"),
                   C = c("4","5","2","*"),
                   D = c("*","9","*","4"),stringsAsFactors = F)

dfbb <- data.frame(variable = c("A","B","C","D"),
                   Value    = c( 2L, 1L, 9L, 0L),stringsAsFactors = F)

dfbb["Drop_Variable"] <- "No"

ui <-  fluidPage(titlePanel("Sample"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("select", label = h3("Select Variable"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     numericInput("num", label = h3("Replace * in A with"),
                                  value = unique(dfbb$Value)[1]),
                     selectInput("select2", label = h3("Select any other Variable to drop"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     selectInput("select3", label = h3("Yes/No"),
                                 choices = list("Yes", "No"),
                                 selected = "No"),
                     actionButton("applyChanges", "Apply Changes specified in B to A")),
                   mainPanel(
                     h3("Table A"),  dataTableOutput(outputId="tableA"),
                     h3("Table B"),  dataTableOutput(outputId="tableB")
                   )))

server <- function(input, output) {
  rv <- reactiveValues(dfA=dfaa,dfB=dfbb)
  observe({
    # update dfB immediately when the variable or value in the ui changes
    rv$dfB$Value[rv$dfB$variable==input$select] <- input$num
    rv$dfB$Drop_Variable[rv$dfB$variable==input$select2] <- input$select3
  })

  observeEvent(input$applyChanges,{
    # Here we apply the changes that were specified
    dfAcol <-as.character(rv$dfB$variable)
    rv$dfA[dfAcol] <-
      Map(function(x, y) replace(x, x=="*", y), rv$dfA[dfAcol], rv$dfB$Value)
    drop <- as.character(rv$dfB$variable[rv$dfB$Drop_Variable == "Yes"])
    rv$dfA <- rv$dfA[,!(names(rv$dfA) %in% drop)]
  })
  output$tableB <- renderDataTable({ rv$dfB })
  output$tableA <- renderDataTable({ rv$dfA })
}
shinyApp(ui=ui,server=server)
</code>```

答:
You seem to be sub-setting the data-table with variable that dont exist when you update it the first time, try subsetting with %in%. Also there is small error with mappy after but you can sort that out...

Try this:

```<code> observeEvent(input$applyChanges,{
    print("two")
    # Here we apply the changes that were specified
    dfAcol <-as.character(rv$dfB$variable)

    rv$dfA[dfAcol] <-
      Map(function(x, y) replace(x, x=="*", y), rv$dfA[rv$dfA %in% dfAcol,], rv$dfB$Value)
    drop <- as.character(rv$dfB$variable[rv$dfB$Drop_Variable == "Yes"])
    rv$dfA <- rv$dfA[,!(names(rv$dfA) %in% drop)]
  })
</code>```

Body:
I have 2 separate codes which work individually (Code A and Code B). When I club these codes to create single app, it shows error when both inputs are updated. Not sure where the error is?

Code A

library(shiny)
dfaa <- data.frame(A = c( 1L, 4L, 0L, 1L),
                   B = c("3","*","*","2"),
                   C = c("4","5","2","*"),
                   D = c("*","9","*","4"),stringsAsFactors = F)
dfbb <- data.frame(variable = c("A","B","C","D"),
                   Value    = c( 2L, 1L, 9L, 0L),stringsAsFactors = F)

dfbb["Drop_Variable"] <- "No"

ui <-  fluidPage(titlePanel("Sample"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("select2", label = h3("Select any other Variable to drop"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     selectInput("select3", label = h3("Yes/No"),
                                 choices = list("Yes", "No"),
                                 selected = "No"),
                     actionButton("applyChanges", "Apply Changes specified in B to A")),
                   mainPanel(
                     h3("Table A"),  dataTableOutput(outputId="tableA"),
                     h3("Table B"),  dataTableOutput(outputId="tableB")
                   )))

server <- function(input, output) {
  rv <- reactiveValues(dfA=dfaa,dfB=dfbb)
  observe({
    # update dfB immediately when the variable or value in the ui changes

    rv$dfB$Drop_Variable[rv$dfB$variable==input$select2] <- input$select3
  })

  observeEvent(input$applyChanges,{
    drop <- as.character(rv$dfB$variable[rv$dfB$Drop_Variable == "Yes"])
    rv$dfA <- rv$dfA[,!(names(rv$dfA) %in% drop)]
  })
  output$tableB <- renderDataTable({ rv$dfB })
  output$tableA <- renderDataTable({ rv$dfA })
}
       shinyApp(ui=ui,server=server)

Code B

library(shiny)
dfaa <- data.frame(A = c( 1L, 4L, 0L, 1L),
                   B = c("3","*","*","2"),
                   C = c("4","5","2","*"),
                   D = c("*","9","*","4"),stringsAsFactors = F)
dfbb <- data.frame(variable = c("A","B","C","D"),
                   Value    = c( 2L, 1L, 9L, 0L),stringsAsFactors = F)

dfbb["Drop_Variable"] <- "No"

ui <-  fluidPage(titlePanel("Sample"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("select", label = h3("Select Variable"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     numericInput("num", label = h3("Replace * in A with"),
                                  value = unique(dfbb$Value)[1]),
                     actionButton("applyChanges", "Apply Changes specified in B to A")),
                   mainPanel(
                     h3("Table A"),  dataTableOutput(outputId="tableA"),
                     h3("Table B"),  dataTableOutput(outputId="tableB")
                   )))

server <- function(input, output) {
  rv <- reactiveValues(dfA=dfaa,dfB=dfbb)
  observe({
    # update dfB immediately when the variable or value in the ui changes
    rv$dfB$Value[rv$dfB$variable==input$select] <- input$num

  })

  observeEvent(input$applyChanges,{
    # Here we apply the changes that were specified
    dfAcol <-as.character(rv$dfB$variable)
    rv$dfA[dfAcol] <-
      Map(function(x, y) replace(x, x=="*", y), rv$dfA[dfAcol], rv$dfB$Value)

  })
  output$tableB <- renderDataTable({ rv$dfB })
  output$tableA <- renderDataTable({ rv$dfA })
}
shinyApp(ui=ui,server=server)

Combined Code A and B

library(shiny)

dfaa <- data.frame(A = c( 1L, 4L, 0L, 1L),
                   B = c("3","*","*","2"),
                   C = c("4","5","2","*"),
                   D = c("*","9","*","4"),stringsAsFactors = F)

dfbb <- data.frame(variable = c("A","B","C","D"),
                   Value    = c( 2L, 1L, 9L, 0L),stringsAsFactors = F)

dfbb["Drop_Variable"] <- "No"

ui <-  fluidPage(titlePanel("Sample"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("select", label = h3("Select Variable"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     numericInput("num", label = h3("Replace * in A with"),
                                  value = unique(dfbb$Value)[1]),
                     selectInput("select2", label = h3("Select any other Variable to drop"),
                                 choices = unique(dfbb$variable),
                                 selected = unique(dfbb$variable)[1]),
                     selectInput("select3", label = h3("Yes/No"),
                                 choices = list("Yes", "No"),
                                 selected = "No"),
                     actionButton("applyChanges", "Apply Changes specified in B to A")),
                   mainPanel(
                     h3("Table A"),  dataTableOutput(outputId="tableA"),
                     h3("Table B"),  dataTableOutput(outputId="tableB")
                   )))

server <- function(input, output) {
  rv <- reactiveValues(dfA=dfaa,dfB=dfbb)
  observe({
    # update dfB immediately when the variable or value in the ui changes
    rv$dfB$Value[rv$dfB$variable==input$select] <- input$num
    rv$dfB$Drop_Variable[rv$dfB$variable==input$select2] <- input$select3
  })

  observeEvent(input$applyChanges,{
    # Here we apply the changes that were specified
    dfAcol <-as.character(rv$dfB$variable)
    rv$dfA[dfAcol] <-
      Map(function(x, y) replace(x, x=="*", y), rv$dfA[dfAcol], rv$dfB$Value)
    drop <- as.character(rv$dfB$variable[rv$dfB$Drop_Variable == "Yes"])
    rv$dfA <- rv$dfA[,!(names(rv$dfA) %in% drop)]
  })
  output$tableB <- renderDataTable({ rv$dfB })
  output$tableA <- renderDataTable({ rv$dfA })
}
shinyApp(ui=ui,server=server)

Body:
You seem to be sub-setting the data-table with variable that dont exist when you update it the first time, try subsetting with %in%. Also there is small error with mappy after but you can sort that out...

Try this:

 observeEvent(input$applyChanges,{
    print("two")
    # Here we apply the changes that were specified
    dfAcol <-as.character(rv$dfB$variable)

    rv$dfA[dfAcol] <-
      Map(function(x, y) replace(x, x=="*", y), rv$dfA[rv$dfA %in% dfAcol,], rv$dfB$Value)
    drop <- as.character(rv$dfB$variable[rv$dfB$Drop_Variable == "Yes"])
    rv$dfA <- rv$dfA[,!(names(rv$dfA) %in% drop)]
  })


问:
Java: Subtract '0' from char to get an int... why does this work?
This works fine:

```<code>int foo = bar.charAt(1) - '0';
</code>```

Yet this doesn't - because bar.charAt(x) returns a char:

```<code>int foo = bar.charAt(1);
</code>```

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

答:
'0' is a char too.  It turns out, the characters in Java have a unicode (UTF-16) value. When you use the - operator with characters Java performs the operation with the integer values.

For instance,  int x = 'A' - '0';// x = 17

Body:
This works fine:

int foo = bar.charAt(1) - '0';

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

ContentLicense: CC BY-SA 4.0


问:
what is the use of method final Cursor managedQuery (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
Can someone please explain me what exactly is the use of

```<code> final Cursor managedQuery (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
</code>```

method. Although I know its deprecated.

android developer's definition is beyond understanding. I want to understand in simple language

答:
Taken from the Documentation:

Wrapper around query(android.net.Uri, String[], String, String[], String) that gives the resulting Cursor to call startManagingCursor(Cursor) so that the activity will manage its lifecycle for you. If you are targeting HONEYCOMB or later, consider instead using LoaderManager instead, available via getLoaderManager().

It´s an activity lifeclicle managed query.

You can check it here link.

Body:
Can someone please explain me what exactly is the use of

 final Cursor managedQuery (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

method. Although I know its deprecated.

android developer's definition is beyond understanding. I want to understand in simple language


问:
Want to create dynamic subdomain in codeigniter?
In my site i want to add an functionality for user to use their username with domain.

Like in codeigniter right now i want to give the user to use their own url to login in site and do other stuff.

For eg:

i Want www.username.mysite.com/login or www.username.mysite.com/category

so here the user can login with their credential and add the category. so i have two controller in my site with login and category.

So how to do this with the routes Or .htaccess.

答:
Use this code in server Vhost file:

```<code><VirtualHost *:80>
    DocumentRoot "/home/yourdoma/public_html/yourdomain"
    ServerName yourdomain.com
    ErrorLog "logs/yourdomain.local-error.log"
    CustomLog "logs/yourdomain.local-access.log" common
    <Directory "/home/yourdoma/public_html/yourdomain">
        AllowOverride All
        Require all Granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/yourdoma/public_html/yourdomain"
    ServerName dummy-host.yourdomain.com
    ErrorLog "logs/yourdomain.com-error.log"
    CustomLog "logs/yourdomain.com-access.log" common
    ServerAlias *.yourdomain.com
    <Directory "/home/yourdoma/public_html/yourdomain">
        AllowOverride All
        Require all Granted
    </Directory>
</VirtualHost>
</code>```

and For your codeigniter config file:

```<code>$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$schema = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'].'://' : 'http://';
$spl_host = explode("mysite.com", $host);
$subhost = '';
if (count($spl_host) == 2) {
    $subhost = current($spl_host);
}

if($host == $subhost.'mysite.com') {
    $config['base_url'] = $schema.$subhost.'mysite.com';
} else {
    $config['base_url'] = $schema.$host;
}
</code>```

Body:
Use this code in server Vhost file:

<VirtualHost *:80>
    DocumentRoot "/home/yourdoma/public_html/yourdomain"
    ServerName yourdomain.com
    ErrorLog "logs/yourdomain.local-error.log"
    CustomLog "logs/yourdomain.local-access.log" common
    <Directory "/home/yourdoma/public_html/yourdomain">
        AllowOverride All
        Require all Granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/yourdoma/public_html/yourdomain"
    ServerName dummy-host.yourdomain.com
    ErrorLog "logs/yourdomain.com-error.log"
    CustomLog "logs/yourdomain.com-access.log" common
    ServerAlias *.yourdomain.com
    <Directory "/home/yourdoma/public_html/yourdomain">
        AllowOverride All
        Require all Granted
    </Directory>
</VirtualHost>

and For your codeigniter config file:

$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$schema = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'].'://' : 'http://';
$spl_host = explode("mysite.com", $host);
$subhost = '';
if (count($spl_host) == 2) {
    $subhost = current($spl_host);
}

if($host == $subhost.'mysite.com') {
    $config['base_url'] = $schema.$subhost.'mysite.com';
} else {
    $config['base_url'] = $schema.$host;
}


问:
Convert a null-delimited PWideChar to list of strings
From a Windows API call (GetUserPreferredUILanguages()), I get a list of strings as one null-delimited PWideChar. I need to convert this to a list of Delphi strings.  I began writing code to manually loop through the list, looking for #0 chars.

Is there a smarter way to do this?

Example of the PWideChar returned by GetUserPreferredUILanguages:

```<code>('e','n','-','U','S',#0,'f','r','-','F','R',#0,#0,...)
</code>```

(based on what I read in the documentation, because when I call the function on my computer, it only returns one language, i.e. 'en-US'#0#0)

Here is my code so far:

```<code>procedure GetWinLanguages(aList: TStringList);
var lCount, lSize: ULong;
    lChars: array of WideChar;
    lIndex, lLastIndex: integer;
begin
  lSize := 1000;
  SetLength(lChars, lSize);
  GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @lCount, @lChars[0], @lSize);

  // untested quick solution to convert from lChars to aList
  lIndex := 0;
  lLastIndex := -1;
  while (lIndex<=lSize) do
  begin
    while (lIndex<lSize) and (lChars[lIndex]<>#0) do
      inc(lIndex);
    if (lIndex-lLastIndex)>1 then
    begin
      // here: copy range lLastIndex to lIndex, convert to string and add to aList
      lLastIndex := lIndex;
      inc(lIndex);
    end else
      Break;
  end;
end;
</code>```

PS. I am on Windows 10 using Delphi Berlin for a FMX project.

答:
This API returns a double null-terminated string.
This program shows how to parse such a thing:

```<code>{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Winapi.Windows;

procedure Main;
var
  NumLanguages, LanguagesBufferLen: ULONG;
  LanguagesBuffer: TArray<WideChar>;
  P: PWideChar;
  str: string;
begin
  LanguagesBufferLen := 0;
  Win32Check(GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @NumLanguages, nil, @LanguagesBufferLen));
  SetLength(LanguagesBuffer, LanguagesBufferLen);
  Win32Check(GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @NumLanguages, @LanguagesBuffer[0], @LanguagesBufferLen));
  P := @LanguagesBuffer[0];
  while P^<>#0 do begin
    str := P;
    Writeln(str);

    inc(P, Length(str)+1); // step over the string, and its null terminator
  end;
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
</code>```

It should be obvious how to extract from this code a function to parse a null-terminated string to a string list. That would allow you to re-use the code in other places.

Body:
From a Windows API call (GetUserPreferredUILanguages()), I get a list of strings as one null-delimited PWideChar. I need to convert this to a list of Delphi strings.  I began writing code to manually loop through the list, looking for #0 chars.

Is there a smarter way to do this?

Example of the PWideChar returned by GetUserPreferredUILanguages:

('e','n','-','U','S',#0,'f','r','-','F','R',#0,#0,...)

(based on what I read in the documentation, because when I call the function on my computer, it only returns one language, i.e. 'en-US'#0#0)

Here is my code so far:

procedure GetWinLanguages(aList: TStringList);
var lCount, lSize: ULong;
    lChars: array of WideChar;
    lIndex, lLastIndex: integer;
begin
  lSize := 1000;
  SetLength(lChars, lSize);
  GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @lCount, @lChars[0], @lSize);

  // untested quick solution to convert from lChars to aList
  lIndex := 0;
  lLastIndex := -1;
  while (lIndex<=lSize) do
  begin
    while (lIndex<lSize) and (lChars[lIndex]<>#0) do
      inc(lIndex);
    if (lIndex-lLastIndex)>1 then
    begin
      // here: copy range lLastIndex to lIndex, convert to string and add to aList
      lLastIndex := lIndex;
      inc(lIndex);
    end else
      Break;
  end;
end;

PS. I am on Windows 10 using Delphi Berlin for a FMX project.

Body:
This API returns a double null-terminated string.
This program shows how to parse such a thing:

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Winapi.Windows;

procedure Main;
var
  NumLanguages, LanguagesBufferLen: ULONG;
  LanguagesBuffer: TArray<WideChar>;
  P: PWideChar;
  str: string;
begin
  LanguagesBufferLen := 0;
  Win32Check(GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @NumLanguages, nil, @LanguagesBufferLen));
  SetLength(LanguagesBuffer, LanguagesBufferLen);
  Win32Check(GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @NumLanguages, @LanguagesBuffer[0], @LanguagesBufferLen));
  P := @LanguagesBuffer[0];
  while P^<>#0 do begin
    str := P;
    Writeln(str);

    inc(P, Length(str)+1); // step over the string, and its null terminator
  end;
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

It should be obvious how to extract from this code a function to parse a null-terminated string to a string list. That would allow you to re-use the code in other places.


问:
Initialise Array with Constructor - Java
I have 2 classes: Product and Room.
I want the user to be able to say how big the array to be, with creating an Object Room and enter an int.

```<code>public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}
</code>```

Why doesnt the constructor create the array with the input n, I give him?
Any ideas what I'm doing wrong?

答:
The array is initialized before the constructor body, when n is still 0 (by default), so it gets a 0 length.

You need to initialize it in the constructor's body :

```<code>public Room(int n){
    this.n = n;
    this.space = new Product[n];
}
</code>```

Body:
I have 2 classes: Product and Room.
I want the user to be able to say how big the array to be, with creating an Object Room and enter an int.

public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}

Why doesnt the constructor create the array with the input n, I give him?
Any ideas what I'm doing wrong?

Body:
The array is initialized before the constructor body, when n is still 0 (by default), so it gets a 0 length.

You need to initialize it in the constructor's body :

public Room(int n){
    this.n = n;
    this.space = new Product[n];
}


问:
How to create and attach softkeyboard in android
I am new in android development. I want to make and attach one soft keyboard for android and want to open it on edittext's click. I have gone through with soft keyboard sample given by android sdk but not really able to attach it with android. How can I do this ?
Please help me...

Thanks in advance

答:
You can override draws method in LatinKeyboardView :

```<code>  @Override
    public void draw(Canvas canvas) {
        // TODO Auto-generated method stub
        int offsetup=10;//px
        this.setPadding(0, 0, 0,offsetup);
        canvas.clipRect(0, 0, getRight(), getBottom()-offsetup);
        super.draw(canvas);
    }
</code>```

actually here I just shifted it up by padding and cut it by clipRect.
in canvas there are another interesting methods ( rotate, scale, translate , & ...)

This image was taken from Emulator has keybaord with offsetup ( 20 px )

I hope this helps you.

M.

Body:
You can override draws method in LatinKeyboardView :

  @Override
    public void draw(Canvas canvas) {
        // TODO Auto-generated method stub
        int offsetup=10;//px
        this.setPadding(0, 0, 0,offsetup);
        canvas.clipRect(0, 0, getRight(), getBottom()-offsetup);
        super.draw(canvas);
    }

actually here I just shifted it up by padding and cut it by clipRect.
in canvas there are another interesting methods ( rotate, scale, translate , & ...)

This image was taken from Emulator has keybaord with offsetup ( 20 px )

I hope this helps you.

M.


问:
Image from DB isn't displayed on JSF page
I use MySql db with images in blob and try to display them on my JSF page using PrimeFaces galleria. On my page I see this galleria, but images aren't displayed. I see only small green icons in a corner of every image. I get this problem only using DB. If my images are in my file system, everything will be OK. Can someone explain why I can't see images from DB? I wrote this code:

Galleria:

```<code><p:galleria value="#{imagesView.images}" var="image" panelWidth="500" panelHeight="250" showCaption="true">
        <p:graphicImage value="#{image}" alt="Image Description" title="Title"/>
</p:galleria>
</code>```

ImagesView:

```<code>@ManagedBean
public class ImagesView {

    private List<StreamedContent> images;

    @PostConstruct
    public void init() {
        images = new ArrayList<>();
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        int itemId = Integer.parseInt(request.getParameter("item_id"));
        for (int i = 1; i <= 2; i++) {
            images.add(new GraphicImage().getImageFromDB(i, itemId)); //It's so simple because I need it just for test and that's all
        }
    }

    public List<StreamedContent> getImages() {
        return images;
    }
}
</code>```

GraphicImage:

```<code>@RequestScoped
class GraphicImage implements Serializable {

    StreamedContent getImageFromDB(int id, int itemId) {
        if (FacesContext.getCurrentInstance().getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            return new DefaultStreamedContent();
        } else {
            byte[] image = DBUtils.getImage(id, itemId);
            return new DefaultStreamedContent(new ByteArrayInputStream(image), "image/jpg");
        }
    }
}
</code>```

DBUtils method:

```<code>public static byte[] getImage(int id, int itemId) {
        byte[] image = null;
        ResultSet resultSet = null;
        try (Connection connection = DataBase.getConnection();
             PreparedStatement statement = connection.prepareStatement("SELECT content FROM images WHERE id = ? AND item_id = ?")) {
            statement.setInt(1, id);
            statement.setInt(2, itemId);
            resultSet = statement.executeQuery();
            resultSet.next();
            image = resultSet.getBytes("content");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return image;
    }
</code>```

答:
It's not how a p:graphicImage works. You're trying to display an image using a byte array while this tag requires an URL to the image (or a StreamedContent).

```<code><p:graphicImage value="img/myImg.png" />
</code>```

Now, you have 2 options (at least)

either create an image from your byte array (image data) and store
it somewhere where it's accessible by your web application. The value attribute should still contain an URL rather than a byte array.

don't store images in your DB, but rather store an image name (or
    path to a image on the server ) (e.g. your DB will just constain
    img001.png, img002 png etc and you know they're all inside, say, the img
    folder on your server. Then, all you have to do is change the image URL.

```<code><p:graphicImage value=#{imgUrl} />
</code>```

Option 2 is actually recommended especially for large images, but even when your images are not large this method has the advantage of not having to convert images (byte arrays) to files.

In your HTML, this will be rendered as

```<code><img src="img/img001.png" >
</code>```

Body:
I use MySql db with images in blob and try to display them on my JSF page using PrimeFaces galleria. On my page I see this galleria, but images aren't displayed. I see only small green icons in a corner of every image. I get this problem only using DB. If my images are in my file system, everything will be OK. Can someone explain why I can't see images from DB? I wrote this code:

Galleria:

ImagesView:

@ManagedBean
public class ImagesView {

    private List<StreamedContent> images;

    @PostConstruct
    public void init() {
        images = new ArrayList<>();
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        int itemId = Integer.parseInt(request.getParameter("item_id"));
        for (int i = 1; i <= 2; i++) {
            images.add(new GraphicImage().getImageFromDB(i, itemId)); //It's so simple because I need it just for test and that's all
        }
    }

    public List<StreamedContent> getImages() {
        return images;
    }
}

GraphicImage:

@RequestScoped
class GraphicImage implements Serializable {

    StreamedContent getImageFromDB(int id, int itemId) {
        if (FacesContext.getCurrentInstance().getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            return new DefaultStreamedContent();
        } else {
            byte[] image = DBUtils.getImage(id, itemId);
            return new DefaultStreamedContent(new ByteArrayInputStream(image), "image/jpg");
        }
    }
}

DBUtils method:

public static byte[] getImage(int id, int itemId) {
        byte[] image = null;
        ResultSet resultSet = null;
        try (Connection connection = DataBase.getConnection();
             PreparedStatement statement = connection.prepareStatement("SELECT content FROM images WHERE id = ? AND item_id = ?")) {
            statement.setInt(1, id);
            statement.setInt(2, itemId);
            resultSet = statement.executeQuery();
            resultSet.next();
            image = resultSet.getBytes("content");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return image;
    }

Body:
It's not how a p:graphicImage works. You're trying to display an image using a byte array while this tag requires an URL to the image (or a StreamedContent).

<p:graphicImage value="img/myImg.png" />

Now, you have 2 options (at least)

either create an image from your byte array (image data) and store
it somewhere where it's accessible by your web application. The value attribute should still contain an URL rather than a byte array.

don't store images in your DB, but rather store an image name (or
    path to a image on the server ) (e.g. your DB will just constain
    img001.png, img002 png etc and you know they're all inside, say, the img
    folder on your server. Then, all you have to do is change the image URL.

<p:graphicImage value=#{imgUrl} />

Option 2 is actually recommended especially for large images, but even when your images are not large this method has the advantage of not having to convert images (byte arrays) to files.

In your HTML, this will be rendered as

<img src="img/img001.png" >


问:
How to insert data from multiple tables to multiple tables by using SSIS?
I am using SQL Server 2008 R2. I have almost 106+ tables in database and now I need to load data from these tables into another database.

Table structure of source and destination database are same. There is a status table in the database and all tables have a Primary Key ID field. All the tables have Primary key and Foreign key relationship.

Status table contain the ID field of tables and anther column contain a status of related ID field that this ID has completed its task.

I need to transfer data those ID number will match with Status table where ID status is 1 or something like this. I need to insert Identity column also, and because of all the table have PK and FK relationship so i have to insert data into tables with referential constraints.

So, my questions here is: To fulfill my above scenario how can I load data from multiple tables to multiple tables by using SSIS because it is not one time thing.

答:
Status table idea is not clear.i hv 160+ tables then status table will contain what ? give example.

Of course you hv to start with diagram/flow

suppose

```<code>table1 id pk
table2 id pk (table1 id fk)
table3 id pk (table2 id fk)

insert into table1
insert into table2
insert into table3
</code>```

In my example you can't first inert into table3 becasue of FK constraint.
This way first you hv to make flow.

Body:
Status table idea is not clear.i hv 160+ tables then status table will contain what ? give example.

Of course you hv to start with diagram/flow

suppose

table1 id pk
table2 id pk (table1 id fk)
table3 id pk (table2 id fk)

insert into table1
insert into table2
insert into table3

In my example you can't first inert into table3 becasue of FK constraint.
This way first you hv to make flow.


问:
Aggregate Data Based on Rows Python
I have a data set that looks like this:

```<code>      Date          | ID |  Task |   Description
2016-01-06 00:00:00 | 1  |  010  |   This is text
2016-01-06 00:10:00 | 1  |  020  |   This is text
2016-01-06 00:20:00 | 1  |  010  |   This is text
2016-01-06 01:00:00 | 1  |  020  |   This is text
2016-01-06 01:10:00 | 1  |  030  |   This is text
2016-02-06 00:00:00 | 2  |  010  |   This is text
2016-02-06 00:10:00 | 2  |  020  |   This is text
2016-02-06 00:20:00 | 2  |  010  |   This is text
2016-02-06 01:00:00 | 2  |  020  |   This is text
2016-02-06 01:01:00 | 2  |  030  |   This is text
</code>```

Task 020usually occurs after task 010 which means that when Task 020 starts means that task 010 ends, same applies for Task 020, if it comes before any other Task it means that it has stopped.

I need to group by Task calculating the average duration, total sum and count of each type of task in each ID, so I am looking for something like this:

```<code>ID  | Task | Average | Sum | Count
1   |  010 |   25    | 50  |  2
1   |  020 |   10    | 20  |  2
etc |  etc |   etc   | etc |  etc
</code>```

There are more IDs but I only care about 010  and 020, so whatever number is returned from them is acceptable.

Can someone help me on how to do this in Python?

答:
I think it's a simple .groupby() that you need. You sample output doesn't show any complicated linking between timestamps and Task or ID

```<code>df['count'] = df.groupby(['ID','Task']).size()
</code>```

will give you the count of each unique ID/Task in your data. To do a sum or average, it's similar, but you need a column with something to sum.

See here for more details.

Title: Aggregate Data Based on Rows Python

Body:
I have a data set that looks like this:

      Date          | ID |  Task |   Description
2016-01-06 00:00:00 | 1  |  010  |   This is text
2016-01-06 00:10:00 | 1  |  020  |   This is text
2016-01-06 00:20:00 | 1  |  010  |   This is text
2016-01-06 01:00:00 | 1  |  020  |   This is text
2016-01-06 01:10:00 | 1  |  030  |   This is text
2016-02-06 00:00:00 | 2  |  010  |   This is text
2016-02-06 00:10:00 | 2  |  020  |   This is text
2016-02-06 00:20:00 | 2  |  010  |   This is text
2016-02-06 01:00:00 | 2  |  020  |   This is text
2016-02-06 01:01:00 | 2  |  030  |   This is text

Task 020usually occurs after task 010 which means that when Task 020 starts means that task 010 ends, same applies for Task 020, if it comes before any other Task it means that it has stopped.

I need to group by Task calculating the average duration, total sum and count of each type of task in each ID, so I am looking for something like this:

ID  | Task | Average | Sum | Count
1   |  010 |   25    | 50  |  2
1   |  020 |   10    | 20  |  2
etc |  etc |   etc   | etc |  etc

There are more IDs but I only care about 010  and 020, so whatever number is returned from them is acceptable.

Can someone help me on how to do this in Python?

Body:
I think it's a simple .groupby() that you need. You sample output doesn't show any complicated linking between timestamps and Task or ID

df['count'] = df.groupby(['ID','Task']).size()

will give you the count of each unique ID/Task in your data. To do a sum or average, it's similar, but you need a column with something to sum.

See here for more details.


问:
What shall I do to handle dual monitor issue in my delphi application. Using api or application implement in .NET C# code
I want to create a api which can keep track of my delphi application's forms in dual monitor if form open on second monitor then next form should be there. this track will be done my api in c# windows app. please guid

Description:

I have an delphi application. when u used dual monitor then following issue occurred. let see scenario:

there are three from 1, 2 ,3 from 2 will open after clicking on button on from 1 and from 3 will open after clicking on button on from 2. all works fine when monitor is single. Now when i connect second monitor then form 1 will open by default on primary monitor which is first monitor, when i moved form 1 from monitor 1 to monitor 2 and click on button of form 2 to open form 3 then it is opening on monitor 1 instead of monitor 2. it should be open on monitor 2 means on monitor where last open form located. I am not able to implement it in my delphi code. So i thought to make one api in c# which will do this work of tracking window for my delphi application.

答:
You do not need C# to do this, it can be done with Delphi.  The following code can be added to each forms OnCreate or OnShow event:</p>

```<code>var
 m: TMonitor;
 cp: TPoint;
begin
  // Get the Cursor Position
  GetCursorPos(cp);
  // Get the Monitor the Cursor is on
  m := Screen.MonitorFromPoint(cp);
  // Position the Form on the correct Monitor, about the center
  Self.Top  := ((Screen.Monitors[m.MonitorNum].Height - 30) div 2) - (Self.Height div 2);
  Self.Left := (Screen.Monitors[m.MonitorNum].Width div 2) - (Self.Width div 2) + m.Left;
</code>```

Body:
You do not need C# to do this, it can be done with Delphi.  The following code can be added to each forms OnCreate or OnShow event:

var
 m: TMonitor;
 cp: TPoint;
begin
  // Get the Cursor Position
  GetCursorPos(cp);
  // Get the Monitor the Cursor is on
  m := Screen.MonitorFromPoint(cp);
  // Position the Form on the correct Monitor, about the center
  Self.Top  := ((Screen.Monitors[m.MonitorNum].Height - 30) div 2) - (Self.Height div 2);
  Self.Left := (Screen.Monitors[m.MonitorNum].Width div 2) - (Self.Width div 2) + m.Left;


问:
thread 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0) /fatal error: Index out of range
I'm trying to develop  an app and for now I'd like to edit the text of a label by the inputs of 2 different UIPickerViews.

At first I'd get the error.

"thread 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0)"
pointing at a certain bit of code (see code) but now I only get the error
"fatal error: Index out of range"

The problem is in the first picker, if I change anything there (in the simulator!) the app crashes. If I change the second picker only and then update the label it changes to '1 days' or '2 weeks', instead of only 'days' or 'weeks'.

My Storyboard:

My code:

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var PickerView1: UIPickerView!
@IBOutlet weak var PickerView2: UIPickerView!
@IBOutlet weak var outputLabel: UILabel!
@IBAction func changeLabel(_ sender: UIButton) {
    outputLabel.text = outputTotal
}

var list1 = [""]
var list2 = [""]
var output1 = ""
var output2 = ""
var outputTotal = ""

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

// Aangeven welke items er in de pickerview komen
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if (pickerView.tag == 1){
        return "\(list1[row])"
    } else {
        return "\(list2[row])"
    }
}

// Aantal rijen weergeven
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if (pickerView.tag == 1){
        return list1.count
    } else {
        return list2.count
    }
}

// Label veranderen naar input van PickerView1
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    output1 = list1[row]
    output2 = list2[row] // error points here
    outputTotal = output1 + " " + output2
}

override func viewDidLoad() {
    list1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
    list2 = ["days", "weeks"]
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
</code>```

If anyone can help me, thank you!

答:
I think you forgot to detect which pickView is selected in pickerView(_:didSelectRow:inComponent:):

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView.tag == 1 {
        output1 = list1[row]
    } else {
        output2 = list2[row]
    }
    outputTotal = output1 + " " + output2
}
</code>```

Body:
I'm trying to develop  an app and for now I'd like to edit the text of a label by the inputs of 2 different UIPickerViews.

At first I'd get the error.

"thread 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0)"
pointing at a certain bit of code (see code) but now I only get the error
"fatal error: Index out of range"

The problem is in the first picker, if I change anything there (in the simulator!) the app crashes. If I change the second picker only and then update the label it changes to '1 days' or '2 weeks', instead of only 'days' or 'weeks'.

My Storyboard:

My code:

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var PickerView1: UIPickerView!
@IBOutlet weak var PickerView2: UIPickerView!
@IBOutlet weak var outputLabel: UILabel!
@IBAction func changeLabel(_ sender: UIButton) {
    outputLabel.text = outputTotal
}

var list1 = [""]
var list2 = [""]
var output1 = ""
var output2 = ""
var outputTotal = ""

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

// Aangeven welke items er in de pickerview komen
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if (pickerView.tag == 1){
        return "\(list1[row])"
    } else {
        return "\(list2[row])"
    }
}

// Aantal rijen weergeven
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if (pickerView.tag == 1){
        return list1.count
    } else {
        return list2.count
    }
}

// Label veranderen naar input van PickerView1
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    output1 = list1[row]
    output2 = list2[row] // error points here
    outputTotal = output1 + " " + output2
}

override func viewDidLoad() {
    list1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
    list2 = ["days", "weeks"]
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

If anyone can help me, thank you!

Body:
I think you forgot to detect which pickView is selected in pickerView(_:didSelectRow:inComponent:):

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView.tag == 1 {
        output1 = list1[row]
    } else {
        output2 = list2[row]
    }
    outputTotal = output1 + " " + output2
}


答:
Your second snipped should work fine though:

```<code>int foo = bar.charAt(1);
</code>```

A char, just like a short or byte, will always be silently cast to int if needed.

This will compile just fine: int i = 'c';

Title: Java: Subtract '0' from char to get an int... why does this work?

Body:
Your second snipped should work fine though:

int foo = bar.charAt(1);

A char, just like a short or byte, will always be silently cast to int if needed.

This will compile just fine: int i = 'c';


问:
ng-disabled on anchor inside

How can I disable drop down menu item that uses ui-router and looks like this?

```<code> <ul class="dropdown-menu">
    <li><a ui-sref="state.random">A random state</a></li>
</ul>
</code>```

obviously this doesn't work:

```<code><li ng-disabled="true"><a ui-sref="state.random">A random state</a></li>
</code>```

nor this:

```<code><li><a ui-sref="state.random" ng-disabled="true">A random state</a></li>
</code>```

答:
ng-disabled  don't work on the li tag. Need to do this using css styles.

```<code>.disabled {
    pointer-events:none; //This makes it not clickable
    opacity:0.6;         //This grays it out to look disabled
}

<li class="disabled"><a ui-sref="state.random">A random state</a></li>
</code>```

Title: ng-disabled on anchor inside <li>

Body:
How can I disable drop down menu item that uses ui-router and looks like this?

A random state

obviously this doesn't work:

A random state

nor this:

A random state

Body:
ng-disabled  don't work on the li tag. Need to do this using css styles.

.disabled {
    pointer-events:none; //This makes it not clickable
    opacity:0.6;         //This grays it out to look disabled
}

<li class="disabled"><a ui-sref="state.random">A random state</a></li>


问:
How to combine two different linux commands?
I use the following command to get the MAC address of the system.

```<code>ifconfig | grep enp0s20f6 | awk '{print $5}'
</code>```

The following command is used to get the hash of the string:

```<code>echo -n "string to be hashed"| md5sum | awk '{print $1}'
</code>```

I need to get the hashed string for the MAC address by combining both of these commands.

I tried the following, but didn't work.

```<code>ifconfig | grep enp0s20f6 | awk '{print $5}' | md5sum
</code>```

答:
```<code>md5sum /sys/class/net/eth0/address | awk '{print $1}'
</code>```

Body:
I use the following command to get the MAC address of the system.

ifconfig | grep enp0s20f6 | awk '{print $5}'

The following command is used to get the hash of the string:

echo -n "string to be hashed"| md5sum | awk '{print $1}'

I need to get the hashed string for the MAC address by combining both of these commands.

I tried the following, but didn't work.

ifconfig | grep enp0s20f6 | awk '{print $5}' | md5sum


问:
Wrap Selection Snippet on Visual Studio Code (vscode)
I want to create an snippet when triggered it will surround the given text. Currently my snippet is:

```<code>{
  "Function Creator Helper": {
    "prefix": "_w",
    "body": [
      "public function $TM_SELECTED_TEXT () {",
      "  $1",
      "}",
    ],
    "description": "Creates a function given the text selection"
  }
}
</code>```

This results on:

What I do is:

Select the text.

Write the prefix (_w)

Press Tab

This results on:

```<code>public function  () {

}
</code>```

But I was expecting

```<code>public function person () {

}
</code>```

Any ideas on how can I make this snippet or how can I triggered it correctly?

答:
The currently selected text is exposed as ${TM_SELECTED_TEXT}, not $TM_SELECTED_TEXT.

edit: As commented below, this is not the case for this particular use-case

Body:
I want to create an snippet when triggered it will surround the given text. Currently my snippet is:

{
  "Function Creator Helper": {
    "prefix": "_w",
    "body": [
      "public function $TM_SELECTED_TEXT () {",
      "  $1",
      "}",
    ],
    "description": "Creates a function given the text selection"
  }
}

This results on:

What I do is:

Select the text.

Write the prefix (_w)

Press Tab

This results on:

public function  () {

}

But I was expecting

public function person () {

}

Any ideas on how can I make this snippet or how can I triggered it correctly?


问:
android-O : app crash with webview
I have simply put a WebView in layout.

When I run the project in Android-O preview emulator, it gives below error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mvvmrecyclerview, PID: 3527
java.lang.SecurityException: Signature check failed for com.example.mvvmrecyclerview
at android.os.Parcel.readException(Parcel.java:1915)
at android.os.Parcel.readException(Parcel.java:1861)
at com.google.android.gms.common.internal.zzv$zza$zza.zza(Unknown Source:41)
at com.google.android.gms.common.internal.zzf.zza(Unknown Source:0)
at com.google.android.gms.internal.zzzf$zzc.zzxQ(Unknown Source:0)
at com.google.android.gms.internal.zzzf$zzf.run(Unknown Source:0)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at com.google.android.gms.internal.zzabx.run(Unknown Source:7)
at java.lang.Thread.run(Thread.java:764)
</code>```

If you want to generate this error, simply create a new project, Put webview in your layout and try to run the project in Android O emulator.

can anyone help me with this. Thanks.

PS: Android Studio 2.4 Preview 3

答: This is a known issue. Some sketchy workarounds are included in the issue comments. In general, you may need to hold off on O work until ODP2 rolls out (probably around Google I|O in mid-May).</p>

Title: android-O : app crash with webview

Body:
I have simply put a WebView in layout.

When I run the project in Android-O preview emulator, it gives below error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mvvmrecyclerview, PID: 3527
java.lang.SecurityException: Signature check failed for com.example.mvvmrecyclerview
at android.os.Parcel.readException(Parcel.java:1915)
at android.os.Parcel.readException(Parcel.java:1861)
at com.google.android.gms.common.internal.zzv$zza$zza.zza(Unknown Source:41)
at com.google.android.gms.common.internal.zzf.zza(Unknown Source:0)
at com.google.android.gms.internal.zzzf$zzc.zzxQ(Unknown Source:0)
at com.google.android.gms.internal.zzzf$zzf.run(Unknown Source:0)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at com.google.android.gms.internal.zzabx.run(Unknown Source:7)
at java.lang.Thread.run(Thread.java:764)

If you want to generate this error, simply create a new project, Put webview in your layout and try to run the project in Android O emulator.

can anyone help me with this. Thanks.

PS: Android Studio 2.4 Preview 3


问:
Using regex to find sentence between tags in string?
I need to get the sentence between tags like
Hello world!
 using regex .

Attribute of tags may differ like
Hello world!

I have code like this

```<code>var result = elements.match(/<p>(.*?)<\/p>/g).map(function(val1){
    return val1.replace(/<\/?p>/g,'');
});
</code>```

答:
You can do this by using

function findPText(str, tag) {
  if (tag === void 0) {
    tag = "p";
  }
  var fullMatch = new RegExp('\<' + tag + '.*?<\\/' + tag + '>', 'ig').exec(str);
  var startMatch = new RegExp('\<' + tag + '.*?>', 'ig');
  var endMatch = new RegExp('\<\/' + tag + '\s*>', 'ig');
  var matches = [];
  for (var index = 0; index < fullMatch.length; index++) {
    var a = fullMatch[index];
    matches.push(a.replace(startMatch, '').replace(endMatch, ""));
  }
  return matches;
}
var str = '
Hello world
bob
Hello World!
bob';
console.log(findPText(str, "h1"));
console.log(findPText(str, "p"));```
</div>
</div>
</p>

<p>Or render it as DOM:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function findPText(str, tag) {
  if (tag === void 0) {
    tag = "p";
  }
  var myNode = document.createElement("body");
  myNode.innerHTML = str;
  var tags = myNode.querySelectorAll(tag);
  var matches = [];
  for (var index = 0; index < tags.length; index++) {
    var element = tags[index];
    matches.push(element.textContent);
  }
  return matches;
}

var str = '<h1 class="test" style="color:red">Hello <b>world</b></h1>bob<p class="test" style="color:red">Hello World!</p>bob';
console.log(findPText(str, "h1"), findPText(str, "p"));</code>```

Body:
I need to get the sentence between tags like
Hello world!
 using regex .

Attribute of tags may differ like
Hello world!

I have code like this

var result = elements.match(/
(.*?)<\/p>/g).map(function(val1){
    return val1.replace(/<\/?p>/g,'');
});

Body:
You can do this by using

function findPText(str, tag) {
  if (tag === void 0) {
    tag = "p";
  }
  var fullMatch = new RegExp('\<' + tag + '.*?<\\/' + tag + '>', 'ig').exec(str);
  var startMatch = new RegExp('\<' + tag + '.*?>', 'ig');
  var endMatch = new RegExp('\<\/' + tag + '\s*>', 'ig');
  var matches = [];
  for (var index = 0; index < fullMatch.length; index++) {
    var a = fullMatch[index];
    matches.push(a.replace(startMatch, '').replace(endMatch, ""));
  }
  return matches;
}
var str = '<h1 class="test" style="color:red">Hello world</h1>bob<p class="test" style="color:red">Hello World!</p>bob';
console.log(findPText(str, "h1"));
console.log(findPText(str, "p"));

Or render it as DOM:

function findPText(str, tag) {
  if (tag === void 0) {
    tag = "p";
  }
  var myNode = document.createElement("body");
  myNode.innerHTML = str;
  var tags = myNode.querySelectorAll(tag);
  var matches = [];
  for (var index = 0; index < tags.length; index++) {
    var element = tags[index];
    matches.push(element.textContent);
  }
  return matches;
}

var str = '<h1 class="test" style="color:red">Hello <b>world</b></h1>bob<p class="test" style="color:red">Hello World!</p>bob';
console.log(findPText(str, "h1"), findPText(str, "p"));


问:
No DLLs/EXEs produced in the /bin when building in Visual Studio
I'm not newbie in programming but run into some trouble that I can't fix for 2+ hours. I have a solution of 8 projects - 1 is ASP.NET Core (.net framework) web application, 7 are service libraries. All this worked fine until today.

I don't know what I did wrong - just was making some updates on controller actions etc as I've been doing many and many days before. After some point my solution stopped working at all. How it was:

I noticed that after any changes in code breakpoints were no more working - just became disabled and never hit anymore. The solution however kept working with the old logic.

I deleted all /bin and /debug folders and tried to restart application. All 8 projects were built well but only 7 of 8 produced DLLs/EXEs in the corresponding /bin folders. The main ASP.NET Core project reported it is OK but the /bin folder actually was empty. It couldn't start saying "Unable to start process .../bin/debug/net461/win7-x64/.exe. File not found".

I opened a brand new VS instance and tried to create and run an empty default .NET Core project. After it was successfully built no files appear in its /bin folder again and it couldn't start saying same error message. I restored all VS settings to default, tried same project but it still didn't produce DLLs and EXEs.

What might have happened here?

答:
Restart your machine... .NET Core Runtime might have a problem. Also you might have upgraded your nuget packages and not your .NET Core Runtime.

Announcing .NET Core 1.1

.NET Standard Library

Supporting multiple .NET framework versions


问:
How can I put validation in the getter and setter methods in C#?
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

```<code>'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property
</code>```

can now look like this.

```<code>public string PhoneNumber{get;set;}
</code>```

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

```<code>public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }
</code>```

The get part of this code won't compile.
Do I need to revert to using a private variable?

答: You do not necessarily need a local variable. Theoretically, you could implement whatever functionality you want within a get/set property. But, in your example, you have a recursive access of your get/set property what makes no sense in the way it is implemented. So, in your concrete case, you will need a local variable, that's right.

Body:
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property

can now look like this.

public string PhoneNumber{get;set;}

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }

The get part of this code won't compile.
Do I need to revert to using a private variable?


问:
iOS Receipt not found
I am implementing in-app purchases in a Swift 3.0 app so I need to grab the app receipt to verify it against the iTunes store. Here is how I am getting the receipt:

```<code>func getReceipt() -> Data? {
    if Bundle.main.appStoreReceiptURL != nil {
        print("app receipt: \(Bundle.main.appStoreReceiptURL)")
        do {
            let receiptData = try Data(contentsOf: Bundle.main.appStoreReceiptURL!)
            print(receiptData)
            return receiptData
        } catch {
            print("error converting receipt to Data: \(error.localizedDescription)")
        }
    }
    return nil
}
</code>```

my console output for the receipt URL is:

app receipt: Optional(file:///Users/dustinspengler/Library/Developer/XCPGDevices/433E8E8F-B781-4ADC-A92D-5CABC28E94D6/data/Containers/Data/Application/C25BE9B6-FB64-4D49-9CF2-9DA371060A7B/StoreKit/receipt)

It then failed to convert the receipt to Data and the catch statement prints:

error converting receipt to Data: The file “receipt” couldn’t be opened because there is no such file.

I get the exact same output when running this in a playground, simulator, and real devices so does this mean that no receipt exists for the app considering the fact that the user has not made an in-app purchase yet? When reading through Apple's documentation I got the impression that they are always created created regardless of prior purchases.

答:
This answer is based off the context that the app is being run on your local machine. If the app is live in the app store, a receipt will be in place the moment you download the app even if its free.

Answered by @Paulw11:

There is no receipt until the user makes a purchase. For an app downloaded from the App Store (even a free one). This is a purchase, so there will be a receipt. For a debug build from Xcode there is no receipt until an in-app purchase is made.

Title: iOS Receipt not found

Body:
I am implementing in-app purchases in a Swift 3.0 app so I need to grab the app receipt to verify it against the iTunes store. Here is how I am getting the receipt:

func getReceipt() -> Data? {
    if Bundle.main.appStoreReceiptURL != nil {
        print("app receipt: \(Bundle.main.appStoreReceiptURL)")
        do {
            let receiptData = try Data(contentsOf: Bundle.main.appStoreReceiptURL!)
            print(receiptData)
            return receiptData
        } catch {
            print("error converting receipt to Data: \(error.localizedDescription)")
        }
    }
    return nil
}

my console output for the receipt URL is:

app receipt: Optional(file:///Users/dustinspengler/Library/Developer/XCPGDevices/433E8E8F-B781-4ADC-A92D-5CABC28E94D6/data/Containers/Data/Application/C25BE9B6-FB64-4D49-9CF2-9DA371060A7B/StoreKit/receipt)

It then failed to convert the receipt to Data and the catch statement prints:

error converting receipt to Data: The file “receipt” couldn’t be opened because there is no such file.

I get the exact same output when running this in a playground, simulator, and real devices so does this mean that no receipt exists for the app considering the fact that the user has not made an in-app purchase yet? When reading through Apple's documentation I got the impression that they are always created created regardless of prior purchases.


问:
Google Maps Geocoding API "This service requires an API key"
I am trying to use Google geocoding API. However I am getting following error even after mentioning API key
This service requires an API key.  For more information on authentication and Google Maps JavaScript API

Following is my HTML entry with API key:

```<code><script src="//maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyAa7LqHyZpHtQBGR6415pYu1FnwWQBPcnY" type="text/javascript"></script>
</code>```

and this is the angularjs code where I am getting REQEST_DENIED

```<code>    function geocode(dataset){
var coords = [];
var address = dataset.address;
var geocoder = new google.maps.Geocoder();
var defer = $q.defer();
geocoder.geocode({'address': address}, function( results, status ) {
        if (status === google.maps.GeocoderStatus.OK) {
            coords[0] = results[0].geometry.location.lat();
            coords[1] = results[0].geometry.location.lng();
            dataset["coordinates"]=results[0].geometry.location;
            defer.resolve(dataset);
        }
        else {
            coords = 'Could not retrieve coordinates for: ' + address;
            defer.reject();
        }
    });
return defer.promise;
}
</code>```

Is there something I am missing?
Thank you.

答:
So as per the comments above, when I checked network layer after executing fiddle from @FadiAboMsalam I could see the API key being sent into the request URL which was missing in my request.
Am not sure why geocoder.geocode(....) is not sending api ley in my request. I changes this code to send $http request and it is giving proper repsonse. Here is the updated code:

```<code>  function geocode(dataset){
    var coords = [];
    var address = dataset.address;
    var geocoder = new google.maps.Geocoder();
    var defer = $q.defer();

 $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' +
            address + '&key=xxxxxxxx')
    .then(function(results){
     if (results.status === 200) {
        var data = results.data.results;
            dataset["coordinates"]=data[0].geometry.location;
            defer.resolve(dataset);
         }
         else {
             coords = 'Could not retrieve coordinates for: ' + address;
             defer.reject();
         }
     },
     function error(_error){
        defer.reject();
     });

    return defer.promise;
}
</code>```

Thanks @PaulThomasGC  and @FadiAboMsalam for useful inputs and others for investing your precious time.

Cheers!

Body:
I am trying to use Google geocoding API. However I am getting following error even after mentioning API key
This service requires an API key.  For more information on authentication and Google Maps JavaScript API

Following is my HTML entry with API key:

and this is the angularjs code where I am getting REQEST_DENIED

    function geocode(dataset){
var coords = [];
var address = dataset.address;
var geocoder = new google.maps.Geocoder();
var defer = $q.defer();
geocoder.geocode({'address': address}, function( results, status ) {
        if (status === google.maps.GeocoderStatus.OK) {
            coords[0] = results[0].geometry.location.lat();
            coords[1] = results[0].geometry.location.lng();
            dataset["coordinates"]=results[0].geometry.location;
            defer.resolve(dataset);
        }
        else {
            coords = 'Could not retrieve coordinates for: ' + address;
            defer.reject();
        }
    });
return defer.promise;
}

Is there something I am missing?
Thank you.

Body:
So as per the comments above, when I checked network layer after executing fiddle from @FadiAboMsalam I could see the API key being sent into the request URL which was missing in my request.
Am not sure why geocoder.geocode(....) is not sending api ley in my request. I changes this code to send $http request and it is giving proper repsonse. Here is the updated code:

  function geocode(dataset){
    var coords = [];
    var address = dataset.address;
    var geocoder = new google.maps.Geocoder();
    var defer = $q.defer();

 $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' +
            address + '&key=xxxxxxxx')
    .then(function(results){
     if (results.status === 200) {
        var data = results.data.results;
            dataset["coordinates"]=data[0].geometry.location;
            defer.resolve(dataset);
         }
         else {
             coords = 'Could not retrieve coordinates for: ' + address;
             defer.reject();
         }
     },
     function error(_error){
        defer.reject();
     });

    return defer.promise;
}

Thanks @PaulThomasGC  and @FadiAboMsalam for useful inputs and others for investing your precious time.

Cheers!


问:
Make TextBox uneditable
I want to make some TextBoxes on my form uneditable, but I want the text to be clear (black not gray) and that's why I do not want to use

myTextBox.Enabled = false;

Somehow I want it to be disabled but with non-gray fore-color.

Does anyone have any clue?

答:
Just set in XAML:

```<code>        <TextBox IsReadOnly="True" Style="{x:Null}" />
</code>```

So that text will not be grayed-out.

Title: Make TextBox uneditable

Body:
Just set in XAML:

        <TextBox IsReadOnly="True" Style="{x:Null}" />

So that text will not be grayed-out.


问:
How do you model an anonymous user in an existing Rails schema?
I'm working on my first simple Rails app in which users submit sport "tweets" (e.g. "tennis, squash") and the server matches them up with partners. The server will return you a list of SportMatches based on similar tweets and you have different options (e.g. email, SMS) to reply back to someone's tweet and accept him/her as partner. Initially, the modeling was straight forward since: User has_many SportTweets and SportTweet belongs to User. Notifications were simply part of the User, or they could have been modeled as a 1-to-1 relationship to User.

My business requirements changed a little, as now I have anonymous users who can also post SportTweets. Because they don't have an account/profile, they must also submit notifications (e.g. email, SMS) with the tweet. I don't know how to model this the Rails way. SportTweets are now either anonymous, or authenticated-user-posted (AUP). So, now, my SportTweets table will have the following columns:

type: either "anonymous" or "AUP"

user_id: only for AUP

notifications_id: only for anonymous

sports: for all

post_date: for all

post_location: for all

etc.

There would be a Notifications table. A notification record would belong either to a User, or to a SportsTweet. I guess I would model this with polymorphic associations.

That just doesn't look like the Rails way. Did anyone come across a similar problem? How did you solve it?

答:
Use Devise if you can. I think this link might help you.

In some applications, it's useful to have a guest User object to pass around even before the (human) user has registered or logged in. Normally, you want this guest user to persist as long as the browser session persists.

Our approach is to create a guest user object in the database and store its id in session[:guest_user_id]. When (and if) the user registers or logs in, we delete the guest user and clear the session variable. A helper function, current_or_guest_user, returns guest_user if the user is not logged in and current_user if the user is logged in.

Followed by the code which you might find helpful in that page


问:
How to find all rows with background-color yellow using jquery?
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

```<code>$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})
</code>```

Whole example is here

答:
Try this..

$("#btnSearch").click(function(){

  $("#tbl1 tr").each(function () {
     if($(this).css("background-color") == "rgb(255, 255, 0)")
     {
     alert('I am Yellow ;)');
     }
     else{
     alert('I am White ;)');
     }
});
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' class="table table-hover table-bordered">
        <thead>
          <tr>
            <th>#</th>
            <th>Ime izdelka</th>
            <th>Opisni REF</th>
            <th>LOT/serijska/EDI</th>
            <th>Stanje (REF)</th>
            <th>Stanje (LOT)</th>
            <th>Privzeta skupina</th>
          </tr>
        </thead>
        <tfoot>

        </tfoot>
        <tbody>
            <tr style="background-color: rgb(255, 255, 0);">
              <td data-id="iROW_NUMBER" style="background-color: rgb(255, 255, 0);">1</td>
              <td data-id="cPROD_NME" style="background-color: rgb(255, 255, 0);">Kortikalni 2.0/14mm (zlati)</td>
              <td data-id="cPROD_DCD" style="background-color: rgb(255, 255, 0);">401.364</td>
              <td data-id="cPRSE_DCD" style="background-color: rgb(255, 255, 0);">8036572</td>
              <td data-id="iPROD_QUA_QUA" style="background-color: rgb(255, 255, 0);">6</td>
              <td data-id="cPRSS_QUA_QUA" style="background-color: rgb(255, 255, 0);">3</td>
              <td data-id="cPRGR_NME" style="background-color: rgb(255, 255, 0);">Stopalo - SYNTHES</td>
            </tr>
            <tr style="background-color: rgb(255, 255, 0);">
              <td data-id="iROW_NUMBER" style="background-color: rgb(255, 255, 0);">2</td>
              <td data-id="cPROD_NME" style="background-color: rgb(255, 255, 0);">Kortikalni 2.0/14mm (zlati)</td>
              <td data-id="cPROD_DCD" style="background-color: rgb(255, 255, 0);">401.364</td>
              <td data-id="cPRSE_DCD" style="background-color: rgb(255, 255, 0);">8327937</td>
              <td data-id="iPROD_QUA_QUA" style="background-color: rgb(255, 255, 0);">6</td>
              <td data-id="cPRSS_QUA_QUA" style="background-color: rgb(255, 255, 0);">1</td>
              <td data-id="cPRGR_NME" style="background-color: rgb(255, 255, 0);">Stopalo - SYNTHES</td>
            </tr>
            <tr>
              <td data-id="iROW_NUMBER">3</td>
              <td data-id="cPROD_NME">Kortikalni 2.0/14mm (zlati)</td>
              <td data-id="cPROD_DCD">401.364</td>
              <td data-id="cPRSE_DCD">9572333</td>
              <td data-id="iPROD_QUA_QUA">6</td>
              <td data-id="cPRSS_QUA_QUA">2</td>
              <td data-id="cPRGR_NME">Stopalo - SYNTHES</td>
            </tr>
        </tbody>
      </table>

<br/>
<br/>
<button id="btnSearch">Search</button></code>```

Body:
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})

Whole example is here

Body:
Try this..

$("#btnSearch").click(function(){

  $("#tbl1 tr").each(function () {
     if($(this).css("background-color") == "rgb(255, 255, 0)")
     {
     alert('I am Yellow ;)');
     }
     else{
     alert('I am White ;)');
     }
});
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' class="table table-hover table-bordered">
        <thead>
          <tr>
            <th>#</th>
            <th>Ime izdelka</th>
            <th>Opisni REF</th>
            <th>LOT/serijska/EDI</th>
            <th>Stanje (REF)</th>
            <th>Stanje (LOT)</th>
            <th>Privzeta skupina</th>
          </tr>
        </thead>
        <tfoot>

        </tfoot>
        <tbody>
            <tr style="background-color: rgb(255, 255, 0);">
              <td data-id="iROW_NUMBER" style="background-color: rgb(255, 255, 0);">1</td>
              <td data-id="cPROD_NME" style="background-color: rgb(255, 255, 0);">Kortikalni 2.0/14mm (zlati)</td>
              <td data-id="cPROD_DCD" style="background-color: rgb(255, 255, 0);">401.364</td>
              <td data-id="cPRSE_DCD" style="background-color: rgb(255, 255, 0);">8036572</td>
              <td data-id="iPROD_QUA_QUA" style="background-color: rgb(255, 255, 0);">6</td>
              <td data-id="cPRSS_QUA_QUA" style="background-color: rgb(255, 255, 0);">3</td>
              <td data-id="cPRGR_NME" style="background-color: rgb(255, 255, 0);">Stopalo - SYNTHES</td>
            </tr>
            <tr style="background-color: rgb(255, 255, 0);">
              <td data-id="iROW_NUMBER" style="background-color: rgb(255, 255, 0);">2</td>
              <td data-id="cPROD_NME" style="background-color: rgb(255, 255, 0);">Kortikalni 2.0/14mm (zlati)</td>
              <td data-id="cPROD_DCD" style="background-color: rgb(255, 255, 0);">401.364</td>
              <td data-id="cPRSE_DCD" style="background-color: rgb(255, 255, 0);">8327937</td>
              <td data-id="iPROD_QUA_QUA" style="background-color: rgb(255, 255, 0);">6</td>
              <td data-id="cPRSS_QUA_QUA" style="background-color: rgb(255, 255, 0);">1</td>
              <td data-id="cPRGR_NME" style="background-color: rgb(255, 255, 0);">Stopalo - SYNTHES</td>
            </tr>
            <tr>
              <td data-id="iROW_NUMBER">3</td>
              <td data-id="cPROD_NME">Kortikalni 2.0/14mm (zlati)</td>
              <td data-id="cPROD_DCD">401.364</td>
              <td data-id="cPRSE_DCD">9572333</td>
              <td data-id="iPROD_QUA_QUA">6</td>
              <td data-id="cPRSS_QUA_QUA">2</td>
              <td data-id="cPRGR_NME">Stopalo - SYNTHES</td>
            </tr>
        </tbody>
      </table>

<br/>
<br/>
<button id="btnSearch">Search</button>


问:
How to create an in-between library?
I am looking for some information on how to achieve something with libraries in C++ and c#.
What I would like to know is how to approach the following problem:

C# application:    -has a window

C++ library:    -has a function called create_button(x,y), when

invoked, it will create a button on

the c# application's window. (if the
C# application is not running,

nothing will happen)

C++ application:    -dynamicaly links to the C++ library and calls the create_button()
function.

How would I approach this problem, I would be glad to hear some of your ideas.
The platform is windows. My question is, how would I let the C++ library communicate to the c# application to create a new button? Is it linked, sockets, ... I'm particulary thinking of GTK+ in linux, you link to the gtk+ library, but how does the library interface with GNOME to create a new window etc, something like that. I'm not interested in writing dlls and linking those to a c# application, I'm interested in creating an in-between library.

答:
You're going to run into problems here since C# is managed and C++ is native.  As far as I know, the only way of calling native code from managed in the CLI is by using the P/Invoke layer, in which case you would need to import a DLL, write a prototype, etc.

In addition, I believe that the P/Invoke calls are to C functions, and not C++, although you can get past this by adding a C library to call into which in turn calls your C++ library.

Title: How to create an in-between library?


答:
It may look like known issue:

https://code.google.com/p/android/issues/detail?id=267699

https://issuetracker.google.com/issues/36581808

Title: android-O : app crash with webview


问:
Initialise Array with Constructor - Java
I have 2 classes: Product and Room.
I want the user to be able to say how big the array to be, with creating an Object Room and enter an int.

```<code>public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}
</code>```

Why doesnt the constructor create the array with the input n, I give him?
Any ideas what I'm doing wrong?

答:
just try</p>

```<code>public Room(int n){
  this.n = n;
this.space = new Product[n];
}
</code>```

Body:
I have 2 classes: Product and Room.
I want the user to be able to say how big the array to be, with creating an Object Room and enter an int.

public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}

Why doesnt the constructor create the array with the input n, I give him?
Any ideas what I'm doing wrong?

Body:
just try

public Room(int n){
  this.n = n;
this.space = new Product[n];
}


答:
You dont need extra fields for that (n or count), just give the size, and init the Array in the constructor... the rest of information is inside of the array object itself (array.lenght etc )

```<code>public class Room{

  Product [] space;
  public Room(int n){
      space = new Product[n]
  }
}
</code>```

Title: Initialise Array with Constructor - Java

Body:
You dont need extra fields for that (n or count), just give the size, and init the Array in the constructor... the rest of information is inside of the array object itself (array.lenght etc )

public class Room{

  Product [] space;
  public Room(int n){
      space = new Product[n]
  }
}