问:
import angular JSON object
I have an angular 1.x controller with the following object:

```<code>notificationTypes: [ { NotificationType: '*', NotificationTitle: 'All notifications' },
                     { NotificationType: '0', NotificationLabel: 'System Alert', NotificationTitle: 'System alerts' },
                     { NotificationType: '1', NotificationLabel: 'Pending Task', NotificationTitle: 'Pending tasks' },
                     { NotificationType: '2', NotificationLabel: 'Update', NotificationTitle: 'Updates' },
                     { NotificationType: '3', NotificationLabel: 'Missed Message', NotificationTitle: 'Missed messages' }
                    ],
</code>```

It is used to populate a few lists on a single page.  However, I am now in a situation where I need to reuse it on other pages.  I could just copy it over to the appropriate pages, but I'd rather refactor it so both controllers work from the same list for better maintainability.  I've been trying to declare it on the 'MainApp' module as a constant, factory, and/or directive without success.  What am I missing?

答:
Use a factory to solve this problem. Data can persist in factories and services when changing pages. </p>

```<code>angular.module('App', [...])

.factory('NotificationFactory', function () {
    var notificationTypes: [ { NotificationType: '*', NotificationTitle: 'All notifications' },
                 { NotificationType: '0', NotificationLabel: 'System Alert', NotificationTitle: 'System alerts' },
                 { NotificationType: '1', NotificationLabel: 'Pending Task', NotificationTitle: 'Pending tasks' },
                 { NotificationType: '2', NotificationLabel: 'Update', NotificationTitle: 'Updates' },
                 { NotificationType: '3', NotificationLabel: 'Missed Message', NotificationTitle: 'Missed messages' }
                ];

    return notificationTypes;
})
</code>```

Title: import angular JSON object

Body:
I have an angular 1.x controller with the following object:

notificationTypes: [ { NotificationType: '*', NotificationTitle: 'All notifications' },
                     { NotificationType: '0', NotificationLabel: 'System Alert', NotificationTitle: 'System alerts' },
                     { NotificationType: '1', NotificationLabel: 'Pending Task', NotificationTitle: 'Pending tasks' },
                     { NotificationType: '2', NotificationLabel: 'Update', NotificationTitle: 'Updates' },
                     { NotificationType: '3', NotificationLabel: 'Missed Message', NotificationTitle: 'Missed messages' }
                    ],

It is used to populate a few lists on a single page.  However, I am now in a situation where I need to reuse it on other pages.  I could just copy it over to the appropriate pages, but I'd rather refactor it so both controllers work from the same list for better maintainability.  I've been trying to declare it on the 'MainApp' module as a constant, factory, and/or directive without success.  What am I missing?

Body:
Use a factory to solve this problem. Data can persist in factories and services when changing pages.

angular.module('App', [...])

.factory('NotificationFactory', function () {
    var notificationTypes: [ { NotificationType: '*', NotificationTitle: 'All notifications' },
                 { NotificationType: '0', NotificationLabel: 'System Alert', NotificationTitle: 'System alerts' },
                 { NotificationType: '1', NotificationLabel: 'Pending Task', NotificationTitle: 'Pending tasks' },
                 { NotificationType: '2', NotificationLabel: 'Update', NotificationTitle: 'Updates' },
                 { NotificationType: '3', NotificationLabel: 'Missed Message', NotificationTitle: 'Missed messages' }
                ];

    return notificationTypes;
})


来源: stackexchange

问:
Making data the same structure of timestamp
My time data are in this format:

```<code>datatimedf = data.frame(day_time = c('Apr 2005', '1992', "2004", "Jan 2001", "2015"))
</code>```

I would like to add Jan in rows which only have year.

How is it possible to make it?

An example of expected output is this:

```<code>datatimedf = data.frame(day_time = c('Apr 2005', 'Jan 1992', "Jan 2004", "Jan 2001", "Jan 2015"))
</code>```

What I have for only one row is this:

```<code>x[2,1] <- sub("^", "Jan ", x[2,1])
</code>```

but how can I make it to the whole dataframe?

答:
Here is a quick way to do it using dplyr:

```<code>library(dplyr)

datatimedf$day_time <- as.character(datatimedf$day_time)
datatimedf <- datatimedf %>%
    transform(day_time = ifelse(nchar(day_time) == 4, paste("Jan", day_time), day_time))

#> day_time
#> 1 Apr 2005
#> 2 Jan 1992
#> 3 Jan 2004
#> 4 Jan 2001
#> 5 Jan 2015
</code>```

For each line it checks if the length of the string is 4 and if so adds "Jan" to the beginning, otherwise it keeps the original. This isn't very applicable to other situations but it should get you started if you wanted to make it more generic and able to handle more types of input.

ContentLicense: CC BY-SA 3.0

Body:
My time data are in this format:

datatimedf = data.frame(day_time = c('Apr 2005', '1992', "2004", "Jan 2001", "2015"))

I would like to add Jan in rows which only have year.

How is it possible to make it?

An example of expected output is this:

datatimedf = data.frame(day_time = c('Apr 2005', 'Jan 1992', "Jan 2004", "Jan 2001", "Jan 2015"))

What I have for only one row is this:

x[2,1] <- sub("^", "Jan ", x[2,1])

but how can I make it to the whole dataframe?

Body:
Here is a quick way to do it using dplyr:

library(dplyr)

datatimedf$day_time <- as.character(datatimedf$day_time)
datatimedf <- datatimedf %>%
    transform(day_time = ifelse(nchar(day_time) == 4, paste("Jan", day_time), day_time))

#> day_time
#> 1 Apr 2005
#> 2 Jan 1992
#> 3 Jan 2004
#> 4 Jan 2001
#> 5 Jan 2015

For each line it checks if the length of the string is 4 and if so adds "Jan" to the beginning, otherwise it keeps the original. This isn't very applicable to other situations but it should get you started if you wanted to make it more generic and able to handle more types of input.


问:
Loading an Oracle HugeBlob image into an XML image in the visual basic code-behind
I am trying to read an image from an Oracle table and have it as the source of an XML image, to be later printed as part of a report.  I can read the image from the data base just fine.  When I try to set it as the source of the image and then print the page, the page comes out blank.

Here's the VB code after the image is read:

(The HugeBlob is the first item retrieved by a datareader (dr2), so it is referenced as dr2.Item(0))

'Convert the HugeBlob to base64 string
Dim MyImageString As String = Convert.ToBase64String(dr2.Item(0))

'Convert the base64 string to a byte array
Dim b() As Byte = Convert.FromBase64String(MyImageString)

'Create a memory stream
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream

'Load the memory stream from the byte array
MS = New System.IO.MemoryStream(b)

'Create a bitmap image
Dim bmi As New BitmapImage
bmi.BeginInit()

'Load the memory stream into the bitmap image
bmi.StreamSource = MS

'Set the bitmap image as the source for the xml image
PP7.Image.Stretch = Stretch.Fill
PP7.Image.Source = bmi
```

<p>Here's the XML Page:  </p>

<pre class="lang-xml prettyprint-override"><code><FlowDocument x:Class="PrintPreview7Image"
    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:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:PrintAccidentXPSForms"
    FontFamily="Arial"
    RenderOptions.BitmapScalingMode="HighQuality"
    PagePadding="0" PageWidth="816" PageHeight="1056"
    Name="PrintPreview7Image">
    <BlockUIContainer Name="MainBlock" BreakPageBefore="True" Margin="5,0,0,0">
        <Grid Width="816">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
                <Image Name="Image" Height="1056" Width="816"     Grid.Row="0"     Grid.Column="0"/>
        </Grid>
    </BlockUIContainer>
</FlowDocument>
</code>```

答:
Although this code is for SQLServer, I thought it might be adaptable for your problem. I stole this code, probably from SO, but I can't remember so can't give proper attribution.  </p>

```<code>Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection)

connection.Open()

Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())

connection.Close()

Dim picture As Image = Nothing

'Create a stream in memory containing the bytes that comprise the image.
Using stream As New IO.MemoryStream(pictureData)
    'Read the stream and create an Image object from the data.
    picture = Image.FromStream(stream)
End Using
</code>```

Body:
I am trying to read an image from an Oracle table and have it as the source of an XML image, to be later printed as part of a report.  I can read the image from the data base just fine.  When I try to set it as the source of the image and then print the page, the page comes out blank.

Here's the VB code after the image is read:

(The HugeBlob is the first item retrieved by a datareader (dr2), so it is referenced as dr2.Item(0))

'Convert the HugeBlob to base64 string
Dim MyImageString As String = Convert.ToBase64String(dr2.Item(0))

'Convert the base64 string to a byte array
Dim b() As Byte = Convert.FromBase64String(MyImageString)

'Create a memory stream
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream

'Load the memory stream from the byte array
MS = New System.IO.MemoryStream(b)

'Create a bitmap image
Dim bmi As New BitmapImage
bmi.BeginInit()

'Load the memory stream into the bitmap image
bmi.StreamSource = MS

'Set the bitmap image as the source for the xml image
PP7.Image.Stretch = Stretch.Fill
PP7.Image.Source = bmi

Here's the XML Page:

<FlowDocument x:Class="PrintPreview7Image"
    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:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:PrintAccidentXPSForms"
    FontFamily="Arial"
    RenderOptions.BitmapScalingMode="HighQuality"
    PagePadding="0" PageWidth="816" PageHeight="1056"
    Name="PrintPreview7Image">
    <BlockUIContainer Name="MainBlock" BreakPageBefore="True" Margin="5,0,0,0">
        <Grid Width="816">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
                <Image Name="Image" Height="1056" Width="816"     Grid.Row="0"     Grid.Column="0"/>
        </Grid>
    </BlockUIContainer>
</FlowDocument>

Body:
Although this code is for SQLServer, I thought it might be adaptable for your problem. I stole this code, probably from SO, but I can't remember so can't give proper attribution.

Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection)

connection.Open()

Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())

connection.Close()

Dim picture As Image = Nothing

