问:
WPF binding object to template
I have two classes defined which look like this:

```<code>public class Task {

    public string TaskName { get; set; }
    public string Description { get; set; }
    public string Priority { get; set; }
    public List<Job> listofjobs = new List<Job>();

}

public class Job
{
    public string ID { get; set; }
    public string Name { get; set; }

}
</code>```

After generating the data I have several Task objects in a List:

```<code>public static List<Task> tasklist = new List<Task>();
</code>```

Each of those tasks has several jobs in it. This list gets databound to a listbox. like this:

```<code>        Task newTask = new Task();
        Job newJob = new Job();
        Job newJob2 = new Job();

        newTask.Description = "Task 1";
        newJob.job_name = "Job 1";
        newJob.job_name = "Job 2";

        newTask.listofjobs.Add(newJob);
        newTask.listofjobs.Add(newJob2);
        tasklist.Add(newTask);
        joblist.ItemsSource = tasklist;
</code>```

The XAML looks like this:

```<code><ListBox Name="joblist" HorizontalContentAlignment="Stretch" >
      <ListBox.ItemTemplate>

                    <DataTemplate>
              <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">

                  <Expander.ContentTemplate>
                      <DataTemplate>
                          <Border>
                             <WrapPanel>
                                  <Label Content="{Binding Path=ID, RelativeSource={RelativeSource AncestorType=local:Job}}"></Label>
                             </WrapPanel>
                          </Border>
                      </DataTemplate>
                  </Expander.ContentTemplate>
              </Expander>

           </DataTemplate>

      </ListBox.ItemTemplate>
</ListBox>
</code>```

Generating the expanders by Databinding works flawlessly. Generating the the content of the expanders on the other hand just does now want to work.

I want to achieve that the jobs within the Task objects get generated by databinding to the WrapPanels within the designated expander Content.

The result should be that i have several expanders (the Task objects) with several wrappanels in the content (the Job objects of the Parent task).

Does anyone know what I am doing wrong here / how to achieve this?

EDIT:

With the anwers provided I tried:

```<code>  <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Vertical">
                                            <Label Content="{Binding Path=Name}"></Label>

                                        </StackPanel>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </Expander>
</code>```

and also:

```<code>                        <DataTemplate>
                        <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                        <StackPanel Orientation="Vertical">
                                            <Label Content="{Binding Path=Name}"></Label>

                                        </StackPanel>
                            </ListView>
                        </Expander>
                    </DataTemplate>
</code>```

But both does not seem to work. What am i missing here?

EDIT2:

There are several binding errors showing up:

```<code>System.Windows.Data Error: 40 : BindingExpression path error: 'listofjobs' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression path error: 'Name' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
</code>```

答:
I think it would be easier to Bind your VM entirely in your Listbox, like this:

```<code><ListBox Name="joblist" HorizontalContentAlignment="Stretch" ItemsSource={Binding Path=tasklist}> ... </ListBox>
</code>```

The expander could stay the same :

```<code> <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
</code>```

And for your content define do it like this:

```<code><ListView ItemsSource={Binding Path=listofjobs} >
   <StackPanel Orientation="Vertical">
      <Label Content="{Binding Path=ID}"></Label>
   </StackPanel>
 </ListView>
</code>```

Expose your tasklist as a property, and define it as the DataContext of your page/listbox and i think it should be working correctly.

Title: WPF binding object to template

Body:
I have two classes defined which look like this:

public class Task {

    public string TaskName { get; set; }
    public string Description { get; set; }
    public string Priority { get; set; }
    public List<Job> listofjobs = new List<Job>();

}

public class Job
{
    public string ID { get; set; }
    public string Name { get; set; }

}

After generating the data I have several Task objects in a List:

public static List<Task> tasklist = new List<Task>();

Each of those tasks has several jobs in it. This list gets databound to a listbox. like this:

        Task newTask = new Task();
        Job newJob = new Job();
        Job newJob2 = new Job();

        newTask.Description = "Task 1";
        newJob.job_name = "Job 1";
        newJob.job_name = "Job 2";

        newTask.listofjobs.Add(newJob);
        newTask.listofjobs.Add(newJob2);
        tasklist.Add(newTask);
        joblist.ItemsSource = tasklist;

The XAML looks like this:

<ListBox Name="joblist" HorizontalContentAlignment="Stretch" >
      <ListBox.ItemTemplate>

                    <DataTemplate>
              <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">

                  <Expander.ContentTemplate>
                      <DataTemplate>
                          <Border>
                             <WrapPanel>

                             </WrapPanel>
                          </Border>
                      </DataTemplate>
                  </Expander.ContentTemplate>
              </Expander>

           </DataTemplate>

      </ListBox.ItemTemplate>
</ListBox>

Generating the expanders by Databinding works flawlessly. Generating the the content of the expanders on the other hand just does now want to work.

I want to achieve that the jobs within the Task objects get generated by databinding to the WrapPanels within the designated expander Content.

The result should be that i have several expanders (the Task objects) with several wrappanels in the content (the Job objects of the Parent task).

Does anyone know what I am doing wrong here / how to achieve this?

EDIT:

With the anwers provided I tried:

  <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Vertical">

                                        </StackPanel>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </Expander>

and also:

                        <DataTemplate>
                        <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                        <StackPanel Orientation="Vertical">

                                        </StackPanel>
                            </ListView>
                        </Expander>
                    </DataTemplate>

But both does not seem to work. What am i missing here?

EDIT2:

There are several binding errors showing up:

System.Windows.Data Error: 40 : BindingExpression path error: 'listofjobs' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression path error: 'Name' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

Body:
I think it would be easier to Bind your VM entirely in your Listbox, like this:

<ListBox Name="joblist" HorizontalContentAlignment="Stretch" ItemsSource={Binding Path=tasklist}> ... </ListBox>

The expander could stay the same :

 <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">

And for your content define do it like this:

<ListView ItemsSource={Binding Path=listofjobs} >
   <StackPanel Orientation="Vertical">
      <Label Content="{Binding Path=ID}"></Label>
   </StackPanel>
 </ListView>

Expose your tasklist as a property, and define it as the DataContext of your page/listbox and i think it should be working correctly.


来源: stackexchange

问:
Perl IPC - FIFO and daemons & CPU Usage
I have a mail parser perl script which is called every time a mail arrives for a user (using .qmail). It extracts a calendar attachment out of the mail and places the "path" of the file in a FIFO queue implemented using the Directory::Queue module.

Another perl script which reads the path of the calendar attachment and performs certain file operations on the local system as well as on the remote CalDAV server, is being run as a daemon, as explained here. So basically this script looks like:

```<code>my $declarations

sub foo {
.
.
}

sub bar {
.
.
}

while ($keep_running) {
    for(keep-checking-the-queue-for-new-entries) {

        sub caldav_logic1 {
        .
        .
     }
        sub caldav_logic2 {
        .
        .
    }
  }
}
</code>```

I am using Proc::Daemon for running the script as a daemon. Now the problem is, this process has almost 100% CPU usage. What are the suggested ways to implement the daemon in a more standard, safer way ? I am using pretty much the same code as mentioned in the link mentioned for usage of Proc::Daemon.

答:
Maybe you don't want truly continuous polling. Is keep-checking-the-queue-for-new-entries a CPU-intensive part of the code, even when the queue is empty? That would explain why your processor is always busy.

Try putting a sleep 1 statement at the very top (or very bottom) of the while loop to let the processor rest between queue checks. If that doesn't degrade the program performance too much (i.e., if everyone can tolerate waiting an extra second before the company calendars get updated) and if the CPU usage still seems high, try sleep 2, sleep 5, etc.

ContentLicense: CC BY-SA 2.5

Title: Perl IPC - FIFO and daemons & CPU Usage

Body:
I have a mail parser perl script which is called every time a mail arrives for a user (using .qmail). It extracts a calendar attachment out of the mail and places the "path" of the file in a FIFO queue implemented using the Directory::Queue module.

Another perl script which reads the path of the calendar attachment and performs certain file operations on the local system as well as on the remote CalDAV server, is being run as a daemon, as explained here. So basically this script looks like:

my $declarations

sub foo {
.
.
}

sub bar {
.
.
}

while ($keep_running) {
    for(keep-checking-the-queue-for-new-entries) {

        sub caldav_logic1 {
        .
        .
     }
        sub caldav_logic2 {
        .
        .
    }
  }
}

I am using Proc::Daemon for running the script as a daemon. Now the problem is, this process has almost 100% CPU usage. What are the suggested ways to implement the daemon in a more standard, safer way ? I am using pretty much the same code as mentioned in the link mentioned for usage of Proc::Daemon.


问:
Carbon\Carbon not found inconsistently - Laravel 5.5
So currently I pull back a date and convert it to a readable format in carbon:

```<code></div>
<div class="">
 <label for="Name">Letter Sent:</label>
 @if (is_null($Client->letter_posted))
 @else
   {{  \carbon\carbon::createFromFormat('Y-m-d',$Client->letter_posted)->format('d/m/Y')}}
 @endif
</div>
</code>```

And it works when testing  (Testing both whilst letter_posted is null and not) however very occasionally it will spit out the error on the live server:

```<code>Class 'carbon\carbon' not found
</code>```

It has only occurred 3 times in the last 2 months very randomly and a refresh of the page will remove this error eg. the error appears, if you refresh the page it is no longer there.

Any help appreciated.

答:
Change the code to:

```<code>{{  \Carbon\Carbon::createFromFormat('Y-m-d',$Client->letter_posted)->format('d/m/Y')}}
</code>```

This happens when you deploy the system in a case sensitive server.

ContentLicense: CC BY-SA 3.0

