问:
Function that returns the closest number to B that's in an UNSORTED multidimensional array, A?
As the title states, I want to create a function that'll take a multidimensional array A, and a number B, that ultimately returns the number in A that is the closest to B. If the number B is in A, then return it. If there's 2 numbers in A that are equally distant from B, choose the first one by counting from row to row.

This is the code I have so far:

```<code>import numpy as np
def g_C(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2 # to assert that A is a multidimensional array.
  get = (np.abs(A-B)).argmin()
  return (A[get])
</code>```

However from my understanding, I think (np.abs(M-N)).argmin() really only effectively works for sorted arrays? I'm not allowed to sort the array in this problem; I have to work on it for face value, examining row by row, and grabbing the first instance of the closest number to B.

So for example, g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) should return 8

Also, I was given the hint that numpy.argmin would help, and I see that it's purpose is to extract the first occurrence something occurs, which makes sense in this problem, but I'm not sure how exactly to fit that into the code I have at the moment.

EDIT
The flat suggestion works perfectly fine. Thank you everyone.

I'm trying RagingRoosevelt's second suggestion, and I'm stuck.

```<code>def g_C(A,B):
  A = np.asanyarray(A)
  D = np.full_like(A, B) # created an array D with same qualities as array A, but just filled with values of B
  diffs = abs(D-A) # finding absolute value differences between D and A
  close = diffs.argmin(axis=1) # find argmin of 'diffs', row by row
  close = np.asanyarray(close) # converted the argmins of 'diff' into an array
  closer = close.argmin() # the final argmin ??
  return closer
</code>```

I'm trying out this suggestion because I have another problem related to this where I have to extract the row who's sum is the closest number to B. And I figure this is good practice anyway.

