问:
Trying to send the user's value to another HTML file
How to send user'name from a HTML file to another HTML file and show it on the site?

this is inside the HomePage

```<code>    <div class="enterUserName" data-validate = "Enter username">
                        <input class="input1" type="text" name="username" placeholder="Player Name">
                        <span class="hi" data-placeholder=""></span>
                    </div>
                    <div class="container-login102">
                        <button type="button"class="login" onclick="location.href='Index.html'">
                            Start Playing
                        </button>
                    </div>
</code>```

答:
Here is how you could implement it with localStorage:

  <input id="input1" type="text" name="username" placeholder="Player Name">
  <button onclick="saveUserName()">Save</button>
  <button onclick="getUserName()">display</button>

  <button type="button" class="login" onclick="location.href='Index.html'">
            Start Playing
        </button>

```

However, when using localStorage, the value is accessible only on the same origin, see here, otherwise you'll need a server-side proxy.

Body:
How to send user'name from a HTML file to another HTML file and show it on the site?

this is inside the HomePage

                        <input class="input1" type="text" name="username" placeholder="Player Name">

                        <button type="button"class="login" onclick="location.href='Index.html'">
                            Start Playing
                        </button>

Body:
Here is how you could implement it with localStorage:

<div class="enterUserName" data-validate="Enter username">
  <input id="input1" type="text" name="username" placeholder="Player Name">
  <button onclick="saveUserName()">Save</button>
  <button onclick="getUserName()">display</button>
  <span class="hi" data-placeholder="&#xe82a;"></span>
</div>
<div class="container-login102">
  <button type="button" class="login" onclick="location.href='Index.html'">
            Start Playing
        </button>
</div>
<p id="display"></p>

<script>
  function saveUserName() {
    localStorage.setItem('userName', document.getElementById('input1').value)
  }

  function getUserName() {
    if (localStorage.userName) { // userName exists
      document.getElementById('display').innerHTML = localStorage.userName;
    }
  }
</script>

However, when using localStorage, the value is accessible only on the same origin, see here, otherwise you'll need a server-side proxy.


来源: stackexchange

问:
Using Feign in a standalone library vs a Springboot application
I want to create a client for Some-Micro-Service as a library (Some-Micro-Service-Client) that way it can easily be included in the pom of Some-Other-Micro-Service.

I would like to use Feign because it makes things easier, but I am not sure if this is possible with my architecture. All of the Feign examples that I see start with using the @EnableFeignClient annotation on the SpringBootAppplication class, but since I don't want the client library to have to be "started up" I want to know if it is possible just to include it in the library without using the EnableFeignClient annotation.

答:
Yes, you can use feign without @EnableFeingClient annotation. Assume, we want to receive data from this API. In below example I used Feign Core and Feign Gson dependencies.

First of all we need to create class, in which we will get the json result:

```<code>public class TODO {
    private long id;
    private long userId;
    private String title;
    private boolean completed;

    \\ getters and setters ...
}
</code>```

After that we declare the interface with the future rest-client methods:

```<code>public interface TaskApi {

    @RequestLine("GET /todos/{id}")
    TODO getTODO(@Param("id") int id);
}
</code>```

And in conclusion let's build desired rest client and make test request:

```<code>public class FeignTest {

    private static final String API_PATH = "https://jsonplaceholder.typicode.com";

    public static void main(String[] args) {
        TaskApi taskApi = Feign.builder()
                .decoder(new GsonDecoder())
                .target(TaskApi.class, API_PATH);
        TODO todo = taskApi.getTODO(1);
    }
}
</code>```

For more information and possibilities you can read in official repository.

ContentLicense: CC BY-SA 4.0

Body:
Yes, you can use feign without @EnableFeingClient annotation. Assume, we want to receive data from this API. In below example I used Feign Core and Feign Gson dependencies.

First of all we need to create class, in which we will get the json result:

public class TODO {
    private long id;
    private long userId;
    private String title;
    private boolean completed;

    \\ getters and setters ...
}

After that we declare the interface with the future rest-client methods:

public interface TaskApi {

    @RequestLine("GET /todos/{id}")
    TODO getTODO(@Param("id") int id);
}

And in conclusion let's build desired rest client and make test request:

public class FeignTest {

    private static final String API_PATH = "https://jsonplaceholder.typicode.com";

    public static void main(String[] args) {
        TaskApi taskApi = Feign.builder()
                .decoder(new GsonDecoder())
                .target(TaskApi.class, API_PATH);
        TODO todo = taskApi.getTODO(1);
    }
}

For more information and possibilities you can read in official repository.


问:
How can I get count in one window to another in wpf
In my code I'm getting the count of clicks in the second window and showing it in the first window which is the main window.How can I do this. What I tried below is not working</p>

```<code>    C# code in second window

 public partial class Window1 : Window
    {
        int counter = 0;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            counter++;
            hope.Text = counter.ToString();
        }
    }
</code>```

```<code>    Xaml code in Main window
  <TextBlock x:Name="hope" HorizontalAlignment="Left" TextWrapping="Wrap"   FontWeight="Bold" Text="Attendees" VerticalAlignment="Top" Height="23" Width="157"/>

</code>```

答:
Your code isn't working because the TextBox hope is defined as a field in your main class and you're trying to reference it in your second class without specifying an instance of your first class. There's a few ways to get around this (you could expose a reference to hope as a public static variable), but you should definitely look into implementing MVVM. I recommend looking up a detailed tutorial on it so you can get the full story, but I'll try to explain the basics here.

When following MVVM (model-view-viewmodel), you partition your code into several discrete roles. XAML and any associated code-behind are considered part of the view role. The code samples in your question are part of the view as well. In general, you do not want the view to implement any logic outside of what is strictly necessary or else related directly to the UI. There are exceptions to this rule, but in general you should follow it.

The job of the view model is to facilitate communication between your model (data) and your view. For example, you could put your counter variable in a database, or package it into a serializable class and load it from a file. The viewmodel would access whatever model you choose via a public property, whose set and get functions would ensure the data is accessed correctly.

Finally, the view can access the counter by binding to the property on the viewmodel. Binding is really nice because it allows the view to automatically update when the property changes. However, to get this to work you'll need to have your viewmodel implement INotifyPropertyChanged, which notifies your WPF component(s) that they need to display a different value.

Here's how it works:

The value on the viewmodel is changed.

The property that was modified raises a PropertyChanged event.

Any components bound to the property handle the event and update their value.

Finally, to change a property on the viewmodel from the view, you can use commands. Commands are implemented on the viewmodel and can be executed from the view. Commands can be used in place of events in many circumstances.

I wrote a simple counter program that demonstrates a few core MVVM principles. All it does is increment a number when you click on a button, similar to your sample code. It's in one window, but you can easily modify it to work with two different ones. I recommend trying to do that as an exercise so you can get a feel for how everything works.

If you're using Visual Studio, you can copy-paste all of this into a WPF project named "ExampleProject" and run it; I tested it and it works as expected.

XAML:

<Window x:Class="ExampleProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ExampleProject"
        xmlns:viewmodel="clr-namespace:ExampleProject.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>
        <viewmodel:CounterViewModel x:Key="Counter"></viewmodel:CounterViewModel>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0"
                   Text="{Binding Source={StaticResource Counter}, Path=Counter}"
                   FontSize="50"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"/>

        <Button Grid.Row="1"
                Content="Press Me"
                Command="{Binding Source={StaticResource Counter}, Path=Increment}"
                CommandParameter="{StaticResource Counter}"
                FontSize="60"></Button>
    </Grid>
</Window>
```

<p>ViewModel:</p>

<pre class="lang-cs prettyprint-override"><code>using System.ComponentModel;
using System.Windows.Input;
using ExampleProject.Commands;
using ExampleProject.Model;

namespace ExampleProject.ViewModel
{
    //this is the viewmodel. note that it implements INotifyPropertyChanged.
    //you almost always want your viewmodel to do so.
    public class CounterViewModel : INotifyPropertyChanged
    {
        //invoke this whenever you change a property that your controls
        //might be binding to
        public event PropertyChangedEventHandler PropertyChanged;

        //this is the underlying data. including a reference to the model in
        //your viewmodel is one way to facilitate communication between the
        //two, although there are other ways.
        private CounterModel model;

        //this is the most important part; your view will bind to this.
        public int Counter
        {
            get { return model.Counter; }
            set
            {
                model.Counter = value;
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Counter"));
            }
        }

        //this is a function that will increment the counter and can be called
        //directly from XAML.
        public ICommand Increment { get; }

        //this constructor needs to be parameterless in our case, because
        //we will be creating an instance of this class from XAML.
        public CounterViewModel()
        {
            model = new CounterModel(0);
            Increment = new IncrementCommand();
        }
    }
}
</code>```

Model:

namespace ExampleProject.Model
{
    //this is a simple model class. generally, you don't want to
    //implement any logic here; in pure MVVM the model just
    //encapsulates raw data.
    public class CounterModel
    {
        public int Counter;

        public CounterModel(int counterValue)
        {
            Counter = counterValue;
        }
    }
}
```

<p>Increment command:</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Windows.Input;
using ExampleProject.ViewModel;

namespace ExampleProject.Commands
{
    public class IncrementCommand : ICommand
    {
        //necessary to implement because of ICommand but we're not currently using this
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            //if this method returns false, the command won't be executed.
            return true;
        }

