问:
Couchdb view on large documents with strings as keys times out
I'm trying to create a view in CouchDB 2.1 for documents that are very large (around 300k-900k lines for each document, around 15-20 documents in total).

The documents look like this:

```<code>{
"222123456": {
    "_id": "222123456",
    "type": "Order",
    "0300": {
        "51234567": {
            "_id": "51234567",
            "type": "Material",
            "DS": "M532F1234567",
            "HTZ": "M532-F1234-000-00",
            "A name for some material": {
                "_id": "A name for some material",
                "type": "Description",
                "0054": {
                    "600": {
                        "1": {
                            "_id": "1",
                            "type": "Amount",
                            "X": {
                                "11220": {
                                    "_id": "11220",
                                    "type": "row"
                                },
                                "_id": "X",
                                "type": "Bulk"
                            }
                        },
                        "_id": "600",
                        "type": "Site"
                    },
                    "_id": "0054",
                    "type": "Pos"
                }
            }
        },
        "51255111": {
            // And another material
            // ...
        },
        "_id": "0300",
        "type": "Process"
    }
    // + more orders with more items
},
"222555666": {
    // Another order with more processes which contain even more materials
    // ...
},
"_id": "FileImport_001",
"_rev": "1-2f77e699332bb7c76a137b86f83bbe91",
"type": "Machine"
}
</code>```

Every document has 1-n orders, every order has 1-n processes and every process contains 1-n materials which I'm trying to query. My current view iterates through all orders, processes and materials with for loops.

This is the view I'm using:

```<code>function (doc) {
    var splitMsn = doc._id.split("_"); // Split _id into [FileImport, 001] array
    for (var key_order in doc) { // For every order in the document...
        if (typeof doc[key_order] == 'object' && doc[key_order] != '') { // where the value is an object and not empty...
            var order = doc[key_order]; // Save the order as a value
            for (var key_process in order) { // ...and search all processes in that order nr
                if (typeof order[key_process] == 'object' && order[key_process] != '') { // If process contains an object as value and it's not empty
                    var process = order[key_process]; // Save the process as a value
                    for (var key_matnr in process) { // For every material in the process
                        if (typeof process[key_matnr] == 'object' && process[key_matnr] != '') { // If material nr contains an object as value and not empty
                            var matnr = process[key_matnr]; // Save material nr as value
                            for (var key_matname in matnr) { // For every material name in the material number
                                if (typeof matnr[key_matname] == 'object' && matnr[key_matname] != '') { // Contains object and not empty
                                    var matname = matnr[key_matname]; // Save material name
                                    emit([splitMsn[1], key_order, key_process, key_matnr], matname); // emit [001, 222123456, 0300, 51234567], Material name
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

With this view I can query for a specific document number, order, process and the material number. In return I get the material name with the amount (e.g. 1 which I'm after).

When I'm using one document the index is created just fine but even with a second document (let alone 15 or 20) CouchDB says "OS process timed out" while creating the view.

My question: is there a faster and/or more elegant way to iterate through all these steps to finally get to the deeply buried "amount" value that I need?

Many thanks in advance!

答:
The system is protecting itself from you.

In general, using large documents isn't hitting CouchDB's sweetspot. Add in deeply nested structures and very complex maps, and your situation is even worse.

I'd recommend reconsidering your data model. Use (much) smaller documents (one per material, say). Your map function will be much simpler, too.

Body:
I'm trying to create a view in CouchDB 2.1 for documents that are very large (around 300k-900k lines for each document, around 15-20 documents in total).

The documents look like this:

{
"222123456": {
    "_id": "222123456",
    "type": "Order",
    "0300": {
        "51234567": {
            "_id": "51234567",
            "type": "Material",
            "DS": "M532F1234567",
            "HTZ": "M532-F1234-000-00",
            "A name for some material": {
                "_id": "A name for some material",
                "type": "Description",
                "0054": {
                    "600": {
                        "1": {
                            "_id": "1",
                            "type": "Amount",
                            "X": {
                                "11220": {
                                    "_id": "11220",
                                    "type": "row"
                                },
                                "_id": "X",
                                "type": "Bulk"
                            }
                        },
                        "_id": "600",
                        "type": "Site"
                    },
                    "_id": "0054",
                    "type": "Pos"
                }
            }
        },
        "51255111": {
            // And another material
            // ...
        },
        "_id": "0300",
        "type": "Process"
    }
    // + more orders with more items
},
"222555666": {
    // Another order with more processes which contain even more materials
    // ...
},
"_id": "FileImport_001",
"_rev": "1-2f77e699332bb7c76a137b86f83bbe91",
"type": "Machine"
}

Every document has 1-n orders, every order has 1-n processes and every process contains 1-n materials which I'm trying to query. My current view iterates through all orders, processes and materials with for loops.

This is the view I'm using:

function (doc) {
    var splitMsn = doc._id.split("_"); // Split _id into [FileImport, 001] array
    for (var key_order in doc) { // For every order in the document...
        if (typeof doc[key_order] == 'object' && doc[key_order] != '') { // where the value is an object and not empty...
            var order = doc[key_order]; // Save the order as a value
            for (var key_process in order) { // ...and search all processes in that order nr
                if (typeof order[key_process] == 'object' && order[key_process] != '') { // If process contains an object as value and it's not empty
                    var process = order[key_process]; // Save the process as a value
                    for (var key_matnr in process) { // For every material in the process
                        if (typeof process[key_matnr] == 'object' && process[key_matnr] != '') { // If material nr contains an object as value and not empty
                            var matnr = process[key_matnr]; // Save material nr as value
                            for (var key_matname in matnr) { // For every material name in the material number
                                if (typeof matnr[key_matname] == 'object' && matnr[key_matname] != '') { // Contains object and not empty
                                    var matname = matnr[key_matname]; // Save material name
                                    emit([splitMsn[1], key_order, key_process, key_matnr], matname); // emit [001, 222123456, 0300, 51234567], Material name
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

With this view I can query for a specific document number, order, process and the material number. In return I get the material name with the amount (e.g. 1 which I'm after).

When I'm using one document the index is created just fine but even with a second document (let alone 15 or 20) CouchDB says "OS process timed out" while creating the view.

My question: is there a faster and/or more elegant way to iterate through all these steps to finally get to the deeply buried "amount" value that I need?

Many thanks in advance!


来源: stackexchange

问:
Getting Nuget Package missing error
I am getting the following issue while compiling my project. It is a MVC 5 application. Here is the error:

Severity    Code    Description Project File    Line    Suppression State
Error       This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props.    WikidoctorAdmin E:\My Projects\Wiki-Doctor\Wiki-Doctor.com\Wiki-Doctor.com\WikidoctorAdmin\WikidoctorAdmin.csproj   2107

Please help me how to solve this error.

答: The name of the project is longer than 248 characters. You need to rename the path under 248 characters, then open solution and rebuild and the nuget will be updated.</p>

ContentLicense: CC BY-SA 3.0

Title: Getting Nuget Package missing error


问:
iPhone/iPad HTTP streaming library or server
Is there any available open-source (preferred) or commercial library for on-fly segmenting and streaming of video to iPhone / iPad?

Also, is there any open-source/commercial server (alternative to Wowza) which supports this?

答:
Take a look at following link;

http://developer.apple.com/library/ios/#samplecode/MoviePlayer_iPhone/Introduction/Intro.html

This example will show how to play videos from a network based URL.

For more details about playing videos;

ContentLicense: CC BY-SA 2.5


问:
Best way of rendering a component with onClick (react)?
What I'm trying to do: when a user clicks a button, a new component is rendered (that component houses an image).

The problem: The way I have it setup, when a user clicks, the handleClick function sets flips the state to true, which in turn loads the component. However, this only works once. I'd like it keep creating new components, rather than to flip a switch, but I'm a relatively new coder and I can't quite figure out how to go about this.

Would appreciate the help on this :)

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Card from './card.js';

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
        clicked: false
      };
   this.handleClick = this.handleClick.bind(this);

    }

    handleClick() {
   this.setState({
     clicked: true
   });
 }

  render() {
    return (
      <div className="App">
      <h3 className="header">Random.</h3>

<div className="hi">
      <button onClick={this.handleClick}>Hit Me.</button>
</div>
      {this.state.clicked ? <Card /> : null}
      </div>
    );
  }
}

export default App;
</code>```

答:
Set up the state to hold an array.

```<code>this.state = { feedItems: [] }
</code>```

On every click, add an item to the array.

```<code>let { feedItems } = this.state;
feedItems = feedItems.slice();
feedItems.push({ imageUrl: 'some url' });
this.setState({ feedItems });
</code>```

Body:
What I'm trying to do: when a user clicks a button, a new component is rendered (that component houses an image).

The problem: The way I have it setup, when a user clicks, the handleClick function sets flips the state to true, which in turn loads the component. However, this only works once. I'd like it keep creating new components, rather than to flip a switch, but I'm a relatively new coder and I can't quite figure out how to go about this.