答:
This will work for any 2-dimensional array with a nested for-loop, but I am not sure that this is what you want (as in it doesn't use numpy).

```<code>def g_C(A, B):
    i = A[0][0]
    m = abs(B - A[0][0])
    for r in A:
        for i in r:
            if abs(B - i) < m:
                m = abs(B - i)
                n = i
    return n
</code>```

Nevertheless, it does work:

```<code>>>> g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9)
8
</code>```

Body:
As the title states, I want to create a function that'll take a multidimensional array A, and a number B, that ultimately returns the number in A that is the closest to B. If the number B is in A, then return it. If there's 2 numbers in A that are equally distant from B, choose the first one by counting from row to row.

This is the code I have so far:

import numpy as np
def g_C(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2 # to assert that A is a multidimensional array.
  get = (np.abs(A-B)).argmin()
  return (A[get])

However from my understanding, I think (np.abs(M-N)).argmin() really only effectively works for sorted arrays? I'm not allowed to sort the array in this problem; I have to work on it for face value, examining row by row, and grabbing the first instance of the closest number to B.

So for example, g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) should return 8

Also, I was given the hint that numpy.argmin would help, and I see that it's purpose is to extract the first occurrence something occurs, which makes sense in this problem, but I'm not sure how exactly to fit that into the code I have at the moment.

EDIT
The flat suggestion works perfectly fine. Thank you everyone.

I'm trying RagingRoosevelt's second suggestion, and I'm stuck.

def g_C(A,B):
  A = np.asanyarray(A)
  D = np.full_like(A, B) # created an array D with same qualities as array A, but just filled with values of B
  diffs = abs(D-A) # finding absolute value differences between D and A
  close = diffs.argmin(axis=1) # find argmin of 'diffs', row by row
  close = np.asanyarray(close) # converted the argmins of 'diff' into an array
  closer = close.argmin() # the final argmin ??
  return closer

I'm trying out this suggestion because I have another problem related to this where I have to extract the row who's sum is the closest number to B. And I figure this is good practice anyway.

Body:
This will work for any 2-dimensional array with a nested for-loop, but I am not sure that this is what you want (as in it doesn't use numpy).

def g_C(A, B):
    i = A[0][0]
    m = abs(B - A[0][0])
    for r in A:
        for i in r:
            if abs(B - i) < m:
                m = abs(B - i)
                n = i
    return n

Nevertheless, it does work:

>>> g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9)
8


来源: stackexchange

问:
Is it OK to return from an async method before the final await?
I have a web page (aspx) that calls an async method in a class.  The async method looks something like this:

```<code>public async Task<MyThing> GetMyThing()
{
    MyThing thing = new MyThing();
    var stuff = await Repository.GetStuff();
    // apply stuff to thing.

    var morestuff = await Repository.GetMoreStuff();
    // apply more stuff to thing.

    if (someCondition)
    {
        return thing;
    }

    var yetMoreStuff = await Repository.GetYetMoreStuff();
    // apply yet more stuff

    return thing;
}
</code>```

If the condition is met, I don't need the data from the last repository call.  Is the return before the final await going to cause me problems?

The reason I ask is I'm getting this error in the server application log, and I'm hunting for causes...

```<code>Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(System.Threading.SendOrPostCallback, System.Object)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(System.Threading.SendOrPostCallback, System.Object)
   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(System.Threading.ContextCallback, System.Object, System.Threading.Tasks.Task ByRef)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
</code>```

答:
Yes, it is perfectly fine to not run certain async operations. What you have is fine. What would not be so fine would be:

```<code>var notYetAwaited = DoSomethingAsync();

if (done) return "yay!";

await notYetAwaited;
</code>```

i.e. an async operation that spans the return. This has less obvious and predictable behaviour, especially in sync-context environments.

Your problem is unlikely to be because of the return. It sounds like this is simply a NRE happening in your data code that is being surfaced in the sync-context callback.

ContentLicense: CC BY-SA 3.0

Body:
I have a web page (aspx) that calls an async method in a class.  The async method looks something like this:

public async Task<MyThing> GetMyThing()
{
    MyThing thing = new MyThing();
    var stuff = await Repository.GetStuff();
    // apply stuff to thing.

    var morestuff = await Repository.GetMoreStuff();
    // apply more stuff to thing.

    if (someCondition)
    {
        return thing;
    }

    var yetMoreStuff = await Repository.GetYetMoreStuff();
    // apply yet more stuff

    return thing;
}

If the condition is met, I don't need the data from the last repository call.  Is the return before the final await going to cause me problems?

The reason I ask is I'm getting this error in the server application log, and I'm hunting for causes...

Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(System.Threading.SendOrPostCallback, System.Object)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(System.Threading.SendOrPostCallback, System.Object)
   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(System.Threading.ContextCallback, System.Object, System.Threading.Tasks.Task ByRef)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

Body:
Yes, it is perfectly fine to not run certain async operations. What you have is fine. What would not be so fine would be:

var notYetAwaited = DoSomethingAsync();

if (done) return "yay!";

await notYetAwaited;

i.e. an async operation that spans the return. This has less obvious and predictable behaviour, especially in sync-context environments.

Your problem is unlikely to be because of the return. It sounds like this is simply a NRE happening in your data code that is being surfaced in the sync-context callback.


问:
Collecting process ids of parallel process in bash file
Below I have a script that is collecting the process ids of individual commands, and appending them to an array in bash. For some reason as you can see stdout below, the end resulting array just contains one item, the latest id. How can the resulting PROCESS_IDS array at the end of this script contain all four process ids?

```<code>PROCESS_IDS=()

function append {
    echo $1
    PROCESS_IDS=("${PROCESS_IDS[@]}" $1)
}

sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait

echo "${PROCESS_IDS[@]}"
</code>```

Here is the stdout:

```<code>83873
83875
83879
83882
three
one
four
two
83882
</code>```

答:
Don't send the append operation itself to the background. Putting an & after the content you want to background but before the append suffices: The sleep and echo are still backgrounded, but the append is not.

```<code>process_ids=( )
append() { process_ids+=( "$1" ); }       # POSIX-standard function declaration syntax

{ sleep 1 && echo 'one'; } & append "$!"
{ sleep 5 && echo 'two'; } & append "$!"
{ sleep 1 && echo 'three'; } & append "$!"
{ sleep 5 && echo 'four'; } & append "$!"

echo "Background processes:"              # Demonstrate that our array was populated
printf ' - %s\n' "${process_ids[@]}"

wait
</code>```

Body:
Below I have a script that is collecting the process ids of individual commands, and appending them to an array in bash. For some reason as you can see stdout below, the end resulting array just contains one item, the latest id. How can the resulting PROCESS_IDS array at the end of this script contain all four process ids?

PROCESS_IDS=()

function append {
    echo $1
    PROCESS_IDS=("${PROCESS_IDS[@]}" $1)
}

sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait

echo "${PROCESS_IDS[@]}"

Here is the stdout:

83873
83875
83879
83882
three
one
four
two
83882

Body:
Don't send the append operation itself to the background. Putting an & after the content you want to background but before the append suffices: The sleep and echo are still backgrounded, but the append is not.

process_ids=( )
append() { process_ids+=( "$1" ); }       # POSIX-standard function declaration syntax

{ sleep 1 && echo 'one'; } & append "$!"
{ sleep 5 && echo 'two'; } & append "$!"
{ sleep 1 && echo 'three'; } & append "$!"
{ sleep 5 && echo 'four'; } & append "$!"

echo "Background processes:"              # Demonstrate that our array was populated
printf ' - %s\n' "${process_ids[@]}"

wait


问:
Android Layout Fill_Parent Problem
I am fairly new to android and am having some problems with a layout. Below is an approximation of what I want the layout to look like. (I would like the list to be below the screen at first so that the user can scroll down to see it.) However my code as it currently stands makes all of the views on the left only take up a quarter the screen instead of half, as depicted, even though I have all widths set to fill_parent.

Also, this layout seems to mess up the coordinate system on my custom view. Normally this wouldn't be much of an issue, but in this case I am using that view to draw a picture and the picture ends up in the wrong place. Does anybody have any idea how to resolve these issues?

答: Could you show the XML file you are using? This would be helpful. Also, the coordinate system of a View does not change based on the layout.</p>

ContentLicense: CC BY-SA 2.5

Title: Android Layout Fill_Parent Problem


问:
How Do I Print a Vector of Tuples?
So I'm trying to make a vector that contains tuples containing two ints, and I'm acquiring the ints from a text file source. To make sure I have the vector I want, I'm trying the print out my contents, but the output is not showing me anything. I'm not sure if it's because of my code, and where I put my text file. I'm just stuck at this point. If anything could help me with this, I'd appreciate it very much. Thanks

```<code>using namespace std;

int main()
{
ifstream file("source.txt");
typedef vector<tuple<int, int>> streets;
streets t;
int a, b;

if (file.is_open())
{
    while (((file >> a).ignore() >> b).ignore())
    {
        t.push_back(tuple<int, int>(a, b));
        for (streets::const_iterator i = t.begin();i != t.end();++i)
        {
            cout << get<0>(*i) << endl;
            cout << get<1>(*i) << endl;
        }
        cout << get<0>(t[0]) << endl;
        cout << get<1>(t[1]) << endl;
    }
}

file.close();

system("pause");
return 0;
</code>```

Here's my text file and where I placed it
enter image description here

Here's my output from debugging, if that's important

答:
You should use a loop, that will print one tuple at a time.

Complete minimal example:

```<code>#include <iostream>
#include <tuple>
#include <vector>
#include <fstream>
using namespace std;

int main(void) {
    std::ifstream infile("source.txt");
    vector<tuple<int, int>> streets;
    int a, b;
    while (infile >> a >> b)
    {
        streets.push_back(tuple<int, int>(a, b));
    }
    infile.close();
    for(auto& tuple: streets) {
        cout << get<0>(tuple) << " " << get<1>(tuple) << endl;
    }
    return 0;
}
</code>```

Output:

```<code>1 2
3 4
5 6
7 8
</code>```

Title: How Do I Print a Vector of Tuples?

Body:
So I'm trying to make a vector that contains tuples containing two ints, and I'm acquiring the ints from a text file source. To make sure I have the vector I want, I'm trying the print out my contents, but the output is not showing me anything. I'm not sure if it's because of my code, and where I put my text file. I'm just stuck at this point. If anything could help me with this, I'd appreciate it very much. Thanks

using namespace std;

int main()
{
ifstream file("source.txt");
typedef vector<tuple<int, int>> streets;
streets t;
int a, b;

if (file.is_open())
{
    while (((file >> a).ignore() >> b).ignore())
    {
        t.push_back(tuple<int, int>(a, b));
        for (streets::const_iterator i = t.begin();i != t.end();++i)
        {
            cout << get<0>(*i) << endl;
            cout << get<1>(*i) << endl;
        }
        cout << get<0>(t[0]) << endl;
        cout << get<1>(t[1]) << endl;
    }
}

file.close();

system("pause");
return 0;

Here's my text file and where I placed it
enter image description here

Here's my output from debugging, if that's important

Body:
You should use a loop, that will print one tuple at a time.

Complete minimal example:

#include <iostream>
#include <tuple>
#include <vector>
#include <fstream>
using namespace std;

int main(void) {
    std::ifstream infile("source.txt");
    vector<tuple<int, int>> streets;
    int a, b;
    while (infile >> a >> b)
    {
        streets.push_back(tuple<int, int>(a, b));
    }
    infile.close();
    for(auto& tuple: streets) {
        cout << get<0>(tuple) << " " << get<1>(tuple) << endl;
    }
    return 0;
}

Output:

1 2
3 4
5 6
7 8


问:
Livecharts change default legend
Here is my problem.

I am using LiveCharts to display some data.
Everything fine until showing the legend which represents all the data displayed.

chart with legend

Is it possibile to show a legend based on for example color(Stroke) or DefaultGeometries?

Thanks in advance for your help,

Diego

答:
I know this is a little late but I was looking to do something similar, so here is what I was able to come up with.

You would need to create a new collection and follow the example for Live Charts Energy Predictions.

First you need to set the LegendLocation="None" for the Chart

```<code><wpf:CartesianChart Hoverable="False" DataTooltip="{x:Null}" DisableAnimations="True" LegendLocation="None" Series="{Binding AllSeries, ElementName=FastGraphRoot}">
</code>```

New Legend Code (part that matters in .xaml):

```<code><ListBox Name="ListBox" MinHeight="250" ItemsSource="{Binding AllSeriesGroupByName, ElementName=FastGraphRoot}" Panel.ZIndex="1" BorderThickness="0" Background="Transparent">
        <ListBox.ItemTemplate>
            <DataTemplate DataType="{x:Type wpf:LineSeries}">
                <TextBlock Text="{Binding Title}"
                           Foreground="{Binding Stroke}"
                           FontSize="24"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Background" Value="Transparent" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <ContentPresenter />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</code>```

The Binded list would come from the original series but grouped, I have used a property for this:

```<code>private SeriesCollection _allSeriesGroupByName = new SeriesCollection();
public SeriesCollection AllSeriesGroupByName { get { return _allSeriesGroupByName; } set { _allSeriesGroupByName = value; OnPropertyChanged(); } }
</code>```

you could fill it simply with this code(or anything else you think is faster):

```<code>var col = collection.GroupBy(g => ((LineSeries)g).Stroke).Select(p => p.First());
AllSeriesGroupByName = new SeriesCollection();
foreach (var c in col)
{
    AllSeriesGroupByName.Add(c);
}
</code>```

Title: Livecharts change default legend

Body:
I know this is a little late but I was looking to do something similar, so here is what I was able to come up with.

You would need to create a new collection and follow the example for Live Charts Energy Predictions.

First you need to set the LegendLocation="None" for the Chart

<wpf:CartesianChart Hoverable="False" DataTooltip="{x:Null}" DisableAnimations="True" LegendLocation="None" Series="{Binding AllSeries, ElementName=FastGraphRoot}">

New Legend Code (part that matters in .xaml):

<ListBox Name="ListBox" MinHeight="250" ItemsSource="{Binding AllSeriesGroupByName, ElementName=FastGraphRoot}" Panel.ZIndex="1" BorderThickness="0" Background="Transparent">
        <ListBox.ItemTemplate>
            <DataTemplate DataType="{x:Type wpf:LineSeries}">
                <TextBlock Text="{Binding Title}"
                           Foreground="{Binding Stroke}"
                           FontSize="24"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Background" Value="Transparent" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <ContentPresenter />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

The Binded list would come from the original series but grouped, I have used a property for this:

private SeriesCollection _allSeriesGroupByName = new SeriesCollection();
public SeriesCollection AllSeriesGroupByName { get { return _allSeriesGroupByName; } set { _allSeriesGroupByName = value; OnPropertyChanged(); } }

you could fill it simply with this code(or anything else you think is faster):

var col = collection.GroupBy(g => ((LineSeries)g).Stroke).Select(p => p.First());
AllSeriesGroupByName = new SeriesCollection();
foreach (var c in col)
{
    AllSeriesGroupByName.Add(c);
}


问:
.NET Core 2 MVC role based login
I have a .NET Core 2 MVC project and I have a part of the website totally separated from the other one in my project. These both "parts" share the same set of users.
In one of the parts of the project I want users to be able to see the login page, but only users having specific role to be able to actually log in.

Currently I use the IsInRoleAsync method of ASP.NET Identity's user manager, but I am wondering if there is any better solution to this?

Thanks

答:
You can use the Authorize attribute :

```<code>public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Login()
    {
         // shows the login page
    }

    [HttpPost]
    [Authorize(Roles = "Administrator")]
    public ActionResult Login(LoginViewModel model)
    {
         // Process login
    }
}
</code>```

Title: .NET Core 2 MVC role based login

Body:
You can use the Authorize attribute :

public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Login()
    {
         // shows the login page
    }

    [HttpPost]
    [Authorize(Roles = "Administrator")]
    public ActionResult Login(LoginViewModel model)
    {
         // Process login
    }
}


问:
jQuery datepicker stays open after focus set through code
Here is jsFiddle with problem.

I am looping through all input elements, setting focus. When done, last datepicker stays open.

HTML:

```<code><input id="id1" type="text" class="datepicker" />
<input id="id2" type="text" class="datepicker" />
<input id="id3" type="text" class="not-datepicker" />
</code>```

JavaScript:

```<code>$(function() {
    $(".datepicker").datepicker({
    changeMonth: true,
    changeYear: true
  });
});

$("input").each(function() {
    $(this).focus();
});
</code>```

How do I close it?

UPDATE

Adding screenshot from Chrome on Mac, it does work fine on Firefox. As you can see focus is on 3rd input element, yet second input is showing datepicker.

答:
JqueryUi auto-closes the datepicker when an element loses focus by user interaction.  You can add a callback to hide the datepicker, or destroy it.

Hiding it: $('.datepicker').hide();

Removing it entirely: $(".datepicker").datepicker('destroy');

Worth noting- if you destroy it, you'd need to reinstantiate for further user to be able to make further changes/select again.

Body:
Here is jsFiddle with problem.

I am looping through all input elements, setting focus. When done, last datepicker stays open.

HTML:

<input id="id1" type="text" class="datepicker" />
<input id="id2" type="text" class="datepicker" />
<input id="id3" type="text" class="not-datepicker" />

JavaScript:

$(function() {
    $(".datepicker").datepicker({
    changeMonth: true,
    changeYear: true
  });
});

$("input").each(function() {
    $(this).focus();
});

How do I close it?

UPDATE

Adding screenshot from Chrome on Mac, it does work fine on Firefox. As you can see focus is on 3rd input element, yet second input is showing datepicker.


问:
Delete records from SQL Server backup file
It is an insane idea to delete records from backup since the notion of backup is to serve on disaster. But in our case, data deletion is a valid use-case.

Requirement: in brief, we are in need of a system which is capable of deleting a specific record from an active database instance and from all its backups.

We have a fully functional internal system which is capable of performing the mentioned requirement of deleting data from active database. But what we don't know is how to do the same agonist all these database backups.

Question:

Is it possible to find a specific record from a backup?

Is there any predefined schema or data allocation style within SQL Server backup file, which allow us to isolate a specific record?

Can you share any thoughts or experience you have on such style of deletion?

Note: we take 2 full backup daily and store a week worth (14 in total) at any point in time.

答:
I do understand the business concept of "deleted everywhere".

I do not know of any way to do this. I do not believe the format of the backup is even published. That doesn't mean that someone hasn't hacked it, but it certainly isn't a broadly known capability.

I think that, in order to do this, you will need to securely wipe all copies of backups and take new backups. You then lose the point in time recovery capability.

Solution: The way that I would address this business requirement is to recover each backup, delete the desired record(s), secure wipe the backup media (or destroy the old media and use new media), and then take a new backup of THAT recovered version. That will give you a point in time recovery of that data without the specific record(s).


问:
Configuring Multiple Web Sites to run under one Web Role
I'm trying to configure my Solution to publish multiple web sites to Azure using the 1.3 SDK and I want them to run under one Web Role.  I've added the entry to the Sites element as per the CHM file and when I deploy to Azure the Instance starts up.  Now for the symptoms:

Browsing to the "Primary" (first site added to the solution) everything works fine.

Browsing to the "Secondary" site throws the following error:

Exception type: ConfigurationErrorsException
    Exception message: Could not load file or assembly 'System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. (E:\approot_WASR_\1\web.config line 28)

What have I tried so far without success (sigh):
 1. I noticed that by default VStudio (2010 Ultimate) did not include the "Secondary" project output in the cspkg file.  Setting a project dependency seems to have fixed that problem (or at least I now see it in the output window during the build process).
 2. I've set "Copy Local=true" for the System.Web.Mvc on the "Secondary" project still nothing.
 3. I have a CName setup for the "Secondary" project and use the hostHeader parameter on the Binding element so I haven't found a good way of testing this local so I'm limited in diagnostic info.

One thought that I had was that both projects now contain a WebRole.cs file, should that be the case in this configuration?  As both of those handle startup events could that be the issue?

I'm not really sure what may be helpful to provide in this scenario so will be happy to fill in the blanks if someone could please direct me a bit.  Am I doing this all wrong?

Thanks in advance!

答:
One thing you'll want to make sure is that the second website is built before packaging.  It sounds like setting the project dependency probably took care of that.

You can test locally by adding an entry to your hosts file (edit %windir%\system32\drivers\etc\hosts as admin, and add "127.0.0.1 www.mysite.com" at the bottom).  This might help you get to the bottom of it.

After you run locally, you should be able to find the .csx directory and check what's in there... make sure the second site (under "_wasr_\1", I believe) looks like you expect it to.

Oh, the second webrole.cs is probably not an issue.  (It should be safely ignored.)


问:
MySQL String to Time Format
Could you please help.

In the database time represent in string format like 5.5 (hours) how to convert to 5:30 min

I tried

```<code>select CAST('5.50' AS DATETIME)

select STR_TO_DATE('5.50', '%h:%i %p') ;
</code>```

but this is not working.

Thank you

答:
I don't know of a neat way to do this but here is a hacky way off the top of my head.

```<code>select SEC_TO_TIME(5.5 * 3600)
</code>```

I'm converting 5.5 into seconds then from seconds to a time.

Hope this helps

Title: MySQL String to Time Format

Body:
Could you please help.

In the database time represent in string format like 5.5 (hours) how to convert to 5:30 min

I tried

select CAST('5.50' AS DATETIME)

select STR_TO_DATE('5.50', '%h:%i %p') ;

but this is not working.

Thank you

Body:
I don't know of a neat way to do this but here is a hacky way off the top of my head.

select SEC_TO_TIME(5.5 * 3600)

I'm converting 5.5 into seconds then from seconds to a time.

Hope this helps


问:
What is the exact chain of events when GNU make updates the .d files?
Consider the following simple makefile:

```<code>#------------------------------#
#    List all object files     #
#------------------------------#
objects := main.o foo.o bar.o baz.o

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)
</code>```

If you give the command make all, GNU make will start at the target myApp.elf. It looks at all the prerequisites main.o, foo.o, bar.o and baz.o and attempts to update them.

To do that, make uses the pattern rule defined in the middle of the makefile. This pattern rule expands like this:

```<code>main.o: main.c
    $(CC) -c $(CFLAGS) main.c -o main.o

foo.o: foo.c
    $(CC) -c $(CFLAGS) foo.c -o foo.o

bar.o: bar.c
    $(CC) -c $(CFLAGS) bar.c -o bar.o

baz.o: baz.c
    $(CC) -c $(CFLAGS) baz.c -o baz.o
</code>```

So far, so good. But you can clearly see that dependencies (included h-files) are missing.

I found some sources that recommend the following approach:

```<code>#------------------------------#
#    List all object files     #
#    and all dependency files  #
#------------------------------#
objects := main.o foo.o bar.o baz.o
deps := $(objects:.o=.d)

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) -MMD -MP $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

-include $(deps)
</code>```

I'm trying to wrap my head around this approach. First GNU make reads the makefile and looks for other included makefiles (see GNU make manual paragraph 3.5 "How Makefiles Are Remade"). Make attempts to update each included makefile it can find (in this case the dependency files main.d, foo.d, bar.d and baz.d) before starting execution of the makefiles. I've summarized this in the following figure:

Exactly. I don't see any rule where the dependency files are specified as targets.

Please help me to understand what actually happens next. Please, write your answer as a step-by-step chain of events. That would be great to gain insight in the matter.

Note:

Of course, the -MMD and -MP arguments in the compilation command (see pattern rule in the middle) lead to dependency files getting created. But the targets of this pattern rule are the object-files, not the dependency-files.

Note:

I had wrongly assumed that GNU make has an implicit rule getting activated here. But thanks to your comments and answers, I now know this was wrong :-)