'Create a stream in memory containing the bytes that comprise the image.
Using stream As New IO.MemoryStream(pictureData)
    'Read the stream and create an Image object from the data.
    picture = Image.FromStream(stream)
End Using


问:
Simplify overlapping And condition statements
I'm trying to figure out the best way to simplify conditional statements that are of the form:

```<code>if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}
</code>```

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

```<code>bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}
</code>```

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

```<code>bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}
</code>```

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

答:
One version involves saving all the functions into a std::vector<std::function<bool()>>, which creates very simple calling-conventions and simplifies the logic:

```<code>#include<vector>
#include<functional>
#include<iostream>

bool evaluate_vec(std::vector<std::function<bool()>> const& funcs) {
    bool a, b;
    for (size_t index = 0; index < funcs.size(); index++) {
        //We'll ping-pong between the two cached evaluations of the variables
        if ((index & 1) == 0)
            a = funcs[index]();
        else
            b = funcs[index]();
        if (index > 0)
            //The short-circuiting behavior we intend to have
            if (a && b)
                return true;
    }
    return false;
}

int main() {
    bool evaluation = evaluate_vec({ A, B, C, D });
}
</code>```

Body:
I'm trying to figure out the best way to simplify conditional statements that are of the form:

if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

Body:
One version involves saving all the functions into a std::vector<std::function<bool()>>, which creates very simple calling-conventions and simplifies the logic:

#include<vector>
#include<functional>
#include<iostream>

bool evaluate_vec(std::vector<std::function<bool()>> const& funcs) {
    bool a, b;
    for (size_t index = 0; index < funcs.size(); index++) {
        //We'll ping-pong between the two cached evaluations of the variables
        if ((index & 1) == 0)
            a = funcs[index]();
        else
            b = funcs[index]();
        if (index > 0)
            //The short-circuiting behavior we intend to have
            if (a && b)
                return true;
    }
    return false;
}

int main() {
    bool evaluation = evaluate_vec({ A, B, C, D });
}


问:
Bootstrap columns in a php while loop
I've read a ton of different ideas out there for this but can't seem to get any of them to work for my piece of code. Currently my products are displaying in a singular column but I'd like them to display in either a 3 or 4 column grid. Here's the code I have so far, hopefully someone can see where I'm going wrong.</p>

```<code>if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { ?>
        <div class="container">
          <div class="col-sm-4">
            <?php echo $row["ID"] . " - " . $row["item"] . "<br>";?>
            <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;"><br>
            <?php echo $row["description"] . " - $" . $row["price"]; ?>
        <form method="post" action="viewcart.php">
            <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
            <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
            <button type="submit">Add To Cart</button>
       </form>
    </div>
</div>
</code>```

答:
Put your container outside of while loop:</p>

```<code>    if ($result->num_rows > 0) {
       echo '<div class="container">';
        while($row = $result->fetch_assoc()) { ?>
              <div class="col-sm-4">
                <?php echo $row["ID"] . " - " . $row["item"] . "<br>";?>
                <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;"><br>
                <?php echo $row["description"] . " - $" . $row["price"]; ?>
            <form method="post" action="viewcart.php">
                <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
                <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
                <button type="submit">Add To Cart</button>
           </form>
         </div>
    <?php } // end while loop
    ?>
       </div>
    <?php } //end if statement
   ?>
</code>```

Title: Bootstrap columns in a php while loop

Body:
I've read a ton of different ideas out there for this but can't seem to get any of them to work for my piece of code. Currently my products are displaying in a singular column but I'd like them to display in either a 3 or 4 column grid. Here's the code I have so far, hopefully someone can see where I'm going wrong.

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { ?>

            <?php echo $row["ID"] . " - " . $row["item"] . "
";?>
            <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;">

            <?php echo $row["description"] . " - $" . $row["price"]; ?>
        <form method="post" action="viewcart.php">
            <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
            <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
            <button type="submit">Add To Cart</button>
       </form>

Body:
Put your container outside of while loop:

    if ($result->num_rows > 0) {
       echo '<div class="container">';
        while($row = $result->fetch_assoc()) { ?>
              <div class="col-sm-4">
                <?php echo $row["ID"] . " - " . $row["item"] . "<br>";?>
                <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;"><br>
                <?php echo $row["description"] . " - $" . $row["price"]; ?>
            <form method="post" action="viewcart.php">
                <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
                <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
                <button type="submit">Add To Cart</button>
           </form>
         </div>
    <?php } // end while loop
    ?>
       </div>
    <?php } //end if statement
   ?>


问:
PHP reflection and invokeArgs(): forcing a parameter to use its default value
I need to call a function using the Reflection API. The function has optional parameters, and I need to invoke it providing just some of them.

For example, I have this function:

```<code>public function doSomething($firstParam, $secondParam = "default", $thirdParam = "default)
</code>```

And I'm using invokeArgs() to invoke doSomething(), passing an array of values representing the arguments omitting to set a value to the optional $secondParam:

```<code>$parameters = array("firstParam"=>"value", "thirdParam"=>"thirdValue");
$reflectedDoSomething->invokeArgs($instance, $parameters);
</code>```

What happens here is that invokeArgs() invokes the method setting its parameters in a row, without skipping the $secondParam, that now is valued "thirdValue" and omitting the $thirdParam. And that's logically correct. The method is invoked like doSomething("value", "thirdValue").

What I'd like to do here is to force the $secondParam to use its default value. Setting "secondParam" => null in the $parameters array is not a solution because null is a value.

Is it possibile using Reflection?

Thanks

答:
See the first comment on the docs for invokeArgs().

So, just run the params through a simple algorithm (you could create a function for wrapping this if you wanted to):

```<code>$reflection = new ReflectionMethod($obj, $method);

$pass = array();
foreach($reflection->getParameters() as $param) {
   /* @var $param ReflectionParameter */
   if(isset($args[$param->getName()])) {
       $pass[] = $args[$param->getName()];
   } else {
       $pass[] = $param->getDefaultValue();
   }
}
$reflection->invokeArgs($obj, $pass);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to call a function using the Reflection API. The function has optional parameters, and I need to invoke it providing just some of them.

For example, I have this function:

public function doSomething($firstParam, $secondParam = "default", $thirdParam = "default)

And I'm using invokeArgs() to invoke doSomething(), passing an array of values representing the arguments omitting to set a value to the optional $secondParam:

$parameters = array("firstParam"=>"value", "thirdParam"=>"thirdValue");
$reflectedDoSomething->invokeArgs($instance, $parameters);

What happens here is that invokeArgs() invokes the method setting its parameters in a row, without skipping the $secondParam, that now is valued "thirdValue" and omitting the $thirdParam. And that's logically correct. The method is invoked like doSomething("value", "thirdValue").

What I'd like to do here is to force the $secondParam to use its default value. Setting "secondParam" => null in the $parameters array is not a solution because null is a value.

Is it possibile using Reflection?

Thanks

Body:
See the first comment on the docs for invokeArgs().

So, just run the params through a simple algorithm (you could create a function for wrapping this if you wanted to):

$reflection = new ReflectionMethod($obj, $method);

$pass = array();
foreach($reflection->getParameters() as $param) {
   /* @var $param ReflectionParameter */
   if(isset($args[$param->getName()])) {
       $pass[] = $args[$param->getName()];
   } else {
       $pass[] = $param->getDefaultValue();
   }
}
$reflection->invokeArgs($obj, $pass);


问:
Is there any way to apply a custom flow layout for a particular section in UICollectionView?
I just want to use custom flowlayout for a particular section in UICollectionView.
Different different layout for different sections.
Here is the attached image for reference.

Please help!!

答: You have multiple options. You could create two different types of cells or just create a second collection view. You also might be able to apply different layout attributes in your layout subclass depending on the index path's section. I'm not sure if that last idea is possible or even makes sense though as I haven't worked with iOS in a while and I don't remember ever trying this.</p>


问:
sapui5 how can i get selected item from value help into table cell?
I have a table.a column consists of input fields. How can I get value from searchHelpDialog to table item?

Below is a sample table:

And the value help dialog:

答:
Thanks friends.
Problem solved.Code;

_handleValueHelp: function(oEvent) {

```<code>this.selectedValueHelp = oEvent.getSource();
</code>```

}

_handleValueHelpClose: function(oEvent) {

```<code>        var oSelectedItem = oEvent.getParameter("selectedItem");
        if (oSelectedItem) {
         this.selectedValueHelp.setValue(oSelectedItem.getTitle());
        var productInput = this.getView().byId("helpvalue");
        productInput.setValue(oSelectedItem.getTitle());
        }
    }
</code>```

Body:
Thanks friends.
Problem solved.Code;

_handleValueHelp: function(oEvent) {

this.selectedValueHelp = oEvent.getSource();

}

_handleValueHelpClose: function(oEvent) {

        var oSelectedItem = oEvent.getParameter("selectedItem");
        if (oSelectedItem) {
         this.selectedValueHelp.setValue(oSelectedItem.getTitle());
        var productInput = this.getView().byId("helpvalue");
        productInput.setValue(oSelectedItem.getTitle());
        }
    }


问:
js pass function by reference to override it
I have a decorator that overrides a function:

```<code>function decorator(target, key, descriptor) {
    descriptor.value = function() {
        console.log('overridden')
    }
}
</code>```

Now I would like to perform the override in another function and I therefore need to pass it as an argument in a way so I can still replace the method:

```<code>function decorator(target, key, descriptor) {
    replaceMethod(descriptor.value)
}

function replaceMethod(originalMethod) {
    originalMethod = function() {
        console.log('overridden')
    }
}
</code>```

Is it somehow possible to do it in this way?

答:
This might satisfy your objective:</p>

```<code>function decorator(target, key, descriptor) {
    replaceMethod(descriptor, 'value')
}