Would appreciate the help on this :)

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Card from './card.js';

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
        clicked: false
      };
   this.handleClick = this.handleClick.bind(this);

    }

    handleClick() {
   this.setState({
     clicked: true
   });
 }

  render() {
    return (

Random.

      <button onClick={this.handleClick}>Hit Me.</button>

      {this.state.clicked ? <Card /> : null}

    );
  }
}

export default App;

Body:
Set up the state to hold an array.

this.state = { feedItems: [] }

On every click, add an item to the array.

let { feedItems } = this.state;
feedItems = feedItems.slice();
feedItems.push({ imageUrl: 'some url' });
this.setState({ feedItems });


问:
WPF: How can I make the view dynamic?
I have the following xaml: What is needed that the following xaml must be filled dynamic at runtime, but how? The MainWorkspaceViewModel has a property named "View". This property is of type object, so I can set every view in it.</p>

```<code><UserControl x:Class="DesignerWorkspace.Views.MainWorkspaceView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DesignerWorkspace.Views"
             xmlns:vm="clr-namespace:DesignerWorkspace.ViewModels"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <ContentControl Content="{Binding View}"/>
    </Grid>
</UserControl>
</code>```

答:
The minimum would be to add a context that has the view and updates on property changed.

From somewhere else in the code you can then manage the displayed view by setting the new view.

Here is a simplistic implementation with missing checks you may want to add.

```<code>class MainWorkspaceViewModel : INotifyPropertyChanged
{
    private object _view;
    public object View {
        get { return _view; }
        set { _view = value; OnPropertyChanged(); }
    }
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

internal class MyViewManager
{
    internal static MainWorkspaceView MakeMainView()
    {
        var view = new MainWorkspaceView();
        view.DataContext = new MainWorkspaceViewModel();
        return view;
    }

    internal static void UpdateView(MainWorkspaceViewModel viewmodel, object _next)
    {
        viewmodel.View = _next;
    }
    internal static void UpdateView(MainWorkspaceView view, object _next)
    {
        (view.DataContext as MainWorkspaceViewModel).View = _next;
    }
}
</code>```

Title: WPF: How can I make the view dynamic?

Body:
I have the following xaml: What is needed that the following xaml must be filled dynamic at runtime, but how? The MainWorkspaceViewModel has a property named "View". This property is of type object, so I can set every view in it.

<UserControl x:Class="DesignerWorkspace.Views.MainWorkspaceView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DesignerWorkspace.Views"
             xmlns:vm="clr-namespace:DesignerWorkspace.ViewModels"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <ContentControl Content="{Binding View}"/>
    </Grid>
</UserControl>

Body:
The minimum would be to add a context that has the view and updates on property changed.

From somewhere else in the code you can then manage the displayed view by setting the new view.

Here is a simplistic implementation with missing checks you may want to add.

class MainWorkspaceViewModel : INotifyPropertyChanged
{
    private object _view;
    public object View {
        get { return _view; }
        set { _view = value; OnPropertyChanged(); }
    }
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

internal class MyViewManager
{
    internal static MainWorkspaceView MakeMainView()
    {
        var view = new MainWorkspaceView();
        view.DataContext = new MainWorkspaceViewModel();
        return view;
    }