答:
Here's what happens when you run make after make clean and dependency files don't exist yet:

make reads the text and reaches -include directive.

For each argument of the -include directive make tries to find a rule that has it as a target and run that rule.  make does this as part of processing of -include directive. No such rule will be found, because you didn't provide one.

make attempts to read files specified in -include directive and just skips those which don't exist (all of them in this case).

make goes to build the project, which in turn creates those *.d files.

If you run make again:

[same as before]

[same as before]

Since files do exist now, make reads them.

[same as before]

You might notice that this implies that make uses dependencies from the previous run, which is exactly how it works.
Dependencies lag behind changes in the source files.
This doesn't usually cause inconveniences though, and when it does removing dependency files can be used to fix the build.

Body:
Consider the following simple makefile:

#------------------------------#
#    List all object files     #
#------------------------------#
objects := main.o foo.o bar.o baz.o

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

If you give the command make all, GNU make will start at the target myApp.elf. It looks at all the prerequisites main.o, foo.o, bar.o and baz.o and attempts to update them.

To do that, make uses the pattern rule defined in the middle of the makefile. This pattern rule expands like this:

main.o: main.c
    $(CC) -c $(CFLAGS) main.c -o main.o

foo.o: foo.c
    $(CC) -c $(CFLAGS) foo.c -o foo.o