function replaceMethod(obj, prop) {
    obj[prop] = function() {
        console.log('overridden')
    }
}
</code>```

Body:
I have a decorator that overrides a function:

function decorator(target, key, descriptor) {
    descriptor.value = function() {
        console.log('overridden')
    }
}

Now I would like to perform the override in another function and I therefore need to pass it as an argument in a way so I can still replace the method:

function decorator(target, key, descriptor) {
    replaceMethod(descriptor.value)
}

function replaceMethod(originalMethod) {
    originalMethod = function() {
        console.log('overridden')
    }
}

Is it somehow possible to do it in this way?

Body:
This might satisfy your objective:

function decorator(target, key, descriptor) {
    replaceMethod(descriptor, 'value')
}

function replaceMethod(obj, prop) {
    obj[prop] = function() {
        console.log('overridden')
    }
}


问:
Accessing other methods of an anonymous class from a lambda passed as parameter
Let's say I have a method that creates an anonymous object and store it somewhere. This anonymous object calls lambdas in its methods, that have been passed as parameters.

```<code>public class myCallBackManager {

    private List<MyCallBack<?>> callBackList = new LinkedList<MyCallBack<?>>();

    public <T> void addCallBack(Consumer<MyCallBack<T> onCall, Runnable something){
        callBackList.add(new MyCallback<T>() {
            @Override
            protected void call(MyCallback<T> callback) {
                onCall.accept(callback);
            }
            @Override
            protected void doSomething() {
                something.run());
            }
        }
    }

    public void runAll() {
        for (MyCallback<?> myCallback : callBackList) {
            myCallback.call();
        }
    }
}
</code>```

This stores the objects internally and ask for them to all be executed at once later.

But then, I want to add this:

```<code>public static void main(String[] args) {

    Runnable someRunnable = () -> System.out.println("Doing something");

    MyCallBackManager myCallBackManager = new MyCallbackManager();
    myCallBackManager.<SomeObject> addCallback(
            (callback) -> {
                doSomething(); // WON'T WORK
                System.out.println(callback.toString());
            },
            someRunnable
    };

    myCallBackManager.runAll();

}
</code>```

Here, I am trying to call doSomething() from the onCall lambda as it is run by the call() of the anonymous function as it is called. The problem is, I don't have a handle on still non-existant object where this will happen, so obviously it won't be able to call its methods. Is there a way to call doSomething() from the lambda?

There are workarounds in this particular case, for example calling someRunnable.run() instead of trying to access the doSomething() method, but I am asking specifically to a way to call the method instead.

答:
This is one solution. What are you really trying to do?

```<code>import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class Test {

    public static class MyCallback<T> {

        public void call() {
            System.out.println("Test.MyCallback.call()");
        }

        protected void call(MyCallback<?> callback) {
            System.out.println("Test.MyCallback.call(MyCallback<?>)");
        }

        protected void doSomething() {
            System.out.println("Test.MyCallback.doSomething()");
        }

    }

    static public class CallBackManager {

        private List<MyCallback<?>> callBackList = new LinkedList<>();

        public void addCallBack(Consumer<MyCallback<?>> onCall, Runnable something){
            callBackList.add(new MyCallback<Object>() {
                @Override
                protected void call(MyCallback callback) {
                    onCall.accept(callback);
                }
                @Override
                protected void doSomething() {
                    something.run();
                }
            }
                    );
        }

        public void runAll() {
            for (MyCallback<?> myCallback : callBackList) {
                myCallback.call();
            }
        }
    }

    public static void main(String[] args) {

        Runnable someRunnable = () -> System.out.println("Doing something");

        CallBackManager myCallBackManager = new CallBackManager();
        myCallBackManager.addCallBack(
                (MyCallback<?> callback) -> {
                    callback.doSomething(); // WON'T WORK
                    System.out.println(callback.toString());
                },
                someRunnable
                );

        myCallBackManager.runAll();

    }

}
</code>```

you never use onCall in Test.CallBackManager.addCallBack(Consumer>, Runnable) maybe that is the problem also.

Or are you trying this:

```<code>import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class Test {

    public static class MyCallback<T> {

        public void call() {
            System.out.println("Test.MyCallback.call()");
        }

        protected void call(MyCallback<?> callback) {
            System.out.println("Test.MyCallback.call(MyCallback<?>)");
        }

        protected void doSomething() {
            System.out.println("Test.MyCallback.doSomething()");
        }

        @Override
        public String toString() {
            System.out.println("Test.MyCallback.toString()");
            return "[CLASS Test.MyCallback<T>]";
        }

    }

    static public class CallBackManager {

        private List<MyCallback<?>> callBackList = new LinkedList<>();

        public void addCallBack(Consumer<MyCallback<?>> onCall, Runnable something){
            callBackList.add(new MyCallback<Object>() {
                @Override
                protected void call(MyCallback callback) {
                    onCall.accept(callback);
                }
                @Override
                protected void doSomething() {
                    something.run();
                }
            }
                    );
        }

        public void runAll() {
            for (MyCallback<?> myCallback : callBackList) {
                myCallback.call();
                myCallback.call(myCallback);//OR THIS?
            }
        }
    }

    public static void main(String[] args) {

        Runnable someRunnable = () -> System.out.println("Doing something");

        CallBackManager myCallBackManager = new CallBackManager();
        myCallBackManager.addCallBack(
                (MyCallback<?> callback) -> {
                    callback.doSomething(); // WON'T WORK
                    System.out.println(callback.toString());
                },
                someRunnable
                );

        myCallBackManager.runAll();

    }

}
</code>```

Body:
Let's say I have a method that creates an anonymous object and store it somewhere. This anonymous object calls lambdas in its methods, that have been passed as parameters.

public class myCallBackManager {

    private List<MyCallBack<?>> callBackList = new LinkedList<MyCallBack<?>>();

    public <T> void addCallBack(Consumer<MyCallBack<T> onCall, Runnable something){
        callBackList.add(new MyCallback<T>() {
            @Override
            protected void call(MyCallback<T> callback) {
                onCall.accept(callback);
            }
            @Override
            protected void doSomething() {
                something.run());
            }
        }
    }

    public void runAll() {
        for (MyCallback<?> myCallback : callBackList) {
            myCallback.call();
        }
    }
}

This stores the objects internally and ask for them to all be executed at once later.

But then, I want to add this:

public static void main(String[] args) {

    Runnable someRunnable = () -> System.out.println("Doing something");

    MyCallBackManager myCallBackManager = new MyCallbackManager();
    myCallBackManager.<SomeObject> addCallback(
            (callback) -> {
                doSomething(); // WON'T WORK
                System.out.println(callback.toString());
            },
            someRunnable
    };

    myCallBackManager.runAll();

}

Here, I am trying to call doSomething() from the onCall lambda as it is run by the call() of the anonymous function as it is called. The problem is, I don't have a handle on still non-existant object where this will happen, so obviously it won't be able to call its methods. Is there a way to call doSomething() from the lambda?

There are workarounds in this particular case, for example calling someRunnable.run() instead of trying to access the doSomething() method, but I am asking specifically to a way to call the method instead.

Body:
This is one solution. What are you really trying to do?

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class Test {

    public static class MyCallback<T> {

        public void call() {
            System.out.println("Test.MyCallback.call()");
        }

        protected void call(MyCallback<?> callback) {
            System.out.println("Test.MyCallback.call(MyCallback<?>)");
        }

        protected void doSomething() {
            System.out.println("Test.MyCallback.doSomething()");
        }

    }

    static public class CallBackManager {

        private List<MyCallback<?>> callBackList = new LinkedList<>();

        public void addCallBack(Consumer<MyCallback<?>> onCall, Runnable something){
            callBackList.add(new MyCallback<Object>() {
                @Override
                protected void call(MyCallback callback) {
                    onCall.accept(callback);
                }
                @Override
                protected void doSomething() {
                    something.run();
                }
            }
                    );
        }

        public void runAll() {
            for (MyCallback<?> myCallback : callBackList) {
                myCallback.call();
            }
        }
    }

    public static void main(String[] args) {

        Runnable someRunnable = () -> System.out.println("Doing something");

        CallBackManager myCallBackManager = new CallBackManager();
        myCallBackManager.addCallBack(
                (MyCallback<?> callback) -> {
                    callback.doSomething(); // WON'T WORK
                    System.out.println(callback.toString());
                },
                someRunnable
                );

        myCallBackManager.runAll();

    }

}

you never use onCall in Test.CallBackManager.addCallBack(Consumer>, Runnable) maybe that is the problem also.

Or are you trying this:

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class Test {

    public static class MyCallback<T> {

        public void call() {
            System.out.println("Test.MyCallback.call()");
        }

        protected void call(MyCallback<?> callback) {
            System.out.println("Test.MyCallback.call(MyCallback<?>)");
        }

        protected void doSomething() {
            System.out.println("Test.MyCallback.doSomething()");
        }

        @Override
        public String toString() {
            System.out.println("Test.MyCallback.toString()");
            return "[CLASS Test.MyCallback<T>]";
        }

    }

    static public class CallBackManager {

        private List<MyCallback<?>> callBackList = new LinkedList<>();

        public void addCallBack(Consumer<MyCallback<?>> onCall, Runnable something){
            callBackList.add(new MyCallback<Object>() {
                @Override
                protected void call(MyCallback callback) {
                    onCall.accept(callback);
                }
                @Override
                protected void doSomething() {
                    something.run();
                }
            }
                    );
        }

        public void runAll() {
            for (MyCallback<?> myCallback : callBackList) {
                myCallback.call();
                myCallback.call(myCallback);//OR THIS?
            }
        }
    }

    public static void main(String[] args) {

        Runnable someRunnable = () -> System.out.println("Doing something");

        CallBackManager myCallBackManager = new CallBackManager();
        myCallBackManager.addCallBack(
                (MyCallback<?> callback) -> {
                    callback.doSomething(); // WON'T WORK
                    System.out.println(callback.toString());
                },
                someRunnable
                );

        myCallBackManager.runAll();

    }

}


问:
Encrypting in .Net decrypting in php
I am writing some C# encrypting that is decrypted by php. They aren't working together very well. The php client has informed me of their configuration (RSSL_KEYGEN_PKCS5_V20, 256 bit AES in CBC mode, RSSL_PAD_ANSIX923). Here is what I put together:

```<code>public static byte[] Encrypt(byte[] plainText, string password,
         CipherMode cipherMode, int keySize, PaddingMode paddingMode)
    {
        byte[] salt = new byte[8];
        new RNGCryptoServiceProvider().GetBytes(salt);

        // PKCS#5 V2.0 PBKDF2 keyGenerator (uses default iteration count of 1000)
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.Mode = cipherMode;
        aes.KeySize = keySize;
        aes.Padding = paddingMode;
        aes.Key = keyGenerator.GetBytes(aes.KeySize / 8);

        // aes.Padding is left default PaddingMode.PKCS7
        // aes.IV should be automatically set to some random value by .NET
        // (as described in http://msdn.microsoft.com/en-us/library/5e9ft273(VS.71).aspx)

        // Overestimate encrypted size requirements
        byte[] encryptedDataBuffer = new byte[plainText.Length + 32 + 32 + 8];
        MemoryStream encryptedOutput = new MemoryStream(encryptedDataBuffer, true);
        CryptoStream encStream = new CryptoStream(encryptedOutput, aes.CreateEncryptor(),
                                                  CryptoStreamMode.Write);

        encryptedOutput.Write(salt, 0, salt.Length);
        encryptedOutput.Write(aes.IV, 0, aes.IV.Length);
        encStream.Write(plainText, 0, plainText.Length);

        encStream.FlushFinalBlock();
        byte[] encryptedData = new byte[encryptedOutput.Position];
        Array.Copy(encryptedDataBuffer, encryptedData, encryptedData.Length);
        encStream.Close();

        return encryptedData;
    }