        public void Execute(object parameter)
        {
            //parameter is passed in via XAML; it's always an instance of CounterViewModel
            //but i double-check what kind of object it is anyway.
            if (parameter is CounterViewModel viewModel)
            {
                viewModel.Counter++;
            }
        }
    }
}
</code>```

Note that I didn't need to add anything to the code-behind. This isn't always possible, but it's often a good thing when you can manage it.

Body:
In my code I'm getting the count of clicks in the second window and showing it in the first window which is the main window.How can I do this. What I tried below is not working

    C# code in second window

 public partial class Window1 : Window
    {
        int counter = 0;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            counter++;
            hope.Text = counter.ToString();
        }
    }

    Xaml code in Main window
  <TextBlock x:Name="hope" HorizontalAlignment="Left" TextWrapping="Wrap"   FontWeight="Bold" Text="Attendees" VerticalAlignment="Top" Height="23" Width="157"/>

Body:
Your code isn't working because the TextBox hope is defined as a field in your main class and you're trying to reference it in your second class without specifying an instance of your first class. There's a few ways to get around this (you could expose a reference to hope as a public static variable), but you should definitely look into implementing MVVM. I recommend looking up a detailed tutorial on it so you can get the full story, but I'll try to explain the basics here.

When following MVVM (model-view-viewmodel), you partition your code into several discrete roles. XAML and any associated code-behind are considered part of the view role. The code samples in your question are part of the view as well. In general, you do not want the view to implement any logic outside of what is strictly necessary or else related directly to the UI. There are exceptions to this rule, but in general you should follow it.

The job of the view model is to facilitate communication between your model (data) and your view. For example, you could put your counter variable in a database, or package it into a serializable class and load it from a file. The viewmodel would access whatever model you choose via a public property, whose set and get functions would ensure the data is accessed correctly.

Finally, the view can access the counter by binding to the property on the viewmodel. Binding is really nice because it allows the view to automatically update when the property changes. However, to get this to work you'll need to have your viewmodel implement INotifyPropertyChanged, which notifies your WPF component(s) that they need to display a different value.

Here's how it works:

The value on the viewmodel is changed.

The property that was modified raises a PropertyChanged event.

Any components bound to the property handle the event and update their value.

Finally, to change a property on the viewmodel from the view, you can use commands. Commands are implemented on the viewmodel and can be executed from the view. Commands can be used in place of events in many circumstances.

I wrote a simple counter program that demonstrates a few core MVVM principles. All it does is increment a number when you click on a button, similar to your sample code. It's in one window, but you can easily modify it to work with two different ones. I recommend trying to do that as an exercise so you can get a feel for how everything works.

If you're using Visual Studio, you can copy-paste all of this into a WPF project named "ExampleProject" and run it; I tested it and it works as expected.

XAML:

<Window x:Class="ExampleProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ExampleProject"
        xmlns:viewmodel="clr-namespace:ExampleProject.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <!-- we reference our CounterViewModel class via XAML here. note that to access it,
    we need to specify the namespace it's in by adding
    xmlns:viewmodel="clr-namespace:ExampleProject.ViewModel"-->
    <Window.Resources>
        <viewmodel:CounterViewModel x:Key="Counter"></viewmodel:CounterViewModel>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <!-- here we bind to the Counter property in the viewmodel. we reference it in
        XAML via the value assigned to x:Key (in this case, Counter). the value assigned
        to the "Source" parameter tells WPF where to look for properties. the value
        assigned to Path tells it which property to bind to.-->
        <TextBlock Grid.Row="0"
                   Text="{Binding Source={StaticResource Counter}, Path=Counter}"
                   FontSize="50"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"/>

        <Button Grid.Row="1"
                Content="Press Me"
                Command="{Binding Source={StaticResource Counter}, Path=Increment}"
                CommandParameter="{StaticResource Counter}"
                FontSize="60"></Button>
    </Grid>
</Window>

ViewModel:

using System.ComponentModel;
using System.Windows.Input;
using ExampleProject.Commands;
using ExampleProject.Model;

namespace ExampleProject.ViewModel
{
    //this is the viewmodel. note that it implements INotifyPropertyChanged.
    //you almost always want your viewmodel to do so.
    public class CounterViewModel : INotifyPropertyChanged
    {
        //invoke this whenever you change a property that your controls
        //might be binding to
        public event PropertyChangedEventHandler PropertyChanged;

        //this is the underlying data. including a reference to the model in
        //your viewmodel is one way to facilitate communication between the
        //two, although there are other ways.
        private CounterModel model;

        //this is the most important part; your view will bind to this.
        public int Counter
        {
            get { return model.Counter; }
            set
            {
                model.Counter = value;
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Counter"));
            }
        }

        //this is a function that will increment the counter and can be called
        //directly from XAML.
        public ICommand Increment { get; }

        //this constructor needs to be parameterless in our case, because
        //we will be creating an instance of this class from XAML.
        public CounterViewModel()
        {
            model = new CounterModel(0);
            Increment = new IncrementCommand();
        }
    }
}

Model:

namespace ExampleProject.Model
{
    //this is a simple model class. generally, you don't want to
    //implement any logic here; in pure MVVM the model just
    //encapsulates raw data.
    public class CounterModel
    {
        public int Counter;

        public CounterModel(int counterValue)
        {
            Counter = counterValue;
        }
    }
}

Increment command:

using System;
using System.Windows.Input;
using ExampleProject.ViewModel;

namespace ExampleProject.Commands
{
    public class IncrementCommand : ICommand
    {
        //necessary to implement because of ICommand but we're not currently using this
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            //if this method returns false, the command won't be executed.
            return true;
        }

        public void Execute(object parameter)
        {
            //parameter is passed in via XAML; it's always an instance of CounterViewModel
            //but i double-check what kind of object it is anyway.
            if (parameter is CounterViewModel viewModel)
            {
                viewModel.Counter++;
            }
        }
    }
}

Note that I didn't need to add anything to the code-behind. This isn't always possible, but it's often a good thing when you can manage it.


问:
Using Mongoid query syntax vs Activerecord
I'm having a little conundrum that I am confused by.

In rails console if I use

```<code>@o = ObjName.where(o_id: "VAL")
</code>```

I don't get an object returned.  I get this though:

```<code> => #<Mongoid::Criteria
  selector: {:conditions=>{:site_id=>"PST"}},
  options:  {},
  class:    Site,
  embedded: false>
</code>```

But if I use:

```<code>@o = ObjName.first(:conditions => {:o_id => "VAL"})
</code>```

I do.  There where function is used within Mongoid, and my model includes Mongoid.  So I don't understand why this doesn't work.

答: Maybe you just need a ".all" at the end of your query.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm having a little conundrum that I am confused by.

In rails console if I use

@o = ObjName.where(o_id: "VAL")

I don't get an object returned.  I get this though:

 => #<Mongoid::Criteria
  selector: {:conditions=>{:site_id=>"PST"}},
  options:  {},
  class:    Site,
  embedded: false>

But if I use:

@o = ObjName.first(:conditions => {:o_id => "VAL"})

I do.  There where function is used within Mongoid, and my model includes Mongoid.  So I don't understand why this doesn't work.


问:
Websocket : Error during WebSocket handshake: Unexpected response code: 504
I have been developing a live chat that uses a websocket connection. It works fine on my localhost and on http servers. However, I am trying to get it working on a secure GoDaddy server with Deluxe Linux Hosting.
While the client is trying to open a websocket connection from javascript, it eventually responds with "WebSocket connection to 'wss://jhaubrich.com/new.projecthandle.io/Demo/include/projectChat/php-socket.php?username=Justin' failed: Error during WebSocket handshake: Unexpected response code: 504"

A 504 Gateway Timeout Error indicates an issue with the gateway or proxy server.

If I try to open the connection again without killing the PID for the lsphp, the error written to error_log by the php-socket.php file reads "PHP Warning:  socket_bind(): unable to bind address [98]: Address already in use in /home/fq2cvob2t06k/public_html/new.projecthandle.io/Demo/include/projectChat/php-socket.php on line 12"

For the socket_bind() in php-socket.php I am using port 8090.

I have tried changing ports. I have tried adding 'websocket' to the end of the url in the websocket js.

//my js to initiate the websocket
    var websocket = new WebSocket("ws://jhaubrich.com/new.projecthandle.io/Demo/include/projectChat/php-socket.php?username=" + userName + "" );

I expected a websocket connection to be made.
Instead I get this error : "WebSocket connection to 'wss://jhaubrich.com/new.projecthandle.io/Demo/include/projectChat/php-socket.php?username=Justin' failed: Error during WebSocket handshake: Unexpected response code: 504"

答: I came to the realization that I am use a shared hosting environment. I need to purchase a Virtual Private Server where I will have root privileges. Then I will be able to use WebSockets...</p>


问:
template tag slice won't work while truncatechars works
season1-theOffice. I want to remove -theOffice. Thus I did season1|truncatechars: "9" but with this it gives season 1...
I don't want to see ...
So I used season1|slice:" :9" but this does nothing.
Here's my code.

```<code>        <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season|slice:":5" }}
</code>```

My fulll code

```<code><div class="row">
  {% for all_episode in episode %}
    <div class="col-6 card" style="padding:20px">
      <a href="{% url 'episode_detail' slug=all_episode.slug %}">
        <img class="card-img-top" src='{{all_episode.image.url}}'>
      </a>
      <div class="card-body">
        <h5 class="card-title">
          <a href="{% url 'episode_detail' slug=all_episode.slug %}">{{ all_episode.title }}</a>
        </h5>
        <p class="card-text">{{ all_episode.story |slice:":100" }}...</p>
      </div>

      <div class="card-footer">
        <small class="text-muted">
          <span class="h5">
            <a href="{% url 'series_detail' slug=all_episode.series.slug %}">{{ all_episode.series }}</a>
          </span> /
          <span class="h6">
            <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season|slice:":9" }}     </a>
          </span>
        </small>
      </div>
    </div>
  {% endfor %}