Body:
So currently I pull back a date and convert it to a readable format in carbon:

 Letter Sent:
 @if (is_null($Client->letter_posted))
 @else
   {{  \carbon\carbon::createFromFormat('Y-m-d',$Client->letter_posted)->format('d/m/Y')}}
 @endif

And it works when testing  (Testing both whilst letter_posted is null and not) however very occasionally it will spit out the error on the live server:

Class 'carbon\carbon' not found

It has only occurred 3 times in the last 2 months very randomly and a refresh of the page will remove this error eg. the error appears, if you refresh the page it is no longer there.

Any help appreciated.

Body:
Change the code to:

{{  \Carbon\Carbon::createFromFormat('Y-m-d',$Client->letter_posted)->format('d/m/Y')}}

This happens when you deploy the system in a case sensitive server.


问:
Adding a dropdown list outside or RenderBody call
I have a .NET MVC project with Razor views and I would like to implement search functionality that consists of a dropdown list, a text box and a search button.

The problem is that I would like to implement this search snippet in my _Layout.cshtml file outside of the @RenderBody() call.  This means that the search functionality would be accessible on every page (it would be located at the very top right corner).

I'm trying to find out what is a good way of implementing this.  I can get it to work but it would involve adding same code (do get dropdown values) to all controllers and actions.

```<code>ViewBag.States = new SelectList(db.States, "Id", "Name");
</code>```

Is there a better way to implement this?  It feels very repetitive to do it this way.

答:
You can have a child action method which returns the partial view needed for your header and call this action method in your layout.

Create a view model for the properties needed.

```<code>public class AllPageVm
{
    public int SelectedItem { set; get; }
    public List<SelectListItem> Items { set; get; }
}
</code>```

Now create an action method in any of your controller. Mark this action method with ChildActionOnly decorator.

```<code>public class HomeController : Controller
{
    [ChildActionOnly]
    public ActionResult HeaderSearch()
    {
        var vm = new AllPageVm()
        {
            Items = db.States
                      .Select(a => new SelectListItem() {Value = a.Id.ToString(),
                                                         Text = a.Name})
                     .ToList()
        };
        return PartialView(vm);
    }
</code>```

Now in the HeaderSearch.cshtml partial view, you can render whatever markup you want for your search header. Here is a simple example to render the dropdown. You may update this part to include whatever markup you want (Ex : a form tag which has textbox, dropdown and the button etc)

```<code>@model AllPageVm
<div>
    <label>Select one state</label>
    @Html.DropDownListFor(a => a.SelectedItem, Model.Items, "Select")
</div>
</code>```

Now in your layout, you can call this child action method

```<code><div class="container body-content">
    @Html.Action("HeaderSearch", "Home")
    @RenderBody()
    <hr/>
    <footer>
        <p>© @DateTime.Now.Year - My ASP.NET Application</p>
    </footer>
</div>
</code>```

Make sure you are calling PartialView method from the HeaderSearch child action method instead of View method. If you call View method, it will recursively call the same method and you will get a StackOverflow exception

Body:
I have a .NET MVC project with Razor views and I would like to implement search functionality that consists of a dropdown list, a text box and a search button.

The problem is that I would like to implement this search snippet in my _Layout.cshtml file outside of the @RenderBody() call.  This means that the search functionality would be accessible on every page (it would be located at the very top right corner).

I'm trying to find out what is a good way of implementing this.  I can get it to work but it would involve adding same code (do get dropdown values) to all controllers and actions.

ViewBag.States = new SelectList(db.States, "Id", "Name");

Is there a better way to implement this?  It feels very repetitive to do it this way.

Body:
You can have a child action method which returns the partial view needed for your header and call this action method in your layout.

Create a view model for the properties needed.

public class AllPageVm
{
    public int SelectedItem { set; get; }
    public List<SelectListItem> Items { set; get; }
}

Now create an action method in any of your controller. Mark this action method with ChildActionOnly decorator.

public class HomeController : Controller
{
    [ChildActionOnly]
    public ActionResult HeaderSearch()
    {
        var vm = new AllPageVm()
        {
            Items = db.States
                      .Select(a => new SelectListItem() {Value = a.Id.ToString(),
                                                         Text = a.Name})
                     .ToList()
        };
        return PartialView(vm);
    }

Now in the HeaderSearch.cshtml partial view, you can render whatever markup you want for your search header. Here is a simple example to render the dropdown. You may update this part to include whatever markup you want (Ex : a form tag which has textbox, dropdown and the button etc)

@model AllPageVm
<div>
    <label>Select one state</label>
    @Html.DropDownListFor(a => a.SelectedItem, Model.Items, "Select")
</div>

Now in your layout, you can call this child action method

<div class="container body-content">
    @Html.Action("HeaderSearch", "Home")
    @RenderBody()
    <hr/>
    <footer>
        <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    </footer>
</div>

Make sure you are calling PartialView method from the HeaderSearch child action method instead of View method. If you call View method, it will recursively call the same method and you will get a StackOverflow exception


问:
highcharts col width and border-top
Hello I have highcharts diagram and some problem.

1) How can I set the width of my column to the width of the area of the month? (I try change "width" in CSS it's no working)

2)How to remove all borders, but the top border save? (I try change "stroke-width" in CSS it's no working)

Maybe some js config solution have for it?

I updated post using answers, it's work! Thank all.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 54.4, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

.highcharts-series rect {
    stroke-dasharray: 45, 1000;
    stroke-width: 3;
    stroke: #00ff00;
}

.highcharts-grid path {
display: none;
}</code>```

```

答:
You can set the width with pointWidth:

```<code>plotOptions: {
        series: {
            pointWidth: 40
        }
    },
</code>```

You can remove grid lines with the following:

```<code>yAxis: [{
            gridLineWidth: 0,
            minorGridLineWidth: 0
}],
</code>```

Check it out:

Highcharts.chart('container', {

   yAxis: [{
            gridLineWidth: 0,
            minorGridLineWidth: 0
}],
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

plotOptions: {
    series: {
        pointWidth: 40
    }
},

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        type: 'column'
    }]

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}</code>```

```

Title: highcharts col width and border-top

Body:
Hello I have highcharts diagram and some problem.

1) How can I set the width of my column to the width of the area of the month? (I try change "width" in CSS it's no working)

2)How to remove all borders, but the top border save? (I try change "stroke-width" in CSS it's no working)

Maybe some js config solution have for it?

I updated post using answers, it's work! Thank all.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 54.4, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

.highcharts-series rect {
    stroke-dasharray: 45, 1000;
    stroke-width: 3;
    stroke: #00ff00;
}

.highcharts-grid path {
display: none;
}

Body:
You can set the width with pointWidth:

plotOptions: {
        series: {
            pointWidth: 40
        }
    },

You can remove grid lines with the following:

yAxis: [{
            gridLineWidth: 0,
            minorGridLineWidth: 0
}],

Check it out:

Highcharts.chart('container', {

   yAxis: [{
            gridLineWidth: 0,
            minorGridLineWidth: 0
}],
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

plotOptions: {
    series: {
        pointWidth: 40
    }
},

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        type: 'column'
    }]

});

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js">
</script>

<div id="container"></div>


问:
How to find all children from another table?
I have two tables

CATEGORY

```<code>id   category     parent_id
1    Electronic
2    Furniture
3    Phone        1
4    LCD          1
5    Watch        1
6    Desk         2
</code>```

ORDER

```<code>id customer product      category_id
1  John     Smartphone   3
2  Marry    Montior      4
3  King     Wood-Desk    6
</code>```

I want to find all of electronic result by child_id.

Like this..

```<code>SELECT product FROM order WHERE category_id = (category.id = 1)
</code>```

RESULT

```<code>product
Smartphone
Monitor
</code>```

Is there any expression like this in MySQL?

答:
You can use a join for this. You also will need to encapsulate the order table name with backticks because order is reserved (alternatively you could rename that table to save yourself from encapsulating everytime).

```<code>SELECT product FROM `order` as o
join category as c
on o.category_id = c.id
WHERE c.parent_id = 1
</code>```

The on tells the DB what to data to join on. The as creates an alias so the full table name doesn't need to be written out everytime. (The as also is optional, I find it easier to read, FROM `order` o would be the same)

An alternative approach could be using a sub-query:

```<code>SELECT product
FROM `order`
WHERE category_id in (SELECT id FROM CATEGORY where parent_id = 1)
</code>```

Body:
I have two tables

CATEGORY

id   category     parent_id
1    Electronic
2    Furniture
3    Phone        1
4    LCD          1
5    Watch        1
6    Desk         2

ORDER

id customer product      category_id
1  John     Smartphone   3
2  Marry    Montior      4
3  King     Wood-Desk    6

I want to find all of electronic result by child_id.

Like this..

SELECT product FROM order WHERE category_id = (category.id = 1)

RESULT

product
Smartphone
Monitor

Is there any expression like this in MySQL?

Body:
You can use a join for this. You also will need to encapsulate the order table name with backticks because order is reserved (alternatively you could rename that table to save yourself from encapsulating everytime).

SELECT product FROM `order` as o
join category as c
on o.category_id = c.id
WHERE c.parent_id = 1

The on tells the DB what to data to join on. The as creates an alias so the full table name doesn't need to be written out everytime. (The as also is optional, I find it easier to read, FROM `order` o would be the same)

An alternative approach could be using a sub-query:

SELECT product
FROM `order`
WHERE category_id in (SELECT id FROM CATEGORY where parent_id = 1)


问:
How to sort an array in BigQuery standard SQL?
I am wondering if it is possible to order (apply order by) for individual array values in Google BigQuery?