</code>```

I can encrypt and decrypt it on my side, but they cannot decrypt it. Is there something I am doing wrong here? I pass in something like this:

```<code>Encrypt(mytext, myPassword, CipherMode.CBC, 256, PaddingMode.ANSIX923);
</code>```

Thanks.

答:
Narrow it down first:
Are you generating the same key?

Once you're certain of that, then you can consider the encyption.

Title: Encrypting in .Net decrypting in php

Body:
I am writing some C# encrypting that is decrypted by php. They aren't working together very well. The php client has informed me of their configuration (RSSL_KEYGEN_PKCS5_V20, 256 bit AES in CBC mode, RSSL_PAD_ANSIX923). Here is what I put together:

public static byte[] Encrypt(byte[] plainText, string password,
         CipherMode cipherMode, int keySize, PaddingMode paddingMode)
    {
        byte[] salt = new byte[8];
        new RNGCryptoServiceProvider().GetBytes(salt);

        // PKCS#5 V2.0 PBKDF2 keyGenerator (uses default iteration count of 1000)
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.Mode = cipherMode;
        aes.KeySize = keySize;
        aes.Padding = paddingMode;
        aes.Key = keyGenerator.GetBytes(aes.KeySize / 8);

        // aes.Padding is left default PaddingMode.PKCS7
        // aes.IV should be automatically set to some random value by .NET
        // (as described in http://msdn.microsoft.com/en-us/library/5e9ft273(VS.71).aspx)

        // Overestimate encrypted size requirements
        byte[] encryptedDataBuffer = new byte[plainText.Length + 32 + 32 + 8];
        MemoryStream encryptedOutput = new MemoryStream(encryptedDataBuffer, true);
        CryptoStream encStream = new CryptoStream(encryptedOutput, aes.CreateEncryptor(),
                                                  CryptoStreamMode.Write);

        encryptedOutput.Write(salt, 0, salt.Length);
        encryptedOutput.Write(aes.IV, 0, aes.IV.Length);
        encStream.Write(plainText, 0, plainText.Length);

        encStream.FlushFinalBlock();
        byte[] encryptedData = new byte[encryptedOutput.Position];
        Array.Copy(encryptedDataBuffer, encryptedData, encryptedData.Length);
        encStream.Close();

        return encryptedData;
    }

I can encrypt and decrypt it on my side, but they cannot decrypt it. Is there something I am doing wrong here? I pass in something like this:

Encrypt(mytext, myPassword, CipherMode.CBC, 256, PaddingMode.ANSIX923);

Thanks.


问:
"_version_ field must exist in schema", but it already does
I've taken over an abandoned project that is supposed to use Solr for searching and indexing, but Solr isn't working properly. There appear to be 3 cores, none of which had a conf directory or schema.xml files, so I wrote the schema below and pasted it onto the 3 cores' conf

```<code><?xml version="1.0" encoding="UTF-8" ?>
<schema name="mwplus_schema" version="1.6">

  <field name="_version_" type="long" indexed="true" stored="false" />
  <field name="pid" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
  <field name="text" type="text" indexed="true" stored="true" multiValued="true"/>

  <uniqueKey>pid</uniqueKey>
  <defaultSearchField>text</defaultSearchField>
  <solrQueryParser defaultOperator="OR"/>

</schema>
</code>```

As you can see, the _version_ field exists, however when I do bin/solr start -f -p <port>, none of the 3 cores that are using this schema are able to be created because of this error:

Error creating core [xmeld_shard1_replica1]: Unable to use updateLog: _version_ field must exist in schema, using indexed="true" or docValues="true", stored="true" and multiValued="false" (_version_ does not exist)

I'm sorry I can't post more details, I'm not too familiar with Solr or with the project itself. Any suggestions or ideas on why this is happening and how to fix it?

EDIT: I changed schema.xml based on the answer to another question in SO, but the problem persists. Above is the updated version.

答:
You may be using a cloud mode (though you command line does not seem to point that way). If you do, your schema is stored in Zookeeper instead and putting one on the filesystem does nothing.

Access the Admin UI and look through the various overview pages, paying attention to the path and working directory information. They may be pointing to places different what what you expect. Even if it is not in cloud mode, you may be using shared configuration (configset), which will be reflected in the overview information and possible in core.properties file.

If you are in the cloud mode, read the relevant guide in the reference guide for details on how to update the schema. Though I would not be modifying anything just yet until you know exactly what you have and backed those up.

Body:
I've taken over an abandoned project that is supposed to use Solr for searching and indexing, but Solr isn't working properly. There appear to be 3 cores, none of which had a conf directory or schema.xml files, so I wrote the schema below and pasted it onto the 3 cores' conf

<?xml version="1.0" encoding="UTF-8" ?>
<schema name="mwplus_schema" version="1.6">

  <field name="_version_" type="long" indexed="true" stored="false" />
  <field name="pid" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
  <field name="text" type="text" indexed="true" stored="true" multiValued="true"/>

  <uniqueKey>pid</uniqueKey>
  <defaultSearchField>text</defaultSearchField>
  <solrQueryParser defaultOperator="OR"/>

</schema>

As you can see, the _version_ field exists, however when I do bin/solr start -f -p <port>, none of the 3 cores that are using this schema are able to be created because of this error:

Error creating core [xmeld_shard1_replica1]: Unable to use updateLog: _version_ field must exist in schema, using indexed="true" or docValues="true", stored="true" and multiValued="false" (_version_ does not exist)

I'm sorry I can't post more details, I'm not too familiar with Solr or with the project itself. Any suggestions or ideas on why this is happening and how to fix it?

EDIT: I changed schema.xml based on the answer to another question in SO, but the problem persists. Above is the updated version.


问:
Google Chart loads extremely small when included in jQuery-based tabs
I am using Google's line chart almost exactly as the demo - only the data has changed - inside of this jQuery tab plugin with no modification. Maybe 50% of the time, the chart will load at 400x200 even though it has been specified to load at 700x250. The containing div will have the proper width and height, but the chart as rendered by the API will load inside of that at 400x200.

I suspect this is because the tabs aren't being displayed when the API tries to render. Because of that, it tries to render in something it considers null and therefore forces itself into the smallest default resolution.

My thought is that if the display of the chart can be delayed until the appropriate tab is clicked, it would resolve the problem. Sadly, I have no idea how to do that, and my research hasn't been fruitful. The closest I could find is this thread, but I didn't find any real answers there.

I'd appreciate any advice if you have any, and I'd be glad to follow up with more information if necessary.

答:
I stumbled across this "feature" of Bootstrap tabs. When cut-and-pasting multiple tabs in my HTML, I accidentally left the
 in the "active" state for all the tabs.  The result was that the content for all the tabs displayed sequentially in the first tab, but went away as you switched tabs.

My solution to the hidden tabs is to define them as active and then remove the "active" class from the div after I call chart.draw.

```<code><div class="tab-pane active" id="myid" role="tabpanel">
    <script type="text/javascript">
        // all the chart stuff
        chart.draw(data, options);
        $('#myid').removeClass('active');
    </script>
</div>
</code>```

I see that jQuery tabs also use the "active" class.  Perhaps this trick will work there too.

Body:
I stumbled across this "feature" of Bootstrap tabs. When cut-and-pasting multiple tabs in my HTML, I accidentally left the <div class=" tab-pane active"> in the "active" state for all the tabs.  The result was that the content for all the tabs displayed sequentially in the first tab, but went away as you switched tabs.

My solution to the hidden tabs is to define them as active and then remove the "active" class from the div after I call chart.draw.

<div class="tab-pane active" id="myid" role="tabpanel">
    <script type="text/javascript">
        // all the chart stuff
        chart.draw(data, options);
        $('#myid').removeClass('active');
    </script>
</div>

I see that jQuery tabs also use the "active" class.  Perhaps this trick will work there too.


问:
Django 1.11 - CSRF Verification failed despite having csrf_token template tag
New to django, making a to-do list page. I get the CSRF error after entering text in the input text box and hitting ENTER. I know this is likely a duplicate but after reading many of the forums and docs I'm still getting this issue. Here's what I've tried:

I have the {% csrf_token %} template tag inside my form tag.

I have 'django.middleware.csrf.CsrfViewMiddleware' in the MIDDLEWARE section of my settings.

CSRF_COOKIE_SECURE = False is the default in Django 1.11. I am using http, not https.

I'm using the render() function in my view.

My Firefox Privacy settings are set to allow third-party cookies. Doesn't work in Chrome either.

I'm not using the enctype="text/plain" tag in my HTML form tag.

I've tried supplying a context dict to abide by this excerpt of the release:

Here is my code:

home.html

```<code><!DOCTYPE html>
<html>
    <head>
        <title>To-do List</title>
    </head>
    <body>
        <h1>To-do List</h1>
        <form method="POST"> <!--tried adding action="" as well-->
            <input name="item_text" id="id_new_item" placeholder="Enter a to-do list item" />
            {% csrf_token %}
        </form>
        <table id="id_table">
            <tr><td>{{ new_item_text }}</td></tr>
        </table>
    </body>