bar.o: bar.c
    $(CC) -c $(CFLAGS) bar.c -o bar.o

baz.o: baz.c
    $(CC) -c $(CFLAGS) baz.c -o baz.o

So far, so good. But you can clearly see that dependencies (included h-files) are missing.

I found some sources that recommend the following approach:

#------------------------------#
#    List all object files     #
#    and all dependency files  #
#------------------------------#
objects := main.o foo.o bar.o baz.o
deps := $(objects:.o=.d)

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) -MMD -MP $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

-include $(deps)

I'm trying to wrap my head around this approach. First GNU make reads the makefile and looks for other included makefiles (see GNU make manual paragraph 3.5 "How Makefiles Are Remade"). Make attempts to update each included makefile it can find (in this case the dependency files main.d, foo.d, bar.d and baz.d) before starting execution of the makefiles. I've summarized this in the following figure:

Exactly. I don't see any rule where the dependency files are specified as targets.

Please help me to understand what actually happens next. Please, write your answer as a step-by-step chain of events. That would be great to gain insight in the matter.

Note:

Of course, the -MMD and -MP arguments in the compilation command (see pattern rule in the middle) lead to dependency files getting created. But the targets of this pattern rule are the object-files, not the dependency-files.

Note:

I had wrongly assumed that GNU make has an implicit rule getting activated here. But thanks to your comments and answers, I now know this was wrong :-)


问:
how use sessions and store value in a session and use for login sysytem
i am trying to create an custom   login process and for this a want use sessions but i cant find any source for that how i can use sessions in asp.net MVC please guide me how i can use sessions i just check from them that user log out or not so he can be able to access on dashboard without log in again. thanks in advance. </p>

```<code>Session["user"] = profile.userName;
                var admin = db.userProfiles.Where(x => x.userName == user.userName && x.password == user.password && x.admin==1).FirstOrDefault();
                if(admin==null)
                {
                    if (Session["user"] != null)
                    {
                        ViewBag.userName = user.userName;
                        return View();
                    }
                    else
                    {
                       return RedirectToAction("login");
                    }

                }
                else
                {

                    if (Session["user"] != null)
                    {
                        return RedirectToAction("index");
                    }
                    else
                    {
                       return RedirectToAction("login");
                    }
</code>```

答:
You're reinventing the wheel. Have you considered using the built-in Identity and authentication schemes?

Create an ASP.NET Core app with user data protected by authorization
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/secure-data

Building a simple ToDo application with ASP.NET Identity and associating Users with ToDoes
https://blogs.msdn.microsoft.com/webdev/2013/10/20/building-a-simple-todo-application-with-asp-net-identity-and-associating-users-with-todoes/

Body:
i am trying to create an custom   login process and for this a want use sessions but i cant find any source for that how i can use sessions in asp.net MVC please guide me how i can use sessions i just check from them that user log out or not so he can be able to access on dashboard without log in again. thanks in advance.

Session["user"] = profile.userName;
                var admin = db.userProfiles.Where(x => x.userName == user.userName && x.password == user.password && x.admin==1).FirstOrDefault();
                if(admin==null)
                {
                    if (Session["user"] != null)
                    {
                        ViewBag.userName = user.userName;
                        return View();
                    }
                    else
                    {
                       return RedirectToAction("login");
                    }

                }
                else
                {

                    if (Session["user"] != null)
                    {
                        return RedirectToAction("index");
                    }
                    else
                    {
                       return RedirectToAction("login");
                    }


问:
Powerful algorithms too complex to implement
What are some algorithms of legitimate utility that are simply too complex to implement?

Let me be clear: I'm not looking for algorithms like the current asymptotic optimal matrix multiplication algorithm, which is reasonable to implement but has a constant that makes it useless in practice. I'm looking for algorithms that could plausibly have practical value, but are so difficult to code that they have never been implemented, only implemented in extremely artificial settings, or only implemented for remarkably special-purpose applications.

Also welcome are near-impossible-to-implement algorithms that have good asymptotics but would likely have poor real performance.

答:
If we can equate "tedious" with "difficult" then some mathematical proofs can have a very large number of special cases such as Hale's proof or Kepler's conjecture: http://en.wikipedia.org/wiki/Kepler_conjecture

Following the approach suggested by
  Fejes Tóth (1953), Thomas Hales, then
  at the University of Michigan,
  determined that the maximum density of
  all arrangements could be found by
  minimizing a function with 150
  variables. In 1992, assisted by his
  graduate student Samuel Ferguson, he
  embarked on a research program to
  systematically apply linear
  programming methods to find a lower
  bound on the value of this function
  for each one of a set of over 5,000
  different configurations of spheres.
  If a lower bound (for the function
  value) could be found for every one of
  these configurations that was greater
  than the value of the function for the
  cubic close packing arrangement, then
  the Kepler conjecture would be proved.
  To find lower bounds for all cases
  involved solving around 100,000 linear
  programming problems.

When presenting the progress of his
  project in 1996, Hales said that the
  end was in sight, but it might take "a
  year or two" to complete. In August
  1998 Hales announced that the proof
  was complete. At that stage it
  consisted of 250 pages of notes and 3
  gigabytes of computer programs, data
  and results.


问:
How do i tell the browser to use cache manifest if the browser doesn't support service workers?
How do i tell the browser to use cache manifest if the browser doesn't support service workers?

I have an Angular 4 app that needs to run offline. Service workers do the job brilliantly but it isn't supported by Safari which is a required browser that it needs to run on.

I need to generate a cache manifest file if service workers is not supported by the browser then for the browser to use the cache manifest file once the browser goes offline

current code (typescript):

```<code>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../../service-worker.js').then(function(registration) {
    //TODO: Implement Logging
  }).catch(function(err) {
    //TODO: Implement Logging
  });
} else {
  //Not currently supported on Internet explorer, Safari, IE Mobile and Safari Mobile. Use old Application Caching instead.
  console.log("Not Supported");
  //Use cache manifest
}
</code>```

答:
How about just create an element <link> in the else statement with all the required properties of the manifest file ? I guess you have to put that part of the script in the

```<code>const linkMeta = document.createElement('link');
linkMeta.setAttribute('rel', 'manifest');
linkMeta.setAttribute('href', '/manifest.webmanifes');
</code>```

and append it to the

Body:
How do i tell the browser to use cache manifest if the browser doesn't support service workers?

I have an Angular 4 app that needs to run offline. Service workers do the job brilliantly but it isn't supported by Safari which is a required browser that it needs to run on.

I need to generate a cache manifest file if service workers is not supported by the browser then for the browser to use the cache manifest file once the browser goes offline

current code (typescript):

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../../service-worker.js').then(function(registration) {
    //TODO: Implement Logging
  }).catch(function(err) {
    //TODO: Implement Logging
  });
} else {
  //Not currently supported on Internet explorer, Safari, IE Mobile and Safari Mobile. Use old Application Caching instead.
  console.log("Not Supported");
  //Use cache manifest
}

Body:
How about just create an element <link> in the else statement with all the required properties of the manifest file ? I guess you have to put that part of the script in the <head>

const linkMeta = document.createElement('link');
linkMeta.setAttribute('rel', 'manifest');
linkMeta.setAttribute('href', '/manifest.webmanifes');

and append it to the <head>


问:
Test instrumentation process crashed when injecting mocked object
I am trying to run a UI test. When I do not mock any injected dependency everything runs well. When I switch module's @Provides return to mocked object, I get the following message:

Started running tests

Test instrumentation process crashed.

Check
com.nerfy.features.core.CoreTest#a_shouldDisplayLocationPermissionRequestDialogAtStartup.txt
for details.

Tests ran to completion.

I cannot find this txt file anywhere, only some test xmls which are not informative at all.

Edit: The file contains only: INSTRUMENTATION_RESULT: shortMsg=Process crashed. INSTRUMENTATION_CODE: 0.