I am able to achieve this by applying order by on the whole transactonal base table first, then aggregating array; but when table is too large, resource errors appear for ordering by a large table..

So i am wondering if each individual array value can be ordered by using SQL or UDF.

This was asked once Order of data in bigquery repeated records but it was 4,5 years ago.

答:
Sure, you can use the ARRAY function. It supports an optional ORDER BY clause. You haven't provided sample data, but supposing that you have a top level array column named arr, you can do something like this:

```<code>SELECT
  col1,
  col2,
  ARRAY(SELECT x FROM UNNEST(arr) AS x ORDER BY x) AS arr
FROM MyTable;
</code>```

This sorts the elements of arr by their values.

If you actually have an array of a struct type, such as ARRAY<STRUCTINT64, b STRING>>, you can sort by one of the struct fields:

```<code>SELECT
  col1,
  col2,
  ARRAY(SELECT x FROM UNNEST(arr) AS x ORDER BY a) AS arr
FROM MyTable;
</code>```

Body:
Sure, you can use the ARRAY function. It supports an optional ORDER BY clause. You haven't provided sample data, but supposing that you have a top level array column named arr, you can do something like this:

SELECT
  col1,
  col2,
  ARRAY(SELECT x FROM UNNEST(arr) AS x ORDER BY x) AS arr
FROM MyTable;

This sorts the elements of arr by their values.

If you actually have an array of a struct type, such as ARRAY<STRUCT<a INT64, b STRING>>, you can sort by one of the struct fields:

SELECT
  col1,
  col2,
  ARRAY(SELECT x FROM UNNEST(arr) AS x ORDER BY a) AS arr
FROM MyTable;

ContentLicense: CC BY-SA 4.0


问:
plsql cannot use variables in sql select
I am getting very fed up of APEX in recent days, i am trying to run a interactive report within application express and cannot seem to use variables i declare within my sql queries. Below is the error, i also included the code that works. the get_longlat() function is tested and works it returns a SDO_GEOMETRY data type.

ORA-06550: line 7, column 12: PLS-00306: wrong number or types of
  arguments in call to '||' ORA-06550: line 7, column 1: PL/SQL:
  Statement ignored

```<code>DECLARE
l_query VARCHAR2(4096);
l_location SDO_GEOMETRY := get_longlat(v('P2_POSTCODE'));
BEGIN

l_query := '
                SELECT
                "VENUE_ID",
                "VENUE_NAME",
                "CITY",
                "VENUE_NO",
                "POSTCODE",
                dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                "DESCRIPTION",
                SDO_GEOM.SDO_DISTANCE(G_LOCATION, '  || l_location || ',0.005,''unit=mile'') "G_LOCATION"
                FROM   "GAMEVENUE"
                WHERE (SDO_WITHIN_DISTANCE(G_LOCATION,' || l_location || ',''distance=250 unit=mile'') = ''TRUE'');';

RETURN l_query;
</code>```

This works

```<code>l_query := '
                SELECT
                "VENUE_ID",
                "VENUE_NAME",
                "CITY",
                "VENUE_NO",
                "POSTCODE",
                dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                "DESCRIPTION",
                SDO_GEOM.SDO_DISTANCE(G_LOCATION, MDSYS.SDO_GEOMETRY(2001,4326,SDO_POINT_TYPE(-4.1530439,50.371089,NULL),NULL,NULL),0.005,''unit=mile'') "G_LOCATION"
                FROM   "GAMEVENUE"
                WHERE (SDO_WITHIN_DISTANCE(G_LOCATION,SDO_GEOMETRY(2001,4326,SDO_POINT_TYPE(-4.1530439,50.371089,null),null,null),''distance=250 unit=mile'') = ''TRUE'')';
</code>```

答:
Because SDO_GEOMETRY is not of type char or number( implicitly considerable as char ), you can't use it in direct concetenation.
Try this instead :

```<code>l_query := '
                SELECT
                "VENUE_ID",
                "VENUE_NAME",
                "CITY",
                "VENUE_NO",
                "POSTCODE",
                dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                "DESCRIPTION",
                SDO_GEOM.SDO_DISTANCE(G_LOCATION, MDSYS.SDO_GEOMETRY('||l_sdo_gtype||','||l_sdo_srid||',MDSYS.SDO_POINT_TYPE('||l_longitude||','||l_latitude||',NULL),NULL,NULL),0.005,''unit=mile'') "G_LOCATION"
                FROM   "GAMEVENUE"
                WHERE (SDO_WITHIN_DISTANCE(G_LOCATION,SDO_GEOMETRY('||l_sdo_gtype||','||l_sdo_srid||',SDO_POINT_TYPE('||l_longitude||','||l_latitude||',null),null,null),''distance=250 unit=mile'') = ''TRUE'')';
</code>```

where l_sdo_gtype,l_sdo_srid, l_longitude, l_latitude are of type number;

Body:
I am getting very fed up of APEX in recent days, i am trying to run a interactive report within application express and cannot seem to use variables i declare within my sql queries. Below is the error, i also included the code that works. the get_longlat() function is tested and works it returns a SDO_GEOMETRY data type.

ORA-06550: line 7, column 12: PLS-00306: wrong number or types of
  arguments in call to '||' ORA-06550: line 7, column 1: PL/SQL:
  Statement ignored

DECLARE
l_query VARCHAR2(4096);
l_location SDO_GEOMETRY := get_longlat(v('P2_POSTCODE'));
BEGIN

l_query := '
                SELECT
                "VENUE_ID",
                "VENUE_NAME",
                "CITY",
                "VENUE_NO",
                "POSTCODE",
                dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                "DESCRIPTION",
                SDO_GEOM.SDO_DISTANCE(G_LOCATION, '  || l_location || ',0.005,''unit=mile'') "G_LOCATION"
                FROM   "GAMEVENUE"
                WHERE (SDO_WITHIN_DISTANCE(G_LOCATION,' || l_location || ',''distance=250 unit=mile'') = ''TRUE'');';

RETURN l_query;

This works

l_query := '
                SELECT
                "VENUE_ID",
                "VENUE_NAME",
                "CITY",
                "VENUE_NO",
                "POSTCODE",
                dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                "DESCRIPTION",
                SDO_GEOM.SDO_DISTANCE(G_LOCATION, MDSYS.SDO_GEOMETRY(2001,4326,SDO_POINT_TYPE(-4.1530439,50.371089,NULL),NULL,NULL),0.005,''unit=mile'') "G_LOCATION"
                FROM   "GAMEVENUE"
                WHERE (SDO_WITHIN_DISTANCE(G_LOCATION,SDO_GEOMETRY(2001,4326,SDO_POINT_TYPE(-4.1530439,50.371089,null),null,null),''distance=250 unit=mile'') = ''TRUE'')';

Body:
Because SDO_GEOMETRY is not of type char or number( implicitly considerable as char ), you can't use it in direct concetenation.
Try this instead :

l_query := '
                SELECT
                "VENUE_ID",
                "VENUE_NAME",
                "CITY",
                "VENUE_NO",
                "POSTCODE",
                dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                "DESCRIPTION",
                SDO_GEOM.SDO_DISTANCE(G_LOCATION, MDSYS.SDO_GEOMETRY('||l_sdo_gtype||','||l_sdo_srid||',MDSYS.SDO_POINT_TYPE('||l_longitude||','||l_latitude||',NULL),NULL,NULL),0.005,''unit=mile'') "G_LOCATION"
                FROM   "GAMEVENUE"
                WHERE (SDO_WITHIN_DISTANCE(G_LOCATION,SDO_GEOMETRY('||l_sdo_gtype||','||l_sdo_srid||',SDO_POINT_TYPE('||l_longitude||','||l_latitude||',null),null,null),''distance=250 unit=mile'') = ''TRUE'')';

where l_sdo_gtype,l_sdo_srid, l_longitude, l_latitude are of type number;


问:
Giving error on first load
Having problem on first load but when i refresh the page it seems okay. Is it problem with firebase database plugin loading?
How to get rid of this issue?

答:
I think your definition of pays in wrong, try </p>

```<code>pays : any[] = [];
</code>```

Title: Giving error on first load

Body:
I think your definition of pays in wrong, try

pays : any[] = [];


问:
Easiest way to share development secrets in aspnetcore application
I want to store a development-time secret somewhere outside of my code repository, that developers are able to use without any manual tasks. (As close to Build, Run, and it will just work).

The secrets have to be configured in the aspnetcore Configuration Builder like this:

```<code>var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json";
builder.AddDevelopmentSecrets(...);
</code>```

The official recommendation by the aspnetcore team seems to be to use the Secret Manager Tool. But this requires every developer to configure the secrets manually. For example, they'd have to run dotnet user-secrets set key value for every secret.

The 2nd thing I looked at was Azure KeyVault. This seemed ideal, because I'd only have to call builder.AddAzureKeyVault(...). The only problem is that I'd have to store the clientId and clientSecret to access the keyvault somewhere.

Ideally I want something that the AWS Toolkit for Visual Studio extension does. Once the extension is installed, you simply login with your AWS credentials and the extension simply injects your credentials into every official AWS call that is used.

Does Azure have anything like this? Something that allows me to inject (or access) my Azure credentials, so they can be used in the call to AddAzureKeyVault(...)? And if not, what's the closest solution that comes close to this?

答:
Azure AD Managed Service Identity can help here. The implementation based on my suggestion:

```<code>var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
    new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault("https://x.vault.azure.net/", keyVaultClient, new DefaultKeyVaultSecretManager());
</code>```

Now you can sign in to the Azure CLI 2.0 and those credentials will be automatically used to access KeyVault.