</div>
</code>```

答:
That is because you have added a space in your template filter (or at least in the question text, like slice:" :9").

You should write it like:

```<code>{{ all_episode.season|slice:<b>":-9"</b> }}</code>```

not:

```<code>{{ all_episode.season|slice:<s>" :-9"</s> }}</code>```

The -9 means that you count from the end of the string to the start of the string, so here we will omit 9 characters. -1 would thus remove the last character.

For example:

```<code>>>> Template('{{ s|slice:":-9" }}').render(Context({'s': 'season1-theOffice'}))
'season1-'
</code>```

Body:
season1-theOffice. I want to remove -theOffice. Thus I did season1|truncatechars: "9" but with this it gives season 1...
I don't want to see ...
So I used season1|slice:" :9" but this does nothing.
Here's my code.

        {{ all_episode.season|slice:":5" }}

My fulll code

  {% for all_episode in episode %}

          {{ all_episode.title }}

{{ all_episode.story |slice:":100" }}...

            {{ all_episode.series }}
           /

            {{ all_episode.season|slice:":9" }}

  {% endfor %}

Body:
That is because you have added a space in your template filter (or at least in the question text, like slice:" :9").

You should write it like:

{{ all_episode.season|slice:":-9" }}

not:

{{ all_episode.season|slice:<s>" :-9"</s> }}

The -9 means that you count from the end of the string to the start of the string, so here we will omit 9 characters. -1 would thus remove the last character.

For example:

>>> Template('{{ s|slice:":-9" }}').render(Context({'s': 'season1-theOffice'}))
'season1-'


问:
Change remote repository credentials (authentication) on Intellij IDEA 14
I recently changed my Bitbucket password for security reasons. However, IntelliJ didn't update my repository to the new credentials, so it stops me from pulling/pushing anything to my repository. I am not using any plugins for this, just the integrated VCS operations inside the IDE.

Every time I pull/push, this pops out:

fatal: Authentication failed for     'https://momothereal:xxxxxxxxxxxx@bitbucket.org/team/repo.git/

Where xxxxxxxxxxxx is my old password. I think changing this remote address with the correct password would fix it, though I cannot find where to do so.

答:
For MACOS users

if you see credentials failed but you are sure that is is working previously then:

probably you made a software update to the system. System uses git bundled with xcode. its better to open Xcode and click install extra components on startup of xcode. it will say installing components. when you accept the license agreement if will start working again.

in short:

open Xcode, install additional components. accept user licence agreement.

on Xcode updates this step should be repeated.


问:
Sqrt(n) time complexity
I am new to time complexities and asymptotic notation. I was looking at this video: https://www.youtube.com/watch?v=9TlHvipP5yA to figure out the time complexity of a piece of code shown below

The code concludes that the time complexity for the code below is O(Sqrt(n));

When I supply different n values, I am expecting Sqrt(n) # of outputs but this doesn't verify the O(Sqrt(n)) analysis. Can someone please explain why it is so?

For example if I have n = 10, I am expecting Sqrt(10) outputs which is ~ 3 outputs or 4 if you round up I guess. IS this illogical?

Thanks in advance.

```<code>p = 0;
for( int i = 0; p <= n; i++){
  p = p + i;
  System.out.println(p);
}
</code>```

答:
Big O is not used to compute the number of instructions you are expected to execute. For a given n, calculating the square root of n will not give you the exact number of times the instruction executes. Big O describes what happens with your function as input size gets very large. Analysis of your function when n is 10 or even 100 does not apply to Big O.

When we say a function's time complexity is O(sqrt(n)), we mean that the function belongs in a class of functions where the time required is proportional to the square root of the value of n, but only for very large values of n.

If you watch the video, the instructor simplifies the k(k+1) / 2 term to k^2 by taking the leading term, because the k term becomes insignificant compared to the k^2 term, when k is very large.

Title: Sqrt(n) time complexity

Body:
I am new to time complexities and asymptotic notation. I was looking at this video: https://www.youtube.com/watch?v=9TlHvipP5yA to figure out the time complexity of a piece of code shown below

The code concludes that the time complexity for the code below is O(Sqrt(n));

When I supply different n values, I am expecting Sqrt(n) # of outputs but this doesn't verify the O(Sqrt(n)) analysis. Can someone please explain why it is so?

For example if I have n = 10, I am expecting Sqrt(10) outputs which is ~ 3 outputs or 4 if you round up I guess. IS this illogical?

Thanks in advance.

p = 0;
for( int i = 0; p <= n; i++){
  p = p + i;
  System.out.println(p);
}


问:
Making / Testing a Connection Using VersionOne .Net SDK
I'm new to VersionOne and have limited C#. Need help connecting and testing connection to VersionOne instance using .Net SDK to make sure I'm actually making a connection.

I have some sample code that runs without error, but not sure it is connecting.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VersionOne.SDK.APIClient;

namespace VersionOneExtract3
{
    public class Connection1
    {
         V1Connector connector = V1Connector

    .WithInstanceUrl("https://www14.v1host.com/MyCompanySite")

    .WithUserAgentHeader("VersionOneExtract2", "1.0")

    .WithWindowsIntegrated("XA\\MyUsername", "MyPassword")

    .Build();
    }
}
enter code here
</code>```

No results or errors. Is there a way I can create a variable and have it return some sort of confirmed connection info? Help appreciated!

答:
Think of your code as code that describes and sets up a VersionOne connection.  You are building an object that contains everything needed for a connection.  You are not connecting yet.

if your variable connector is null, you know for a fact that you are not connected to VersionOne. On the other hand, your connector might have what looks like valid info in the setting up of the connection so you need to add the next piece of code

```<code>IServices services = new Services(connector);
</code>```

Once you hit this piece of code, this will throw an exception if the connector object is invalid.  To get confirmation of this, connect to https://www14.v1host.com/MyCompanySiteWrongURL. If you run your code, connector will reference an object but it will have virtual "junk" in it because it won't connect.  As soon as you hit the above new code that I have suggested, it will throw an exception. Conversely, if you enter the correct URL and credentials, you should not throw an exception. You can use @DCCoders chunk of code for querying for member:20.  I also recommend using the VersionOne API to do queries in the browser so you can get instant results and get a feel of the VersionOne data model.  https://community.versionone.com/VersionOne_Connect/Developer_Library/Learn_the_API/VersionOne_REST_API_Tutorial

Body:
I'm new to VersionOne and have limited C#. Need help connecting and testing connection to VersionOne instance using .Net SDK to make sure I'm actually making a connection.

I have some sample code that runs without error, but not sure it is connecting.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VersionOne.SDK.APIClient;

namespace VersionOneExtract3
{
    public class Connection1
    {
         V1Connector connector = V1Connector

    .WithInstanceUrl("https://www14.v1host.com/MyCompanySite")

    .WithUserAgentHeader("VersionOneExtract2", "1.0")

    .WithWindowsIntegrated("XA\\MyUsername", "MyPassword")

    .Build();
    }
}
enter code here

No results or errors. Is there a way I can create a variable and have it return some sort of confirmed connection info? Help appreciated!

Body:
Think of your code as code that describes and sets up a VersionOne connection.  You are building an object that contains everything needed for a connection.  You are not connecting yet.

if your variable connector is null, you know for a fact that you are not connected to VersionOne. On the other hand, your connector might have what looks like valid info in the setting up of the connection so you need to add the next piece of code

IServices services = new Services(connector);

Once you hit this piece of code, this will throw an exception if the connector object is invalid.  To get confirmation of this, connect to https://www14.v1host.com/MyCompanySiteWrongURL. If you run your code, connector will reference an object but it will have virtual "junk" in it because it won't connect.  As soon as you hit the above new code that I have suggested, it will throw an exception. Conversely, if you enter the correct URL and credentials, you should not throw an exception. You can use @DCCoders chunk of code for querying for member:20.  I also recommend using the VersionOne API to do queries in the browser so you can get instant results and get a feel of the VersionOne data model.  https://community.versionone.com/VersionOne_Connect/Developer_Library/Learn_the_API/VersionOne_REST_API_Tutorial


问:
A good database schema
ok so i have this problem that i need to achieve...Here is my site

What i need to do is for each product sold i need to have 2 other products that are either an upgrade or a downgrade.

so there each product has 3 classes standard, business, and premium and based on what the current product is they either increase or decrease in price..

so basically they are customizing each solution. So what i need is figure out the best way to structure my db for this...here is the query i use to pull what i have now

```<code> $query = "SELECT p.ProductName, p.price, pc.quantity, p.ProductImage, p.Features
            FROM productinfo as p
              join preconfig_categories as pc on p.ProductID = pc.product_id
              join preconfig as c on c.id = pc.category_id
              join subcategory as sc on p.SubCategoryID = sc.SubCategoryID
              WHERE  c.code      = '{$type}_{$count}_{$class}'
              order by sc.ordering";
</code>```

I was thinking of in the productinfo table which is currently structured like this

```<code>CREATE TABLE `productinfo` (
  `ProductID` int(11) NOT NULL AUTO_INCREMENT,
  `ProductName` varchar(255) NOT NULL,
  `ProductImage` varchar(255) NOT NULL,
  `CategoryID` int(11) NOT NULL,
  `SubCategoryID` int(11) NOT NULL,
  `ProductBrief` varchar(255) NOT NULL,
  `Features` text NOT NULL,
  `Specifications` text NOT NULL,
  `Reviews` text NOT NULL,
  `Price` varchar(255) NOT NULL,
  `Status` tinyint(4) NOT NULL,
  `PartName` varchar(255) NOT NULL,
  `skip_step` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`ProductID`)
) ENGINE=MyISAM AUTO_INCREMENT=164 DEFAULT CHARSET=latin1;
</code>```

I was thinking off adding three extra fields

```<code>class
product1
product2
</code>```

so basically i can use the class to tell what the current product is and then the other two fields product1 and product2 which will have the ProductID of the other two products....This seems like it could work but i feel like theres probably a better solution out there then can work a bit better....any ideas input would be strongly appreciated

答:
A few questions...

If the product displayed is standard, does it just show the business and premium products?  if the product is already the lowest, does it just show upgrades... and if it is premium, does it just show downgrades?  If not, does it show a different category of product in order to always show one upgrade and one downgrade?

How is it determined which products are associated as alternatives to other products?  Is this something that is determined programmatically, or does someone just manually pick out which products are associated?