</html>
</code>```

urls.py

```<code>from django.conf.urls import url
from django.contrib import admin
from lists import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home_page, name='home')
]
</code>```

settings.py

```<code>MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
</code>```

views.py

```<code>from django.shortcuts import render
from lists.models import Item

def home_page(request):
    if request.method == 'POST':
        Item.objects.create(text=request.POST['item_text'])
        return redirect('/')

    items = Item.objects.all()
    return render(request, 'lists/home.html', {'items': items}, {})
</code>```

models.py

```<code>from django.db import models

class Item(models.Model):
    text = models.TextField(default='')
</code>```

答:
You can also pass the csrf token direct without using a template tag

```<code>from django.core.context_processors import csrf
from django.shortcuts import render

def home_page(request):
    c = {}
    c.update(csrf(request))

    if request.method == 'POST':
        Item.objects.create(text=request.POST['item_text'])
        return redirect('/')

    items = Item.objects.all()
    return render(request, 'lists/home.html', {'items': items,
                                               'csrf':c})
</code>```

On your template tag simply use

```<code><input type='hidden' name='csrfmiddlewaretoken' value='{{csrf}}' />
</code>```

Body:
New to django, making a to-do list page. I get the CSRF error after entering text in the input text box and hitting ENTER. I know this is likely a duplicate but after reading many of the forums and docs I'm still getting this issue. Here's what I've tried:

I have the {% csrf_token %} template tag inside my form tag.

I have 'django.middleware.csrf.CsrfViewMiddleware' in the MIDDLEWARE section of my settings.

CSRF_COOKIE_SECURE = False is the default in Django 1.11. I am using http, not https.

I'm using the render() function in my view.

My Firefox Privacy settings are set to allow third-party cookies. Doesn't work in Chrome either.

I'm not using the enctype="text/plain" tag in my HTML form tag.

I've tried supplying a context dict to abide by this excerpt of the release:

Here is my code:

home.html

<!DOCTYPE html>

        <title>To-do List</title>

To-do List

        <form method="POST">
            <input name="item_text" id="id_new_item" placeholder="Enter a to-do list item" />
            {% csrf_token %}
        </form>

{{ new_item_text }}

urls.py

from django.conf.urls import url
from django.contrib import admin
from lists import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home_page, name='home')
]

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

views.py

from django.shortcuts import render
from lists.models import Item

def home_page(request):
    if request.method == 'POST':
        Item.objects.create(text=request.POST['item_text'])
        return redirect('/')

    items = Item.objects.all()
    return render(request, 'lists/home.html', {'items': items}, {})

models.py

from django.db import models

class Item(models.Model):
    text = models.TextField(default='')

Body:
You can also pass the csrf token direct without using a template tag

from django.core.context_processors import csrf
from django.shortcuts import render

def home_page(request):
    c = {}
    c.update(csrf(request))

    if request.method == 'POST':
        Item.objects.create(text=request.POST['item_text'])
        return redirect('/')

    items = Item.objects.all()
    return render(request, 'lists/home.html', {'items': items,
                                               'csrf':c})

On your template tag simply use

<input type='hidden' name='csrfmiddlewaretoken' value='{{csrf}}' />


问:
Can I access a database during startup in ASP.NET Core?
I have recently been working on a .NET Core web API. I have just attempted authentication using JWT, by following the guide on https://stormpath.com/blog/token-authentication-asp-net-core.

All was going well until I had to replace the hard-coded username and passwords in the GetIdentity method with a DB query and realized I do not know how to access the DB from within this file!

The method I am referring to is shown in the link below on line 70.
https://github.com/nbarbettini/SimpleTokenProvider/blob/master/test/SimpleTokenProvider.Test/Startup.Auth.cs

My questions are as follows.

Can I access the database here? If so how?

Should this be where the GetIdentity method is, or is there a better way?

答:
I might be wrong on some other level but the solution I found is to create a scope.

I passed the app instead of the ctx in GetIdentity, then in GetIdentity using a scope:

```<code>using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) {
    if (serviceScope.ServiceProvider.GetService<YourAppDbContext>() != null)
    {
      var ctx = serviceScope.ServiceProvider.GetService<YourAppDbContext>();

      if (AnAuthenticateMethodHereMaybe(ctx, username, password)) {
        return Task.FromResult(new ClaimsIdentity(new
GenericIdentity(username, "Token"), new Claim[] { }));
      }
    }
  }
</code>```

Body:
I might be wrong on some other level but the solution I found is to create a scope.

I passed the app instead of the ctx in GetIdentity, then in GetIdentity using a scope:

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) {
    if (serviceScope.ServiceProvider.GetService<YourAppDbContext>() != null)
    {
      var ctx = serviceScope.ServiceProvider.GetService<YourAppDbContext>();

      if (AnAuthenticateMethodHereMaybe(ctx, username, password)) {
        return Task.FromResult(new ClaimsIdentity(new
GenericIdentity(username, "Token"), new Claim[] { }));
      }
    }
  }


问:
js callee.caller as object instead of function
I have an OOP project in JS and I want to find the owner object of a the caller.callee

Example:
myObj.someFunc is called by yourObj.someFunc
I want to get a reference to yourObj from within myObj.someFunc and I need to do this without passing a reference to yourObj as a parameter.

Something like callee.caller.object would be nice, but of course, doesn't exist.

答:
You're looking for the this binding of the calling function -- unfortunately, the ECMAScript standard provides no way to obtain this.

Further, arguments.callee.caller has also been removed in ECMAScript 5, so you should no longer rely on using it.


问:
Dotcover does not resolve dependencies when Resharper does
I have a seperate MSTest project that runs tests against two other c# projects within the same solution. The tests are all MSTests and run succesfully in both the Visual Studio Test Explorer and Resharper (with MSTest set). Both are using my *.testsettings file that specifies the dependencies. Trying to get dotCover to generate coverage results gives me a FileNotFoundException on both the ddls from the referenced projects. This is similar to the exception I got with VS Test Explorer before adding dependencies in the testsettings file. Both dotCover and Resharper have the same test settings in options. Any ideas why dotCover cannot resolve the dependencies when Resharper can?</p>

答:
I've come across the same problem and had to do the following to get Resharper running dotCover again correctly for my solution:

Delete the resharper cache for your solution.  It will be located something like :

```<code>%LOCALAPPDATA%\JetBrains\Transient\ReSharperPlatformVs14\v09\SolutionCaches\{folder with solution name in it}
</code>```

Numbers may be different based on which version of Resharper you have (I have 2017.2 Ultimate).

Delete the visual studio solution cache:

```<code>{solutionfolder}\.vs\{solutionname}\v14\*.suo
</code>```

Again, numbers depend on which version of visual studio you have (I have VS2015)

Finally, you may have to give a hint in the test project files to run the correct version of the .net framework.  Insert the following into the <configuration> node of your app.config file in your test project(s):

```<code><startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
</code>```

Again, your supported runtime depends on which version of the .net framework your project is configured to use (in my case, .net 4.5.2).

Body:
I've come across the same problem and had to do the following to get Resharper running dotCover again correctly for my solution:

Delete the resharper cache for your solution.  It will be located something like :

%LOCALAPPDATA%\JetBrains\Transient\ReSharperPlatformVs14\v09\SolutionCaches\{folder with solution name in it}

Numbers may be different based on which version of Resharper you have (I have 2017.2 Ultimate).

Delete the visual studio solution cache:

{solutionfolder}\.vs\{solutionname}\v14\*.suo

Again, numbers depend on which version of visual studio you have (I have VS2015)

Finally, you may have to give a hint in the test project files to run the correct version of the .net framework.  Insert the following into the <configuration> node of your app.config file in your test project(s):

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>

Again, your supported runtime depends on which version of the .net framework your project is configured to use (in my case, .net 4.5.2).


答:
If you want more columns, make it like below:

```<code><div class="container">
  <div class="row">
    <div class="col-sm-4">

    </div>
    <div class="col-sm-6">

    </div>
    <div class="col-sm-2">

    </div>
  </div>
</div>
</code>```

The total number of columns when you add up, must be 12

Title: Bootstrap columns in a php while loop

Body:
If you want more columns, make it like below:

<div class="container">
  <div class="row">
    <div class="col-sm-4">

    </div>
    <div class="col-sm-6">

    </div>
    <div class="col-sm-2">

    </div>
  </div>
</div>

The total number of columns when you add up, must be 12


问:
SQL to migrate bad table design to good table design?
I am working to convert an old Access database to SQL Server.  All has been fairly straightforward in normalizing the database, but I have come upon an obstacle I can't seem to cross.

The old database uses a table to hold the movements of objects between boxes.  The problem is that the old table does not hold the new box that the object was moved to, just a log of all the old boxes.  The current box is held in the Obj table.  Check this fiddle, http://sqlfiddle.com/#!6/382bb/7/0

Is there an elegant solution to this?

TL:DR;

The old table is returning data like this,

```<code>MoveID ObjectID   OldBoxID DTMoved
1      27         22       2009-09-11
2      27         16       2008-01-19
3      27         29       2004-10-31
</code>```

I want it to return,

```<code>MoveID ObjectID   OldBoxID NewBoxID   DTMoved
1      27         22       24**      2009-09-11
2      27         16       22        2008-01-19
3      27         29       16        2004-10-31