You can read more about MSI here: https://joonasw.net/view/azure-ad-managed-service-identity

Body:
I want to store a development-time secret somewhere outside of my code repository, that developers are able to use without any manual tasks. (As close to Build, Run, and it will just work).

The secrets have to be configured in the aspnetcore Configuration Builder like this:

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json";
builder.AddDevelopmentSecrets(...);

The official recommendation by the aspnetcore team seems to be to use the Secret Manager Tool. But this requires every developer to configure the secrets manually. For example, they'd have to run dotnet user-secrets set key value for every secret.

The 2nd thing I looked at was Azure KeyVault. This seemed ideal, because I'd only have to call builder.AddAzureKeyVault(...). The only problem is that I'd have to store the clientId and clientSecret to access the keyvault somewhere.

Ideally I want something that the AWS Toolkit for Visual Studio extension does. Once the extension is installed, you simply login with your AWS credentials and the extension simply injects your credentials into every official AWS call that is used.

Does Azure have anything like this? Something that allows me to inject (or access) my Azure credentials, so they can be used in the call to AddAzureKeyVault(...)? And if not, what's the closest solution that comes close to this?

Body:
Azure AD Managed Service Identity can help here. The implementation based on my suggestion:

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
    new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault("https://x.vault.azure.net/", keyVaultClient, new DefaultKeyVaultSecretManager());

Now you can sign in to the Azure CLI 2.0 and those credentials will be automatically used to access KeyVault.

You can read more about MSI here: https://joonasw.net/view/azure-ad-managed-service-identity


问:
Unity fog glitch on Android
I'm following a tutorial by Brackeys, and i did everything correctly, and on the Editor, everything works like charm,

But when i build it for android, some weird bug/glitch pops up.

The bug in phone build, is that the scaled Cube i'm using as plane ( tried plane, same problem ) gradually changes color, and becomes same as the color of Camera background.
I'll add pictures of Camera and Lighting settings.

I'm using fog mode : Exponential Squared, and it works best to show what i want, on phone this mode bugs.

i tried other mode : Exponential and Linear, the bug didn't show, but so didn't the desired effect.

Here are two videos of comparaison :

Editor :
https://youtu.be/gRIcu2Ubqd4

Phone :
https://youtu.be/UW8v49SGjOs

答:
I got the same problem and I solved it changing the fog mode.

Go to Window > Lighting > Settings and at the bottom change the Fog Mode to Exponential:

This is a weird bug that doesn't happens on editor or PC build but happens in android builds... I also figured out that the size of the ground is related to the issue, if you change to a smaller z scale (instead of 10.000 change to 1000) the bug will not occurs.

I hope it works for you!

Title: Unity fog glitch on Android


问:
getting vector-tags pair after training in words2vec
I am trying to convert a bunch of poems into vectors, and then use my own implementation of k-means on them, but I can't figure out how to get the vectors with tags attached after training in doc2vec. I also find that when I train on 11 files I get 14 back out (I would like the same number of vectors in as out obviously).

My code takes in a path to a folder with a few text files in it. Right now I am just printing the vectors given by learner.docvecs, and have no idea which vector is which.

Code:

```<code>import os
import gensim

def parse_doc2vec(direc):

    # gets list of file names
    files = os.listdir(direc)

    translator = str.maketrans("", "", string.punctuation)

    tovecpoems=[]

    count = 0
    for filename in files:

        file = open(direc + "/" + filename)
        list = file.read().split(sep= "\n")
        subject = list[0].split(" ",1)[0]

        poem = list[3:]
        poem = ''.join(poem)
        poem = poem.split()
        for i in range (len(poem)):
            poem[i] = poem[i].replace('\t','').replace('\n','')
            poem[i] = poem[i].translate(translator)
            if poem[i] == '':
                poem.remove(poem[i])

        tovecpoem = gensim.models.doc2vec.LabeledSentence(words = poem, tags = [filename,subject])
        tovecpoems.append(tovecpoem)
        count += 1

    learner = gensim.models.doc2vec.Doc2Vec(tovecpoems,alpha=0.025, min_alpha=0.025)

    for epoch in range(10):
        learner.train(tovecpoems,total_examples = learner.corpus_count, epochs = learner.iter)
        learner.alpha -= 0.002
        learner.min_alpha = learner.alpha

    vectors = learner.docvecs

    for vec in vectors:
        print(vec,'\n')
</code>```

If someone could please tell me how to retrieve vectors with filename attached from tags, and why vectors has more objects in it then tovecpoemsdoes, I would be grateful.

答:
You should show what your code is printing, to let answerers know what's not appearing correct from what you see.

You're supplying Doc2Vec with 10 text examples, but every text example you're providing has 2 tags: tags=[filename, subject]. So the 4 extra tags, that aren't filenames, are probably unique values of subject that repeat.

Separately, it's a bad idea to try to manage alpha/min_alpha yourself, or call train() multiple times in your own loop. Just leave those values as their defaults, use Doc2Vec's iter parameter to specify how many training passes you want.

And by providing tovecpoems as an argument to Doc2Vec, you've already triggered training - there's no need to call train() at all. (If you'd not supplied the corpus already, it would make sense to call build_vocab() and train() exactly once each, but no more.)

So for example your code would make more sense as just:

```<code>learner = gensim.models.doc2vec.Doc2Vec(tovecpoems, iter=10)
vectors = learner.docvecs
# ...etc
</code>```

Note that you won't get a good Doc2Vec/Word2Vec results from tiny toy-sized datasets. They generally need many thousands of examples (containing hundred-of-thousands to millions of words) to obtain the sort of vector-qualities people usually want from them. (You can sometimes squeeze a little demo-able value out of a small dataset by (1) shrinking the model vector size radically; and (2) increasing the number of iter training-passes, but that's hit-or-miss.)

Body:
I am trying to convert a bunch of poems into vectors, and then use my own implementation of k-means on them, but I can't figure out how to get the vectors with tags attached after training in doc2vec. I also find that when I train on 11 files I get 14 back out (I would like the same number of vectors in as out obviously).

My code takes in a path to a folder with a few text files in it. Right now I am just printing the vectors given by learner.docvecs, and have no idea which vector is which.

Code:

import os
import gensim

def parse_doc2vec(direc):

    # gets list of file names
    files = os.listdir(direc)

    translator = str.maketrans("", "", string.punctuation)

    tovecpoems=[]

    count = 0
    for filename in files:

        file = open(direc + "/" + filename)
        list = file.read().split(sep= "\n")
        subject = list[0].split(" ",1)[0]

        poem = list[3:]
        poem = ''.join(poem)
        poem = poem.split()
        for i in range (len(poem)):
            poem[i] = poem[i].replace('\t','').replace('\n','')
            poem[i] = poem[i].translate(translator)
            if poem[i] == '':
                poem.remove(poem[i])

        tovecpoem = gensim.models.doc2vec.LabeledSentence(words = poem, tags = [filename,subject])
        tovecpoems.append(tovecpoem)
        count += 1

    learner = gensim.models.doc2vec.Doc2Vec(tovecpoems,alpha=0.025, min_alpha=0.025)

    for epoch in range(10):
        learner.train(tovecpoems,total_examples = learner.corpus_count, epochs = learner.iter)
        learner.alpha -= 0.002
        learner.min_alpha = learner.alpha

    vectors = learner.docvecs

    for vec in vectors:
        print(vec,'\n')

If someone could please tell me how to retrieve vectors with filename attached from tags, and why vectors has more objects in it then tovecpoemsdoes, I would be grateful.

Body:
You should show what your code is printing, to let answerers know what's not appearing correct from what you see.

You're supplying Doc2Vec with 10 text examples, but every text example you're providing has 2 tags: tags=[filename, subject]. So the 4 extra tags, that aren't filenames, are probably unique values of subject that repeat.

Separately, it's a bad idea to try to manage alpha/min_alpha yourself, or call train() multiple times in your own loop. Just leave those values as their defaults, use Doc2Vec's iter parameter to specify how many training passes you want.

And by providing tovecpoems as an argument to Doc2Vec, you've already triggered training - there's no need to call train() at all. (If you'd not supplied the corpus already, it would make sense to call build_vocab() and train() exactly once each, but no more.)

So for example your code would make more sense as just:

learner = gensim.models.doc2vec.Doc2Vec(tovecpoems, iter=10)
vectors = learner.docvecs
# ...etc

Note that you won't get a good Doc2Vec/Word2Vec results from tiny toy-sized datasets. They generally need many thousands of examples (containing hundred-of-thousands to millions of words) to obtain the sort of vector-qualities people usually want from them. (You can sometimes squeeze a little demo-able value out of a small dataset by (1) shrinking the model vector size radically; and (2) increasing the number of iter training-passes, but that's hit-or-miss.)


问:
EF from Task: System.InvalidOperationException: Reader closed
I'm using a Task to send an Email in the background.
Despite the fact that the PDF (included in the mail as attachment) is generated (GeneratePdf()). I get following exception:

Below is the code that calls GetRegistrationOfChild:

EDIT
Below is the code where the dbContext is loaded (Startup.cs, method ConfigureServices). Afterwards its resolved with DI in the constructor.

services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

答:
There's a lot of problems here, actually. Your core problem is likely inside the SendRegisterConfirmationAsync method. However, you haven't provided the code for that method. If I had to guess, you're using using statements in a not thread-safe way, based on the error message.

However, it's also entirely possible this is just due to handling async improperly. You're calling an async method from a sync method. Since SendEmail returns void, you're either swallowing the return value of the async method or the async method is async void (which you should pretty much never do). In either case, since you're not awaiting the result of the async method, the rest of your code is moving on potentially taking dependencies with it. For example, things like your DbContext are request-scoped, so if that async method utilizes your DbContext, but doesn't finish before the response is sent, the context will be disposed right from under it, causing exceptions. If you use async, you need to go async all the way.