If the associated products can be determined through logic, I think it would be worth considering not adding the extra fields to the products table, and instead resolve the associations on demand through the queries.  The reasoning being that if some criteria of a product were to change, such as the price... then it might no longer be considered an upgrade or downgrade for a product that currently references it... and then you have a data inconsistency issue.

--EDIT--

Thank you for the answers.  So if the products associations are chosen manually, and every product will have 2 and only two associations, then your initial design looks good to me (I would just be sure to add the FKs).  However, if you think there's a chance that someday products might have a variable number of associations... like one product only has one alternative, while another could have 4 alternatives, then I might put the associations into a separate table.  Something like...

```<code>CREATE TABLE `associatedproduct` (
  `ProductID` int(11),
  `AssociatedProductID` int(11)
)
</code>```

That way it wouldn't be set in stone that a product has to have exactly two associations.  You could also add additional columns to this table that could describe the association between the two products... like product 'A' is an upgrade, while product 'B' is a premium upgrade.

Title: A good database schema

Body:
ok so i have this problem that i need to achieve...Here is my site

What i need to do is for each product sold i need to have 2 other products that are either an upgrade or a downgrade.

so there each product has 3 classes standard, business, and premium and based on what the current product is they either increase or decrease in price..

so basically they are customizing each solution. So what i need is figure out the best way to structure my db for this...here is the query i use to pull what i have now

 $query = "SELECT p.ProductName, p.price, pc.quantity, p.ProductImage, p.Features
            FROM productinfo as p
              join preconfig_categories as pc on p.ProductID = pc.product_id
              join preconfig as c on c.id = pc.category_id
              join subcategory as sc on p.SubCategoryID = sc.SubCategoryID
              WHERE  c.code      = '{$type}_{$count}_{$class}'
              order by sc.ordering";

I was thinking of in the productinfo table which is currently structured like this

CREATE TABLE `productinfo` (
  `ProductID` int(11) NOT NULL AUTO_INCREMENT,
  `ProductName` varchar(255) NOT NULL,
  `ProductImage` varchar(255) NOT NULL,
  `CategoryID` int(11) NOT NULL,
  `SubCategoryID` int(11) NOT NULL,
  `ProductBrief` varchar(255) NOT NULL,
  `Features` text NOT NULL,
  `Specifications` text NOT NULL,
  `Reviews` text NOT NULL,
  `Price` varchar(255) NOT NULL,
  `Status` tinyint(4) NOT NULL,
  `PartName` varchar(255) NOT NULL,
  `skip_step` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`ProductID`)
) ENGINE=MyISAM AUTO_INCREMENT=164 DEFAULT CHARSET=latin1;

I was thinking off adding three extra fields

class
product1
product2

so basically i can use the class to tell what the current product is and then the other two fields product1 and product2 which will have the ProductID of the other two products....This seems like it could work but i feel like theres probably a better solution out there then can work a bit better....any ideas input would be strongly appreciated

Body:
A few questions...

If the product displayed is standard, does it just show the business and premium products?  if the product is already the lowest, does it just show upgrades... and if it is premium, does it just show downgrades?  If not, does it show a different category of product in order to always show one upgrade and one downgrade?

How is it determined which products are associated as alternatives to other products?  Is this something that is determined programmatically, or does someone just manually pick out which products are associated?

If the associated products can be determined through logic, I think it would be worth considering not adding the extra fields to the products table, and instead resolve the associations on demand through the queries.  The reasoning being that if some criteria of a product were to change, such as the price... then it might no longer be considered an upgrade or downgrade for a product that currently references it... and then you have a data inconsistency issue.

--EDIT--

Thank you for the answers.  So if the products associations are chosen manually, and every product will have 2 and only two associations, then your initial design looks good to me (I would just be sure to add the FKs).  However, if you think there's a chance that someday products might have a variable number of associations... like one product only has one alternative, while another could have 4 alternatives, then I might put the associations into a separate table.  Something like...

CREATE TABLE `associatedproduct` (
  `ProductID` int(11),
  `AssociatedProductID` int(11)
)

That way it wouldn't be set in stone that a product has to have exactly two associations.  You could also add additional columns to this table that could describe the association between the two products... like product 'A' is an upgrade, while product 'B' is a premium upgrade.


问:
Simulate change does not work for formik's select elements
I am trying to test some of the formik's select elements, and Simulate change does not work.

whereas the same simulate change works fine for formik's input elements.

Component:

```<code> <Field
                      type="text"
                      name={'clientsData.language1_id'}
                      className={this.props.classes.textField}
                      label="Primary Language"
                      select
                      margin="normal"
                      variant="outlined"
                      component={TextField}
                      InputLabelProps={{
                        shrink: true
                      }}>
                      }}>
                      {this.props.languages.map(val => (
                        <MenuItem key={val.id} value={val.id}>
                          {val.value}
                        </MenuItem>
                      ))}
                    </Field>
</code>```

Mount Wrapper:

```<code>wrapper = mount(
      <Router history={hist}>
        <ClientsContacts
          clientsData={clientsData}
          languages={languages}
          gender={gender}
          race={race}
          genders_identified={genderIdentified}
          actions={{ getDictionaryApiCall: mockGetDictionaryApiCall, getListApiCall: mockGetListApiCall }}
        />
      </Router>
    )
</code>```

Simulate change and some console logs for better understanding:

```<code>console.log(
      wrapper
        // .find('Select')
        .find('input')
        .at(6)
        .debug()
    )

    wrapper
      .find('input')
      .at(6)
      .simulate('change', { target: { value: '122344556644', name: 'clientsData.language1_id' } })

    console.log(
      wrapper
        .find('input')
        .at(6)
        .props()
    )
</code>```

Screenshot of console.log:

Above screenshot of console log shows value is not changed even after the simulate change.

答:
I Was able to fix it by using directly props.onChange</p>

```<code>wrapper
      .find('SelectInput')
      .at(0)
      .props()
      .onChange({ target: { id: 1, value: 'American Sign Language', name: 'clientsData.language1_id' } })
    wrapper.update()
</code>```

Body:
I am trying to test some of the formik's select elements, and Simulate change does not work.

whereas the same simulate change works fine for formik's input elements.

Component:

 <Field
                      type="text"
                      name={'clientsData.language1_id'}
                      className={this.props.classes.textField}
                      label="Primary Language"
                      select
                      margin="normal"
                      variant="outlined"
                      component={TextField}
                      InputLabelProps={{
                        shrink: true
                      }}>
                      }}>
                      {this.props.languages.map(val => (
                        <MenuItem key={val.id} value={val.id}>
                          {val.value}
                        </MenuItem>
                      ))}
                    </Field>

Mount Wrapper:

wrapper = mount(
      <Router history={hist}>
        <ClientsContacts
          clientsData={clientsData}
          languages={languages}
          gender={gender}
          race={race}
          genders_identified={genderIdentified}
          actions={{ getDictionaryApiCall: mockGetDictionaryApiCall, getListApiCall: mockGetListApiCall }}
        />
      </Router>
    )

Simulate change and some console logs for better understanding:

console.log(
      wrapper
        // .find('Select')
        .find('input')
        .at(6)
        .debug()
    )

    wrapper
      .find('input')
      .at(6)
      .simulate('change', { target: { value: '122344556644', name: 'clientsData.language1_id' } })

    console.log(
      wrapper
        .find('input')
        .at(6)
        .props()
    )

Screenshot of console.log:

Above screenshot of console log shows value is not changed even after the simulate change.

Body:
I Was able to fix it by using directly props.onChange

wrapper
      .find('SelectInput')
      .at(0)
      .props()
      .onChange({ target: { id: 1, value: 'American Sign Language', name: 'clientsData.language1_id' } })
    wrapper.update()


问:
How to store values of different types in a single Structure
I have a text file in that has a list of strings (Example  6|Chicago|Illinois|I-98;I-90). I am trying to create two Classes. One class (CityReader) reads the text file and other file prints it. I declared a class(CityItem) with 4 variables, int population, string city, string state, List<int> Interstates.

In the CityReader class I created a CityItem Object(CIObj) and was able to read the file and delimit it and returning CIObj. But when I access this object from a different class I am only seeing the last line in the text file. This object is not returning all the values.

I realized though I am reading the file in each loop. I am not storing those values and hence the object is holding only the last object.

```<code>    CityItem Class-----

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ReadingAtxtFile
    {
        public class CityItem
        {
    public int Population { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public List<int> Interstates = new List<int>();

         }
    }

    CityReader Class-----

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Collections;
    namespace ReadingAtxtFile
    {
        public class CityReader
        {
             public CityItem ReadCities(string FilePath)
             {
        CityItem CIObj = new CityItem();
        var AllLines = File.ReadAllLines(FilePath, Encoding.UTF8);
        try
        {
            foreach (var item1 in AllLines)
            {
                string[] EachLine = item1.Split('|');

                CIObj.Population = Convert.ToInt32(EachLine[0]);
                CIObj.City = EachLine[1];
                CIObj.State = EachLine[2];

                    string[] IStates = EachLine[3].Split(';');

                    foreach (var item2 in IStates)
                    {
                        var IStatesAfterSplit = item2.Split("-");
                      CIObj.Interstates.Add(Convert.ToInt32(IStatesAfterSplit[1]));
                    }
            }
        }
        catch (Exception)
        {
            Console.WriteLine("There is an issue with processing the data");
        }
        return CIObj;
        }
        }
       }
</code>```

Input TextFile:

```<code>6|Oklahoma City|Oklahoma|I-35;I-44;I-40
6|Boston|Massachusetts|I-90;I-93
8|Columbus|Ohio|I-70;I-71
</code>```

I am trying to process the text file and print the data as I like. For example. population

```<code>Population,
City, State,
Interstates: I-35,I-40,I-45 (Sorted order)
</code>```

答:
Your ReadCities method needs to return some kind of collection of CityItem objects, not just a single CityItem object.  .Net supports various kinds of collections, but a List is probably best for this instance.