App works well otherwise.

Application code:

```<code>public class Nerfy extends Application {

private AppComponent appComponent;

public static Nerfy get(Context context) {
    return (Nerfy) context.getApplicationContext();
}

@Override
public void onCreate() {
    super.onCreate();
    System.out.println("on create");
    if (appComponent == null) {
        appComponent = buildProdAppComponent();
        appComponent.inject(this);
    }
}

public AppComponent buildProdAppComponent() {
    return DaggerAppComponent.builder()
            .appModule(new AppModule(this))
            .navigationModule(new NavigationModule())
            .refreshModule(new RefreshModule())
            .repoModule(new RepoModule())
            .sharedDataModule(new SharedDataModule())
            .threadsModule(new ThreadsModule())
            .build();
}

//@VisibleForTesting
public void setAppComponent(AppComponent appComponent) {
    System.out.println("on set");

    this.appComponent = appComponent;
    this.appComponent.inject(this);
}

public AppComponent getAppComponent() {
    return appComponent;
}
</code>```

}

Here is some test code:

```<code>@RunWith(AndroidJUnit4.class)
@LargeTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CoreTest {

private UiDevice device;
public SharedData sharedData;
private AppComponent espressoAppComponent;

@Rule
public ActivityTestRule<Core> mActivityRule =
        new ActivityTestRule<Core>(Core.class) {
            @Override
            protected void beforeActivityLaunched() {
                System.out.println("beforeActivityLaunched");
                sharedData = mock(SharedData.class);
                System.out.println("shared data " + sharedData);

                espressoAppComponent = DaggerAppComponent.builder()
                        .appModule(new AppModule((Application) getTargetContext().getApplicationContext()))
                        .navigationModule(new NavigationModule())
                        .refreshModule(new RefreshModule())
                        .repoModule(new RepoModule())
                        .sharedDataModule(new SharedDataModule(){
                            @Override
                            public SharedData providesSharedData(Application application) {
                                return sharedData;
                            }
                        })
                        .threadsModule(new ThreadsModule())
                        .build();
                ((Nerfy) getTargetContext().getApplicationContext()).setAppComponent(espressoAppComponent);
                super.beforeActivityLaunched();
            }
        };

@Before
public void setUp() {
}

@Test
    @SdkSuppress(minSdkVersion = 23)
    public void a_shouldDisplayLocationPermissionRequestDialogAtStartup() throws Exception {
        assertViewWithTextIsVisible(device, TEXT_ALLOW);
        assertViewWithTextIsVisible(device, TEXT_DENY);
        denyCurrentPermission(device);
    }
</code>```

Nothing gets printed out.

But if I switch mocked shared data to real one

```<code>@Override
public SharedData providesSharedData(Application application) {
      return super.providesSharedData(application);
</code>```

It all runs well, test fails properly because shared data is not mocked.
Then I also noticed that application's onCreate is called before test activity rule's beforeActivityLaunched, even though on some tutorials they say it should be called before applications on create.

I have followed tutorials like
http://blog.sqisland.com/2015/04/dagger-2-espresso-2-mockito.html

Android Mocking a Dagger2 injected dependency for a Espresso test

How do you override a module/dependency in a unit test with Dagger 2.0?

and similar; also official dagger2 docs.

I have tried subclassing application, creating new model and subclassing component for test only; also not initing activityRule until on setUp() end, after injecting component here instead on overriding of beforeActivityLaunched().

Also tried trivial fixes like rebuilding the project, restarting android studio, updating dependencies.

Mocking some other modules also brings the same result while mocking others works fine.

Any ideas?

答:
I have tested other modules. Found out that mocked Refresher module would crash the test process due to it having Observable field. The tested activity tries to  subscribe on it, but it's null.

The SharedData was much more difficult to figure out - it handles shared preferences, so basically just strings and booleans. I had to check all the usages. The crash happened while trying to put string value as url (not mocked, so null again) to Picasso to get an image.

Moral of the story - one proper crash message is worth two days of blind debugging.

Body:
I am trying to run a UI test. When I do not mock any injected dependency everything runs well. When I switch module's @Provides return to mocked object, I get the following message:

Started running tests

Test instrumentation process crashed.

Check
com.nerfy.features.core.CoreTest#a_shouldDisplayLocationPermissionRequestDialogAtStartup.txt
for details.

Tests ran to completion.

I cannot find this txt file anywhere, only some test xmls which are not informative at all.

Edit: The file contains only: INSTRUMENTATION_RESULT: shortMsg=Process crashed. INSTRUMENTATION_CODE: 0.

App works well otherwise.

Application code:

public class Nerfy extends Application {

private AppComponent appComponent;

public static Nerfy get(Context context) {
    return (Nerfy) context.getApplicationContext();
}

@Override
public void onCreate() {
    super.onCreate();
    System.out.println("on create");
    if (appComponent == null) {
        appComponent = buildProdAppComponent();
        appComponent.inject(this);
    }
}

public AppComponent buildProdAppComponent() {
    return DaggerAppComponent.builder()
            .appModule(new AppModule(this))
            .navigationModule(new NavigationModule())
            .refreshModule(new RefreshModule())
            .repoModule(new RepoModule())
            .sharedDataModule(new SharedDataModule())
            .threadsModule(new ThreadsModule())
            .build();
}

//@VisibleForTesting
public void setAppComponent(AppComponent appComponent) {
    System.out.println("on set");

    this.appComponent = appComponent;
    this.appComponent.inject(this);
}

public AppComponent getAppComponent() {
    return appComponent;
}

}

Here is some test code:

@RunWith(AndroidJUnit4.class)
@LargeTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CoreTest {

private UiDevice device;
public SharedData sharedData;
private AppComponent espressoAppComponent;

@Rule
public ActivityTestRule<Core> mActivityRule =
        new ActivityTestRule<Core>(Core.class) {
            @Override
            protected void beforeActivityLaunched() {
                System.out.println("beforeActivityLaunched");
                sharedData = mock(SharedData.class);
                System.out.println("shared data " + sharedData);

                espressoAppComponent = DaggerAppComponent.builder()
                        .appModule(new AppModule((Application) getTargetContext().getApplicationContext()))
                        .navigationModule(new NavigationModule())
                        .refreshModule(new RefreshModule())
                        .repoModule(new RepoModule())
                        .sharedDataModule(new SharedDataModule(){
                            @Override
                            public SharedData providesSharedData(Application application) {
                                return sharedData;
                            }
                        })
                        .threadsModule(new ThreadsModule())
                        .build();
                ((Nerfy) getTargetContext().getApplicationContext()).setAppComponent(espressoAppComponent);
                super.beforeActivityLaunched();
            }
        };

@Before
public void setUp() {
}

@Test
    @SdkSuppress(minSdkVersion = 23)
    public void a_shouldDisplayLocationPermissionRequestDialogAtStartup() throws Exception {
        assertViewWithTextIsVisible(device, TEXT_ALLOW);
        assertViewWithTextIsVisible(device, TEXT_DENY);
        denyCurrentPermission(device);
    }

Nothing gets printed out.

But if I switch mocked shared data to real one

@Override
public SharedData providesSharedData(Application application) {
      return super.providesSharedData(application);

It all runs well, test fails properly because shared data is not mocked.
Then I also noticed that application's onCreate is called before test activity rule's beforeActivityLaunched, even though on some tutorials they say it should be called before applications on create.

I have followed tutorials like
http://blog.sqisland.com/2015/04/dagger-2-espresso-2-mockito.html

Android Mocking a Dagger2 injected dependency for a Espresso test

How do you override a module/dependency in a unit test with Dagger 2.0?

and similar; also official dagger2 docs.

I have tried subclassing application, creating new model and subclassing component for test only; also not initing activityRule until on setUp() end, after injecting component here instead on overriding of beforeActivityLaunched().

Also tried trivial fixes like rebuilding the project, restarting android studio, updating dependencies.

Mocking some other modules also brings the same result while mocking others works fine.

Any ideas?


问:
Specify custom output file path for browserify
Using CLI , set value to -o to specify the output filepath( bundle)

```<code>node node_modules/browserify/bin/cmd src/index -o lib/bundle.js
</code>```

In the above example , the output file path is ./lib/bundle.js.

However, I don't want to use CLI , i want to use JS SDK :

```<code>    const browserify = require('browserify');

    const b = browserify();
    b.add('./src/index.js');
    b.bundle(/* Where to specify the output filepath, is it here */)
     .pipe(/* or here*/)
</code>```

My head will break because of this library. Frankly, webpack documentation is better.

Any help is appreciative

答:
If you happen to be using the Gulp build system, you can also do it like this.

(Much thanks to Dan Tello for his article that helped me get this going in my own environment!).

This approach utilizes the help of another Node module called vinyl-source-stream.  By using this helper module, you're not dependent upon the deprecated gulp-browserify package - you can use the latest vanilla browserify package as-is.

```<code>var gulp = require('gulp');

// add in browserify module to bundle the JS
// We can use this directly instead of 'gulp-browserify' with help
// from 'vinyl-source-stream'
var browserify = require('browserify');

// Add in vinyl-source-stream to help link browserify and gulp streams
var source = require('vinyl-source-stream');

gulp.task('browserify', () => {

    return browserify('./js/main.js') // source to compile
        .bundle()   // compile it...
        .pipe(source('popup.js'))  // pipe to output file
        .pipe(gulp.dest('./js/'));  // put output back into ./js/
});
</code>```

Body:
Using CLI , set value to -o to specify the output filepath( bundle)

node node_modules/browserify/bin/cmd src/index -o lib/bundle.js

In the above example , the output file path is ./lib/bundle.js.

However, I don't want to use CLI , i want to use JS SDK :

    const browserify = require('browserify');

    const b = browserify();
    b.add('./src/index.js');
    b.bundle(/* Where to specify the output filepath, is it here */)
     .pipe(/* or here*/)

My head will break because of this library. Frankly, webpack documentation is better.

Any help is appreciative

Body:
If you happen to be using the Gulp build system, you can also do it like this.

(Much thanks to Dan Tello for his article that helped me get this going in my own environment!).

This approach utilizes the help of another Node module called vinyl-source-stream.  By using this helper module, you're not dependent upon the deprecated gulp-browserify package - you can use the latest vanilla browserify package as-is.

var gulp = require('gulp');

// add in browserify module to bundle the JS
// We can use this directly instead of 'gulp-browserify' with help
// from 'vinyl-source-stream'
var browserify = require('browserify');

// Add in vinyl-source-stream to help link browserify and gulp streams
var source = require('vinyl-source-stream');

gulp.task('browserify', () => {

    return browserify('./js/main.js') // source to compile
        .bundle()   // compile it...
        .pipe(source('popup.js'))  // pipe to output file
        .pipe(gulp.dest('./js/'));  // put output back into ./js/
});


问:
How to delete single (many-) rows from one-to-many relations in Laravel 5.5
I got two models in Laravel: Label

```<code>class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}
</code>```

And Channel

```<code>class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}
</code>```

Now when a label is deleted, I want to make sure, the label belongs to the channel.

This works pretty good, as it even is atomic, so the row will just be deleted, if the label really belongs to the channel.

LabelController:

```<code>/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}
</code>```

And my question is now: How to build that with Eloquent, so it is elegant? Something like:

```<code>    $channel->labels()->destroy($id);
</code>```

But there is no destroy function on the relation.

Update:

I managed to achieve something in the right direction:

```<code>$channel->labels()->find($id)->delete();
</code>```

This deletes the label with $id BUT just if the label has the right channel_id assigned. If not, I get the following error, which I could catch and handle:

```<code>FatalThrowableError (E_ERROR) Call to a member function delete() on null
</code>```

Still, as Apache is threaded, there could be the case that another thread changes the channel_id after I read it. So the only way besides my query is to run a transaction?

答:
If you want to delete related items of your model but not model itself you can do like this:

$channel->labels()->delete(); It will delete all labels related to the channel.

If you want to delete just some of labels you can use where()

$channel->labels()->where('id',1)->delete();

Also if your relation is many to many it will delete from third table too.

Body:
I got two models in Laravel: Label

class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}

And Channel

class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}

Now when a label is deleted, I want to make sure, the label belongs to the channel.

This works pretty good, as it even is atomic, so the row will just be deleted, if the label really belongs to the channel.

LabelController:

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}

And my question is now: How to build that with Eloquent, so it is elegant? Something like:

    $channel->labels()->destroy($id);

But there is no destroy function on the relation.

Update:

I managed to achieve something in the right direction:

$channel->labels()->find($id)->delete();

This deletes the label with $id BUT just if the label has the right channel_id assigned. If not, I get the following error, which I could catch and handle:

FatalThrowableError (E_ERROR) Call to a member function delete() on null

Still, as Apache is threaded, there could be the case that another thread changes the channel_id after I read it. So the only way besides my query is to run a transaction?

ContentLicense: CC BY-SA 4.0


问:
How to get a time zone from a location using latitude and longitude coordinates?
Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?

In most cases, we are looking for an IANA/Olson time zone id, although some services may return just a UTC offset, or some other time zone identifier.  Please read the timezone tag info for details.

答:
Here's how you can use Google's script editor to get the timezoneName and timeZoneId inside a gsheet.

Step 1. Get an API key for Google's timezone API

Step 2. Create a new gsheet. Underneath the 'tools' menu click 'script editor'. Add the following code:

```<code>function getTimezone(lat, long) {
  var apiKey = 'INSERTAPIKEYHERE'
  var url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + lat + ',' + long + '&timestamp=1331161200&key=' + apiKey
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());
  return data["timeZoneName"];
}
</code>```

Step 3. Save and publish your getTimezone() function and use it as shown in the image above.

Body:
Here's how you can use Google's script editor to get the timezoneName and timeZoneId inside a gsheet.

Step 1. Get an API key for Google's timezone API

Step 2. Create a new gsheet. Underneath the 'tools' menu click 'script editor'. Add the following code:

function getTimezone(lat, long) {
  var apiKey = 'INSERTAPIKEYHERE'
  var url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + lat + ',' + long + '&timestamp=1331161200&key=' + apiKey
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());
  return data["timeZoneName"];
}

Step 3. Save and publish your getTimezone() function and use it as shown in the image above.


问:
How to grep with a regex to eliminate this stacktrace?
I would like to eliminate a stacktrace from my log file, such that only the SQL text is displayed. This works as I would like on RegExr.com:

'java.lang((.|\n)*)java:745'

But it does not work with grep -v

grep -v 'java.lang((.|\n)*)java:745'

Any suggestions how I can use grep -v to only display the query text?

```<code>CONFIG: 204658E4 SQL: select  *
        from    table
        where   column =  :1
java.lang.Throwable: No Error
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1624)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4347)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4426)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:4733)
    at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:125)
    at com.sun.proxy.$Proxy60.executeQuery(Unknown Source)
    at sqlj.runtime.ExecutionContext$OracleContext.oracleExecuteQuery(ExecutionContext.java:71)
    at me.loadQuery(DataBean.java:364)
    at me.loadQuery(DataBean.java:411)
    at org.apache.jsp.jsp.secure.navigate_jsp.displayMenu(navigate_jsp.java:43)
    at org.apache.jsp.jsp.secure.navigate_jsp._jspService(navigate_jsp.java:472)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
</code>```

答:
From your given output, you can see that the the Java exception follows a very specific pattern:

the line with the error message, starting with java.lang.Throwable

the stacktrace lines, all starting with 0 or more spaces, followed by at

Using grep to filter the lines, we can see from the man page, that you only need to specify a part of the line to dismiss it (when using the -v flag to ignore lines matching the pattern).

So based on that, we can build the regular expression and the command:

```<code>grep -v '^java.lang.Throwable\| *at' your_log_file.log
</code>```

^<expression> The expression must match a the beginning of the line

<expr1>\|<expr2> The expression matches if expr1 OR expr2 matches.

java.lang.Throwable matches this exact string

*at can be decomposed in 2:

* (a space followed by a *) matches any number of spaces (0 or more)

at matches this exact string

So to sum it up, it will ignore all the lines that starts by either java.lang.Throwable or any number of spaces followed by at.

Body:
I would like to eliminate a stacktrace from my log file, such that only the SQL text is displayed. This works as I would like on RegExr.com:

'java.lang((.|\n)*)java:745'

But it does not work with grep -v

grep -v 'java.lang((.|\n)*)java:745'

Any suggestions how I can use grep -v to only display the query text?

CONFIG: 204658E4 SQL: select  *
        from    table
        where   column =  :1
java.lang.Throwable: No Error
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1624)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4347)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4426)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:4733)
    at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:125)
    at com.sun.proxy.$Proxy60.executeQuery(Unknown Source)
    at sqlj.runtime.ExecutionContext$OracleContext.oracleExecuteQuery(ExecutionContext.java:71)
    at me.loadQuery(DataBean.java:364)
    at me.loadQuery(DataBean.java:411)
    at org.apache.jsp.jsp.secure.navigate_jsp.displayMenu(navigate_jsp.java:43)
    at org.apache.jsp.jsp.secure.navigate_jsp._jspService(navigate_jsp.java:472)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Body:
From your given output, you can see that the the Java exception follows a very specific pattern:

the line with the error message, starting with java.lang.Throwable