Further, there's really no such thing as a true "background" task in a web application context. Task.Run merely pulls another thread from the same pool your requests are being handled from. You may allow one thread to return, but you're still sitting on another, so the best case scenario is that you've bought yourself nothing. The worst case scenario is that you've now effectively halved your server's throughput and killed your ability to scale.

If you want to do something in the background, offload it to a background process, i.e. outside the context of your web application. You can use something like Hangfire or Revalee.


问:
IntelliJ + Groovy + Spock: no Groovy library is defined for module
I have been trying to create a Groovy project with Spock testing in IntelliJ IDEA.

Here are steps that I followed:

Created Groovy project and added Maven support.

Added Spock dependencies and plugin. I am using POM very similar to this one:
https://github.com/mariuszs/java-spock-test-sample/blob/master/pom.xml

Due to conflicting Groovy dependency I removed Groovy 2.2 library from the Module Settings->Libraries. This allowed me to run tests.

I created a Groovy class in "src/main".. but I get the error when I try to run it:

Groovyc: Cannot compile Groovy files: no Groovy library is defined for module...

I am probably missing something because I am tired of trying different configurations for half of the day.

答: For me the solution was to open a .groovy file in the specific folder/module and then idea gave a little popup showing the the Groovy SDK is not configured. Then I clicked on configure -> OK and voila.</p>


问:
The date format in the CSV file reverts back to dd/mm/yyyy from set dd/mm/yy
I'm using the following code (which is being executed on a .CSV file):

```<code>....code

ws1.Range("E2:E300000").NumberFormat = "dd/mm/yy"

....code
</code>```

The problem is that even though the date format is defined (by the code above) as "dd/mm/yy", after saving and reopening the file date format reverts back to "dd/mm/yyyy". It seems it only happens with .CSV files (I've tried with xlsm and the format remained as "dd/mm/yy").

Any ideas how to preserve defined "dd/mm/yy" format?

答: As @Scott_Craner mentioned CSV does not retain the format. It seems that the only sensible way to end this question is for me to post this statement. Thanks</p>

Body:
I'm using the following code (which is being executed on a .CSV file):

....code

ws1.Range("E2:E300000").NumberFormat = "dd/mm/yy"

....code

The problem is that even though the date format is defined (by the code above) as "dd/mm/yy", after saving and reopening the file date format reverts back to "dd/mm/yyyy". It seems it only happens with .CSV files (I've tried with xlsm and the format remained as "dd/mm/yy").

Any ideas how to preserve defined "dd/mm/yy" format?


问:
Authorization failure when creating new business network in local playground
I am trying follow the steps of Composer Playground tutorial for local version of the playground and using local fabric peer.

I have done prescribed sequence of steps: downloadFabric.sh, startFabric.sh, createPeerAdminCard.sh. Once I bring up the playground, I can see network card PeerAdmin@hlfv1 showing no business network attached to it.

Then I click on Deploy a New Business Network, and select "vehicles-lifecycle-network" example. The dialog looks similar to the one in tutorial, but it has additional fields asking for credentials for network administrator, and I am not sure what to put there.

I tried copying in key and certificate that were generated by createPeerAdminCard script, and I also tried using ID and Secret option putting in PeerAdmin or PeerAdmin@hlfv1. I found this answer which indicates that it does not matter what secret you specify as the user is already imported into the keystore -- not sure if it is relevant. It certainly did not make any difference.

When I click deploy, the new network seems to appear in the composer dashboard. However, if I click on "Connect Now", a popup shows "Error trying to login and get user context" and [[{"code":400,"message":"Authorization Failure"}]].

It seems I am missing something very basic, but cannot really figure it out on my own.

Edit:

Simple steps to reproduce (assuming basic-sample-network.bna is available locally):

```<code>> composer runtime install -c PeerAdmin@hlfv1 -n basic-sample-network
> composer network start -a <path to basic-sample-network.bna> -A admin -c PeerAdmin@hlfv1 -C <path to PeerAdmin certificate> -f admin.card
> composer card import -f admin.card
> composer network ping -c admin@basic-sample-network
</code>```

Last command produces the same error as above in the console.

Edit 2:

If I open up ~/.composer/cards/PeerAdmin@hlfv1/metadata.json and add "businessNetwork":"basic-sample-network" parameter, I am able to do composer network ping -c PeerAdmin@hlfv1 successfully, and also can connect to the network from the Playground -- this will do as a workaround for now. However, I must be doing something wrong with the way I create new network and its admin card.

答:
The Playground Tutorial assumes that you are connecting to an Online Hosted Playground hosted on IBM Cloud (Bluemix).  For the Online Playground the underlying Fabric is 'Web' - i.e. the Fabric is stored only in the local browser.  This document may help explain the different Fabric Runtimes: Typical Solution Architecture

The Local Playground gives you the additional option of deploying a Business Network to an hlfv1 Fabric, using the PeerAdmin card that you created with the createPeerAdmin.sh script.

After creating the PeerAdmin card you should be able to start Playground locally with the composer-playground command and you should be able to deploy a Business Network.  In this development scenario the Credentials for the Network Administrator should be Id and Secret specifying admin / adminpw. There is no need to run CLI commands prior to starting local playground. (createPeerAdminCard.sh is not a CLI command but is a Dev environment setup script - and it should be run.)

If you want to go down the CLI route please see the Developer Tutorial

Body:
I am trying follow the steps of Composer Playground tutorial for local version of the playground and using local fabric peer.

I have done prescribed sequence of steps: downloadFabric.sh, startFabric.sh, createPeerAdminCard.sh. Once I bring up the playground, I can see network card PeerAdmin@hlfv1 showing no business network attached to it.

Then I click on Deploy a New Business Network, and select "vehicles-lifecycle-network" example. The dialog looks similar to the one in tutorial, but it has additional fields asking for credentials for network administrator, and I am not sure what to put there.

I tried copying in key and certificate that were generated by createPeerAdminCard script, and I also tried using ID and Secret option putting in PeerAdmin or PeerAdmin@hlfv1. I found this answer which indicates that it does not matter what secret you specify as the user is already imported into the keystore -- not sure if it is relevant. It certainly did not make any difference.

When I click deploy, the new network seems to appear in the composer dashboard. However, if I click on "Connect Now", a popup shows "Error trying to login and get user context" and [[{"code":400,"message":"Authorization Failure"}]].

It seems I am missing something very basic, but cannot really figure it out on my own.

Edit:

Simple steps to reproduce (assuming basic-sample-network.bna is available locally):

> composer runtime install -c PeerAdmin@hlfv1 -n basic-sample-network
> composer network start -a <path to basic-sample-network.bna> -A admin -c PeerAdmin@hlfv1 -C <path to PeerAdmin certificate> -f admin.card
> composer card import -f admin.card
> composer network ping -c admin@basic-sample-network

Last command produces the same error as above in the console.

Edit 2:

If I open up ~/.composer/cards/PeerAdmin@hlfv1/metadata.json and add "businessNetwork":"basic-sample-network" parameter, I am able to do composer network ping -c PeerAdmin@hlfv1 successfully, and also can connect to the network from the Playground -- this will do as a workaround for now. However, I must be doing something wrong with the way I create new network and its admin card.


问:
Why do you skip void function calls without catching them?

I want to call a function that calculates the width of a circle.

```<code>#include <stdio.h>
void area(double*);
int main()
{
    void* vp = NULL;
    double r;
    printf("input value : ");
    scanf(" %lf", &r);
    (double*)vp = &r;
    void area(vp);
}
void area(double* dp)
{
    double result;
    result = (*dp) * (*dp) * (3.14);
    printf("circle are is : %.2lf", result);
    return 1;
}*
</code>```

I want to call a function in the //void area (vp)//, but I can not catch the error in visual stdio and proceed as it is. Do you know what the cause is?

答:
You should write

```<code>  area(&r);
</code>```

instead of the wrong and superfluous

```<code> void area(vp);
</code>```

Adding to the obvious mistake you made in the syntax

I don't see any reason for vp to be there.

to ensure success for scanf(), always check for the return value of the call.

Quoting C11, chapter §6.8.6.4,

A return statement with an expression shall not appear in a function whose return type
  is void.  [....]

Body:
I want to call a function that calculates the width of a circle.

#include <stdio.h>
void area(double*);
int main()
{
    void* vp = NULL;
    double r;
    printf("input value : ");
    scanf(" %lf", &r);
    (double*)vp = &r;
    void area(vp);
}
void area(double* dp)
{
    double result;
    result = (*dp) * (*dp) * (3.14);
    printf("circle are is : %.2lf", result);
    return 1;
}*

I want to call a function in the //void area (vp)//, but I can not catch the error in visual stdio and proceed as it is. Do you know what the cause is?

Body:
You should write

  area(&r);

instead of the wrong and superfluous

 void area(vp);

Adding to the obvious mistake you made in the syntax

I don't see any reason for vp to be there.

to ensure success for scanf(), always check for the return value of the call.

Quoting C11, chapter §6.8.6.4,

A return statement with an expression shall not appear in a function whose return type
  is void.  [....]


问:
Integrating Stack Blur C++ Port to iPhone SDK
Can anybody give me a pointer as to how to integrate the Stack Blur C++ library to Objective C?

http://antigrain.com/index.html

It's probably straightforward. I used to be a C programmer long, long time ago and now I'm comfortable enough with Objective C but I completely bypassed C++ so it gives me a headache just looking at the code.

Any help would be greatly appreciated.

答: You'll want to look at the docs regarding "Objective-C++". Basically, you can semi-freely intermix Obj-C and C++ with a few restrictions. The main one is that Obj-C classes can't inherit from C++ or vice versa. You can have C++ members in an obj-c class, and vice versa, because it's just pointers.</p>


问:
Find out whether a table has some unique columns
I use SQL Server.

I've been handed some large tables with no constrains on them, no keys no nothing.

I know some of the columns have unique values. Is there a smart way for a given table to find the cols that have unique values?

Right now I do it manually for each column by counting if there is as many DISTINCT values as there are rows in the table.

```<code>SELECT COUNT(DISTINCT col) FROM table
</code>```

Could probably make a cursor to loop over all the columns but want to hear if someone knows a smarter or built-in function.

答:
What about simple one line of code:

```<code>CREATE UNIQUE INDEX index_name ON table_name (column_name);
</code>```

If the index is created then your column_name has only unique values. If there are dupes in your column_name, you will get an error message.

Body:
I use SQL Server.

I've been handed some large tables with no constrains on them, no keys no nothing.

I know some of the columns have unique values. Is there a smart way for a given table to find the cols that have unique values?

Right now I do it manually for each column by counting if there is as many DISTINCT values as there are rows in the table.

SELECT COUNT(DISTINCT col) FROM table

Could probably make a cursor to loop over all the columns but want to hear if someone knows a smarter or built-in function.

Body:
What about simple one line of code:

CREATE UNIQUE INDEX index_name ON table_name (column_name);

If the index is created then your column_name has only unique values. If there are dupes in your column_name, you will get an error message.


问:
Java- How to remove background color from an image
First off I am new to this and also coding.  I apologize in advance for anything that is misleading.

I am currently writing a Java program that uses an image as input.  What I have currently is scanning each pixel by the width and height of the image saving the HSB in an array and then outputting the percentage of each color in the image.  I now want to omit the background from that calculation.  To start off lets just say the background is white.  There are also pixels in the image that are not in the background that is white though.

thank you,

答:
Here is an example of full working code.

You can add a cursor to pick color and jslider for fuzz or threshold. Use backColor and threshold for your needs.

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Convert {
    private static final Color backColor = new Color(255,255,255);
    private static final int THRESHOLD = 35;
    private static final int TRANSPARENT = 0;  // 0x00000000;

    static File base  = new File("f://mortar1.png");
    static File base2 = new File("f://outtrans.png");

    public static void main(String[] args) throws IOException {
        System.out.println("Convert.main()");
        for (File file : base.listFiles())
        {
            BufferedImage initImage = ImageIO.read(base);
            int width = initImage.getWidth(null),
              height = initImage.getHeight(null);

            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics g = image.getGraphics();
            g.drawImage(initImage, 0, 0, null);

            System.out.println("before: " + image.getRGB(0, 0));
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int pixel = image.getRGB(x, y);
                    Color color = new Color(pixel);

                    int dr = Math.abs(color.getRed()   - backColor.getRed()),
                    dg = Math.abs(color.getGreen() - backColor.getGreen()),
                    db = Math.abs(color.getBlue()  - backColor.getBlue());

                    if (dr < THRESHOLD && dg < THRESHOLD && db < THRESHOLD) {
                        image.setRGB(x, y, TRANSPARENT);
                    }
                }
            }
            System.out.println("   after: " + image.getRGB(0, 0));

           File file = new File("f://outtrans1.png");
            ImageIO.write(image, "png", file);
        }
    }
}
</code>```

Body:
Here is an example of full working code.

You can add a cursor to pick color and jslider for fuzz or threshold. Use backColor and threshold for your needs.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Convert {
    private static final Color backColor = new Color(255,255,255);
    private static final int THRESHOLD = 35;
    private static final int TRANSPARENT = 0;  // 0x00000000;

    static File base  = new File("f://mortar1.png");
    static File base2 = new File("f://outtrans.png");

    public static void main(String[] args) throws IOException {
        System.out.println("Convert.main()");
        for (File file : base.listFiles())
        {
            BufferedImage initImage = ImageIO.read(base);
            int width = initImage.getWidth(null),
              height = initImage.getHeight(null);

            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics g = image.getGraphics();
            g.drawImage(initImage, 0, 0, null);

            System.out.println("before: " + image.getRGB(0, 0));
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int pixel = image.getRGB(x, y);
                    Color color = new Color(pixel);

                    int dr = Math.abs(color.getRed()   - backColor.getRed()),
                    dg = Math.abs(color.getGreen() - backColor.getGreen()),
                    db = Math.abs(color.getBlue()  - backColor.getBlue());

                    if (dr < THRESHOLD && dg < THRESHOLD && db < THRESHOLD) {
                        image.setRGB(x, y, TRANSPARENT);
                    }
                }
            }
            System.out.println("   after: " + image.getRGB(0, 0));

           File file = new File("f://outtrans1.png");
            ImageIO.write(image, "png", file);
        }
    }
}


问:
How to Loop Range number in Excel VBA without changing letter
How do I get this to work?
I have this code written so far:

```<code>Sub RemoveLoop()