Then, after populating your CityItem object, before moving to the next iteration of the loop, add the CityItem object to your List.  Something like...

```<code>List<CityItem> listOfCityItems = new List<CityItem>();
foreach (var line in AllLines)
{
    CityItem ci = new CityITem();
    // Populate the properties of ci
    listOfCityItems.Add(ci);
}
</code>```

Body:
I have a text file in that has a list of strings (Example  6|Chicago|Illinois|I-98;I-90). I am trying to create two Classes. One class (CityReader) reads the text file and other file prints it. I declared a class(CityItem) with 4 variables, int population, string city, string state, List<int> Interstates.

In the CityReader class I created a CityItem Object(CIObj) and was able to read the file and delimit it and returning CIObj. But when I access this object from a different class I am only seeing the last line in the text file. This object is not returning all the values.

I realized though I am reading the file in each loop. I am not storing those values and hence the object is holding only the last object.

    CityItem Class-----

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ReadingAtxtFile
    {
        public class CityItem
        {
    public int Population { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public List<int> Interstates = new List<int>();

         }
    }

    CityReader Class-----

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Collections;
    namespace ReadingAtxtFile
    {
        public class CityReader
        {
             public CityItem ReadCities(string FilePath)
             {
        CityItem CIObj = new CityItem();
        var AllLines = File.ReadAllLines(FilePath, Encoding.UTF8);
        try
        {
            foreach (var item1 in AllLines)
            {
                string[] EachLine = item1.Split('|');

                CIObj.Population = Convert.ToInt32(EachLine[0]);
                CIObj.City = EachLine[1];
                CIObj.State = EachLine[2];

                    string[] IStates = EachLine[3].Split(';');

                    foreach (var item2 in IStates)
                    {
                        var IStatesAfterSplit = item2.Split("-");
                      CIObj.Interstates.Add(Convert.ToInt32(IStatesAfterSplit[1]));
                    }
            }
        }
        catch (Exception)
        {
            Console.WriteLine("There is an issue with processing the data");
        }
        return CIObj;
        }
        }
       }

Input TextFile:

6|Oklahoma City|Oklahoma|I-35;I-44;I-40
6|Boston|Massachusetts|I-90;I-93
8|Columbus|Ohio|I-70;I-71

I am trying to process the text file and print the data as I like. For example. population

Population,
City, State,
Interstates: I-35,I-40,I-45 (Sorted order)

Body:
Your ReadCities method needs to return some kind of collection of CityItem objects, not just a single CityItem object.  .Net supports various kinds of collections, but a List is probably best for this instance.

Then, after populating your CityItem object, before moving to the next iteration of the loop, add the CityItem object to your List.  Something like...

List<CityItem> listOfCityItems = new List<CityItem>();
foreach (var line in AllLines)
{
    CityItem ci = new CityITem();
    // Populate the properties of ci
    listOfCityItems.Add(ci);
}


问:
Laravel Get Distinct / Unique Records of Day, Week, Month, Year
I am working on a simple dashboard using Laravel which tracks mostly visitors info.
I can't able to write laravel query builder or eloquent code to

Select unique visitors of today

Select unique visitors of this month

select unique visitors of this week

select unique visitors of this year

Here is my DB table columns.

I'm stuck to get unique data if someone can help.

答:
Just write the raw queries and use these.

Today : select distinct id, ip_address, browser from table_name where DATE(visited_time) = CURDATE();

Month : select distinct id, ip_address, browser from table_name where month(visited_time) = month(NOW()) and year(visited_time) = year(NOW());

Week  : select distinct id, ip_address, browser from table_name where week(visited_time) = week(NOW()) and year(visited_time) = year(NOW());

Year  : select distinct id, ip_address, browser from table_name where year(visited_time) = year(NOW());


问:
How do I define callback in Stencil Handlebars
Some is a block helper that returns the block if the callback returns true for some value in the given array.

```<code>{{#some array isString}}
  Render me if the array has a string.
{{else}}
  Render me if it doesn't.
{{/some}}
//=> 'Render me if the array has a string.'
</code>```

How do I define the callback in a a stencil theme

答: In a Stencil theme, the callback function would need to be a helper that exists in Stencil, rather than a function you define. We'll update the docs to note that the callback must be a pre-existing helper.</p>

Body:
Some is a block helper that returns the block if the callback returns true for some value in the given array.

{{#some array isString}}
  Render me if the array has a string.
{{else}}
  Render me if it doesn't.
{{/some}}
//=> 'Render me if the array has a string.'

How do I define the callback in a a stencil theme


问:
How to solve 'java.sql.SQLException: Column count doesn't match value count at row 1' error?
I am a beginner to Java, trying to insert values to the database. Please find the code attached

These two tables I have -

create table user_data(uname varchar(50) ,info varchar(1000),title varchar(100));

create table users ( uname varchar(20), email varchar(20), pswd varchar(20), country varchar(20), state varchar(20), phone_no varchar(20));

public void actionPerformed(ActionEvent e) {

```<code>    if (e.getSource() == encode)
     {

        String s1 = ta.getText();
        //System.out.println(s1);
        String s2 = tf.getText();
        int i=0;
        String[] datas = new String[20];
        for (String line : ta.getText().split("\\n"))
        {
            datas[i]=line ;
            i=i+1;
        }
        StringBuilder strBuilder = new StringBuilder();
        for (int j = 0; j < i; j++) {
           strBuilder.append(datas[j]+'\n');
        }
        String newString = strBuilder.toString();
        //System.out.println(newString);

        String s3 = tf1.getText();

            try
           {
    Connection con=ConnectionProvider.getCon();
    AES a=new AES(newString,s2,0);
    //RSA rs = new RSA(newString);

    PreparedStatement ps=con.prepareStatement("INSERT INTO user_data (uname, info, title) VALUES (?,?,?,?)");
    ps.setString(1, st);
    ps.setString(2, newString);
    ps.setString(3, s3);
    ps.setString(4, s2);
    ps.executeUpdate();

    JOptionPane.showMessageDialog(null,"Database Updated");
    this.dispose();
    new reservations(st);
           }
            catch (Exception ex)
            {
               System.out.println(ex);
           }
     }
    else if(e.getSource()== reset)
    {
        ta.setText("");
        tf.setText("");
        tf1.setText("");
    }
    else{
        this.dispose();
        new reservations(st);
    }
}
</code>```

I am expecting the values to be inserted. Please help me in finding the result.

Thanks in advance.

答:
UserData table has only three parameters but you try to add four values.</p>

```<code>INSERT INTO user_data (uname, info, title) VALUES (?,?,?,?)
</code>```

Body:
I am a beginner to Java, trying to insert values to the database. Please find the code attached

These two tables I have -

create table user_data(uname varchar(50) ,info varchar(1000),title varchar(100));

create table users ( uname varchar(20), email varchar(20), pswd varchar(20), country varchar(20), state varchar(20), phone_no varchar(20));

public void actionPerformed(ActionEvent e) {

    if (e.getSource() == encode)
     {

        String s1 = ta.getText();
        //System.out.println(s1);
        String s2 = tf.getText();
        int i=0;
        String[] datas = new String[20];
        for (String line : ta.getText().split("\\n"))
        {
            datas[i]=line ;
            i=i+1;
        }
        StringBuilder strBuilder = new StringBuilder();
        for (int j = 0; j < i; j++) {
           strBuilder.append(datas[j]+'\n');
        }
        String newString = strBuilder.toString();
        //System.out.println(newString);

        String s3 = tf1.getText();

            try
           {
    Connection con=ConnectionProvider.getCon();
    AES a=new AES(newString,s2,0);
    //RSA rs = new RSA(newString);

    PreparedStatement ps=con.prepareStatement("INSERT INTO user_data (uname, info, title) VALUES (?,?,?,?)");
    ps.setString(1, st);
    ps.setString(2, newString);
    ps.setString(3, s3);
    ps.setString(4, s2);
    ps.executeUpdate();

    JOptionPane.showMessageDialog(null,"Database Updated");
    this.dispose();
    new reservations(st);
           }
            catch (Exception ex)
            {
               System.out.println(ex);
           }
     }
    else if(e.getSource()== reset)
    {
        ta.setText("");
        tf.setText("");
        tf1.setText("");
    }
    else{
        this.dispose();
        new reservations(st);
    }
}

I am expecting the values to be inserted. Please help me in finding the result.

Thanks in advance.

Body:
UserData table has only three parameters but you try to add four values.

INSERT INTO user_data (uname, info, title) VALUES (?,?,?,?)


问:
is there a way to generate all unique permutations of a list of items
I have a list of five attributes, each attribute has five different values. I want to generate the Cartesian product of them and filter all unique permutations.

Some background:

I need them to be my input values to solve a logic puzzle. Where I check rules against them to find the right solution.

from itertools import product

# input
names = ['Dana', 'Ingo', 'Jessica', 'Sören', 'Valerie']
ages = [26, 27, 30, 33, 35]
tops = ['Blouse', 'Poloshirt', 'Pullover', 'Sweatshirt', 'T-Shirt']
colors = ['blue', 'yellow', 'green', 'red', 'black']
sizes = ['XS', 'S', 'M', 'L', 'XL']

all_attributes = [names, ages, tops, colors, sizes]

# cartesian product (superset)
inputs = list(product(*all_attributes))

# the following code you do that...
```

<p>Perhaps a simplified example can make it clear.</p>

<p>Data:</p>

<pre class="lang-py prettyprint-override"><code>[['Dana', 'Ingo'], [26, 27]]
</code>```

Cartesian Product of Data:

[('Dana', 26), ('Dana', 27), ('Ingo', 26), ('Ingo', 27)]
```

<p>What I want:</p>

<pre class="lang-py prettyprint-override"><code>[[('Dana', 26), ('Ingo', 27)],
 [('Dana', 27), ('Ingo', 26)],
 [('Ingo', 26), ('Dana', 27)],
 [('Ingo', 27), ('Dana', 26)]]
</code>```

What I don't want:

[[('Dana', 26), ('Ingo', 26)], ...
```

<p>I don't want multiple occurrences of the same value. The place matters, so it should have permutative character and that for a list of lists with five elements. I guess the output size will be enormous and maybe that isn't possible to compute so it would be nice to specify some place values which are fixed. For example, I Want to set 'Dana' as a first Element name.</p>

<p>Output:</p>

<pre class="lang-py prettyprint-override"><code>[[('Dana', 26), ('Ingo', 27),
 [('Dana', 27), ('Ingo', 26)]]
</code>```

Maybe you can tell me, out of curiosity, what the specific mathematical names for the concepts are, which I need?

The puzzle:

There are five friends (Dana, Ingo, Jessica, Sören, Valerie) waiting in line at the cash register of a shopping center. They are all of different ages (26, 27, 30, 33, 35) and want to buy different tops (Blouse, Poloshirt, Pullover, Sweatshirt, T-Shirt) for themselves. The tops have different colors (blue, yellow, green, red, black) and sizes (XS, S, M, L, XL).

Rules:

The top 'Dana' wants to buy is 'XL'. Behind her (but not directly behind) is someone with a 'black' top.

'Jessica' waits directly in front of a person who wants to buy a 'Poloshirt'.

The second person in line wants to buy a 'yellow' top.

'T-Shirt' isn't 'red'.

'Sören' wants to buy a 'Sweatshirt'. The person who waits directly in front of him is older than the one behind him.

'Ingo' needs a top in size 'L'.

The last person in line is 30 years old.

The oldest person is going to buy the top with the smallest size.

The person who waits directly behind 'Valerie', wants to buy a 'red' top, which is bigger than size 'S'.

The youngest person wants to buy a 'yellow' top.

Jessica is going to buy a 'Blouse'.

The third person waiting in line wants to buy a top of size 'M'.

The 'Poloshirt' is 'red' or 'yellow' or 'green'.

答:
There is a fundamental problem with the approach of using permutations for the type of logic puzzle you have. The issue is not even that there are so many of them that your solver is unlikely to finish in a reasonable amount of time. The issue is that you don't have an automated way of checking the rules against the problem: having all the possibilities in front of you is pointless unless you have a method to verify them.

To address these issues, I have created a project called Puzzle Solvers:

https://github.com/madphysicist/puzzle-solvers

https://pypi.org/project/puzzle-solvers/

https://puzzle-solvers.readthedocs.io/en/latest/

This is a small project that currently contains a single class of interest: puzzle_solvers.elimination.Solver. This class implements most of the operations you need to solve the process-of-elimination type problem presented in your question. All of the logic is documented, and the tutorial is a walkthrough of your exact problem. I will explain the basics here, so you can understand what I did, and perhaps improve it.

Step 1 is to recognize that position in the queue is an attribute just like age, name, etc. That means that the order is not relevant any more.

Step 2 is to recognize that this is a graph problem in disguise. You have 30 nodes: all the possible attributes (six of them) of each of five individuals. The graph starts out almost complete. Only the edges between attributes of a given type are missing, so you start with 375 instead of the complete 435 edges.

The final goal is to have one edge between each class of attribute among five connected components in the graph. The final number of edges is therefore 5 * 15 = 75.

So how do you remove edges? The simple rules like "'T-Shirt' isn't 'red'" are quite straightforward: just remove that edge. Rules like  "The last person in the queue is 30 years old." are simple too, and more profitable in terms of edge removal. All edges between ages that aren't 30 and position 5 are removed, as well as all edges between positions that aren't 5 and age 30. I added a couple of half-baked utility wrappers to check greater than and less than conditions and remove edges that represented impossible combinations.

The most important aspect of the solver is the fact that any time an edge is removed, it completely follows through with all of the logical implications of that operation. Imagine that you have "The 'Poloshirt' is 'red' or 'yellow' or 'green'" and that you have reached a point in your puzzle where none of those three colors is linked to say age 30. That means that whoever is wearing the poloshirt can not be 30 years old. In fact 'Poloshirt' can not have any edges with endpoints that are not shared by those three colors. If you recursively follow through with those inferences, you get a complete solution.

I'm sorry for the shameless plug of my package, but in justification, I did write it just to answer this question.

Body:
I have a list of five attributes, each attribute has five different values. I want to generate the Cartesian product of them and filter all unique permutations.

Some background:

I need them to be my input values to solve a logic puzzle. Where I check rules against them to find the right solution.

from itertools import product

# input
names = ['Dana', 'Ingo', 'Jessica', 'Sören', 'Valerie']
ages = [26, 27, 30, 33, 35]
tops = ['Blouse', 'Poloshirt', 'Pullover', 'Sweatshirt', 'T-Shirt']
colors = ['blue', 'yellow', 'green', 'red', 'black']
sizes = ['XS', 'S', 'M', 'L', 'XL']

all_attributes = [names, ages, tops, colors, sizes]

# cartesian product (superset)
inputs = list(product(*all_attributes))

# the following code you do that...

Perhaps a simplified example can make it clear.

Data:

[['Dana', 'Ingo'], [26, 27]]

Cartesian Product of Data:

[('Dana', 26), ('Dana', 27), ('Ingo', 26), ('Ingo', 27)]

What I want:

[[('Dana', 26), ('Ingo', 27)],
 [('Dana', 27), ('Ingo', 26)],
 [('Ingo', 26), ('Dana', 27)],
 [('Ingo', 27), ('Dana', 26)]]

What I don't want:

[[('Dana', 26), ('Ingo', 26)], ...

I don't want multiple occurrences of the same value. The place matters, so it should have permutative character and that for a list of lists with five elements. I guess the output size will be enormous and maybe that isn't possible to compute so it would be nice to specify some place values which are fixed. For example, I Want to set 'Dana' as a first Element name.

Output:

[[('Dana', 26), ('Ingo', 27),
 [('Dana', 27), ('Ingo', 26)]]

Maybe you can tell me, out of curiosity, what the specific mathematical names for the concepts are, which I need?

The puzzle:

There are five friends (Dana, Ingo, Jessica, Sören, Valerie) waiting in line at the cash register of a shopping center. They are all of different ages (26, 27, 30, 33, 35) and want to buy different tops (Blouse, Poloshirt, Pullover, Sweatshirt, T-Shirt) for themselves. The tops have different colors (blue, yellow, green, red, black) and sizes (XS, S, M, L, XL).

Rules:

The top 'Dana' wants to buy is 'XL'. Behind her (but not directly behind) is someone with a 'black' top.

'Jessica' waits directly in front of a person who wants to buy a 'Poloshirt'.

The second person in line wants to buy a 'yellow' top.

'T-Shirt' isn't 'red'.

'Sören' wants to buy a 'Sweatshirt'. The person who waits directly in front of him is older than the one behind him.

'Ingo' needs a top in size 'L'.

The last person in line is 30 years old.

The oldest person is going to buy the top with the smallest size.

The person who waits directly behind 'Valerie', wants to buy a 'red' top, which is bigger than size 'S'.

The youngest person wants to buy a 'yellow' top.

Jessica is going to buy a 'Blouse'.

The third person waiting in line wants to buy a top of size 'M'.

The 'Poloshirt' is 'red' or 'yellow' or 'green'.


问:
Read file on remote machine in Apache Spark using ftp
I am trying to read a file on an remote machine in Apache Spark (the Scala version) using ftp. Currently, I have followed an example in the Learning Spark repo of Databricks on GitHub. Using curl, I am able to download the file, so the path I uses exists.

Below is a snippet of the code I try to execute:

```<code>var file = sc.textFile("ftp://user:pwd/192.168.1.5/brecht-d-m/map/input.nt")
var fileDF = file.toDF()
fileDF.write.parquet("out")
</code>```

After trying to execute a count on the dataframe, I get following stacktrace (http://pastebin.com/YEq8c2Hf):

```<code>org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
TungstenAggregate(key=[], functions=[(count(1),mode=Final,isDistinct=false)], output=[count#1L])
+- TungstenExchange SinglePartition, None
   +- TungstenAggregate(key=[], functions=[(count(1),mode=Partial,isDistinct=false)], output=[count#4L])
      +- Project
         +- Scan ExistingRDD[_1#0]

...

Caused by: org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: ftp://user:pwd@192.168.1.5/brecht-d-m/map/input.nt
</code>```

I would assume that the file would be unreachable, but this is in contradiction with that I am able to retrieve the file via curl:

```<code>curl ftp://user:pwd@192.168.1.5/brecht-d-m/map/input.nt
</code>```

This will print out the specific file on my terminal. I do not see what I am doing wrong in the Scala code. Is there an error in the code snippet I gave above, or is that code totally wrong?

Thanks in advance,
Brecht

Note:

Specifying the whole path (/home/brecht-d-m/map/input.nt) also does not work (as expected, since this also does not work in curl; "server denied you to change to the given directory"). Trying this in Spark, gives the IOException that seek is not supported (http://pastebin.com/b9EB9ru2).

Working locally (e.g. sc.textFile("/home/brecht-d-m/map/input.nt")) works perfectly.

File permissions for specific file is set to R+W for all users.

The file size (15MB) should not be a problem, and it should be able to handle much bigger files.

Software versions: Scala 2.11.7, Apache Spark 1.6.0, Java 1.8.0_74, Ubuntu 14.04.4

答:
I had the same requirement to fetch remote files using scala. The current answer does not solve the problem for sftp (mostly applicable across companies).

I am using the below scala code to create an inputStream from  the file.
I transform it to String. But we can choose to create rdd / save to filesystem a well.

Sharing this incase someone has to use scala.

Entry to import jsch into build.sbt:

```<code>libraryDependencies += "com.jcraft" % "jsch" % "0.1.55"
</code>```

Now create the below method using jsch built-in classes:

```<code>import com.jcraft.jsch.{ChannelSftp, JSch, JSchException}
      def getRemoteFile: String = {
        val jsch = new JSch()
        try{
          val session = jsch.getSession("devuser", "175.1.6.60", 22)
          session.setConfig("StrictHostKeyChecking", "no")
          session.setPassword("devpassword")
          session.connect()

          val channel = session.openChannel("sftp")
          channel.connect()
          val sftpChannel = channel.asInstanceOf[ChannelSftp]
          val output = sftpChannel.get("/tmp/monitoring/greenplum_space_report.txt")
          val displayAns = scala.io.Source.fromInputStream(output).mkString
          sftpChannel.exit()
          session.disconnect()
          displayAns
        }
        catch {
          case ex : JSchException => ex.printStackTrace().toString
        }
      }
</code>```

Body:
I am trying to read a file on an remote machine in Apache Spark (the Scala version) using ftp. Currently, I have followed an example in the Learning Spark repo of Databricks on GitHub. Using curl, I am able to download the file, so the path I uses exists.

Below is a snippet of the code I try to execute:

var file = sc.textFile("ftp://user:pwd/192.168.1.5/brecht-d-m/map/input.nt")
var fileDF = file.toDF()
fileDF.write.parquet("out")

After trying to execute a count on the dataframe, I get following stacktrace (http://pastebin.com/YEq8c2Hf):

org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
TungstenAggregate(key=[], functions=[(count(1),mode=Final,isDistinct=false)], output=[count#1L])
+- TungstenExchange SinglePartition, None
   +- TungstenAggregate(key=[], functions=[(count(1),mode=Partial,isDistinct=false)], output=[count#4L])
      +- Project
         +- Scan ExistingRDD[_1#0]

...

Caused by: org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: ftp://user:pwd@192.168.1.5/brecht-d-m/map/input.nt

I would assume that the file would be unreachable, but this is in contradiction with that I am able to retrieve the file via curl:

curl ftp://user:pwd@192.168.1.5/brecht-d-m/map/input.nt

This will print out the specific file on my terminal. I do not see what I am doing wrong in the Scala code. Is there an error in the code snippet I gave above, or is that code totally wrong?

Thanks in advance,
Brecht

Note:

Specifying the whole path (/home/brecht-d-m/map/input.nt) also does not work (as expected, since this also does not work in curl; "server denied you to change to the given directory"). Trying this in Spark, gives the IOException that seek is not supported (http://pastebin.com/b9EB9ru2).

Working locally (e.g. sc.textFile("/home/brecht-d-m/map/input.nt")) works perfectly.

File permissions for specific file is set to R+W for all users.

The file size (15MB) should not be a problem, and it should be able to handle much bigger files.

Software versions: Scala 2.11.7, Apache Spark 1.6.0, Java 1.8.0_74, Ubuntu 14.04.4

Body:
I had the same requirement to fetch remote files using scala. The current answer does not solve the problem for sftp (mostly applicable across companies).

I am using the below scala code to create an inputStream from  the file.
I transform it to String. But we can choose to create rdd / save to filesystem a well.

Sharing this incase someone has to use scala.

Entry to import jsch into build.sbt:

libraryDependencies += "com.jcraft" % "jsch" % "0.1.55"

Now create the below method using jsch built-in classes:

import com.jcraft.jsch.{ChannelSftp, JSch, JSchException}
      def getRemoteFile: String = {
        val jsch = new JSch()
        try{
          val session = jsch.getSession("devuser", "175.1.6.60", 22)
          session.setConfig("StrictHostKeyChecking", "no")
          session.setPassword("devpassword")
          session.connect()

          val channel = session.openChannel("sftp")
          channel.connect()
          val sftpChannel = channel.asInstanceOf[ChannelSftp]
          val output = sftpChannel.get("/tmp/monitoring/greenplum_space_report.txt")
          val displayAns = scala.io.Source.fromInputStream(output).mkString
          sftpChannel.exit()
          session.disconnect()
          displayAns
        }
        catch {
          case ex : JSchException => ex.printStackTrace().toString
        }
      }


问:
How can I generate translation files if the kendo-ui uses English expressions by default but I'm using another language in my app?
I'm trying to integrate i18n to my angular7 application. It uses kendo-ui too.
Kendo-ui templates contains English expressions, but my app code contains Hungarian expressions.
If I generate the messages.xlf file with the ng xi18n --output-path translate, the generated file will contain the English expressions from kendo-ui and the Hungarian expressions from my app.

What could be the proper way to generate the messages.xlf?

答:
I was wrong because not necessary to use angular i18n for Kenod-UI translations.
The MessageService was perfect for me: https://www.telerik.com/kendo-angular-ui/components/globalization/localization/messages/#toc-using-the-message-service

So I kept the original ngx-translate solution in my app code and I've added a new provider (the implementation of MessageService) which resolves the translations from Kendo-UI.

This is the code of my MessagesService:

```<code>export class KendoMessageService extends MessageService {
  constructor(private translateService: TranslateService) {}

  public get(key: string): string {
    const resolvedValue = this.translateService.instant(key);
    return resolvedValue !== key ? resolvedValue : void 0;
  }
}
</code>```

Body:
I was wrong because not necessary to use angular i18n for Kenod-UI translations.
The MessageService was perfect for me: https://www.telerik.com/kendo-angular-ui/components/globalization/localization/messages/#toc-using-the-message-service

So I kept the original ngx-translate solution in my app code and I've added a new provider (the implementation of MessageService) which resolves the translations from Kendo-UI.

This is the code of my MessagesService:

export class KendoMessageService extends MessageService {
  constructor(private translateService: TranslateService) {}

  public get(key: string): string {
    const resolvedValue = this.translateService.instant(key);
    return resolvedValue !== key ? resolvedValue : void 0;
  }
}


问:
Perl convert microseconds since epoch to localtime
In perl, given microseconds since epoch how do I convert to localtime in a format like </p>

```<code>my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;
</code>```

<p>Eg: "Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750" </p>

答:
The core Time::Piece can do the conversion, but it doesn't handle subseconds so you'd need to handle those yourself.

```<code>use strict;
use warnings;
use Time::Piece;
my $input = '1555329743301750';
my ($sec, $usec) = $input =~ m/^([0-9]*)([0-9]{6})$/;
my $time = localtime($sec);
print $time->strftime('%H%M%S') . ".$usec\n";
</code>```

Time::Moment provides a nicer option for dealing with subseconds, but needs some help to find the UTC offset for the arbitrary time in system local time, we can use Time::Moment::Role::TimeZone.

```<code>use strict;
use warnings;
use Time::Moment;
use Role::Tiny ();
my $input = '1555329743301750';
my $sec = $input / 1000000;
my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
my $time = $class->from_epoch($sec, precision => 6)->with_system_offset_same_instant;
print $time->strftime('%H%M%S%6f'), "\n";
</code>```

Finally, DateTime is a bit heavier but can handle everything naturally, at least to microsecond precision.

```<code>use strict;
use warnings;
use DateTime;
my $input = '1555329743301750';
my $sec = $input / 1000000;
my $time = DateTime->from_epoch(epoch => $sec, time_zone => 'local');
print $time->strftime('%H%M%S.%6N'), "\n";
</code>```

(To avoid possible floating point issues, you could replace my $sec = $input / 1000000 with substr(my $sec = $input, -6, 0, '.') so it's purely a string operation until it goes to the module, if you are sure it will be in that string form - but it's unlikely to be an issue at this scale.)

Body:
In perl, given microseconds since epoch how do I convert to localtime in a format like

my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;

Eg: "Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750"

Body:
The core Time::Piece can do the conversion, but it doesn't handle subseconds so you'd need to handle those yourself.

use strict;
use warnings;
use Time::Piece;
my $input = '1555329743301750';
my ($sec, $usec) = $input =~ m/^([0-9]*)([0-9]{6})$/;
my $time = localtime($sec);
print $time->strftime('%H%M%S') . ".$usec\n";

Time::Moment provides a nicer option for dealing with subseconds, but needs some help to find the UTC offset for the arbitrary time in system local time, we can use Time::Moment::Role::TimeZone.

use strict;
use warnings;
use Time::Moment;
use Role::Tiny ();
my $input = '1555329743301750';
my $sec = $input / 1000000;
my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
my $time = $class->from_epoch($sec, precision => 6)->with_system_offset_same_instant;
print $time->strftime('%H%M%S%6f'), "\n";

Finally, DateTime is a bit heavier but can handle everything naturally, at least to microsecond precision.

use strict;
use warnings;
use DateTime;
my $input = '1555329743301750';
my $sec = $input / 1000000;
my $time = DateTime->from_epoch(epoch => $sec, time_zone => 'local');
print $time->strftime('%H%M%S.%6N'), "\n";

(To avoid possible floating point issues, you could replace my $sec = $input / 1000000 with substr(my $sec = $input, -6, 0, '.') so it's purely a string operation until it goes to the module, if you are sure it will be in that string form - but it's unlikely to be an issue at this scale.)


问:
Jest/Enzyme - TypeError: div.find is not a function
Below is a a little test file that I made for a React project that is using both Jest and Enzyme for testing. In this test, I'm simply trying to find an element in the component and see that it exists (as a truthy conditional). The whole point of this test wasn't just to see if the element existed, but I figured I'd start here. I'm very new to testing, so this syntax/implementation may be bonkers:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('my first test -- will add better text here later', () => {
  const div = document.createElement('div');
  ReactDOM.render(<HamburgerIcon />, div);

  expect(div.find('.closed').exists()).toBeTruthy();

  ReactDOM.unmountComponentAtNode(div);
});
</code>```

Running this results in this error:

TypeError: div.find is not a function

I originally built this test after seeing this Stack Overflow answer.

I'm not sure how to troubleshoot this, but I'm guessing that maybe I haven't properly "mounted" the component in this test? In the same Stack Overflow thread from the previous link, this answer shows how you would mount a component, but another comment on that answer says that another package needs to be installed in order to do that.

I sort of figured that using the div variable as the container to be searched with find would work, but am I wrong in thinking that?

答:
Here's the sample code for you, may not be 100% what you need but should get you started. I also included console.log so that you know what gets rendered.

To explain a bit on what happens, is in your test case you are calling shallow method and passing your React component to it to render. Test cases are run in virtual browser/renderer not the real browser (unless you configure it that way).

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('my first test -- will add better text here later', () => {
  const wrapper = shallow(<HamburgerIcon />);
  console.log(wrapper);
  expect(wrapper.find('.closed').exists()).toBeTruthy();
});
</code>```

Body:
Below is a a little test file that I made for a React project that is using both Jest and Enzyme for testing. In this test, I'm simply trying to find an element in the component and see that it exists (as a truthy conditional). The whole point of this test wasn't just to see if the element existed, but I figured I'd start here. I'm very new to testing, so this syntax/implementation may be bonkers:

import React from 'react';
import ReactDOM from 'react-dom';

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('my first test -- will add better text here later', () => {
  const div = document.createElement('div');
  ReactDOM.render(<HamburgerIcon />, div);

  expect(div.find('.closed').exists()).toBeTruthy();

  ReactDOM.unmountComponentAtNode(div);
});

Running this results in this error:

TypeError: div.find is not a function

I originally built this test after seeing this Stack Overflow answer.

I'm not sure how to troubleshoot this, but I'm guessing that maybe I haven't properly "mounted" the component in this test? In the same Stack Overflow thread from the previous link, this answer shows how you would mount a component, but another comment on that answer says that another package needs to be installed in order to do that.

I sort of figured that using the div variable as the container to be searched with find would work, but am I wrong in thinking that?

Body:
Here's the sample code for you, may not be 100% what you need but should get you started. I also included console.log so that you know what gets rendered.

To explain a bit on what happens, is in your test case you are calling shallow method and passing your React component to it to render. Test cases are run in virtual browser/renderer not the real browser (unless you configure it that way).

import React from 'react';
import ReactDOM from 'react-dom';

import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('my first test -- will add better text here later', () => {
  const wrapper = shallow(<HamburgerIcon />);
  console.log(wrapper);
  expect(wrapper.find('.closed').exists()).toBeTruthy();
});


问:
Trouble calling C++ code from MATLAB 2016 using a helper C file w/MEX Wrapper
I need to call a C++ non-member function from MATLAB 2016. MATLAB did not support C++ MEX until 2018, so this poses an issue.

I am doing this in Windows under mingw64.

To get around this, I attempted to make a C file with a MEX wrapper, with the C implementation purely just calling the C++ function using a shared header file with extern "C" based on some advice online.

However, I am very new to MATLAB, calling C++ from C and some other concepts here. So nothing compiles properly whatsoever.

Any advice on properly approaching this is greatly appreciated.

The header file myFunc.h:

```<code>#ifndef CPP_H
#define CPP_H

#ifdef __cplusplus
void myFunc(const std::vector<myStruct>& a,
            const std::vector<myStruct>& b,
            const double c,
            std::vector<std::pair>& d,
            mxArray **e
            );
extern "C" {
#endif
void myFunc(const std::vector<myStruct>& a,
            const std::vector<myStruct>& b,
            const double c,
            std::vector<std::pair>& d,
            mxArray **e
            );
#ifdef __cplusplus
}
#endif

#endif
</code>```

The C file to call it, myFuncCaller.c:

```<code>#include "myFunc.h"
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    myFunc(prhs[0], prhs[1], prhs[2], prhs[3], prhs[4]);
}
</code>```

The actual implementation:myFunc.cpp:

```<code>#include "myFunc.h"

void myFunc(const std::vector<myStruct>& a,
            const std::vector<myStruct>& b,
            const double c,
            std::vector<std::pair>& d,
            mxArray **e
            )
{
  //things done here, pushes results to d
}
</code>```

The end result of trying to compile both of these is that:

the C file doesn't see mex.h (unsure why, as MATLAB claims that mingw is complaint)

the header file is likely all wrong, and claims that "type defaults to int in declaration of std". I'm assuming it's because I have some C++-related things in a C section. I'm not sure how to approach this.

The C++ file complains the most. I could post all the errors, but I don't think it would be productive considering there's likely a fundamental flaw in my logic.

One large hurdle is the approach of passing input arguments from MATLAB -> C -> C++. I don't want things to be "lost" and ideally don't want to do conversion unless necessary, and I'm not sure where that would be.

答:
You cannot put std::vector<> in an extern "C" section, as it's not valid C syntax. You need to create a pure C function stub, compiled as C++, that calls the C++ function.

But, you don't need to do any of that because you can compile a C++ MEX-file just fine. The API is C, but you can call C functions from C++ without problem.

The actual problem in your mexFunction is that you pass pointers to mxArray objects where the function expects references to std::vector<> etc. The only way to do this right is to copy the data from the MATLAB array into a C++ vector:

#include "myFunc.h"
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
   if (nrhs < 5) {
      mexErrMsgTxt("Not enough input arguments! 5 expected.");
   }

   // arg 1: std::vector<myStruct>
   if (!mxIsDouble(prhs[0])) {
      mexErrMsgTxt("First input argument must be a double array.");
   }
   std::size_t N = mxGetNumberOfElements(prhs[0]);
   double* pr = mxGetPr(prhs[0]);
   std::vector<myStruct> a(N);
   std::copy(pr, pr+N, a.begin());

   // arg 2: std::vector<myStruct>
   std::vector<myStruct> b;
   // ...

   // arg 3: double
   double c = mxGetScalar(prhs[2]);

   // arg 4: std::vector<std::pair> // This makes no sense in C++, std::pair<> is a template, 2 template arguments missing!!
   std::vector<std::pair> d;
   // ...

   // arg 5: mxArray **  // is this the output? Why does your C++ function take an mxArray?

   myFunc(a, b, c, d, &prhs[4]);
}
```

Body:
I need to call a C++ non-member function from MATLAB 2016. MATLAB did not support C++ MEX until 2018, so this poses an issue.

I am doing this in Windows under mingw64.

To get around this, I attempted to make a C file with a MEX wrapper, with the C implementation purely just calling the C++ function using a shared header file with extern "C" based on some advice online.

However, I am very new to MATLAB, calling C++ from C and some other concepts here. So nothing compiles properly whatsoever.

Any advice on properly approaching this is greatly appreciated.

The header file myFunc.h:

#ifndef CPP_H
#define CPP_H

#ifdef __cplusplus
void myFunc(const std::vector<myStruct>& a,
            const std::vector<myStruct>& b,
            const double c,
            std::vector<std::pair>& d,
            mxArray **e
            );
extern "C" {
#endif
void myFunc(const std::vector<myStruct>& a,
            const std::vector<myStruct>& b,
            const double c,
            std::vector<std::pair>& d,
            mxArray **e
            );
#ifdef __cplusplus
}
#endif

#endif

The C file to call it, myFuncCaller.c:

#include "myFunc.h"
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    myFunc(prhs[0], prhs[1], prhs[2], prhs[3], prhs[4]);
}

The actual implementation:myFunc.cpp:

#include "myFunc.h"

void myFunc(const std::vector<myStruct>& a,
            const std::vector<myStruct>& b,
            const double c,
            std::vector<std::pair>& d,
            mxArray **e
            )
{
  //things done here, pushes results to d
}

The end result of trying to compile both of these is that:

the C file doesn't see mex.h (unsure why, as MATLAB claims that mingw is complaint)

the header file is likely all wrong, and claims that "type defaults to int in declaration of std". I'm assuming it's because I have some C++-related things in a C section. I'm not sure how to approach this.

The C++ file complains the most. I could post all the errors, but I don't think it would be productive considering there's likely a fundamental flaw in my logic.

One large hurdle is the approach of passing input arguments from MATLAB -> C -> C++. I don't want things to be "lost" and ideally don't want to do conversion unless necessary, and I'm not sure where that would be.


问:
Angular5: Hide ag-gird rows based on condition
I have the below response from the service, when ever the flag is true I have to hide the whole row (total 20 columns I have) else show it. How can I achieve this in ag-grid?

```<code>data = {
    name: "A",
    flag: true
   },
   {
    name: "B",
    flag: false
   },
   {
    name: "C",
    flag: false
   }
</code>```

I did try the useExternalFilter like below and then I got stuck as to how to use this useExternalFilter further. Can any one please guide me through.

```<code>this.filterOptions = {
  useExternalFilter: true
};

this.gridOptions = {
  filterOptions:  this.filterOptions
 };
</code>```

答:
what you want is this:

```<code>this.gridOptions = {
  // is always present, so return true
  isExternalFilterPresent: function() {
    return true;
  },

  // return true if flag=true
  doesExternalFilterPass: function(rowNode) {
    return rowNode.data.flag;
  }
};
</code>```

see ag-Grid Docs for more details

Body:
I have the below response from the service, when ever the flag is true I have to hide the whole row (total 20 columns I have) else show it. How can I achieve this in ag-grid?

data = {
    name: "A",
    flag: true
   },
   {
    name: "B",
    flag: false
   },
   {
    name: "C",
    flag: false
   }

I did try the useExternalFilter like below and then I got stuck as to how to use this useExternalFilter further. Can any one please guide me through.

this.filterOptions = {
  useExternalFilter: true
};

this.gridOptions = {
  filterOptions:  this.filterOptions
 };

Body:
what you want is this:

this.gridOptions = {
  // is always present, so return true
  isExternalFilterPresent: function() {
    return true;
  },

  // return true if flag=true
  doesExternalFilterPass: function(rowNode) {
    return rowNode.data.flag;
  }
};

see ag-Grid Docs for more details


问:
Sum of two arrays
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

```<code>#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}
</code>```

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

答:
change the function summary signature (the definition part of the declaration) to this and try it out:

void sumarray(int k,int* A,int* B){

Title: Sum of two arrays

Body:
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).