**This value will be from the Obj table that shows the current BoxID for the object.
</code>```

In case the fiddle is gone, here is my schema,

```<code>CREATE TABLE Box (
[BoxID] int IDENTITY(1,1) NOT NULL,
[BoxName] varchar(20) NULL,
CONSTRAINT [PK_Box] PRIMARY KEY CLUSTERED
(
    [BoxID] ASC
))
GO

INSERT INTO Box (BoxName) VALUES ('Box1')
INSERT INTO Box (BoxName) VALUES ('Box2')
INSERT INTO Box (BoxName) VALUES ('Box3')
INSERT INTO Box (BoxName) VALUES ('Box4')
INSERT INTO Box (BoxName) VALUES ('Box5')
INSERT INTO Box (BoxName) VALUES ('Box6')
INSERT INTO Box (BoxName) VALUES ('Box7')
INSERT INTO Box (BoxName) VALUES ('Box8')
INSERT INTO Box (BoxName) VALUES ('Box9')
INSERT INTO Box (BoxName) VALUES ('Box10')

CREATE TABLE Obj (
    [ObjectID] int IDENTITY(1,1) NOT NULL,
    [ObjectName] varchar(20) NULL,
    [CurrentBoxID] int NULL
CONSTRAINT [PK_Obj] PRIMARY KEY CLUSTERED
(
[ObjectID] ASC
))
GO

INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('tiger',3)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('file',8)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('press',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('heap',4)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('careful',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('fairies',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('uneven',7)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('fertile',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('brass',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('hospitable',8)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('stem',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('pastoral',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('strip',10)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('spiteful',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('scribble',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('vest',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('soothe',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('sin',4)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('fanatical',10)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('scissors',7)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('rat',3)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('plastic',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('store',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('mighty',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('juice',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('angry',8)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('zephyr',2)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('decorous',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('stretch',4)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('complete',9)

CREATE TABLE Move (
    [MoveID] int IDENTITY(1,1) NOT NULL,
    [ObjectID] int NULL,
    [OldBoxID] int NULL,
    [DTMoved] datetime NULL
 CONSTRAINT [PK_Move] PRIMARY KEY CLUSTERED
(
    [MoveID] ASC
))
GO

INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (5,10,'01/15/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (30,6,'05/21/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,10,'06/12/2010')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (25,6,'10/30/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (19,10,'08/30/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (19,2,'05/01/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (29,4,'01/24/2013')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (16,10,'04/08/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (17,3,'03/11/2014')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (3,4,'02/25/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (17,9,'06/05/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,5,'12/31/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (11,8,'01/08/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,1,'09/21/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (21,7,'07/22/2017')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (16,1,'02/19/2005')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (12,3,'09/12/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (3,3,'05/08/2016')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (6,1,'09/12/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (20,1,'12/13/2015')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (13,4,'10/20/2017')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (2,5,'06/21/2015')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (6,5,'11/21/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (15,5,'09/10/2005')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (15,10,'10/20/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (10,10,'06/07/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (9,2,'10/19/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (3,1,'10/27/2011')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,1,'03/03/2010')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (2,8,'12/06/2013')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (2,4,'03/29/2017')
</code>```

I am looking for a query to return the following structure,

```<code>MoveID,ObjectID,DTMoved,OldBox,NewBox
12,27,'2008-12-31',Box5,Box1
29,27,'2010-03-03',Box1,Box10
3,27,'2010-06-12',Box10,Box1
14,27,'2012-09-21',Box1,Box2
</code>```

Here are the queries I was using to show the examples in the fiddle,

```<code>--Move joins
SELECT MoveID, M.ObjectID, DTMoved, BB.BoxName AS OldBox, B.BoxName AS CurrentBox
FROM Move M
   INNER JOIN Obj O ON M.ObjectID = O.ObjectID
   INNER JOIN Box B ON O.CurrentBoxID = B.BoxID
   INNER JOIN Box BB ON M.OldBoxID = BB.BoxID
ORDER BY O.ObjectID, DTMoved

--How many moves per box
SELECT ObjectID, COUNT(ObjectID)
FROM Move
GROUP BY ObjectID
ORDER BY COUNT(ObjectID) DESC

--Look at Object ID 27
SELECT MoveID, M.ObjectID, DTMoved, BB.BoxName AS OldBox, '' AS NewBox, B.BoxName AS CurrentBox
FROM Move M
   INNER JOIN Obj O ON M.ObjectID = O.ObjectID
   INNER JOIN Box B ON O.CurrentBoxID = B.BoxID
   INNER JOIN Box BB ON M.OldBoxID = BB.BoxID
WHERE M.ObjectID = 27
ORDER BY DTMoved DESC
</code>```

答:
Try This :-</p>

```<code>SELECT MoveID, M.ObjectID, DTMoved, BB.BoxName AS OldBox
,isnull(lead(oldboxid) OVER (ORDER BY DTMoved), O.CurrentBoxID) As newBoxId
FROM Move M
   INNER JOIN Obj O ON M.ObjectID = O.ObjectID
   INNER JOIN Box BB ON M.OldBoxId = BB.BoxID
WHERE M.ObjectID = 27
ORDER BY DTMoved
</code>```

Body:
I am working to convert an old Access database to SQL Server.  All has been fairly straightforward in normalizing the database, but I have come upon an obstacle I can't seem to cross.

The old database uses a table to hold the movements of objects between boxes.  The problem is that the old table does not hold the new box that the object was moved to, just a log of all the old boxes.  The current box is held in the Obj table.  Check this fiddle, http://sqlfiddle.com/#!6/382bb/7/0

Is there an elegant solution to this?

TL:DR;

The old table is returning data like this,

MoveID ObjectID   OldBoxID DTMoved
1      27         22       2009-09-11
2      27         16       2008-01-19
3      27         29       2004-10-31

I want it to return,

MoveID ObjectID   OldBoxID NewBoxID   DTMoved
1      27         22       24**      2009-09-11
2      27         16       22        2008-01-19
3      27         29       16        2004-10-31

**This value will be from the Obj table that shows the current BoxID for the object.

In case the fiddle is gone, here is my schema,

CREATE TABLE Box (
[BoxID] int IDENTITY(1,1) NOT NULL,
[BoxName] varchar(20) NULL,
CONSTRAINT [PK_Box] PRIMARY KEY CLUSTERED
(
    [BoxID] ASC
))
GO

INSERT INTO Box (BoxName) VALUES ('Box1')
INSERT INTO Box (BoxName) VALUES ('Box2')
INSERT INTO Box (BoxName) VALUES ('Box3')
INSERT INTO Box (BoxName) VALUES ('Box4')
INSERT INTO Box (BoxName) VALUES ('Box5')
INSERT INTO Box (BoxName) VALUES ('Box6')
INSERT INTO Box (BoxName) VALUES ('Box7')
INSERT INTO Box (BoxName) VALUES ('Box8')
INSERT INTO Box (BoxName) VALUES ('Box9')
INSERT INTO Box (BoxName) VALUES ('Box10')

CREATE TABLE Obj (
    [ObjectID] int IDENTITY(1,1) NOT NULL,
    [ObjectName] varchar(20) NULL,
    [CurrentBoxID] int NULL
CONSTRAINT [PK_Obj] PRIMARY KEY CLUSTERED
(
[ObjectID] ASC
))
GO

INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('tiger',3)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('file',8)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('press',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('heap',4)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('careful',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('fairies',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('uneven',7)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('fertile',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('brass',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('hospitable',8)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('stem',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('pastoral',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('strip',10)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('spiteful',9)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('scribble',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('vest',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('soothe',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('sin',4)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('fanatical',10)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('scissors',7)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('rat',3)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('plastic',5)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('store',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('mighty',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('juice',6)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('angry',8)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('zephyr',2)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('decorous',1)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('stretch',4)
INSERT INTO Obj (ObjectName,CurrentBoxID) VALUES ('complete',9)

CREATE TABLE Move (
    [MoveID] int IDENTITY(1,1) NOT NULL,
    [ObjectID] int NULL,
    [OldBoxID] int NULL,
    [DTMoved] datetime NULL
 CONSTRAINT [PK_Move] PRIMARY KEY CLUSTERED
(
    [MoveID] ASC
))
GO

INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (5,10,'01/15/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (30,6,'05/21/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,10,'06/12/2010')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (25,6,'10/30/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (19,10,'08/30/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (19,2,'05/01/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (29,4,'01/24/2013')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (16,10,'04/08/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (17,3,'03/11/2014')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (3,4,'02/25/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (17,9,'06/05/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,5,'12/31/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (11,8,'01/08/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,1,'09/21/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (21,7,'07/22/2017')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (16,1,'02/19/2005')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (12,3,'09/12/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (3,3,'05/08/2016')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (6,1,'09/12/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (20,1,'12/13/2015')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (13,4,'10/20/2017')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (2,5,'06/21/2015')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (6,5,'11/21/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (15,5,'09/10/2005')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (15,10,'10/20/2006')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (10,10,'06/07/2008')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (9,2,'10/19/2012')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (3,1,'10/27/2011')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (27,1,'03/03/2010')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (2,8,'12/06/2013')
INSERT INTO Move (ObjectID,OldBoxID,DTMoved) VALUES (2,4,'03/29/2017')

I am looking for a query to return the following structure,

MoveID,ObjectID,DTMoved,OldBox,NewBox
12,27,'2008-12-31',Box5,Box1
29,27,'2010-03-03',Box1,Box10
3,27,'2010-06-12',Box10,Box1
14,27,'2012-09-21',Box1,Box2

Here are the queries I was using to show the examples in the fiddle,

--Move joins
SELECT MoveID, M.ObjectID, DTMoved, BB.BoxName AS OldBox, B.BoxName AS CurrentBox
FROM Move M
   INNER JOIN Obj O ON M.ObjectID = O.ObjectID
   INNER JOIN Box B ON O.CurrentBoxID = B.BoxID
   INNER JOIN Box BB ON M.OldBoxID = BB.BoxID
ORDER BY O.ObjectID, DTMoved

--How many moves per box
SELECT ObjectID, COUNT(ObjectID)
FROM Move
GROUP BY ObjectID
ORDER BY COUNT(ObjectID) DESC

--Look at Object ID 27
SELECT MoveID, M.ObjectID, DTMoved, BB.BoxName AS OldBox, '' AS NewBox, B.BoxName AS CurrentBox
FROM Move M
   INNER JOIN Obj O ON M.ObjectID = O.ObjectID
   INNER JOIN Box B ON O.CurrentBoxID = B.BoxID
   INNER JOIN Box BB ON M.OldBoxID = BB.BoxID
WHERE M.ObjectID = 27
ORDER BY DTMoved DESC

Body:
Try This :-

SELECT MoveID, M.ObjectID, DTMoved, BB.BoxName AS OldBox
,isnull(lead(oldboxid) OVER (ORDER BY DTMoved), O.CurrentBoxID) As newBoxId
FROM Move M
   INNER JOIN Obj O ON M.ObjectID = O.ObjectID
   INNER JOIN Box BB ON M.OldBoxId = BB.BoxID
WHERE M.ObjectID = 27
ORDER BY DTMoved


问:
Specical formatting of textarea output to page creating a link with some data
I am not sure if this is possible.  I have searched for a couple of days with no luck. I would like to take information from a TEXT field of my database and create a list with the actors name being a link.

For example....

As it is now, the TEXT field outputs this:

Bill Murray - Peter Venkman

Dan Aykroyd - Ray Stantz

Harold Ramis - Egon Spengler

Sigourney Weaver - Dana Barrett

Ernie Hudson - Winston Zeddemore

What I would like to do is have the Actor's Name a link...  So, Bill Murray would be a link, Dan Aykroyd would be a link and so on. I would like the actors name to be passed as a variable for a search.

Is this possible?

Thanks

EDIT - 12/8/2017

I found a way to somewhat do this....

```<code>$data = $acast;
list($actor, $char) = explode("-", $data);
$actorlink = preg_replace('/\s+/', '+', $actor);
echo '<a href=index.php?actor='.$actorlink.'>'.$actor.'</a> - '.$char.'<br>';
</code>```

This will produce the 1st line perfect. and start the 2nd line with just the actors name, no link and no character.  Like so.

Main Cast:

Mary Elizabeth Winstead - Michelle

John Goodman

I think a foreach statement is needed but I cannot figure out how to incorporate it with the results. Or expand the list results to beyond 1.  I have 5 cast members per movie. I have tried this...

```<code>list($actor, $char) = explode("-", $data, 2);
</code>```

That will list all 5 actors but only the 1st has a link. Like this....

Main Cast:

Mary Elizabeth Winstead - Michelle

John Goodman - Howard

John Gallagher Jr. - Emmett

Bradley Cooper - Ben

Douglas M. Griffin - Driver

Any suggestions?
Thanks

答:
I GOT IT!!  1st off - Sorry.... I just noticed that this was Javascript, I thought I was posting under PHP. Ooops....

That said... If anyone needs a PHP solution to my problem, I figured it out.

```<code><?php
                //Seperate data into rows.
                $c_row = list($all) = explode("\n", $row['Cast']);
                //Seperate and list the values from the row.
                echo '<ul>';
                foreach ($c_row as $cast) {
                    list($actor, $char) = preg_split("/[-]/", $cast);
                    if ($char == "") {
                        $char = "Not Added Yet.";
                    }
                    echo "<li><a style='color: #e33e32; font-size: 14px;' href='index.php?actor=" . $actor . "'data-toggle='tooltip' data-placement='auto' title=' List all " . $actor . " movies. '>" . $actor . "</a>  :  " . $char . " </li>";
                }
                echo '</ul>';
                ?>
</code>```

The above code will give me the desired results.  You can see them in action here.  Also notice that I used a similar process to separate out directors when there are more than one.

Body:
I am not sure if this is possible.  I have searched for a couple of days with no luck. I would like to take information from a TEXT field of my database and create a list with the actors name being a link.

For example....

As it is now, the TEXT field outputs this:

Bill Murray - Peter Venkman

Dan Aykroyd - Ray Stantz

Harold Ramis - Egon Spengler

Sigourney Weaver - Dana Barrett

Ernie Hudson - Winston Zeddemore

What I would like to do is have the Actor's Name a link...  So, Bill Murray would be a link, Dan Aykroyd would be a link and so on. I would like the actors name to be passed as a variable for a search.

Is this possible?

Thanks

EDIT - 12/8/2017

I found a way to somewhat do this....

$data = $acast;
list($actor, $char) = explode("-", $data);
$actorlink = preg_replace('/\s+/', '+', $actor);
echo ''.$actor.' - '.$char.'
';

This will produce the 1st line perfect. and start the 2nd line with just the actors name, no link and no character.  Like so.

Main Cast:

Mary Elizabeth Winstead - Michelle

John Goodman

I think a foreach statement is needed but I cannot figure out how to incorporate it with the results. Or expand the list results to beyond 1.  I have 5 cast members per movie. I have tried this...

list($actor, $char) = explode("-", $data, 2);

That will list all 5 actors but only the 1st has a link. Like this....

Main Cast:

Mary Elizabeth Winstead - Michelle

John Goodman - Howard

John Gallagher Jr. - Emmett

Bradley Cooper - Ben

Douglas M. Griffin - Driver

Any suggestions?
Thanks

Body:
I GOT IT!!  1st off - Sorry.... I just noticed that this was Javascript, I thought I was posting under PHP. Ooops....

That said... If anyone needs a PHP solution to my problem, I figured it out.

<?php
                //Seperate data into rows.
                $c_row = list($all) = explode("\n", $row['Cast']);
                //Seperate and list the values from the row.
                echo '<ul>';
                foreach ($c_row as $cast) {
                    list($actor, $char) = preg_split("/[-]/", $cast);
                    if ($char == "") {
                        $char = "Not Added Yet.";
                    }
                    echo "<li><a style='color: #e33e32; font-size: 14px;' href='index.php?actor=" . $actor . "'data-toggle='tooltip' data-placement='auto' title=' List all " . $actor . " movies. '>" . $actor . "</a>&nbsp;&nbsp;:&nbsp;&nbsp;" . $char . " </li>";
                }
                echo '</ul>';
                ?>

The above code will give me the desired results.  You can see them in action here.  Also notice that I used a similar process to separate out directors when there are more than one.


问:
Why postfixed has higher precedence than prefixed?
Case 1:

```<code>int i = 10;
int j = i++;
</code>```

Here, first the value of i is assigned to j and than i is increased by 1.

Case 2:

```<code>int i = 10;
int j = ++i;
</code>```

Here, first i is increased by 1 and than it is assigned to j.

So, If the operation of increment is done first in the prefixed form, then why postfixed has higher precedence than prefixed?

答:
This has nothing to do with precedence.(here) In pre-increment the value that is assigned is the value before the side effect takes place.
For pre increment it will be the value after the side effect.

```<code>int i = 10;
int j = i++;
</code>```

Before incrementing value of i is 10. So j=10 after these 2 statements are executed.

```<code>int i = 10;
int j = ++i;
</code>```

Here the value will be 11. because incremenet is done first and then it is assigned.

Body:
Case 1:

int i = 10;
int j = i++;

Here, first the value of i is assigned to j and than i is increased by 1.

Case 2:

int i = 10;
int j = ++i;

Here, first i is increased by 1 and than it is assigned to j.

So, If the operation of increment is done first in the prefixed form, then why postfixed has higher precedence than prefixed?

Body:
This has nothing to do with precedence.(here) In pre-increment the value that is assigned is the value before the side effect takes place.
For pre increment it will be the value after the side effect.

int i = 10;
int j = i++;

Before incrementing value of i is 10. So j=10 after these 2 statements are executed.

int i = 10;
int j = ++i;

Here the value will be 11. because incremenet is done first and then it is assigned.


问:
Firebug is not working with Firefox version 50.0
I am using Firefox 50.0. After auto update of Firefox to version 50.0, Firebug has stopped working and attempting to use it is showing an inbuilt Firefox console while inspecting any DOM element.

Is there any patch to use Firebug on Firefox 50.0 version?

答:
I managed to resolve this issue by simply downgrading to mozilla old version using this url:

open https://ftp.mozilla.org/pub/firefox/releases/50.0/win64/en-US/

download and run the .exe setup

Go to Settings - > Add Ons

Click on extensions and search for firebug and firepath and then add those extensions

Hope this should resolve the issue. For those using Windows 32 machine can use the url
https://ftp.mozilla.org/pub/firefox/releases/50.0/win32/en-US/


问:
Using SSML (interpret-as="characters") removes punctuation
If I use the <say-as interpret-as="characters"></say-as> tag in my voice response, google assistant suddenly pronounces the whole response differently. It sounds as if google assistant removes punctuation without any reason. The pauses, which are initiated by the ".", are suddenly gone.

To reproduce this behaviour, just launch the actions on google simulator, choose "English (United States)" as langauge and listen to this audio snippet:

<speak>This is a test with number spelled as digit. The number is <say-as interpret-as="characters">12345</say-as>. Ask me "What to do with this number?" if you'd like to have more information.</speak>

If you remove the <say-as interpret-as="characters"></say-as> tag, the pronounciation works again:

<speak>This is a test with number spelled as digit. The number is 12345. Ask me "What to do with this number?" if you'd like to have more information.</speak>

This now sounds like it should sound. You will get the same result if you leave out the speak tag at all.

In German, this issue is even more critical. Using <say-as interpret-as="characters"></say-as> in a German voice response leads to a response which honestly is barely understandable.

答:
This is because of "text normalization" in Google Assistant's TTS process.

Because of that, SSML without using the <s> element won't always do what you expect for pauses if you are using embedded markup like <say-as>.

Here's an example using <s> to provide intended pauses in the TTS:

```<code><speak>
  This is a test with number spelled as digit.
  <s>The number is <say-as interpret-as="characters">12345</say-as>.</s>
  Ask me "What to do with this number?" if you'd like to have more information.
</speak>
</code>```

You can still feel free to input multiple sentences separated by periods into SSML without needing <s> to separate sentences and let Google Assistant handle the break generation as long as you are not using embedded markup like <say-as>.

More information about the <s> element can be found in the docs where it talks about
,<s>
https://developers.google.com/actions/reference/ssml

It will link to the W3C spec on those elements.

Body:
This is because of "text normalization" in Google Assistant's TTS process.

Because of that, SSML without using the <s> element won't always do what you expect for pauses if you are using embedded markup like <say-as>.

Here's an example using <s> to provide intended pauses in the TTS:

<speak>
  This is a test with number spelled as digit.
  <s>The number is <say-as interpret-as="characters">12345</say-as>.</s>
  Ask me "What to do with this number?" if you'd like to have more information.
</speak>

You can still feel free to input multiple sentences separated by periods into SSML without needing <s> to separate sentences and let Google Assistant handle the break generation as long as you are not using embedded markup like <say-as>.

More information about the <s> element can be found in the docs where it talks about <p>,<s>
https://developers.google.com/actions/reference/ssml

It will link to the W3C spec on those elements.


问:
Quartz.Net ITrigger Showing wrong Hour
I'm working with Quartz.net trying to make a event trigger from Tuesday to Saturday at 8:30am.

I use the following code to define the trigger time

```<code>IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        IJobDetail job = JobBuilder.Create<DailyAutomationProcess>().Build();
        ITrigger trigger = TriggerBuilder.Create().WithCronSchedule("0 30 8 ? * TUE,WED,THU,FRI,SAT *").Build();
        scheduler.ScheduleJob(job, trigger);
        scheduler.Start();
</code>```

The "0 30 8 ? * TUE,WED,THU,FRI,SAT *" is generated from http://www.cronmaker.com/.

But for some reason during run-time when I check ITrigger trigger it shows the wrong time.
It shows the "nextFireTime: 12/01/2017 16:30:00 +00:00}"

The hour seems always wrong.

And if the next firing hour is 16:30 the firing date should be 11/30(today) since it is not 16:30 yet.

I'm confused here any suggestion can help.

Thanks in advance.

Edit: CK my Quartz.Net is on 2.6.1

Edit:The following is my Application_Start

```<code>public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ScheduledTasks.DailyAutomationTrigger();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}
</code>```

答:
I totally forgot the time is UTC time shown on next firing time.
And the event firing just fine now.
Sometime need to rebuild the solution to make sure it got a new firing time table</p>

Title: Quartz.Net ITrigger Showing wrong Hour

Body:
I'm working with Quartz.net trying to make a event trigger from Tuesday to Saturday at 8:30am.

I use the following code to define the trigger time

IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        IJobDetail job = JobBuilder.Create<DailyAutomationProcess>().Build();
        ITrigger trigger = TriggerBuilder.Create().WithCronSchedule("0 30 8 ? * TUE,WED,THU,FRI,SAT *").Build();
        scheduler.ScheduleJob(job, trigger);
        scheduler.Start();

The "0 30 8 ? * TUE,WED,THU,FRI,SAT *" is generated from http://www.cronmaker.com/.

But for some reason during run-time when I check ITrigger trigger it shows the wrong time.
It shows the "nextFireTime: 12/01/2017 16:30:00 +00:00}"

The hour seems always wrong.

And if the next firing hour is 16:30 the firing date should be 11/30(today) since it is not 16:30 yet.

I'm confused here any suggestion can help.

Thanks in advance.

Edit: CK my Quartz.Net is on 2.6.1

Edit:The following is my Application_Start

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ScheduledTasks.DailyAutomationTrigger();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}


问:
how to convert JPEG image to TIFF image?
I am developing an app for image processing for that I need to convert JPEG file to TIFF file.

I have tried below code snippet for conversion. But, it is generating corrupt tiff file.

Here is the code:

```<code>package javaapplication2;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.idrsolutions.image.tiff.TiffEncoder;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class JavaApplication2
{
    public static void main(String[] args)
    {
        BufferedImage bufferedImage;
        try
        {
            bufferedImage = ImageIO.read(new File("C:\\Users\\Jay Tanna\\Desktop\\image1.jpg"));

            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
            bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);

            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

            OutputStream   out      =   new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.tiff");
            TiffEncoder tiffEncoder =   new TiffEncoder();
            tiffEncoder.setCompressed(true);
            tiffEncoder.write(newBufferedImage, out);

            System.out.println("Done");

    }
        catch (IOException e)
        {

            e.printStackTrace();

    }

   }

}
</code>```

Kindly help me with this issue.

答:
Change the extension of the file, try this:

```<code>OutputStream   out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.tiff");
</code>```

for this:

```<code>OutputStream   out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.TIF");
</code>```

Body:
I am developing an app for image processing for that I need to convert JPEG file to TIFF file.

I have tried below code snippet for conversion. But, it is generating corrupt tiff file.

Here is the code:

package javaapplication2;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.idrsolutions.image.tiff.TiffEncoder;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class JavaApplication2
{
    public static void main(String[] args)
    {
        BufferedImage bufferedImage;
        try
        {
            bufferedImage = ImageIO.read(new File("C:\\Users\\Jay Tanna\\Desktop\\image1.jpg"));

            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
            bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);

            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

            OutputStream   out      =   new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.tiff");
            TiffEncoder tiffEncoder =   new TiffEncoder();
            tiffEncoder.setCompressed(true);
            tiffEncoder.write(newBufferedImage, out);

            System.out.println("Done");

    }
        catch (IOException e)
        {

            e.printStackTrace();

    }

   }

}

Kindly help me with this issue.

Body:
Change the extension of the file, try this:

OutputStream   out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.tiff");

for this:

OutputStream   out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.TIF");


问:
Distinct list of Items after Query
I have a table with two filters on it. Both filters are in the form of Dropdown widgets; when a user selects an item from the list of options in the Dropdowns, the table is filtered to include only records with that item. Each Dropdown filter is a Relation to the table's datasource.

Currently, each Dropdown's Options is just the full list of Items from that Dropdown's particular datasource. However, when the value of one Dropdown is changed by the user, I would like the other Dropdown's Options list to be populated only with

For example, I have a table of US and Canadian citizens and their home state/province. The first Dropdown filters the table by country, the second by state/province. If I select 'Canada' from the first Dropdown, then when I select an item for the second Dropdown, only Canadian provinces appear as options, and none of the US states would.

答:
Let's say that you have three independent datasources:

Countries

States

People

To filter items in States dropdown you can reload its datasource in onValueChange event of dropdown with Сountries. You can also simplify your life by binding @datasources.States.query.filters.Country._equals to Countries's dropdown value.

// Countries dropdown onValueChange event handler
// newValue - new selected country
app.datasources.States.load();

// unfortunately App Maker doesn't allow to bind multiple things to
// one value, so we need explicitly set filter for People datasource
app.datasources.People.query.filters.Country._equals = newValue;
app.datasources.People.load();
```

<p>Depending on your business needs, you maybe will want to force users first select country by disabling dropdown with states:</p>

<pre class="lang-js prettyprint-override"><code>// States dropdown `enabled` property binding
@datasources.States.query.filters.Country._equals !== null
</code>```

Title: Distinct list of Items after Query

Body:
Let's say that you have three independent datasources:

Countries

States

People

To filter items in States dropdown you can reload its datasource in onValueChange event of dropdown with Сountries. You can also simplify your life by binding @datasources.States.query.filters.Country._equals to Countries's dropdown value.

// Countries dropdown onValueChange event handler
// newValue - new selected country
app.datasources.States.load();

// unfortunately App Maker doesn't allow to bind multiple things to
// one value, so we need explicitly set filter for People datasource
app.datasources.People.query.filters.Country._equals = newValue;
app.datasources.People.load();

Depending on your business needs, you maybe will want to force users first select country by disabling dropdown with states:

// States dropdown `enabled` property binding
@datasources.States.query.filters.Country._equals !== null


问:
values overwriting each other in object in setState reactjs
I am trying to pre-populate filter values that I have saved in the redux store when a user navigates back to that page where they set the filters. However, when I am going to set the state, I'm having trouble with the last set value overwriting the existing one. This is how I set the state in the constructor:

```<code>this.state = {
  hierarchyTableFilters: {
    hierarchy: null,
    signOffStatus: null,
  },
};
</code>```

and then this is how I'm going to set the state in the called function with the stored data from redux:

```<code>const {userState} = this.props.userInfo;
const previouslySelectedFilter = userState.state.hierarchyTableFilters;

if (previouslySelectedFilter) {
  this.setState({
    hierarchyTableFilters: {
      hierarchy: previouslySelectedFilter.hierarchy,
      signOffStatus: previouslySelectedFilter.signOffStatus,
    },
  });
</code>```

Whatever state gets set last is the only filter that appears pre-filtered. Is there a way to set state for two different values in an object or do I have to go about this in a different way?

答:
If you need to set local state based on previous local state, you should use the setState callback pattern instead.

```<code>this.setState(previousState => ({ ... }))
</code>```

This is because setState does batch updates. See the docs on setState

Body:
I am trying to pre-populate filter values that I have saved in the redux store when a user navigates back to that page where they set the filters. However, when I am going to set the state, I'm having trouble with the last set value overwriting the existing one. This is how I set the state in the constructor:

this.state = {
  hierarchyTableFilters: {
    hierarchy: null,
    signOffStatus: null,
  },
};

and then this is how I'm going to set the state in the called function with the stored data from redux:

const {userState} = this.props.userInfo;
const previouslySelectedFilter = userState.state.hierarchyTableFilters;

if (previouslySelectedFilter) {
  this.setState({
    hierarchyTableFilters: {
      hierarchy: previouslySelectedFilter.hierarchy,
      signOffStatus: previouslySelectedFilter.signOffStatus,
    },
  });

Whatever state gets set last is the only filter that appears pre-filtered. Is there a way to set state for two different values in an object or do I have to go about this in a different way?

Body:
If you need to set local state based on previous local state, you should use the setState callback pattern instead.

this.setState(previousState => ({ ... }))

This is because setState does batch updates. See the docs on setState