Dim i As Long

For i = 6 To 15
If Range("B" + i) = "YES" Then
    Range("C" + i + ":" + "P" + i).ClearContents
End If

Next i
End Sub
</code>```

Instead of doing each individually like this:
This is what I'm trying to shorten/accomplish, below:

```<code>Sub Remove()

If Range("B6") = "YES" Then
    Range("C6:P6").ClearContents
End If
If Range("B7") = "YES" Then
    Range("C7:P7").ClearContents
End If
If Range("B8") = "YES" Then
    Range("C8:P8").ClearContents
End If
If Range("B9") = "YES" Then
    Range("C9:P9").ClearContents
End If
If Range("B10") = "YES" Then
    Range("C10:P10").ClearContents
End If
If Range("B11") = "YES" Then
    Range("C11:P11").ClearContents
End If
If Range("B12") = "YES" Then
    Range("C12:P12").ClearContents
End If
If Range("B13") = "YES" Then
    Range("C13:P13").ClearContents
End If
If Range("B14") = "YES" Then
    Range("C14:P14").ClearContents
End If
If Range("B15") = "YES" Then
    Range("C15:P15").ClearContents
End If
End Sub
</code>```

Simple question for you guys, thank you for your help.
I don't know what else to say, it's pretty straight forwards I believe. But I'm still getting the, "Looks like your most is mostly code error."
This should be an easy one for you VBA experts to solve.

Thanks again.

答:
Try this:

```<code>Sub RemoveLoop()

Dim i As Long
Set WSheet = Worksheets("Sheet1") ' This enables the change in the mentioned sheet and not the Active sheet.
For i = 6 To 15
    If WSheet.Range("B" & i) = "YES" Then
        WSheet.Range("C" & i & ":P" & i).ClearContents
    End If
Next i

End Sub
</code>```

Body:
How do I get this to work?
I have this code written so far:

Sub RemoveLoop()

Dim i As Long

For i = 6 To 15
If Range("B" + i) = "YES" Then
    Range("C" + i + ":" + "P" + i).ClearContents
End If

Next i
End Sub

Instead of doing each individually like this:
This is what I'm trying to shorten/accomplish, below:

Sub Remove()

If Range("B6") = "YES" Then
    Range("C6:P6").ClearContents
End If
If Range("B7") = "YES" Then
    Range("C7:P7").ClearContents
End If
If Range("B8") = "YES" Then
    Range("C8:P8").ClearContents
End If
If Range("B9") = "YES" Then
    Range("C9:P9").ClearContents
End If
If Range("B10") = "YES" Then
    Range("C10:P10").ClearContents
End If
If Range("B11") = "YES" Then
    Range("C11:P11").ClearContents
End If
If Range("B12") = "YES" Then
    Range("C12:P12").ClearContents
End If
If Range("B13") = "YES" Then
    Range("C13:P13").ClearContents
End If
If Range("B14") = "YES" Then
    Range("C14:P14").ClearContents
End If
If Range("B15") = "YES" Then
    Range("C15:P15").ClearContents
End If
End Sub

Simple question for you guys, thank you for your help.
I don't know what else to say, it's pretty straight forwards I believe. But I'm still getting the, "Looks like your most is mostly code error."
This should be an easy one for you VBA experts to solve.

Thanks again.

Body:
Try this:

Sub RemoveLoop()

Dim i As Long
Set WSheet = Worksheets("Sheet1") ' This enables the change in the mentioned sheet and not the Active sheet.
For i = 6 To 15
    If WSheet.Range("B" & i) = "YES" Then
        WSheet.Range("C" & i & ":P" & i).ClearContents
    End If
Next i

End Sub


问:
Issue with my var getting undefined
I am trying to create a reverse function to the String type in javascript. My code is like

```<code>String.prototype.reverse = function () {
    var s = "";
    for(var i=this.length;i>=0;i--){
            s+=this[i];
    }
    return s;
}
</code>```

When I try to use it on for example like "test".reverse();

instead of giving "tset" it's giving "undefinedtset"

I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?

答:
The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:

String.prototype.reverse = function(){
  return this.split('').reverse().join('');
}

console.log('Hello World'.reverse())```

Title: Issue with my var getting undefined

Body:
I am trying to create a reverse function to the String type in javascript. My code is like

String.prototype.reverse = function () {
    var s = "";
    for(var i=this.length;i>=0;i--){
            s+=this[i];
    }
    return s;
}

When I try to use it on for example like "test".reverse();

instead of giving "tset" it's giving "undefinedtset"

I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?


问:
Sorting Tableview by distance, Swift
i am pretty new at coding and currently stuck, i have not been able to find a working solution, so here is my problem, and hopefully someone here is able to help me.