    internal static void UpdateView(MainWorkspaceViewModel viewmodel, object _next)
    {
        viewmodel.View = _next;
    }
    internal static void UpdateView(MainWorkspaceView view, object _next)
    {
        (view.DataContext as MainWorkspaceViewModel).View = _next;
    }
}


问:
Implement perceptual loss with pretrained VGG using keras
I am relatively new to DL and Keras.

I am trying to implement perceptual loss using the pretrained VGG16 in Keras but have some troubles. I already found that question but I am still struggling :/

A short explanation of what my network should do:

I have a CNN (subsequent called mainModel) that gets grayscale images as input (#TrainData, 512, 512, 1) and outputs grayscale images with the same size. The network should reduce artifacts in the images - but I think it is not that important for this question. Instead of using e.g. MSE as loss function, I would like to implement the perceptual loss.

What I want to do (I hope I have properly understood the concept of perceptual loss):

I would like to append a lossModel (pretrained VGG16 with fixed params) to my mainModel. Then I would like to pass the output of the mainModel to the lossModel. In addition I pass the label images (Y_train) to the lossModel. Further on I compare the activations at a specific layer (e.g. block1_conv2) of the lossModel using e.g. MSE and use it as loss function.

What I did so far:

Load in data and create the mainModel:

```<code>### Load data ###
with h5py.File('.\train_test_val.h5', 'r') as hf:
    X_train = hf['X_train'][:]
    Y_train = hf['Y_train'][:]
    X_test = hf['X_test'][:]
    Y_test = hf['Y_test'][:]
    X_val = hf['X_val'][:]
    Y_val = hf['Y_val'][:]

### Create Main Model ###
input_1 = Input((512,512,9))
conv0 = Conv2D(64, (3,3), strides=(1,1), activation=relu, use_bias=True, padding='same')(input_1)
.
.
.

mainModel = Model(inputs=input_1, outputs=output)
</code>```

Create lossModel, append it to mainModel and fix params:

```<code>### Create Loss Model (VGG16) ###
lossModel = vgg16.VGG16(include_top=False, weights='imagenet', input_tensor=mainModel.output, input_shape=(512,512, 1))
lossModel.trainable=False

for layer in lossModel.layers:
    layer.trainable=False
</code>```

Create new model including both networks and compile it

```<code>### Create new Model ###
fullModel = Model(inputs=mainModel.input, outputs=lossModel.output)

fullModel.compile(loss='mse', optimizer='adam',metrics=['mse','mae'])
fullModel.summary()
</code>```

Adjust label images by passing them through the lossNetwork:

```<code>Y_train_lossModel = lossModel.predict(Y_train)
</code>```

Fit the fullModel using the perceptual loss:

```<code>fullModel.fit(X_train, Y_train_lossModel, batch_size=32, epochs=5, validation_data=[X_val,Y_val])
</code>```

Problems occurring:

VGG16 wants to get inputs of shape (?,?,3) but my mainModel outputs a grayscale image (?,?,1)

Some issue with appending the lossModel to the mainModel

RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("conv2d_2/Relu:0", shape=(?, 512, 512, 3), dtype=float32) at layer "input_2". The following previous layers were accessed without issue: []

How can I calculate the MSE at a specific layers activation and not at the output of the lossModel?

Thank you so much for your help and sorry for the extremely long question :)

答:
Number of channels

Well, the first problem is significant.

VGG models were made to color images with 3 channels... so, it's quite not the right model for your case. I'm not sure if there are models for black & white images, but you should search for them.

A workaround for that, which I don't know if will work well, is to make 3 copies  of mainModel's output.

```<code>tripleOut = Concatenate()([mainModel.output,mainModel.output,mainModel.output])
</code>```

Graph disconnected

This means that nowhere in your code, you created a connection between the input and output of fullModel. You must connect the output of mainModel to the input of lossModel

But first, let's prepare the VGG model for multiple outputs.

Preparing lossModel for multiple outputs

You must select which layers of the VGG model will be used to calculate the loss. If you use only the final output there won't be really a good perceptual loss because the final output is made more of concepts than of features.

So, after you select the layers, make a list of their indices or names:

```<code>selectedLayers = [1,2,9,10,17,18] #for instance
</code>```

Let's make a new model from VGG16, but with multiple outputs:

```<code>#a list with the output tensors for each selected layer:
selectedOutputs = [lossModel.layers[i].output for i in selectedLayers]
     #or [lossModel.get_layer(name).output for name in selectedLayers]

#a new model that has multiple outputs:
lossModel = Model(lossModel.inputs,selectedOutputs)
</code>```

Joining the models

Now, here we create the connection between the two models.

We call the lossModel (as if it were a layer) taking the output of the mainModel as input:

```<code>lossModelOutputs = lossModel(tripleOut) #or mainModel.output if not using tripeOut
</code>```

Now, with the graph entirely connected from the input of mainModel to the output of lossModel, we can create the fullModel:

```<code>fullModel = Model(mainModel.input, lossModelOutputs)

#if the line above doesn't work due to a type problem, make a list with lossModelOutputs:
lossModelOutputs = [lossModelOutputs[i] for i in range(len(selectedLayers))]
</code>```

Training

Take the predictions of this new lossModel, just as you did. But for the workaround, let's make it triple channel as well:

```<code>triple_Y_train = np.concatenate((Y_train,Y_train,Y_train),axis=-1)
Y_train_lossModel = lossModel.predict(triple_Y_train)
#the output will be a list of numpy arrays, one for each of the selected layers
</code>```

Make sure you make each layer of lossModel non trainable before fullModel.compile().

If you want 'mse' for all outputs, you just do:

```<code>fullModel.compile(loss='mse', ...)
</code>```

If you want a different loss for each layer, pass a list of losses:

```<code>fullModel.compile(loss=[loss1,loss2,loss3,...], ...)
</code>```

Additional considerations

Since VGG is supposed to work with images in the caffe format, you might want to add a few layers after mainModel to make the output suitable. It's not absolutely required, but it would use the best performance from VGG.

See how keras transforms an input image ranging from 0 to 255 into a caffe format here at line 15 or 44

Body:
I am relatively new to DL and Keras.

I am trying to implement perceptual loss using the pretrained VGG16 in Keras but have some troubles. I already found that question but I am still struggling :/

A short explanation of what my network should do:

I have a CNN (subsequent called mainModel) that gets grayscale images as input (#TrainData, 512, 512, 1) and outputs grayscale images with the same size. The network should reduce artifacts in the images - but I think it is not that important for this question. Instead of using e.g. MSE as loss function, I would like to implement the perceptual loss.

What I want to do (I hope I have properly understood the concept of perceptual loss):

I would like to append a lossModel (pretrained VGG16 with fixed params) to my mainModel. Then I would like to pass the output of the mainModel to the lossModel. In addition I pass the label images (Y_train) to the lossModel. Further on I compare the activations at a specific layer (e.g. block1_conv2) of the lossModel using e.g. MSE and use it as loss function.

What I did so far:

Load in data and create the mainModel:

### Load data ###
with h5py.File('.\train_test_val.h5', 'r') as hf:
    X_train = hf['X_train'][:]
    Y_train = hf['Y_train'][:]
    X_test = hf['X_test'][:]
    Y_test = hf['Y_test'][:]
    X_val = hf['X_val'][:]
    Y_val = hf['Y_val'][:]

### Create Main Model ###
input_1 = Input((512,512,9))
conv0 = Conv2D(64, (3,3), strides=(1,1), activation=relu, use_bias=True, padding='same')(input_1)
.
.
.

mainModel = Model(inputs=input_1, outputs=output)

Create lossModel, append it to mainModel and fix params:

### Create Loss Model (VGG16) ###
lossModel = vgg16.VGG16(include_top=False, weights='imagenet', input_tensor=mainModel.output, input_shape=(512,512, 1))
lossModel.trainable=False

for layer in lossModel.layers:
    layer.trainable=False

Create new model including both networks and compile it

### Create new Model ###
fullModel = Model(inputs=mainModel.input, outputs=lossModel.output)

fullModel.compile(loss='mse', optimizer='adam',metrics=['mse','mae'])
fullModel.summary()

Adjust label images by passing them through the lossNetwork:

Y_train_lossModel = lossModel.predict(Y_train)

Fit the fullModel using the perceptual loss:

fullModel.fit(X_train, Y_train_lossModel, batch_size=32, epochs=5, validation_data=[X_val,Y_val])

Problems occurring:

VGG16 wants to get inputs of shape (?,?,3) but my mainModel outputs a grayscale image (?,?,1)

Some issue with appending the lossModel to the mainModel

RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("conv2d_2/Relu:0", shape=(?, 512, 512, 3), dtype=float32) at layer "input_2". The following previous layers were accessed without issue: []

How can I calculate the MSE at a specific layers activation and not at the output of the lossModel?

Thank you so much for your help and sorry for the extremely long question :)

Body:
Number of channels

Well, the first problem is significant.

VGG models were made to color images with 3 channels... so, it's quite not the right model for your case. I'm not sure if there are models for black & white images, but you should search for them.

A workaround for that, which I don't know if will work well, is to make 3 copies  of mainModel's output.

tripleOut = Concatenate()([mainModel.output,mainModel.output,mainModel.output])

Graph disconnected

This means that nowhere in your code, you created a connection between the input and output of fullModel. You must connect the output of mainModel to the input of lossModel

But first, let's prepare the VGG model for multiple outputs.

Preparing lossModel for multiple outputs

You must select which layers of the VGG model will be used to calculate the loss. If you use only the final output there won't be really a good perceptual loss because the final output is made more of concepts than of features.

So, after you select the layers, make a list of their indices or names:

selectedLayers = [1,2,9,10,17,18] #for instance

Let's make a new model from VGG16, but with multiple outputs:

#a list with the output tensors for each selected layer:
selectedOutputs = [lossModel.layers[i].output for i in selectedLayers]
     #or [lossModel.get_layer(name).output for name in selectedLayers]

#a new model that has multiple outputs:
lossModel = Model(lossModel.inputs,selectedOutputs)

Joining the models

Now, here we create the connection between the two models.

We call the lossModel (as if it were a layer) taking the output of the mainModel as input:

lossModelOutputs = lossModel(tripleOut) #or mainModel.output if not using tripeOut

Now, with the graph entirely connected from the input of mainModel to the output of lossModel, we can create the fullModel:

fullModel = Model(mainModel.input, lossModelOutputs)

#if the line above doesn't work due to a type problem, make a list with lossModelOutputs:
lossModelOutputs = [lossModelOutputs[i] for i in range(len(selectedLayers))]

Training

Take the predictions of this new lossModel, just as you did. But for the workaround, let's make it triple channel as well:

triple_Y_train = np.concatenate((Y_train,Y_train,Y_train),axis=-1)
Y_train_lossModel = lossModel.predict(triple_Y_train)
#the output will be a list of numpy arrays, one for each of the selected layers

Make sure you make each layer of lossModel non trainable before fullModel.compile().

If you want 'mse' for all outputs, you just do:

fullModel.compile(loss='mse', ...)

If you want a different loss for each layer, pass a list of losses:

fullModel.compile(loss=[loss1,loss2,loss3,...], ...)

Additional considerations

Since VGG is supposed to work with images in the caffe format, you might want to add a few layers after mainModel to make the output suitable. It's not absolutely required, but it would use the best performance from VGG.

See how keras transforms an input image ranging from 0 to 255 into a caffe format here at line 15 or 44


问:
Visual Studio C++ 2015 std::codecvt with char16_t or char32_t
This code compiled OK under VS2013:

```<code>std::string Unicode::utf16_to_utf8(std::u16string utf16_string)
{
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
    return convert.to_bytes(utf16_string);
}
</code>```

Now with VS2015 I get:

```<code>1>unicode.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static class std::locale::id std::codecvt<char16_t,char,struct _Mbstatet>::id" (__imp_?id@?$codecvt@_SDU_Mbstatet@@@std@@2V0locale@2@A)
</code>```

答:
Another possible workaround is to use default second template parameter (wchar_t) for wstring_convert. It is working for "MS Visual Studio 2015 update 3". Please note that it is not platform-independent solution. Windows only.

```<code>std::string utf16_to_utf8(std::u16string u16_string)
{
    std::wstring wide_string(u16_string.begin(), u16_string.end());
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;
    return convert.to_bytes(wide_string);
}
</code>```

Body:
This code compiled OK under VS2013:

std::string Unicode::utf16_to_utf8(std::u16string utf16_string)
{
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
    return convert.to_bytes(utf16_string);
}

Now with VS2015 I get:

1>unicode.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static class std::locale::id std::codecvt<char16_t,char,struct _Mbstatet>::id" (__imp_?id@?$codecvt@_SDU_Mbstatet@@@std@@2V0locale@2@A)

Body:
Another possible workaround is to use default second template parameter (wchar_t) for wstring_convert. It is working for "MS Visual Studio 2015 update 3". Please note that it is not platform-independent solution. Windows only.

std::string utf16_to_utf8(std::u16string u16_string)
{
    std::wstring wide_string(u16_string.begin(), u16_string.end());
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;
    return convert.to_bytes(wide_string);
}


问:
How to get data from parsedJSON reactJS
I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :

```<code>  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => console.log(parsedJSON._id))
      .catch(error => alert('Check your data', error))
      .then(this.props.history.push('/get')) // change page layout and URL
    }
    console.log(this.state.id); //debug to see if the _id is saved in my state
  }
</code>```

Here is my constructor:

```<code>  constructor(props){
    super(props);
    this.state={
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:'',
      id:''
    }
  }
</code>```

I tried calling a function after parsedJSON that used this.setState(), using function(parsedJSON){this.state.id : parsedJSON._id}. I tried with a new function like this:

```<code>  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }
</code>```

and changing the .then(parsedJSON => console.log(parsedJSON._id)) to .then(parsedJSON => this.cahngeID(parsedJSON)). But none of then worked...

I left the code with .then(parsedJSON => console.log(parsedJSON._id)) so can make sure that I can see this value, and in my console it`s printed perfectly.

Here is a example of the response send by my backend:    {"email":"testing@gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}

How can I get the "_id" from my response?

答:
You should not touch the this.state property directly. React will throw an error if you do this because React needs to know when this.state has been updated so that it can keep track of the changes. It cannot do this if you manipulate the property directly. That's why we have React.Component#setState. The "shallow" version is the most commonly used, where you pass an object that will be merged into your state. For example, the following:

```<code>.then(parsedJSON => this.setState({ id: parsedJSON._id }))
</code>```

is equivalent to:

```<code>Object.assign(this.state, { id: parsedJSON._id });
</code>```

except that React gets to keep track of when the state is updated.

Note that setState is also asynchronous and takes a callback as the second parameter. You can read more about that here.

As per the comment below, this other Stack Overflow question was helpful to the OP (Why calling react setState method doesn't mutate the state immediately?)

Title: How to get data from parsedJSON reactJS

Body:
I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => console.log(parsedJSON._id))
      .catch(error => alert('Check your data', error))
      .then(this.props.history.push('/get')) // change page layout and URL
    }
    console.log(this.state.id); //debug to see if the _id is saved in my state
  }

Here is my constructor:

  constructor(props){
    super(props);
    this.state={
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:'',
      id:''
    }
  }

I tried calling a function after parsedJSON that used this.setState(), using function(parsedJSON){this.state.id : parsedJSON._id}. I tried with a new function like this:

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

and changing the .then(parsedJSON => console.log(parsedJSON._id)) to .then(parsedJSON => this.cahngeID(parsedJSON)). But none of then worked...

I left the code with .then(parsedJSON => console.log(parsedJSON._id)) so can make sure that I can see this value, and in my console it`s printed perfectly.

Here is a example of the response send by my backend:    {"email":"testing@gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}

How can I get the "_id" from my response?

Body:
You should not touch the this.state property directly. React will throw an error if you do this because React needs to know when this.state has been updated so that it can keep track of the changes. It cannot do this if you manipulate the property directly. That's why we have React.Component#setState. The "shallow" version is the most commonly used, where you pass an object that will be merged into your state. For example, the following:

.then(parsedJSON => this.setState({ id: parsedJSON._id }))

is equivalent to:

Object.assign(this.state, { id: parsedJSON._id });

except that React gets to keep track of when the state is updated.

Note that setState is also asynchronous and takes a callback as the second parameter. You can read more about that here.

As per the comment below, this other Stack Overflow question was helpful to the OP (Why calling react setState method doesn't mutate the state immediately?)


问:
How can I get Iframe event before load?
In my site, I use an iframeA in an iframeB, and, when the iframeA changes it's content I have to set the src. I can set it only with the onload event, but this called when the site is loaded. I am looking for some event or trigger, that helps me detect the location/src change before it starts loading. I don't want to wait the whole page load, before the src set. I have no direct access to iframeA (just the script below)

Some code:

```<code>var myframe = document.getElementById('frameB').contentWindow.document.getElementById('frameA');
myframe.onload=function (funcname) {...};
</code>```

答:
Check this gist or my answer to this question. The code there does exactly that:

```<code>function iframeURLChange(iframe, callback) {
    var unloadHandler = function () {
        // Timeout needed because the URL changes immediately after
        // the `unload` event is dispatched.
        setTimeout(function () {
            callback(iframe.contentWindow.location.href);
        }, 0);
    };

    function attachUnload() {
        // Remove the unloadHandler in case it was already attached.
        // Otherwise, the change will be dispatched twice.
        iframe.contentWindow.removeEventListener("unload", unloadHandler);
        iframe.contentWindow.addEventListener("unload", unloadHandler);
    }

    iframe.addEventListener("load", attachUnload);
    attachUnload();
}
</code>```

It utilizes the unload event. Whenever a page is unloaded, a new one is expected to start loading. If you listen for that event, though, you will get the current URL, not the new one. By adding a timeout with 0 milliseconds delay, and then checking the URL, you get the new iframe URL.

However, that unload listener is removed each time a new page is loaded, so it must be re-added again on each load.

The function takes care of all that, though. To use it, you only have to do:

```<code>iframeURLChange(document.getElementById("myframe"), function (url) {
    console.log("URL changed:", url);
});
</code>```

Title: How can I get Iframe event before load?

Body:
In my site, I use an iframeA in an iframeB, and, when the iframeA changes it's content I have to set the src. I can set it only with the onload event, but this called when the site is loaded. I am looking for some event or trigger, that helps me detect the location/src change before it starts loading. I don't want to wait the whole page load, before the src set. I have no direct access to iframeA (just the script below)

Some code:

var myframe = document.getElementById('frameB').contentWindow.document.getElementById('frameA');
myframe.onload=function (funcname) {...};

Body:
Check this gist or my answer to this question. The code there does exactly that:

function iframeURLChange(iframe, callback) {
    var unloadHandler = function () {
        // Timeout needed because the URL changes immediately after
        // the `unload` event is dispatched.
        setTimeout(function () {
            callback(iframe.contentWindow.location.href);
        }, 0);
    };

    function attachUnload() {
        // Remove the unloadHandler in case it was already attached.
        // Otherwise, the change will be dispatched twice.
        iframe.contentWindow.removeEventListener("unload", unloadHandler);
        iframe.contentWindow.addEventListener("unload", unloadHandler);
    }

    iframe.addEventListener("load", attachUnload);
    attachUnload();
}

It utilizes the unload event. Whenever a page is unloaded, a new one is expected to start loading. If you listen for that event, though, you will get the current URL, not the new one. By adding a timeout with 0 milliseconds delay, and then checking the URL, you get the new iframe URL.

However, that unload listener is removed each time a new page is loaded, so it must be re-added again on each load.

The function takes care of all that, though. To use it, you only have to do:

iframeURLChange(document.getElementById("myframe"), function (url) {
    console.log("URL changed:", url);
});


问:
Looping for json object not working in javascript
I am having json values in an object called dataResponse. What I want is, I want to loop the object and fill values to the control. SO for looping I tried like this below

```<code>for (var i = 0; i < dataResponse.Table.length; i++) {
                if (dataResponse.Table[i] != "" || dataResponse.Table[i] != null) {
                    $("#spnLinkId").text(dataResponse.Table[i].LINK_ID);
                    $("#spnSpanLength").text(dataResponse.Table[i].NE_SPAN_LENGTH);
                    $("#txtFiberActlength").val(dataResponse.Table[i].HOTO_ACTUAL_LENGTH);
                    $("#txtLITActlength").val(dataResponse.Table[i].LIT_ACTUAL_LENGTH);

                    var hotoOfferedDate = new Date(dataResponse.Table[i].HOTO_OFFERED_DATE);
                    var FinalHotoOfferedDate = hotoOfferedDate.getDate() + '/' + (hotoOfferedDate.getMonth() + 1) + '/' + hotoOfferedDate.getFullYear();
                    $("#spnHotoOfferDt").text(FinalHotoOfferedDate);
                    $('#spnApprRejRemarks').text(dataResponse.Table[i].APPROV_REJECT_REMARK);

                }
                if (dataResponse.Table[i].ISABDMISSING != "" || dataResponse.Table[i].ISABDMISSING != null) {
                    if (dataResponse.Table[i].ISABDMISSING == 1) {
                        $("#FEmissingAsBuiltYes").prop("checked", true);
                    }
                    else {
                        $("#FEmissingAsBuiltNo").prop("checked", true);
                    }
                }
            }
</code>```

But I have 4 tables in an object. So for other tables it is not working as expected.

Below is my screenshot for your reference.

Also see

And my response code is below

var dataResponse = JSON.parse(response);

Please suggest how to loop

JSON DATA

答:
You can use this coding format to iterate over all tables,</p>

```<code>for (var key in response)
{
   console.log(key); //key will give Table, Table1 etc.
   for(var i = 0; i < response[key].length; i++)
     {
        var data = response[key][i]; // data will give object in table based on key
        if (data.ISABDMISSING != null)
           {
              if (data.ISABDMISSING == 1)
                 {
                     console.log(data.ISABDMISSING);
                 }
           }
      }
}
</code>```

Body:
I am having json values in an object called dataResponse. What I want is, I want to loop the object and fill values to the control. SO for looping I tried like this below

for (var i = 0; i < dataResponse.Table.length; i++) {
                if (dataResponse.Table[i] != "" || dataResponse.Table[i] != null) {
                    $("#spnLinkId").text(dataResponse.Table[i].LINK_ID);
                    $("#spnSpanLength").text(dataResponse.Table[i].NE_SPAN_LENGTH);
                    $("#txtFiberActlength").val(dataResponse.Table[i].HOTO_ACTUAL_LENGTH);
                    $("#txtLITActlength").val(dataResponse.Table[i].LIT_ACTUAL_LENGTH);

                    var hotoOfferedDate = new Date(dataResponse.Table[i].HOTO_OFFERED_DATE);
                    var FinalHotoOfferedDate = hotoOfferedDate.getDate() + '/' + (hotoOfferedDate.getMonth() + 1) + '/' + hotoOfferedDate.getFullYear();
                    $("#spnHotoOfferDt").text(FinalHotoOfferedDate);
                    $('#spnApprRejRemarks').text(dataResponse.Table[i].APPROV_REJECT_REMARK);

                }
                if (dataResponse.Table[i].ISABDMISSING != "" || dataResponse.Table[i].ISABDMISSING != null) {
                    if (dataResponse.Table[i].ISABDMISSING == 1) {
                        $("#FEmissingAsBuiltYes").prop("checked", true);
                    }
                    else {
                        $("#FEmissingAsBuiltNo").prop("checked", true);
                    }
                }
            }

But I have 4 tables in an object. So for other tables it is not working as expected.

Below is my screenshot for your reference.

Also see

And my response code is below

var dataResponse = JSON.parse(response);

Please suggest how to loop

JSON DATA

Body:
You can use this coding format to iterate over all tables,

for (var key in response)
{
   console.log(key); //key will give Table, Table1 etc.
   for(var i = 0; i < response[key].length; i++)
     {
        var data = response[key][i]; // data will give object in table based on key
        if (data.ISABDMISSING != null)
           {
              if (data.ISABDMISSING == 1)
                 {
                     console.log(data.ISABDMISSING);
                 }
           }
      }
}


问:
Oracle Trigger How to get Inserted value's parameter
I have a question while studying Oracle Database's triggers.

First of all, I created two tables like below:

```<code>**[Employee]**
(empno NUMBER, VARCHAR2 (20), deptno NUMBER, salary NUMBER)
**[Department]**
(deptno NUMBER, dname VARCHAR2 (20))
</code>```

Employee deptno refers to Department's deptno.

The trigger I want to create is to calculate the salary average of the data with deptno, such as inserted deptno.

For example, suppose I run the following code.

```<code>INSERT INTO employee values (1000, 'PAUL', 10, 4000);
</code>```

Then Trigger would like to have the following output:

```<code>Department [10]'s average of Salary = <avg (salary)>
</code>```

But I do not know how to pass inserted row's parameter in the Trigger.

Does anyone have a good way for me?

答:
This makes no sense to be implemented as a trigger.  This is just a simple SQL query :</p>

```<code>select deptno ,avg(salary)
from employee
group by deptno
</code>```

Body:
I have a question while studying Oracle Database's triggers.

First of all, I created two tables like below:

**[Employee]**
(empno NUMBER, VARCHAR2 (20), deptno NUMBER, salary NUMBER)
**[Department]**
(deptno NUMBER, dname VARCHAR2 (20))

Employee deptno refers to Department's deptno.

The trigger I want to create is to calculate the salary average of the data with deptno, such as inserted deptno.

For example, suppose I run the following code.

INSERT INTO employee values (1000, 'PAUL', 10, 4000);

Then Trigger would like to have the following output:

Department [10]'s average of Salary = <avg (salary)>

But I do not know how to pass inserted row's parameter in the Trigger.

Does anyone have a good way for me?

Body:
This makes no sense to be implemented as a trigger.  This is just a simple SQL query :

select deptno ,avg(salary)
from employee
group by deptno


问:
Order By not working with Top MS SQL Query
I'm creating a query that should fit with the DataTable I'm working on from MsSQL. This is my first time to work on MsSQL so I'm trying to figure out the equivalent MsSQL query from my MySQL.

I made a custom query that will handle the LIMIT function in MySQL to MsSQL(hopefully). I have the following query that I use in my datatable:

```<code>    SELECT * FROM (
        SELECT top 20 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as foo
    except
    SELECT * FROM (
        SELECT top 10 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as bar
</code>```

The result is:

```<code>week_name     | Average_Delivery_Days
==================================
2017 Week 36  | 15
2017 Week 39  | 11
2017 Week 41  | 13
2017 Week 42  | 10
2017 Week 38  | 12
2017 Week 40  | 12
2017 Week 35  | 14
2017 Week 43  | 6
2017 Week 37  | 12
2017 Week 44  | 9
</code>```

But I would like it to be sorted by week number ascending so it should display 36, 37, 38, 39, and so on.

What could be missing in my query?

I appreciate your help. Thanks!

答:
For anyone having a similar situation, I finally got the right query:</p>

```<code>SELECT
/* Explicitly select these columns */
week_name, Average_Delivery_Days, delivery_date_year, delivery_date_week
FROM (
SELECT top 20
CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
DATEPART(YEAR,[DeliveryDate]) as delivery_date_year, DATEPART(WEEK,[DeliveryDate]) as delivery_date_week,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
FROM [CARGODB].[dbo].[Cargo_Transactions]
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
ORDER BY delivery_date_year ASC, delivery_date_week ASC
) as foo
EXCEPT
SELECT week_name, Average_Delivery_Days, delivery_date_year, delivery_date_week
FROM (
SELECT top 10
CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
DATEPART(YEAR,[DeliveryDate]) as delivery_date_year, DATEPART(WEEK,[DeliveryDate]) as delivery_date_week,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
FROM [CARGODB].[dbo].[Cargo_Transactions]
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
ORDER BY delivery_date_year ASC, delivery_date_week ASC
) as bar ORDER BY delivery_date_week, delivery_date_year
</code>```

Body:
I'm creating a query that should fit with the DataTable I'm working on from MsSQL. This is my first time to work on MsSQL so I'm trying to figure out the equivalent MsSQL query from my MySQL.

I made a custom query that will handle the LIMIT function in MySQL to MsSQL(hopefully). I have the following query that I use in my datatable:

    SELECT * FROM (
        SELECT top 20 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as foo
    except
    SELECT * FROM (
        SELECT top 10 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as bar

The result is:

week_name     | Average_Delivery_Days
==================================
2017 Week 36  | 15
2017 Week 39  | 11
2017 Week 41  | 13
2017 Week 42  | 10
2017 Week 38  | 12
2017 Week 40  | 12
2017 Week 35  | 14
2017 Week 43  | 6
2017 Week 37  | 12
2017 Week 44  | 9

But I would like it to be sorted by week number ascending so it should display 36, 37, 38, 39, and so on.

What could be missing in my query?

I appreciate your help. Thanks!

Body:
For anyone having a similar situation, I finally got the right query:

SELECT
/* Explicitly select these columns */
week_name, Average_Delivery_Days, delivery_date_year, delivery_date_week
FROM (
SELECT top 20
CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
DATEPART(YEAR,[DeliveryDate]) as delivery_date_year, DATEPART(WEEK,[DeliveryDate]) as delivery_date_week,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
FROM [CARGODB].[dbo].[Cargo_Transactions]
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
ORDER BY delivery_date_year ASC, delivery_date_week ASC
) as foo
EXCEPT
SELECT week_name, Average_Delivery_Days, delivery_date_year, delivery_date_week
FROM (
SELECT top 10
CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
DATEPART(YEAR,[DeliveryDate]) as delivery_date_year, DATEPART(WEEK,[DeliveryDate]) as delivery_date_week,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
FROM [CARGODB].[dbo].[Cargo_Transactions]
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
ORDER BY delivery_date_year ASC, delivery_date_week ASC
) as bar ORDER BY delivery_date_week, delivery_date_year


问:
Rails - Where condition in models
I am using nested includes on Active Record. I want to add conditions on associated models in nested Includes.
In the following code, I have to add where condition on submissions and user_tutorials associations.

How to conditionally include associated models when using .to_json on a model?

```<code>@courses = Course.where("course_id=?",15).includes(:course_series,{courses_languages:[{courses_tutorials:[{tutorials:[{submissions:[:users]},:user_tutorials]}]}]})

@courses.to_json(:include =>
            [:course_series,
            {:courses_languages =>
                {:include =>
                  {:courses_tutorials =>
                    {:include =>
                      {:tutorials =>
                        {:include =>
                          {:submissions =>
                            {:include =>
                              {users: {only: [:user_id]}}
                          },
                          :user_tutorials => {}
                        }
                      }
                    }
                  }
                }
              }
            }
          ])
</code>```

答:
You can use conditions directly in a where clause:

```<code>@courses = @courses.where(
  submissions: { /* submissions conditions */ },
  user_tutorials: { /* user_tutorial conditions */ })
</code>```

You can also have nested conditions which are useful when your join condition repeats some tables.

For example, if you want to filter submissions by some user's conditions and user_tutorials by other user conditions, you should do the following:

```<code>@courses = @courses.where(
  submissions: { users: { /* will affect submissions rows only */ } },
  user_tutorials: { users: { /* will affect user_tutorials row count only */ } })
</code>```

But in your case, seems that

```<code>@courses = @courses.where(
  submissions: { /* submissions conditions */ },
  user_tutorials: { /* user_tutorial conditions */ })
</code>```

is enough.

Title: Rails - Where condition in models

Body:
I am using nested includes on Active Record. I want to add conditions on associated models in nested Includes.
In the following code, I have to add where condition on submissions and user_tutorials associations.

How to conditionally include associated models when using .to_json on a model?

@courses = Course.where("course_id=?",15).includes(:course_series,{courses_languages:[{courses_tutorials:[{tutorials:[{submissions:[:users]},:user_tutorials]}]}]})

@courses.to_json(:include =>
            [:course_series,
            {:courses_languages =>
                {:include =>
                  {:courses_tutorials =>
                    {:include =>
                      {:tutorials =>
                        {:include =>
                          {:submissions =>
                            {:include =>
                              {users: {only: [:user_id]}}
                          },
                          :user_tutorials => {}
                        }
                      }
                    }
                  }
                }
              }
            }
          ])

Body:
You can use conditions directly in a where clause:

@courses = @courses.where(
  submissions: { /* submissions conditions */ },
  user_tutorials: { /* user_tutorial conditions */ })

You can also have nested conditions which are useful when your join condition repeats some tables.

For example, if you want to filter submissions by some user's conditions and user_tutorials by other user conditions, you should do the following:

@courses = @courses.where(
  submissions: { users: { /* will affect submissions rows only */ } },
  user_tutorials: { users: { /* will affect user_tutorials row count only */ } })

But in your case, seems that

@courses = @courses.where(
  submissions: { /* submissions conditions */ },
  user_tutorials: { /* user_tutorial conditions */ })

is enough.


问:
How to view php logs information with php docker container?
I have a php-fpm docker container .  Php-fpm is run inside container, can i get php-fpm's log on host machine?  If i can,  how to do?</p>

答:
The standard for Docker containers is to log to stdout/stderr. However this doesn't work well for some PHP runtimes, for example php-fpm, because of how logs get mangled in length and format.

Therefore, I switched my approach to write logs on a volume and using a sidecar container to get it into stderr and hence into Docker's log collection and/or your orchestrator.

Sample docker-compose.yml section:

```<code>cli:
    build: .
    volumes:
        - logs:/srv/annotations/var/logs
logger:
    image: busybox:1.27.2
    volumes:
        - logs:/logs
    # be careful, this will only tail alredy existing files
    command: tail -f /logs/all.json
    depends_on:
        - cli
</code>```

Body:
The standard for Docker containers is to log to stdout/stderr. However this doesn't work well for some PHP runtimes, for example php-fpm, because of how logs get mangled in length and format.

Therefore, I switched my approach to write logs on a volume and using a sidecar container to get it into stderr and hence into Docker's log collection and/or your orchestrator.

Sample docker-compose.yml section:

cli:
    build: .
    volumes:
        - logs:/srv/annotations/var/logs
logger:
    image: busybox:1.27.2
    volumes:
        - logs:/logs
    # be careful, this will only tail alredy existing files
    command: tail -f /logs/all.json
    depends_on:
        - cli


问:
C free int array in function after writing value to other variable
i want to free memory allocated to int array in function after assign value from array element to integer variable.

I have code:

```<code> int u(int n)
   {
    int* values = (int*)malloc(sizeof(int)*n + 1);
    int out = 0;
    for (int i = 0; i < 3; i++)
      values[i] = 1;
    if (n < 3)
      return 1;
    else
    {
        for (int i = 3; i <= n; i++)
            values[i] = values[i - values[i - 1]] + values[i - values[i - 2]];
    }
    out = values[n];
    free(values);
    return out;
}
</code>```

Why cant i free memory allocated to array after write a value to another variable?
int out have another adress then allocated memory, all what i want to do its just give a value from array to another variable. Can somebody explain me why i cannot do it?

答:
Have a look to the comments.</p>

```<code>int u(int n)
   {
    if (n < 3)  // moved it here. If n it's smaller you have a smaller array; move it ahead of malloc/free’s
       return 1;
    int* values = (int*)malloc(sizeof(int)*(n + 1));
    int out = 0;
    for (int i = 0; i <= n; i++)
    {
       if(i<3)
          values[i] = 1;
       else
          values[i] = values[i - values[i - 1]] + values[i - values[i - 2]]; // this is suspicious; what do you want to obtain ?
    }

    out = values[n];
    if(values!=NULL)
       free(values);
    return out;
}
</code>```

Body:
i want to free memory allocated to int array in function after assign value from array element to integer variable.

I have code:

 int u(int n)
   {
    int* values = (int*)malloc(sizeof(int)*n + 1);
    int out = 0;
    for (int i = 0; i < 3; i++)
      values[i] = 1;
    if (n < 3)
      return 1;
    else
    {
        for (int i = 3; i <= n; i++)
            values[i] = values[i - values[i - 1]] + values[i - values[i - 2]];
    }
    out = values[n];
    free(values);
    return out;
}

Why cant i free memory allocated to array after write a value to another variable?
int out have another adress then allocated memory, all what i want to do its just give a value from array to another variable. Can somebody explain me why i cannot do it?

Body:
Have a look to the comments.

int u(int n)
   {
    if (n < 3)  // moved it here. If n it's smaller you have a smaller array; move it ahead of malloc/free’s
       return 1;
    int* values = (int*)malloc(sizeof(int)*(n + 1));
    int out = 0;
    for (int i = 0; i <= n; i++)
    {
       if(i<3)
          values[i] = 1;
       else
          values[i] = values[i - values[i - 1]] + values[i - values[i - 2]]; // this is suspicious; what do you want to obtain ?
    }

    out = values[n];
    if(values!=NULL)
       free(values);
    return out;
}


问:
DRF Serializer readable - writeable non-model field
On a project with Django / DRF; I have the following model structure:

```<code>class City(models.Model):
    name = models.CharField(max_length=100)

class Company(models.Model):
    city = models.ForeignKey(City)
    .
    .
</code>```

And following serializer structure for Company model:

```<code>class CompanySerializer(serializers.ModelSerializer):
    city_name = serializers.CharField(write_only=True)
    .
    .

    class Meta:
        model = Company
        fields = ('city_name',)

    def create(self, validated_data):

        # Get city
        city_name = validated_data.pop('city_name')
        try:
            city = City.objects.get(name__iexact=city_name)
        except City.DoesNotExist:
            city = City.objects.create(name=city_name.title())

        company = Company.objects.create(city=city, **validated_data)

        return company
</code>```

While creating a company through the serializer, user provides a city_name, I create a new city with that name if not exists or use an existing entry if exists. In this structure, I want to be able to return city_name field while returning companies. It is not a field on the model, so I could use SerializerMethodField normally, but I also want this field to be writable as well. Do I have any options here?

答:
i think, your solution is simple to add source and remove write_only:

```<code>city_name = serializers.CharField(source='city.name')
</code>```

After changing to this approach, you can get city name in create or update methods as follows:

```<code>city_data = validated_data.pop('city')
city_name = city_data.get('name')
</code>```

Body:
On a project with Django / DRF; I have the following model structure:

class City(models.Model):
    name = models.CharField(max_length=100)

class Company(models.Model):
    city = models.ForeignKey(City)
    .
    .

And following serializer structure for Company model:

class CompanySerializer(serializers.ModelSerializer):
    city_name = serializers.CharField(write_only=True)
    .
    .

    class Meta:
        model = Company
        fields = ('city_name',)

    def create(self, validated_data):

        # Get city
        city_name = validated_data.pop('city_name')
        try:
            city = City.objects.get(name__iexact=city_name)
        except City.DoesNotExist:
            city = City.objects.create(name=city_name.title())

        company = Company.objects.create(city=city, **validated_data)

        return company

While creating a company through the serializer, user provides a city_name, I create a new city with that name if not exists or use an existing entry if exists. In this structure, I want to be able to return city_name field while returning companies. It is not a field on the model, so I could use SerializerMethodField normally, but I also want this field to be writable as well. Do I have any options here?

Body:
i think, your solution is simple to add source and remove write_only:

city_name = serializers.CharField(source='city.name')

After changing to this approach, you can get city name in create or update methods as follows:

city_data = validated_data.pop('city')
city_name = city_data.get('name')


问:
Why does my query to hang/run for ever with variables instead of literals?
I have a relatively simple query that runs in about 2.5 minutes when I run it with literal values in the where clause. But when I run it with local variables containing those same values, the query hangs or runs presumably forever. (I haven't tried letting it run more than 90 minutes.)

Here's the query with names obfuscated (because rules). I've tried replacing the EXISTS with INNER JOINs, but it didn't help. The variables below are local variables, not parameters. This can't be a parameter sniffing issue. But when the variables are replaced with their literal values (two DATETIMEs and three INTs) the query runs fine.

```<code>DECLARE @SubsetStart DATETIME = '2013-01-01 00:00:00'
DECLARE @SubsetEnd DATETIME = '2013-12-31 23:59:59'
DECLARE @SCD INT = 217
DECLARE @MFP INT = 8
DECLARE @EXP INT = 39298

SELECT
    MainTable.MFID ManufacturerID
    ,SUM(MainTable.AMT) AMT
FROM
    MainTable
WHERE
    EXISTS (
        SELECT TID
        FROM MTMTable
        WHERE MTMTable.TID = MainTable.TID
            AND MTMTable.DEL = 0
            AND EXISTS (
                SELECT CID
                FROM RelatedTable
                WHERE RelatedTable.CID = MTMTable.CID
                    AND DEL = 0
                    AND RelatedTable.TD BETWEEN '2013-01-1' AND '2013-12-31 23:59:59'
            )
    )
    AND EXISTS (
        SELECT AID
        FROM OtherTable
        WHERE OtherTable.AID = MainTable.CAID
            AND OtherTable.AHTID = 8
            AND OtherTable.DEL = 0)
    AND MainTable.DAID <> 39298
    AND MainTable.SID = 217
GROUP BY
    MainTable.MFID
</code>```

I am completely at a loss as to why this simple query should behave this way.

答:
The issue is that when you use local variables the optimizer ignores their value and uses general statistic assumptions.  Basically at compile time it does not know the value of those variables.  You can verify this by using the OPTION(RECOMPILE) hint on your query, this will recompile the query using the values in your variables.

You can read about why using local variables in stored procedures can hurt performance here:

https://www.brentozar.com/archive/2014/06/tuning-stored-procedures-local-variables-problems/

and here:

http://www.sqlbadpractices.com/using-local-variables-in-t-sql-queries/

Body:
I have a relatively simple query that runs in about 2.5 minutes when I run it with literal values in the where clause. But when I run it with local variables containing those same values, the query hangs or runs presumably forever. (I haven't tried letting it run more than 90 minutes.)

Here's the query with names obfuscated (because rules). I've tried replacing the EXISTS with INNER JOINs, but it didn't help. The variables below are local variables, not parameters. This can't be a parameter sniffing issue. But when the variables are replaced with their literal values (two DATETIMEs and three INTs) the query runs fine.

DECLARE @SubsetStart DATETIME = '2013-01-01 00:00:00'
DECLARE @SubsetEnd DATETIME = '2013-12-31 23:59:59'
DECLARE @SCD INT = 217
DECLARE @MFP INT = 8
DECLARE @EXP INT = 39298

SELECT
    MainTable.MFID ManufacturerID
    ,SUM(MainTable.AMT) AMT
FROM
    MainTable
WHERE
    EXISTS (
        SELECT TID
        FROM MTMTable
        WHERE MTMTable.TID = MainTable.TID
            AND MTMTable.DEL = 0
            AND EXISTS (
                SELECT CID
                FROM RelatedTable
                WHERE RelatedTable.CID = MTMTable.CID
                    AND DEL = 0
                    AND RelatedTable.TD BETWEEN '2013-01-1' AND '2013-12-31 23:59:59'
            )
    )
    AND EXISTS (
        SELECT AID
        FROM OtherTable
        WHERE OtherTable.AID = MainTable.CAID
            AND OtherTable.AHTID = 8
            AND OtherTable.DEL = 0)
    AND MainTable.DAID <> 39298
    AND MainTable.SID = 217
GROUP BY
    MainTable.MFID

I am completely at a loss as to why this simple query should behave this way.


问:
How to use awk to edit lines in a file
I have a file that has a bunch of unique entries in it, each one on its own line.  I'm trying to take some system variables I've created and insert them into the file on the respective line.  I keep getting it inserted on the next line, or a random carriage return.

Here is an example of the file:

```<code>[default]
access_key =
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com
</code>```

Here is the script / commands I've figured out so far:

```<code>accesskey="ACCESSKEYWOULDENDUPHERE"
awk -i inplace -v x="$accesskey" '{print} /access_key =/ {print x}' /root/.s3cfg
</code>```

This is what happens

```<code>[default]
access_key =
ACCESSKEYWOULDENDUPHERE
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com
</code>```

As you can see, I end up inserting on a new line.

My goal is for it to look like this:

```<code>[default]
access_key = ACCESSKEYWOULDENDUPHERE
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com
</code>```

I am trying to figure out how to use printf but its just not working out so far.

答:
To set the access_key value all you need to do is set the delimiter as = and match the field in $1 to contain access_key (remember the trailing whitespace) and update the $2 value accordingly. The reason is for absolute strings (not changing like access_key), it would be more easy to do a direct comparison than do a regex match of it.

```<code>awk -v x="$accesskey" -vFS='=' -vOFS='=' '$1 == "access_key "{$2=" "x}1' file
</code>```

Add the -i inplace flag once you find it working as you wanted it.

Title: How to use awk to edit lines in a file

Body:
I have a file that has a bunch of unique entries in it, each one on its own line.  I'm trying to take some system variables I've created and insert them into the file on the respective line.  I keep getting it inserted on the next line, or a random carriage return.

Here is an example of the file:

[default]
access_key =
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com

Here is the script / commands I've figured out so far:

accesskey="ACCESSKEYWOULDENDUPHERE"
awk -i inplace -v x="$accesskey" '{print} /access_key =/ {print x}' /root/.s3cfg

This is what happens

[default]
access_key =
ACCESSKEYWOULDENDUPHERE
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com

As you can see, I end up inserting on a new line.

My goal is for it to look like this:

[default]
access_key = ACCESSKEYWOULDENDUPHERE
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com

I am trying to figure out how to use printf but its just not working out so far.

Body:
To set the access_key value all you need to do is set the delimiter as = and match the field in $1 to contain access_key (remember the trailing whitespace) and update the $2 value accordingly. The reason is for absolute strings (not changing like access_key), it would be more easy to do a direct comparison than do a regex match of it.

awk -v x="$accesskey" -vFS='=' -vOFS='=' '$1 == "access_key "{$2=" "x}1' file

Add the -i inplace flag once you find it working as you wanted it.


问:
iphone reposition UITableView when hidding element above it
I would like to make this:

So... when a user clicks on the search icon (top-left) the searchBar is set to hidden and UITableView is resized to top. How can I resize a table? Is it possible to achieve this not usign dimensions (like just set table's top to the navigation's bottom or smth)?

Thx.

答:
You have to modify the table view's frame inside an animation block. It is up to you to calculate the correct dimensions of the frame rectangle.

```<code>CGRect newFrame = self.tableView.frame;
newFrame.origin.x -= self.navigationBar.frame.size.height;
newFrame.size.height += self.navigationBar.frame.size.height;
[UIView animateWithDuration:0.25 animations:^{
    self.tableView.frame = newFrame;
}];
</code>```

Body:
You have to modify the table view's frame inside an animation block. It is up to you to calculate the correct dimensions of the frame rectangle.

CGRect newFrame = self.tableView.frame;
newFrame.origin.x -= self.navigationBar.frame.size.height;
newFrame.size.height += self.navigationBar.frame.size.height;
[UIView animateWithDuration:0.25 animations:^{
    self.tableView.frame = newFrame;
}];


问:
any way to cache routes.php file in codeigniter?
i'm trying to add dynamic routes from database in CI. but my website is really slow after adding data into my table.

anyway to performed routes.php file? or anyway to speed up my site?

NOTE: i have more than 60,000 record for SEO friendly url.

routes affected my response server time, its about 4 seconds.

here is my code:

```<code>require_once(BASEPATH . 'database/DB' . EXT);
require_once(BASEPATH . 'helpers/url_helper' . EXT);
require_once(BASEPATH . 'helpers/text_helper' . EXT);
$db = &DB();

$query = $db->query('select id,title from news');
$result = $query->result();
foreach ($result as $row) {
    $string = strtolower(str_replace(' ', '-', $row->title));
    $route["funny-news/" . $string] = "news/newsDetails/$row->id";
}
</code>```

Thanks.

EDIT:

newsDetails Controller code:

```<code>public function newsDetails($id)
    {
        $hdata['active'] = "news";
        $result['news'] = $this->mytestdb->getNewsById($id);
        $this->load->view('nheader', $hdata);
        $this->load->view('newsDetails', $result);
        $this->load->view('footer');
    }
</code>```

答: My advice would be to build your own subclass(MY_Controller).In your controller load the database and write routing directly into routes file with file_put_contents.</p>

Body:
i'm trying to add dynamic routes from database in CI. but my website is really slow after adding data into my table.

anyway to performed routes.php file? or anyway to speed up my site?

NOTE: i have more than 60,000 record for SEO friendly url.

routes affected my response server time, its about 4 seconds.

here is my code:

require_once(BASEPATH . 'database/DB' . EXT);
require_once(BASEPATH . 'helpers/url_helper' . EXT);
require_once(BASEPATH . 'helpers/text_helper' . EXT);
$db = &DB();

$query = $db->query('select id,title from news');
$result = $query->result();
foreach ($result as $row) {
    $string = strtolower(str_replace(' ', '-', $row->title));
    $route["funny-news/" . $string] = "news/newsDetails/$row->id";
}

Thanks.

EDIT:

newsDetails Controller code:

public function newsDetails($id)
    {
        $hdata['active'] = "news";
        $result['news'] = $this->mytestdb->getNewsById($id);
        $this->load->view('nheader', $hdata);
        $this->load->view('newsDetails', $result);
        $this->load->view('footer');
    }


问:
how to open the RDP dialog using Selenium Webdriver C#
I'm trying to open a dialog to open an RDP session

Also will I be able to run any of my scripts on a VM.

I wanted to check if the folders exist on the VM.

答: You can't do this with Selenium. Use MS Ui Automation or any wrapper like FlaUI or TestStack.White</p>


问:
How to read target names from file, append some string to them, and create make rules from them?
I want to have file, when I can list of names (one in the line), so that when make is invoked, rules are generated on the fly from this names with some string appended to it.

Example:

file contents:

```<code>target1
target2
target3
</code>```

String to concatenate: my_task_

From this I want to have 3 rules:

```<code>my_task_target1:
    <some things to do>

my_task_target2:
    <some things to do>

my_task_target3:
    <some things to do>
</code>```

I know, that when I have array with all this targets names, I can do this like in this answer, but I need to read data from file.

I want it to be this way, because I will have many targets, and there is different list of tasks for every target. Each task will have it's own file with list of targets. At the end I will also create rules with names after target, but without prefix, and this rules will have all tasks, that are assigned to some target, so that I can invoke separated tasks, and also all needed tasks for target with one make command.

How can I achieve this? Or maybe there is a better way to do what I want to do?

答:
The following Makefile dynamically creates the targets read from the file list:

```<code># the file with the targets
targets-file := list

# the string to concatenate
prefix := my_tasks_

# read the targets from the file indicated by the variable targets-file
targets != cat "$(targets-file)"

# concatenate the string to each target
targets := $(addprefix $(prefix),$(targets))

.PHONY: all
all: $(targets)

# function for creating a target
define create_target
$(eval $1:; @echo "some things to do for $$@")
endef

# create the targets
$(foreach target,$(targets),$(call create_target,$(target)))
</code>```

Considering that the contents of the file list is:

```<code>target1
target2
target3
</code>```

By running make with the Makefile above:

```<code>$ make
some things to do for my_tasks_target1
some things to do for my_tasks_target2
some things to do for my_tasks_target3
</code>```

Body:
I want to have file, when I can list of names (one in the line), so that when make is invoked, rules are generated on the fly from this names with some string appended to it.

Example:

file contents:

target1
target2
target3

String to concatenate: my_task_

From this I want to have 3 rules:

my_task_target1:
    <some things to do>

my_task_target2:
    <some things to do>

my_task_target3:
    <some things to do>

I know, that when I have array with all this targets names, I can do this like in this answer, but I need to read data from file.

I want it to be this way, because I will have many targets, and there is different list of tasks for every target. Each task will have it's own file with list of targets. At the end I will also create rules with names after target, but without prefix, and this rules will have all tasks, that are assigned to some target, so that I can invoke separated tasks, and also all needed tasks for target with one make command.

How can I achieve this? Or maybe there is a better way to do what I want to do?

Body:
The following Makefile dynamically creates the targets read from the file list:

# the file with the targets
targets-file := list

# the string to concatenate
prefix := my_tasks_

# read the targets from the file indicated by the variable targets-file
targets != cat "$(targets-file)"

# concatenate the string to each target
targets := $(addprefix $(prefix),$(targets))

.PHONY: all
all: $(targets)

# function for creating a target
define create_target
$(eval $1:; @echo "some things to do for $$@")
endef

# create the targets
$(foreach target,$(targets),$(call create_target,$(target)))

Considering that the contents of the file list is:

target1
target2
target3

By running make with the Makefile above:

$ make
some things to do for my_tasks_target1
some things to do for my_tasks_target2
some things to do for my_tasks_target3


问:
Read of Integer in Shared Preferences causes Class Cast exception
I am trying to obtain the corresponding number from a single select setting on Android, and for some reason it tells me in the LogCat that "String cannot be cast to Integer at getInt. When I go in to analyze the value of the sharedPref at the time of mEventLanguageSelection assignment. At that point, it says KEY_LANGUAGE_SELECTION_LIST=2, which I am quite certain means that getInt should return a value of 2. What is happening?

EventsActivity.java

http://pastebin.com/85qa72bN

strings_activity_settings.xml

http://pastebin.com/LBVqpjMF

pref_general.xml

http://pastebin.com/NGcRwGhz

```<code>09-22 20:38:25.056: D/libEGL(28573): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
09-22 20:38:25.064: D/libEGL(28573): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
09-22 20:38:25.071: D/libEGL(28573): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
09-22 20:38:25.181: D/OpenGLRenderer(28573): Enabling debug mode 0
09-22 20:38:33.157: D/dalvikvm(28573): GC_CONCURRENT freed 92K, 2% free 9117K/9240K, paused 3ms+2ms, total 25ms
09-22 20:39:33.759: D/AndroidRuntime(28573): Shutting down VM
09-22 20:39:33.759: W/dalvikvm(28573): threadid=1: thread exiting with uncaught exception (group=0x41415930)
09-22 20:39:33.790: E/AndroidRuntime(28573): FATAL EXCEPTION: main
09-22 20:39:33.790: E/AndroidRuntime(28573): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.barjinx.barjinx/com.barjinx.barjinx.EventsActivity}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.os.Looper.loop(Looper.java:137)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.main(ActivityThread.java:5039)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at java.lang.reflect.Method.invokeNative(Native Method)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at java.lang.reflect.Method.invoke(Method.java:511)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at dalvik.system.NativeStart.main(Native Method)
09-22 20:39:33.790: E/AndroidRuntime(28573): Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at com.barjinx.barjinx.EventsActivity.onCreate(EventsActivity.java:65)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.Activity.performCreate(Activity.java:5104)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-22 20:39:33.790: E/AndroidRuntime(28573):    ... 11 more
</code>```

答: I set string value "" in shared preference for integer object, so when i get value using getInt() from preference i am getting this issue, so please make sure you set value into preference is integer only, not string.

Body:
I am trying to obtain the corresponding number from a single select setting on Android, and for some reason it tells me in the LogCat that "String cannot be cast to Integer at getInt. When I go in to analyze the value of the sharedPref at the time of mEventLanguageSelection assignment. At that point, it says KEY_LANGUAGE_SELECTION_LIST=2, which I am quite certain means that getInt should return a value of 2. What is happening?

EventsActivity.java

http://pastebin.com/85qa72bN

strings_activity_settings.xml

http://pastebin.com/LBVqpjMF

pref_general.xml

http://pastebin.com/NGcRwGhz

09-22 20:38:25.056: D/libEGL(28573): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
09-22 20:38:25.064: D/libEGL(28573): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
09-22 20:38:25.071: D/libEGL(28573): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
09-22 20:38:25.181: D/OpenGLRenderer(28573): Enabling debug mode 0
09-22 20:38:33.157: D/dalvikvm(28573): GC_CONCURRENT freed 92K, 2% free 9117K/9240K, paused 3ms+2ms, total 25ms
09-22 20:39:33.759: D/AndroidRuntime(28573): Shutting down VM
09-22 20:39:33.759: W/dalvikvm(28573): threadid=1: thread exiting with uncaught exception (group=0x41415930)
09-22 20:39:33.790: E/AndroidRuntime(28573): FATAL EXCEPTION: main
09-22 20:39:33.790: E/AndroidRuntime(28573): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.barjinx.barjinx/com.barjinx.barjinx.EventsActivity}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.os.Looper.loop(Looper.java:137)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.main(ActivityThread.java:5039)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at java.lang.reflect.Method.invokeNative(Native Method)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at java.lang.reflect.Method.invoke(Method.java:511)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at dalvik.system.NativeStart.main(Native Method)
09-22 20:39:33.790: E/AndroidRuntime(28573): Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at com.barjinx.barjinx.EventsActivity.onCreate(EventsActivity.java:65)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.Activity.performCreate(Activity.java:5104)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-22 20:39:33.790: E/AndroidRuntime(28573):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-22 20:39:33.790: E/AndroidRuntime(28573):    ... 11 more


问:
Multiple upload using Laravel Storage
I was try to upload multiple files using Storage so here's my code:

```<code>public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = 'public'.'/'.str_slug($request->name);
    Storage::makeDirectory(str_slug($request->name));

    $image = new Image();
    if ( is_array($request->images)) {
        foreach ($request->images as $file) {
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->save();
            Storage::putFileAs($path, $file);
        }
    } else {
            $image->gallery_id = $gallery->id;
            $image->name = $request->images->getClientOriginalName();
            $image->save();
    }
}
</code>```

and I already setup my form like this:

```<code><div class="form-group">
    <label for="images" class="col-md-2 control-label">Images</label>
    <div class="col-md-6">
        <input type="file" class="form-control" name="images[]" id="images[]" multiple>
    </div>
</div>
</code>```

it give me an errors like this:

"Type error: Too few arguments to function Illuminate\Filesystem\FilesystemAdapter::putFileAs(), 2 passed in E:\laragon\www\blog\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemManager.php on line 343 and at least 3 expected ◀"

so the problem is it the way I check that it has multiple file using is_array is right? and the second what can cause this problems?

答:
You can use below example. I think this will help you to solve your problem</p>

```<code>public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = '/images/'.str_slug($request->name);

    if( is_array($request->images)){
        foreach ($request->images as $file){
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = 555;
            $image->save();
            $file->move(public_path($path, $image->name);
        }
    }else{
        $image = new Image();
        $image->gallery_id = $gallery->id;
        $image->name = $request->images->getClientOriginalName();;
        $image->save();
        $file->move(public_path($slug, $image->name);
    }
    return back();
}
</code>```

Title: Multiple upload using Laravel Storage

Body:
I was try to upload multiple files using Storage so here's my code:

public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = 'public'.'/'.str_slug($request->name);
    Storage::makeDirectory(str_slug($request->name));

    $image = new Image();
    if ( is_array($request->images)) {
        foreach ($request->images as $file) {
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->save();
            Storage::putFileAs($path, $file);
        }
    } else {
            $image->gallery_id = $gallery->id;
            $image->name = $request->images->getClientOriginalName();
            $image->save();
    }
}

and I already setup my form like this:

    Images

        <input type="file" class="form-control" name="images[]" id="images[]" multiple>

it give me an errors like this:

"Type error: Too few arguments to function Illuminate\Filesystem\FilesystemAdapter::putFileAs(), 2 passed in E:\laragon\www\blog\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemManager.php on line 343 and at least 3 expected ◀"

so the problem is it the way I check that it has multiple file using is_array is right? and the second what can cause this problems?

Body:
You can use below example. I think this will help you to solve your problem

public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = '/images/'.str_slug($request->name);

    if( is_array($request->images)){
        foreach ($request->images as $file){
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = 555;
            $image->save();
            $file->move(public_path($path, $image->name);
        }
    }else{
        $image = new Image();
        $image->gallery_id = $gallery->id;
        $image->name = $request->images->getClientOriginalName();;
        $image->save();
        $file->move(public_path($slug, $image->name);
    }
    return back();
}