the stacktrace lines, all starting with 0 or more spaces, followed by at

Using grep to filter the lines, we can see from the man page, that you only need to specify a part of the line to dismiss it (when using the -v flag to ignore lines matching the pattern).

So based on that, we can build the regular expression and the command:

grep -v '^java.lang.Throwable\| *at' your_log_file.log

^<expression> The expression must match a the beginning of the line

<expr1>\|<expr2> The expression matches if expr1 OR expr2 matches.

java.lang.Throwable matches this exact string

*at can be decomposed in 2:

* (a space followed by a *) matches any number of spaces (0 or more)

at matches this exact string

So to sum it up, it will ignore all the lines that starts by either java.lang.Throwable or any number of spaces followed by at.


问:
How to trap a websocket 503 max connections in javascript?
My websocket code works fine as long as I don't exceed my number of connections.  I want to trap when the 503 error occurs.  Console output that shows up is as follows:

SCRIPT12008: WebSocket Error: Incorrect HTTP response. Status code 503, Number of active WebSocket requests has reached the maximum concurrent WebSocket requests allowed.

WebSocket.OnError handler doesn't surface out the full detail.  How can I get the detail level as shown in the console output above?  Some kind of document collection or, well, I don't know really.

Full code here.  Socket server is alive and INTENTIONALLY limited to 4 connections as of 12/6.  Will chop it down later.

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/base.css" />
<title>Yielding Loop</title>
<script type="text/javascript">
    var c = 0;
    var t;
    var timer_is_on = 0;
    var m_connection = null;
    var m_socket_address = "ws://edgeplay.azurewebsites.net/ws";

    function timedCount()
    {
        echoTest();
        document.getElementById( "txt" ).value = c;
        outmsg( "tick=" + c );
        c = c + 1;
        t = setTimeout( function () { timedCount() }, 3000 );
    }

    function startCount()
    {
        if ( !timer_is_on )
        {
            timer_is_on = 1;
            timedCount();
        }
    }

    function stopCount()
    {
        clearTimeout( t );
        timer_is_on = 0;
    }

    function SocketInit()
    {
        try
        {
            if ( "WebSocket" in window )
            {
                outmsg( "WebSocket supported, gtg." );
            }
            else
            {
                outmsg( "WebSocket NOT SUPPORTED, bailing out" );
                return 0;
            }

            outmsg( "connecting to " + m_socket_address );

            try
            {
                m_connection = new WebSocket( m_socket_address );
            }
            catch ( err )
            {
                outmsg( "error creating new socket - " + err );
                outmsg( "error.name:" + err.name );
                outmsg( "error.message:" + err.message );
            }

            m_connection.onopen = function ( openEvent )
            {
                outmsg( "WebSocket.OnOpen - GTG: " + m_socket_address );
            };

            m_connection.onmessage = function ( messageEvent )
            {
                outmsg( 'WebSocket.onmessage - Server Reply:: ' + messageEvent.data );
            };

            m_connection.onerror = function ( errorEvent )
            {
                outmsg( "WebSocket Status:: Error was reported." );
                outmsg( "WebSocket errorEvent: " + errorEvent );
                outmsg( "Stopping count" );
                var h1 = document.getElementById( "h1Main" );
                h1.style = "background-color:red;";
                stopCount();
            };

            m_connection.onclose = function ( closeEvent )
            {
                outmsg( "WebSocket Status:: Socket Closed" );
                outmsg( "closeEvent.code:" + closeEvent.code );
                outmsg( "closeEvent.data:" + closeEvent.data );
            };
        }
        catch ( exception )
        {
            outmsg( "exception: " + exception );
        }
    }

    var m_input = null;
    var m_querystring = null;
    function echoTest()
    {
        try
        {
            m_input = m_input == null ? document.getElementById( "textEcho" ) : m_input;
            m_connection.send( m_input.value + location.search );
        }
        catch ( err )
        {
            outmsg( "eating error " + err );
        }
    }

    var m_out = null;
    var outd = null;
    function outmsg( msg )
    {
        m_out = ( m_out == null ) ? document.getElementById( "divOutput" ) : m_out;
        outd = new Date();
        m_out.innerHTML = outd.toLocaleTimeString() + ": " + msg + "<br/>" + m_out.innerHTML;
    }
</script>
</head>
<body onload="SocketInit();startCount();">
<h1 id="h1Main">Yielding Loop</h1>
<button onclick="SocketInit();startCount();">Init socket and start count</button>
<input type="text" id="txt">
<button onclick="stopCount()">Stop count!</button>
<br/>
<span>text to echo: </span><input type="text" value="BLUE" id="textEcho"/>

<div id="divOutput" style="background-color:antiquewhite; border:3px; width:900px;">
    ready....
</div>
<hr />
</body>
</html>
</code>```

Errors raised when it fails:

debugged into the error raised.  not much goodness in there.  output lines below.  Reverse chrono.

```<code>1:04:59 PM: --- closeEvent.reason:
1:04:59 PM: --- closeEvent.data:undefined
1:04:59 PM: --- closeEvent.code:1006
1:04:59 PM: WebSocket.onClose
1:04:59 PM: --- Stopping count
1:04:59 PM: --- errorEvent.type: error
1:04:59 PM: --- errorEvent: [object Event]
1:04:59 PM: WebSocket.onerror
</code>```

答:
Apparently you will only ever get a 1006 onclose for security reasons.  Not leaving my happy but that is the way the RFC is written.  https://html.spec.whatwg.org/multipage/web-sockets.html#network

User agents must not convey any failure information to scripts in a
  way that would allow a script to distinguish the following situations:
  A server whose host name could not be resolved.  A server to which
  packets could not successfully be routed.  A server that refused the
  connection on the specified port.  A server that failed to correctly
  perform a TLS handshake (e.g., the server certificate can't be
  verified).  A server that did not complete the opening handshake (e.g.
  because it was not a WebSocket server).  A WebSocket server that sent
  a correct opening handshake, but that specified options that caused
  the client to drop the connection (e.g. the server specified a
  subprotocol that the client did not offer).  A WebSocket server that
  abruptly closed the connection after successfully completing the
  opening handshake.  In all of these cases, the the WebSocket
  connection close code would be 1006, as required by the WebSocket
  Protocol specification. [WSP]

Body:
My websocket code works fine as long as I don't exceed my number of connections.  I want to trap when the 503 error occurs.  Console output that shows up is as follows:

SCRIPT12008: WebSocket Error: Incorrect HTTP response. Status code 503, Number of active WebSocket requests has reached the maximum concurrent WebSocket requests allowed.

WebSocket.OnError handler doesn't surface out the full detail.  How can I get the detail level as shown in the console output above?  Some kind of document collection or, well, I don't know really.

Full code here.  Socket server is alive and INTENTIONALLY limited to 4 connections as of 12/6.  Will chop it down later.

<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/base.css" />
<title>Yielding Loop</title>

Yielding Loop

<button onclick="SocketInit();startCount();">Init socket and start count</button>
<input type="text" id="txt">
<button onclick="stopCount()">Stop count!</button>

text to echo: <input type="text" value="BLUE" id="textEcho"/>

    ready....

Errors raised when it fails:

debugged into the error raised.  not much goodness in there.  output lines below.  Reverse chrono.

1:04:59 PM: --- closeEvent.reason:
1:04:59 PM: --- closeEvent.data:undefined
1:04:59 PM: --- closeEvent.code:1006
1:04:59 PM: WebSocket.onClose
1:04:59 PM: --- Stopping count
1:04:59 PM: --- errorEvent.type: error
1:04:59 PM: --- errorEvent: [object Event]
1:04:59 PM: WebSocket.onerror


问:
Deserialization of object in Class Library while accepting an interface parameter (C#, MVC)
Given the interface:

```<code>interface IObject
{
   public string Name {get;set}
}
</code>```

And the following objects:

```<code>class A: IObject
{
   public string Name {get;set}
   public int ID {get;set;}
}