What i am trying to achieve is to sort my data by distance to the nearest restaurant. I can calculate the distance and display it in my list view, but unfortunately i have not been able to figure out how to sort the list by distance. I am assuming it is due to me calculating the distance and then returning the configured cells. (I have been able to sort the restaurant by name, hours, etc.)

I pull my restaurantdata from firebase in my viewdidload, add it to an array, and the reload my tableview.

Below is the code where i calculate distance.
Any help is greatly appreciated, and let me know if i need to post more info or code.

Nik

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell", for: indexPath) as? RestaurantCell else { return UITableViewCell() }
    cell.selectionStyle = .none
    let restaurantInfo = restaurantDataArray[indexPath.row]

    let coordinate0 = CLLocation(latitude: RestaurationerVC.lat, longitude: RestaurationerVC.lon)
    let coordinate1 = CLLocation(latitude: restaurantInfo.latitude, longitude: restaurantInfo.longitude)
    let mulitplier = pow(10.0, 1.0)
    let distanceInKm = (coordinate0.distance(from: coordinate1)) / 1000
    let distanceRounded = round(distanceInKm * mulitplier) / mulitplier

    cell.configureCell(title: restaurantInfo.title!, restaurantImg: restaurantInfo.subtitle!, distance: "\(distanceRounded) Km", hours: restaurantInfo.hours, restaurantType: restaurantInfo.restaurantType, photo: restaurantInfo.photo)

    return cell
}
</code>```

答: I suggest you sort your array that you get from Firebase and then reload the data in the tableView. It would be very inefficient to try sort the tableview itself. When you say you calculate the distance in just before returning the cell that could be changed to calculate it in yuor datamodel. Try creating a struct that will represent the data for one cell(let's call it struct Restaurant). That can have variables for all your calculated data. Then you can put all of them in restaurants = Restaurant and you can implement sorting by distance,  and then use this array in your tableview cellforrowat indexpath function.</p>

Title: Sorting Tableview by distance, Swift

Body:
i am pretty new at coding and currently stuck, i have not been able to find a working solution, so here is my problem, and hopefully someone here is able to help me.

What i am trying to achieve is to sort my data by distance to the nearest restaurant. I can calculate the distance and display it in my list view, but unfortunately i have not been able to figure out how to sort the list by distance. I am assuming it is due to me calculating the distance and then returning the configured cells. (I have been able to sort the restaurant by name, hours, etc.)

I pull my restaurantdata from firebase in my viewdidload, add it to an array, and the reload my tableview.

Below is the code where i calculate distance.
Any help is greatly appreciated, and let me know if i need to post more info or code.

Nik

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell", for: indexPath) as? RestaurantCell else { return UITableViewCell() }
    cell.selectionStyle = .none
    let restaurantInfo = restaurantDataArray[indexPath.row]

    let coordinate0 = CLLocation(latitude: RestaurationerVC.lat, longitude: RestaurationerVC.lon)
    let coordinate1 = CLLocation(latitude: restaurantInfo.latitude, longitude: restaurantInfo.longitude)
    let mulitplier = pow(10.0, 1.0)
    let distanceInKm = (coordinate0.distance(from: coordinate1)) / 1000
    let distanceRounded = round(distanceInKm * mulitplier) / mulitplier

    cell.configureCell(title: restaurantInfo.title!, restaurantImg: restaurantInfo.subtitle!, distance: "\(distanceRounded) Km", hours: restaurantInfo.hours, restaurantType: restaurantInfo.restaurantType, photo: restaurantInfo.photo)

    return cell
}


答:
Hi try these configurations in your package.json,
Try to avoid ng serve for production.
Use http-serve instead

```<code>"scripts": {
    "postinstall": "ng build --no-progress -prod  --build-optimizer=false",
    "ng": "ng",
    "start": "http-server ./dist/",
    "start:hmr": "ng serve --hmr",
    "start:aot": "ng serve --aot",
    "start:prod": "ng serve --prod",
    "start:prod:aot": "ng serve --prod",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "preinstall": "rm -rf node_modules package-lock.json && npm install -g http-server @angular/cli@1.5.5"
  }
</code>```

Title: Error when access to page given by heroku after a successful build of a mean stack app

Body:
there is a logs file that I get it

2017-12-02T08:12:09.990720+00:00 app[web.1]: npm ERR!     npm bugs my-app

2017-12-02T08:12:09.990867+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:

2017-12-02T08:12:09.991030+00:00 app[web.1]: npm ERR!     npm owner ls my-app

2017-12-02T08:12:09.991159+00:00 app[web.1]: npm ERR! There is likely additional logging output above.

2017-12-02T08:12:10.023279+00:00 app[web.1]:

2017-12-02T08:12:10.023508+00:00 app[web.1]: npm ERR! Please include the following file with any support request:

2017-12-02T08:12:10.023929+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2017-12-02T08_12_09_996Z-debug.log

2017-12-02T08:12:10.096738+00:00 heroku[web.1]: State changed from starting to crashed
2017-12-02T08:12:10.099479+00:00 heroku[web.1]: State changed from crashed to starting

2017-12-02T08:12:12.801622+00:00 heroku[web.1]: Starting process with command npm start

2017-12-02T08:12:15.592323+00:00 app[web.1]:

2017-12-02T08:12:15.592371+00:00 app[web.1]: > my-app@0.0.0 start /app

2017-12-02T08:12:15.592373+00:00 app[web.1]:

2017-12-02T08:12:15.592372+00:00 app[web.1]: > ng serve

2017-12-02T08:12:15.597560+00:00 app[web.1]: sh: 1: ng: not found

2017-12-02T08:12:15.601930+00:00 app[web.1]:

2017-12-02T08:12:15.604876+00:00 app[web.1]: npm ERR! Linux 3.13.0-133-generic

2017-12-02T08:12:15.605094+00:00 app[web.1]: npm ERR! argv

"/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"

2017-12-02T08:12:15.605243+00:00 app[web.1]: npm ERR! node v7.9.0

2017-12-02T08:12:15.605367+00:00 app[web.1]: npm ERR! npm  v4.2.0

2017-12-02T08:12:15.605609+00:00 app[web.1]: npm ERR! code ELIFECYCLE

2017-12-02T08:12:15.605511+00:00 app[web.1]: npm ERR! file sh

2017-12-02T08:12:15.605730+00:00 app[web.1]: npm ERR! errno ENOENT

2017-12-02T08:12:15.605852+00:00 app[web.1]: npm ERR! syscall spawn

2017-12-02T08:12:15.605960+00:00 app[web.1]: npm ERR! my-app@0.0.0 start: ng serve

2017-12-02T08:12:15.606045+00:00 app[web.1]: npm ERR! spawn ENOENT

2017-12-02T08:12:15.606140+00:00 app[web.1]: npm ERR!

2017-12-02T08:12:15.606231+00:00 app[web.1]: npm ERR! Failed at the my-app@0.0.0 start script 'ng serve'.

2017-12-02T08:12:15.606317+00:00 app[web.1]: npm ERR! Make sure you have the latest version of node.js and npm installed.

2017-12-02T08:12:15.606411+00:00 app[web.1]: npm ERR! If you do, this is most likely a problem with the my-app package,

2017-12-02T08:12:15.606479+00:00 app[web.1]: npm ERR! not with npm itself.

2017-12-02T08:12:15.606564+00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:

2017-12-02T08:12:15.606648+00:00 app[web.1]: npm ERR!     ng serve

2017-12-02T08:12:15.606731+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:

2017-12-02T08:12:15.606820+00:00 app[web.1]: npm ERR!     npm bugs my-app

2017-12-02T08:12:15.606902+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:

2017-12-02T08:12:15.606983+00:00 app[web.1]: npm ERR!     npm owner ls my-app

2017-12-02T08:12:15.625719+00:00 app[web.1]:

2017-12-02T08:12:15.625890+00:00 app[web.1]: npm ERR! Please include the following file with any support request:

2017-12-02T08:12:15.607068+00:00 app[web.1]: npm ERR! There is likely additional logging output above.

2017-12-02T08:12:15.626229+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2017-12-02T08_12_15_612Z-debug.log

2017-12-02T08:12:15.719237+00:00 heroku[web.1]: State changed from starting to crashed

2017-12-02T08:12:15.702055+00:00 heroku[web.1]: Process exited with status 1

2017-12-02T08:12:34.000000+00:00 app[api]: Build started by user re@gmail.com

2017-12-02T08:12:34.000000+00:00 app[api]: Build failed -- check your build logs

2017-12-02T08:13:41.000000+00:00 app[api]: Build started by user re@gmail.com

2017-12-02T08:13:57.303585+00:00 app[api]: Deploy b934403c by user re@gmail.com

2017-12-02T08:13:57.303585+00:00 app[api]: Release v8 created by user re@gmail.com

2017-12-02T08:13:41.000000+00:00 app[api]: Build succeeded

2017-12-02T08:13:58.043416+00:00 heroku[web.1]: State changed from crashed to starting

2017-12-02T08:14:00.695597+00:00 heroku[web.1]: Starting process with command npm start

2017-12-02T08:14:02.754000+00:00 app[web.1]:

2017-12-02T08:14:02.754019+00:00 app[web.1]: > my-app@0.0.0 start /app

2017-12-02T08:14:02.754020+00:00 app[web.1]: > ng serve

2017-12-02T08:14:02.754021+00:00 app[web.1]:

2017-12-02T08:14:02.758257+00:00 app[web.1]: sh: 1: ng: not found

2017-12-02T08:14:02.760852+00:00 app[web.1]: npm ERR! file sh

2017-12-02T08:14:02.761025+00:00 app[web.1]: npm ERR! code ELIFECYCLE

2017-12-02T08:14:02.761175+00:00 app[web.1]: npm ERR! errno ENOENT

2017-12-02T08:14:02.761287+00:00 app[web.1]: npm ERR! syscall spawn

2017-12-02T08:14:02.762231+00:00 app[web.1]: npm ERR! my-app@0.0.0 start: ng serve

2017-12-02T08:14:02.762294+00:00 app[web.1]: npm ERR! spawn ENOENT

2017-12-02T08:14:02.762466+00:00 app[web.1]: npm ERR!

2017-12-02T08:14:02.762549+00:00 app[web.1]: npm ERR! Failed at the my-app@0.0.0 start script.

2017-12-02T08:14:02.762640+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

2017-12-02T08:14:02.768294+00:00 app[web.1]:

2017-12-02T08:14:02.768421+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:

2017-12-02T08:14:02.768493+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2017-12-02T08_14_02_763Z-debug.log

2017-12-02T08:14:02.838392+00:00 heroku[web.1]: Process exited with status 1

2017-12-02T08:14:02.851871+00:00 heroku[web.1]: State changed from starting to crashed

2017-12-02T08:15:31.370982+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dry-lowlands-73030.herokuapp.com

request_id=603bf5e0-1b2b-4b34-a016-b5be382f3556 fwd="105.144.187.15" dyno= connect= service= status=503 bytes= protocol=https

2017-12-02T08:15:32.474243+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=dry-lowlands-73030.herokuapp.com request_id=73f09d87-c20a-476b-b7cc-f7830c97b767 fwd="105.144.187.15" dyno= connect= service= status=503 bytes= protocol=https

2017-12-02T08:18:40.000000+00:00 app[api]: Build started by user re@gmail.com

2017-12-02T08:18:40.000000+00:00 app[api]: Build failed -- check your build logs

2017-12-02T08:21:19.000000+00:00 app[api]: Build started by user re@gmail.com

2017-12-02T08:21:33.835951+00:00 app[api]: Release v9 created by user re@gmail.com

2017-12-02T08:21:33.835951+00:00 app[api]: Deploy 4e6ea883 by user re@gmail.com

2017-12-02T08:21:34.328617+00:00 heroku[web.1]: State changed from crashed to starting

2017-12-02T08:21:19.000000+00:00 app[api]: Build succeeded

2017-12-02T08:21:37.664113+00:00 heroku[web.1]: Starting process with command npm start

2017-12-02T08:21:42.152085+00:00 app[web.1]:

2017-12-02T08:21:42.152123+00:00 app[web.1]: > my-app@0.0.0 start /app

2017-12-02T08:21:42.152124+00:00 app[web.1]: > ng serve

2017-12-02T08:21:42.152124+00:00 app[web.1]:

2017-12-02T08:21:42.164295+00:00 app[web.1]: sh: 1: ng: not found

2017-12-02T08:21:42.169858+00:00 app[web.1]: npm ERR! file sh

2017-12-02T08:21:42.170296+00:00 app[web.1]: npm ERR! code ELIFECYCLE

2017-12-02T08:21:42.170752+00:00 app[web.1]: npm ERR! errno ENOENT

2017-12-02T08:21:42.171236+00:00 app[web.1]: npm ERR! syscall spawn

2017-12-02T08:21:42.173965+00:00 app[web.1]: npm ERR! my-app@0.0.0 start: ng serve

2017-12-02T08:21:42.174165+00:00 app[web.1]: npm ERR! spawn ENOENT

2017-12-02T08:21:42.174630+00:00 app[web.1]: npm ERR!

2017-12-02T08:21:42.174867+00:00 app[web.1]: npm ERR! Failed at the my-app@0.0.0 start script.

2017-12-02T08:21:42.175064+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

2017-12-02T08:21:42.185175+00:00 app[web.1]:

2017-12-02T08:21:42.185419+00:00 app[web.1]: npm ERR! A complete log of this run can be found in

2017-12-02T08:21:42.185565+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2017-12-02T08_21_42_176Z-debug.log

2017-12-02T08:21:42.317965+00:00 heroku[web.1]: State changed from starting to crashed

2017-12-02T08:21:42.304608+00:00 heroku[web.1]: Process exited with status 1

2017-12-02T08:23:35.486753+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dry-lowlands-73030.herokuapp.com request_id=b3671dce-3610-47d8-abfa-357c63e329ee fwd="105.144.187.15" dyno= connect= service= status=503 bytes= protocol=https

2017-12-02T08:23:36.383415+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=dry-lowlands-73030.herokuapp.com request_id=1b80ed67-ca00-411b-832c-62812a756f39 fwd="105.144.187.15" dyno= connect= service= status=503 bytes= protocol=https

Body:
Hi try these configurations in your package.json,
Try to avoid ng serve for production.
Use http-serve instead

"scripts": {
    "postinstall": "ng build --no-progress -prod  --build-optimizer=false",
    "ng": "ng",
    "start": "http-server ./dist/",
    "start:hmr": "ng serve --hmr",
    "start:aot": "ng serve --aot",
    "start:prod": "ng serve --prod",
    "start:prod:aot": "ng serve --prod",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "preinstall": "rm -rf node_modules package-lock.json && npm install -g http-server @angular/cli@1.5.5"
  }


问:
Open conversation in Whatsapp and populate the text
I want to open WhatsApp to a specific conversation and populate the text field with some string.

Code that I have and I managed to open the conversation with a contact:

```<code>private void openConversationWithWhatsapp(String e164PhoneNumber){
    String whatsappId = e164PhoneNumber+"@s.whatsapp.net";
    Uri uri = Uri.parse("smsto:" + whatsappId);
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    intent.setPackage("com.whatsapp");

    intent.putExtra(Intent.EXTRA_TEXT, "text");
    intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
    intent.putExtra(Intent.EXTRA_TITLE, "title");
    intent.putExtra(Intent.EXTRA_EMAIL, "email");
    intent.putExtra("sms_body", "The text goes here");
    intent.putExtra("text","asd");
    intent.putExtra("body","body");
    intent.putExtra("subject","subjhect");

    startActivity(intent);
}
</code>```

The text box however is not filled with content. I tried to peek inside the AndroidManifest.xml file and found the following info regarding their conversation activity:

```<code><activity android:theme="@style/Theme.App.CondensedActionBar" android:name="com.whatsapp.Conversation" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="stateUnchanged">
    <intent-filter>
        <action android:name="android.intent.action.SENDTO" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="sms" />
        <data android:scheme="smsto" />
    </intent-filter>
</activity>
</code>```

Does somebody know the extra to use?
Are they blocking this on purpose?
I saw an API for iOS that they have in their FAQ page.

答:
Update in 2017

based on this Whatsapp FAQ

im using this url

```<code>https://api.whatsapp.com/send?phone=62xxxxxxx&text=Hello,%20from%20my%20Apps
</code>```

which 62 is Indonesia's Dialing code

then i use intent like this (im using kotlin)

```<code>val uri = Uri.parse("https://api.whatsapp.com/send?phone=62xxxxxxx&text=Hello,%20from%20my%20Apps")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
</code>```

replace 62xxxxx with your number
this work fine to me

Body:
I want to open WhatsApp to a specific conversation and populate the text field with some string.

Code that I have and I managed to open the conversation with a contact:

private void openConversationWithWhatsapp(String e164PhoneNumber){
    String whatsappId = e164PhoneNumber+"@s.whatsapp.net";
    Uri uri = Uri.parse("smsto:" + whatsappId);
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    intent.setPackage("com.whatsapp");

    intent.putExtra(Intent.EXTRA_TEXT, "text");
    intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
    intent.putExtra(Intent.EXTRA_TITLE, "title");
    intent.putExtra(Intent.EXTRA_EMAIL, "email");
    intent.putExtra("sms_body", "The text goes here");
    intent.putExtra("text","asd");
    intent.putExtra("body","body");
    intent.putExtra("subject","subjhect");

    startActivity(intent);
}

The text box however is not filled with content. I tried to peek inside the AndroidManifest.xml file and found the following info regarding their conversation activity:

<activity android:theme="@style/Theme.App.CondensedActionBar" android:name="com.whatsapp.Conversation" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="stateUnchanged">
    <intent-filter>
        <action android:name="android.intent.action.SENDTO" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="sms" />
        <data android:scheme="smsto" />
    </intent-filter>
</activity>

Does somebody know the extra to use?
Are they blocking this on purpose?
I saw an API for iOS that they have in their FAQ page.

Body:
Update in 2017

based on this Whatsapp FAQ

im using this url

https://api.whatsapp.com/send?phone=62xxxxxxx&text=Hello,%20from%20my%20Apps

which 62 is Indonesia's Dialing code

then i use intent like this (im using kotlin)

val uri = Uri.parse("https://api.whatsapp.com/send?phone=62xxxxxxx&text=Hello,%20from%20my%20Apps")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)

replace 62xxxxx with your number
this work fine to me


问:
Creating entities from a postgresql 9.0.1 database with Netbeans 6.9.1
Basically it doesn't work ... I can install the jdbc driver for pg 90 in netbeans and browse the database, issue sql commands etc. But creating entity beans from the tables via the same connection does not work, Netbeans can't find any tables in the database. Do I have to downgrade to pg 84, or are there some tricks to make it work?</p>

答:
I have the same problem. It happends when using custom domains: Netbeans can see the table but does not generate the entity bean.

I tried to define a table with no custom domains (VARCHAR or INTEGER only) and the entity has been created correctly

A Netbeans bug, I think.