class B: IObject
{
   public string Name {get;set}
   public Guid ID {get;set;}
}
</code>```

I have two consuming applications which are using different database schemae, but do the same job.  This is a matter of maintaining an old app while a team writes a new one.  Requirements include that both use the same library, which is why this problem exists. The apps both call the same external API, and that call is in its own static class and is accessed like so:

```<code>public static IEnumerable<IObject> List(Guid listUniqueIdentifier)
 {
       //a custom class to call the API
       using (var cmd = new WebApiCommand())
       {
                               //custom enum
             cmd.CommandType = ApiComType.GET;
             cmd.Command = "ListObjects";
             cmd.Filter = listUniqueIdentifier.ToString();
             IEnumerable<object> data = cmd.Execute();
             var result = new List<IObject>();
             foreach(var d in data)
             {
               result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
             }
             return result;
       }

}
</code>```

Obviously, you can't instantiate an interface, so

```<code>result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
</code>```

breaks. I don't want to just attempt to construct the GUID-using version and if it fails, use the integer version.  Not only is that a little hacky, but it's the newer DB that is using the integer, so I'd be using a try block as flow control in just about the worse possible way.  How can I deserialize to the right object instance type (A or B) without writing different methods for each type?  Edit: The solutions I've found usually involve either serializing the $type or otherwise saving the instance type during serialization.  That is not possible, as the API is connected to a third party application and cannot store this datum.

答:
Your issue, as far as I can tell, is that you have no way to identify, by "d" which type of class to serialize into.
(Pseudo)

```<code>foreach(var d in data)
    {
       like if(Convert.ToString(d).All(char.IsDigit) && Convert.ToString(d).length <= Int32.MaxValue)
       {
          result.add(JsonConvert.DeserializeObject<A>(Convert.ToString(d)));
       }
       else
       {
          result.add(JsonConvert.DeserializeObject<B>(Convert.ToString(d)));
       }

    }
</code>```

EDIT: I think this is the best approach with the limited info you have given. If not, I would recommend, that you alter the data call itself, so the WebAPI can provide you with two different sets of data depending on the calling application if at all possible.

Body:
Given the interface:

interface IObject
{
   public string Name {get;set}
}

And the following objects:

class A: IObject
{
   public string Name {get;set}
   public int ID {get;set;}
}

class B: IObject
{
   public string Name {get;set}
   public Guid ID {get;set;}
}

I have two consuming applications which are using different database schemae, but do the same job.  This is a matter of maintaining an old app while a team writes a new one.  Requirements include that both use the same library, which is why this problem exists. The apps both call the same external API, and that call is in its own static class and is accessed like so:

public static IEnumerable<IObject> List(Guid listUniqueIdentifier)
 {
       //a custom class to call the API
       using (var cmd = new WebApiCommand())
       {
                               //custom enum
             cmd.CommandType = ApiComType.GET;
             cmd.Command = "ListObjects";
             cmd.Filter = listUniqueIdentifier.ToString();
             IEnumerable<object> data = cmd.Execute();
             var result = new List<IObject>();
             foreach(var d in data)
             {
               result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
             }
             return result;
       }

}

Obviously, you can't instantiate an interface, so

result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));

breaks. I don't want to just attempt to construct the GUID-using version and if it fails, use the integer version.  Not only is that a little hacky, but it's the newer DB that is using the integer, so I'd be using a try block as flow control in just about the worse possible way.  How can I deserialize to the right object instance type (A or B) without writing different methods for each type?  Edit: The solutions I've found usually involve either serializing the $type or otherwise saving the instance type during serialization.  That is not possible, as the API is connected to a third party application and cannot store this datum.

Body:
Your issue, as far as I can tell, is that you have no way to identify, by "d" which type of class to serialize into.
(Pseudo)

foreach(var d in data)
    {
       like if(Convert.ToString(d).All(char.IsDigit) && Convert.ToString(d).length <= Int32.MaxValue)
       {
          result.add(JsonConvert.DeserializeObject<A>(Convert.ToString(d)));
       }
       else
       {
          result.add(JsonConvert.DeserializeObject<B>(Convert.ToString(d)));
       }

    }

EDIT: I think this is the best approach with the limited info you have given. If not, I would recommend, that you alter the data call itself, so the WebAPI can provide you with two different sets of data depending on the calling application if at all possible.


问:
Using endorsements in Hyperledger Composer to design a process
NB: I am seeking to understand how endorsements works in general. This will help me determine how to design applications when using Hyperledger Composer.

When I read the links here and here, I came across this statement: "Transactions have to be “endorsed” and only endorsed transactions may be committed and have an effect on the state". The statement is clear. However, let's consider the composer developer tutorial here. We have a commodity that is currently owned by an owner(Trader1) who could sell it to somebody else(Trader 2). Currently, how many endorsements are needed for the transaction to be put on the blockchain? Because, when running the application, I only submit a transaction Trade and I get results. I only deal with one function, and I get results. The following things are transparent to me as a programmer:

Creation of a transaction proposal,
When the transaction proposal is endorsed and by whom,
Whether an endorsement is performed explicitly by a human on the other end or it's programmatically done by code
That there is a proposal response from the endorser and how many they are,
When the application verifies the endorsing peer signatures
When the application creates a transaction message from the transaction proposal and response
etc.

All I do is submit one transaction and get a result.

So it becomes hard for me to assess the value of endorsement policies besides the theory in the text. And thus, the difficulty in designing a program to utilize the same. For example, consider two scenarios which we could use to handle a Trade:

We need 2 endorsements from the seller and the buyer before a transaction is commited. This would effectively be one transaction (This is what is transparent to me)

We need 2 authorizations from seller and the buyer before a transaction is commited. These authorizations could update states in the commodity such that we capture the approval from both the seller and the buyer. This could be 2 transactions i.e. sellerTradeRequest, buyerTradeApproval. The sellerTradeRequest could update commodity.sellerApproval=true while the buyerTradeApproval could update commodity.buyerApproval=true. Then, a final trade transaction that checks that the states on the commodity are OK i.e. commodity.sellerApproval=true and commodity.buyerApproval=true before commiting the transaction.

If I get a clear distinction between 1 and 2, especially how composer enables 1 above. Then maybe I will start understanding how to use endorsements.

Could anyone help?

答:
The endorsement process is described in the docs. That said, in simple terms, the process of endorsement involves an endorsing peer signing the read/write set of a transaction proposal with its certificate. This basically says: the peer identified by the signing certificate asserts that these are the read/write sets of the proposed transaction simulation.

A client that invokes a proposed transaction will need knowledge of the endorsement policy for that channel/chaincode so that it can transmit the proposed transaction to each of the endorsing peers (or to a sufficient subset of endorsing peers to satisfy the policy). When it has received the responses from each endorsing peer, it will check that the transaction is valid and then broadcast the endorsed transaction to the ordering service, which will add it to a block and broadcast to the validating peers for that channel.

Validating peers will then validate the endorsement policy of the channel/chaincode against the transactions in a block to ensure that:

all endorsements are valid (i.e. they are valid signatures from valid certificates over the expected message)

there are an appropriate number of endorsements

endorsements come from the expected source(s)

If the endorsement policy is satisfied, then the transaction is committed and the world state updated with the read/write set.

At present, Composer cannot manage the endorsement policy, but this is definitely on the development roadmap.


问:
What is the fastest animation on the iPad
What is the fastest animation on the iPad? There are multiple flipping types, what is the fastest one?</p>

答:
It's not really clear what you mean by fastest. If you want a speedier animation, you can always change the duration with ```<code>[UIView setAnimationDuration:(NSTimeInterval)duration];</code>```

If you're talking about performance, on the other hand - It's really not an issue if you're managing your network calls etc. on another thread. The UI updating always happens on the primary thread, so all you have to do is detach your network calls and heavy processing.

If the heavy processing is  too heavy for multithreading to save you, then you can always look at Core Animation. It's much lower level, and faster.

Body:
It's not really clear what you mean by fastest. If you want a speedier animation, you can always change the duration with
[UIView setAnimationDuration:(NSTimeInterval)duration];

If you're talking about performance, on the other hand - It's really not an issue if you're managing your network calls etc. on another thread. The UI updating always happens on the primary thread, so all you have to do is detach your network calls and heavy processing.

If the heavy processing is  too heavy for multithreading to save you, then you can always look at Core Animation. It's much lower level, and faster.


问:
Error when installing pandas with pip macos
I'm getting an error when I try to install pandas on mac terminal from pip

```<code>pip install pandas
</code>```

I've tried many solutions but it didn't work, I've also tried to re-install python and pip.

```<code>-->Installing collected packages: numpy, pandas
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 778, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 754, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/var/folders/1h/7ltq6rkn0h13rhmjyy5lf6cm0000gn/T/pip-a7T5X_-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'
Javis:~ Philip$
</code>```

答:
Here's an answer that I'm sure some people will disagree with... try adding a sudo so you have root privs.</p>

```<code>sudo pip install pandas
</code>```

Body:
I'm getting an error when I try to install pandas on mac terminal from pip

pip install pandas

I've tried many solutions but it didn't work, I've also tried to re-install python and pip.

-->Installing collected packages: numpy, pandas
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 778, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 754, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/var/folders/1h/7ltq6rkn0h13rhmjyy5lf6cm0000gn/T/pip-a7T5X_-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'
Javis:~ Philip$

Body:
Here's an answer that I'm sure some people will disagree with... try adding a sudo so you have root privs.

sudo pip install pandas