答:
From the git submodule docs for foreach...

A non-zero return from the command in any submodule causes the processing to terminate. This can be overridden by adding || : to the end of the command.

It says to keep processing submodules even if the command fails on one of them.

If you're familiar with make, it's similar to putting a - at the front of a command then make will then ignore any errors from that command.

Title: git command "git checkout master || :"


来源: stackexchange

问:
TypeError: <lambda>() missing 1 required positional argument:
I'm trying to populate my Django project with some random data using factory_boy and faker. However, when I try to create an instance of my UserFactory object I'm getting the error TypeError: () missing 1 required positional argument: 'a'.

It seems to have something to do with the fake_date and date_joined attributes and their lambda functions. A couple of the tutorials I've found have laid out using lambda functions in this way for the Factory objects but it isn't working for me.

```<code>import datetime
import factory
import faker
from dataStoreApp.models import Category, Goal, Transaction
from django.contrib.auth.models import User

fake = faker.Faker()

class CategoryFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Category

    name = factory.Iterator(['Category1', 'Category2',
                             'Category3', 'Category4',
                             'Category5', ], cycle=False)

class UserFactory(factory.django.DjangoModelFactory):
    FACTORY_HIDDEN_ARGS = ('fake_date', )

    class Meta:
        model = User

    fake_date = factory.LazyAttribute(
    lambda a: datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    date_joined = factory.LazyFunction(lambda a: a.fake_date)
    first_name = factory.LazyAttribute(lambda b: fake.first_name())
    last_name = factory.LazyAttribute(lambda c: fake.last_name())
    email = factory.LazyAttribute(lambda e: 'test' + '@test_email.com')

class GoalFactory(factory.DjangoModelFactory):
    class Meta:
        model = Goal

class TransactionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Transaction
</code>```

When running in the python console I get the following errors:

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 568, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 505, in _generate
    return step.build()
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 272, in build
    step.resolve(pre)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 221, in resolve
    self.attributes[field_name] = getattr(self.stub, field_name)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 363, in __getattr__
    extra=declaration.context,
  File "C:\Program Files\Python36\lib\site-packages\factory\declarations.py", line 59, in evaluate
    return self.function()
TypeError: <lambda>() missing 1 required positional argument: 'a'
</code>```

答:
You create function with argument a in code

```<code>lambda a: ....
</code>```

but it seems program expects function without arguments

```<code>lambda: ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to populate my Django project with some random data using factory_boy and faker. However, when I try to create an instance of my UserFactory object I'm getting the error TypeError: () missing 1 required positional argument: 'a'.

It seems to have something to do with the fake_date and date_joined attributes and their lambda functions. A couple of the tutorials I've found have laid out using lambda functions in this way for the Factory objects but it isn't working for me.

import datetime
import factory
import faker
from dataStoreApp.models import Category, Goal, Transaction
from django.contrib.auth.models import User

fake = faker.Faker()

class CategoryFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Category

    name = factory.Iterator(['Category1', 'Category2',
                             'Category3', 'Category4',
                             'Category5', ], cycle=False)

class UserFactory(factory.django.DjangoModelFactory):
    FACTORY_HIDDEN_ARGS = ('fake_date', )

    class Meta:
        model = User

    fake_date = factory.LazyAttribute(
    lambda a: datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    date_joined = factory.LazyFunction(lambda a: a.fake_date)
    first_name = factory.LazyAttribute(lambda b: fake.first_name())
    last_name = factory.LazyAttribute(lambda c: fake.last_name())
    email = factory.LazyAttribute(lambda e: 'test' + '@test_email.com')

class GoalFactory(factory.DjangoModelFactory):
    class Meta:
        model = Goal

class TransactionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Transaction

When running in the python console I get the following errors:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 568, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 505, in _generate
    return step.build()
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 272, in build
    step.resolve(pre)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 221, in resolve
    self.attributes[field_name] = getattr(self.stub, field_name)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 363, in __getattr__
    extra=declaration.context,
  File "C:\Program Files\Python36\lib\site-packages\factory\declarations.py", line 59, in evaluate
    return self.function()
TypeError: <lambda>() missing 1 required positional argument: 'a'

Body:
You create function with argument a in code

lambda a: ....

but it seems program expects function without arguments

lambda: ...


问:
Python-PDB automatically raise BdbQuit
I have been using pdb.set_trace() to set some breakpoints in my codes, and always it was smooth.

I have a shell script that run a python script inside a loop:

```<code>cat $file1 | (
#read something from file1
while ...
do
   if ... then
      cat $file2 | (
      # read something from file2
      while ...
          do
               python test.py
               # read something from file2
          done)
   fi
   #read something from file1
done)
</code>```

Assume that test.py is just a simple hello world. I put pdb.set_trace() in my python script. When I run the code outside the loop, simply by python test.py, everything is ok. However, when I execute the .sh script, the moment that it gets to the pdb.set_trace(), it raises a BdbQuit and quite my python script.

I could not realize what the problem is. I really appreciate if anyone can help me to figure this out.

Thank you.

答:
You are redirecting stdin inside the while loop:

```<code>cat $file1 | while ...
</code>```

The interactive pdb prompt reads from stdin as well, but since it's been redirected, it's just going to take input from that file.

The easiest solution in this case is just to use something like remote-pdb, which opens up a network connection to which you can connect using e.g. telnet or nc.

Title: Python-PDB automatically raise BdbQuit

Body:
I have been using pdb.set_trace() to set some breakpoints in my codes, and always it was smooth.

I have a shell script that run a python script inside a loop:

cat $file1 | (
#read something from file1
while ...
do
   if ... then
      cat $file2 | (
      # read something from file2
      while ...
          do
               python test.py
               # read something from file2
          done)
   fi
   #read something from file1
done)

Assume that test.py is just a simple hello world. I put pdb.set_trace() in my python script. When I run the code outside the loop, simply by python test.py, everything is ok. However, when I execute the .sh script, the moment that it gets to the pdb.set_trace(), it raises a BdbQuit and quite my python script.

I could not realize what the problem is. I really appreciate if anyone can help me to figure this out.

Thank you.

Body:
You are redirecting stdin inside the while loop:

cat $file1 | while ...

The interactive pdb prompt reads from stdin as well, but since it's been redirected, it's just going to take input from that file.

The easiest solution in this case is just to use something like remote-pdb, which opens up a network connection to which you can connect using e.g. telnet or nc.


问:
Elixir: application quits immediately, or doesn't receive input when running distillery package. Why does it work that way, and how to work around it?
I have an Elixir application that is structured the following way:

```<code>Application --> Supervisor --> Worker
</code>```

The Application Module is fairly simple, it has a use Application and a

```<code>def start(_type, _args)
  MyApp.Supervisor.start_link()
end
</code>```

The Supervisor is a bit more complicated:

```<code>def start_link() do
    {:ok, pid} = Supervisor.start_link(__MODULE__, [], name: __MODULE__)
    halt_exit(wait_for_child())
    {:ok, pid}
end

def init(data) do
    children =
    [
        worker(MyApp.Worker, [], restart: :transient)
    ]

    Supervisor.init(children, [strategy: :one_for_one])
end
</code>```

where halt_exit(pid) performs a Process.sleep(100) and then calls itself every time it finds the process pid is still alive (or simply returns nil when pid is not alive anymore), and wait_for_child finds the Worker module's pid (taking into consideration that it might have to wait until it's started).

My Worker module interacts with the user using IO.puts and IO.gets. Why all this complicated unnecessary logic? It seems that

when using mix run and omit halting exit, the application immediately dies

when using mix release (distillery) and run myapp.bat console from cmd and omit halting exit, my application starts, immediately dies, and then iex is started

when using mix release w/ myapp.bat console and include halting exit, my app outputs correctly, but can't receive any input (and by this I mean I can't type into the window of werl.exe)

when using mix release w/ myapp.bat foreground, my app starts and only then there is an error in the batch file (The system cannot find the file `%get_pid_cmd%`.
ERROR: The search filter cannot be recognised.
'@call' is not recognized as an internal or external command,
operable program or batch file.) at which point my app terminates.

when using mix run --no-halt (no exit-halting logic inside app), my app starts, terminates immediately, and the erlang VM remains running in the cmd window

only when I mix run and include halt_exit/1 does my app works as expected

From all this, I concluded that 1) the moment my application module's start/2 returns, the app is shut down, which doesn't make much sense as Elixir is designed for applications that put the load on other processes instead of, not besides the application's main module. 2) input is done through the main Application module's process (but for some reason only when run in a separate werl.exe window, seems to work fine with mix run), so I can't put any blocking-until-work-finished logic there if I want my user input.

How can I solve this, and equally importantly (so I can avoid future problems) what behaviour causes my problem? I would need to be able to run this on a computer without mix and Erlang VM installed, so my only option is to make it work with the distillery package generated, which at the moment I can't.

No amount of googling has led me to similar tactics to artificially halt exit, and no forum/tutorial I've found mentions problems with this "early-exit" so I guess the correct way to solve this would be to somehow get it not want to exit while any process is running.

答:
The system cannot find the file %get_pid_cmd%. ERROR: The search filter cannot be recognised

In the following line:

```<code>@for /f "delims=" %%i in (`%%get_pid_cmd%%`) do set pid=%%i
</code>```

Try changing the backticks around %%get_pid_cmd%% to single quotes.

Also, in the following line:

```<code>set get_pid_cmd=%escript% %nodetool% eval %node_type% %node_name% -setcookie "!cookie!" "erlang:list_to_integer(os:getpid()).'
</code>```

Change the final single quote to a double quote.

Source: https://www.bountysource.com/issues/50408118-starting-in-foreground-mode-on-windows-fails-to-get-pid-and-returns-errorlevel-1

Making these two changes in boot_win.eex, deleting the _build folder, and rebuilding worked for me.

Body:
I have an Elixir application that is structured the following way:

Application --> Supervisor --> Worker

The Application Module is fairly simple, it has a use Application and a

def start(_type, _args)
  MyApp.Supervisor.start_link()
end

The Supervisor is a bit more complicated:

def start_link() do
    {:ok, pid} = Supervisor.start_link(__MODULE__, [], name: __MODULE__)
    halt_exit(wait_for_child())
    {:ok, pid}
end

def init(data) do
    children =
    [
        worker(MyApp.Worker, [], restart: :transient)
    ]

    Supervisor.init(children, [strategy: :one_for_one])
end

where halt_exit(pid) performs a Process.sleep(100) and then calls itself every time it finds the process pid is still alive (or simply returns nil when pid is not alive anymore), and wait_for_child finds the Worker module's pid (taking into consideration that it might have to wait until it's started).

My Worker module interacts with the user using IO.puts and IO.gets. Why all this complicated unnecessary logic? It seems that

when using mix run and omit halting exit, the application immediately dies

when using mix release (distillery) and run myapp.bat console from cmd and omit halting exit, my application starts, immediately dies, and then iex is started

when using mix release w/ myapp.bat console and include halting exit, my app outputs correctly, but can't receive any input (and by this I mean I can't type into the window of werl.exe)

when using mix release w/ myapp.bat foreground, my app starts and only then there is an error in the batch file (The system cannot find the file `%get_pid_cmd%`.
ERROR: The search filter cannot be recognised.
'@call' is not recognized as an internal or external command,
operable program or batch file.) at which point my app terminates.

when using mix run --no-halt (no exit-halting logic inside app), my app starts, terminates immediately, and the erlang VM remains running in the cmd window

only when I mix run and include halt_exit/1 does my app works as expected

From all this, I concluded that 1) the moment my application module's start/2 returns, the app is shut down, which doesn't make much sense as Elixir is designed for applications that put the load on other processes instead of, not besides the application's main module. 2) input is done through the main Application module's process (but for some reason only when run in a separate werl.exe window, seems to work fine with mix run), so I can't put any blocking-until-work-finished logic there if I want my user input.

How can I solve this, and equally importantly (so I can avoid future problems) what behaviour causes my problem? I would need to be able to run this on a computer without mix and Erlang VM installed, so my only option is to make it work with the distillery package generated, which at the moment I can't.

No amount of googling has led me to similar tactics to artificially halt exit, and no forum/tutorial I've found mentions problems with this "early-exit" so I guess the correct way to solve this would be to somehow get it not want to exit while any process is running.

Body:
The system cannot find the file %get_pid_cmd%. ERROR: The search filter cannot be recognised

In the following line:

@for /f "delims=" %%i in (`%%get_pid_cmd%%`) do set pid=%%i

Try changing the backticks around %%get_pid_cmd%% to single quotes.

Also, in the following line:

set get_pid_cmd=%escript% %nodetool% eval %node_type% %node_name% -setcookie "!cookie!" "erlang:list_to_integer(os:getpid()).'

Change the final single quote to a double quote.

Source: https://www.bountysource.com/issues/50408118-starting-in-foreground-mode-on-windows-fails-to-get-pid-and-returns-errorlevel-1

Making these two changes in boot_win.eex, deleting the _build folder, and rebuilding worked for me.


问:
Change the color of the input line in the alert Dialog
I need to change the color of the edit text line, in the alert dialog, I'm trying everything, and I'm not working.

```<code>public void alertaComentario()
    {
        AlertDialog.Builder comentario = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        comentario.setMessage("Escreva uma resenha curta");
        final EditText input = new EditText(getActivity());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        comentario.setView(input);

        comentario.setPositiveButton("Enviar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "A sociedade agradece seu comentário", Toast.LENGTH_SHORT).show();
            }
        });
        comentario.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        comentario.show();
    }
</code>```

alert dialog

答:
The line in an editText is usually based on the ColorAccent in the colors.xml:

```<code><resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color> //Change this
</code>```

If you change the color accent, it will change editText color.

Body:
I need to change the color of the edit text line, in the alert dialog, I'm trying everything, and I'm not working.

public void alertaComentario()
    {
        AlertDialog.Builder comentario = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        comentario.setMessage("Escreva uma resenha curta");
        final EditText input = new EditText(getActivity());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        comentario.setView(input);

        comentario.setPositiveButton("Enviar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "A sociedade agradece seu comentário", Toast.LENGTH_SHORT).show();
            }
        });
        comentario.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        comentario.show();
    }

alert dialog

Body:
The line in an editText is usually based on the ColorAccent in the colors.xml:

<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color> //Change this

If you change the color accent, it will change editText color.


问:
How to write linq to get most recent incoming event records
var events = context.Events.........

Events has a property 'DueDate' (Datetime)

I want to select most recent 5 records, how to write such a query? Thanks

答:
If you are interested in the Events that are closest to day you could do this:

```<code>DateTime today = DateTime.Now;
var events = context.Events
                    .OrderBy(e => Math.Abs((today - e.DueDate).Days))
                    .Take(5)
                    .ToList();
</code>```

This takes the events that are the least number of days away from today (in the past OR future).

If you wanted events that are most recent but only in the future, you could do:

```<code>DateTime today = DateTime.Now;
var events = context.Events
                    .Where(e => e.DueDate >= today)
                    .OrderBy(e => (e.DueDate - today).Days)
                    .Take(5)
                    .ToList();
</code>```

Edit:

If you use LINQ to Entities DateTime manipulation is not directly supported, but if you use SQL server something like DateDiff should work (untested you'll have to try out yourself):

```<code>DateTime today = DateTime.Now;
var events = context.Events
                    .Where(e => e.DueDate >= today)
                    .OrderBy(e => System.Data.Objects.SqlClient.SqlFunctions.DateDiff("d", e.DueDate, today))
                    .Take(5)
                    .ToList();
</code>```

If that doesn't work you can always get your data first, then filter with LINQ to objects, which has the added benefits that you're not tying yourself to SQL Server - but obviously it's not very efficient:

```<code>DateTime today = DateTime.Now;
var futureEvents = context.Events
                          .Where(e => e.DueDate >= today);
                          .ToList();

var filteredEvent = futureEvents
                    .OrderBy(e => (e.DueDate - today).Days)
                    .Take(5)
                    .ToList();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you are interested in the Events that are closest to day you could do this:

DateTime today = DateTime.Now;
var events = context.Events
                    .OrderBy(e => Math.Abs((today - e.DueDate).Days))
                    .Take(5)
                    .ToList();

This takes the events that are the least number of days away from today (in the past OR future).

If you wanted events that are most recent but only in the future, you could do:

DateTime today = DateTime.Now;
var events = context.Events
                    .Where(e => e.DueDate >= today)
                    .OrderBy(e => (e.DueDate - today).Days)
                    .Take(5)
                    .ToList();

Edit:

If you use LINQ to Entities DateTime manipulation is not directly supported, but if you use SQL server something like DateDiff should work (untested you'll have to try out yourself):

DateTime today = DateTime.Now;
var events = context.Events
                    .Where(e => e.DueDate >= today)
                    .OrderBy(e => System.Data.Objects.SqlClient.SqlFunctions.DateDiff("d", e.DueDate, today))
                    .Take(5)
                    .ToList();

If that doesn't work you can always get your data first, then filter with LINQ to objects, which has the added benefits that you're not tying yourself to SQL Server - but obviously it's not very efficient:

DateTime today = DateTime.Now;
var futureEvents = context.Events
                          .Where(e => e.DueDate >= today);
                          .ToList();

var filteredEvent = futureEvents
                    .OrderBy(e => (e.DueDate - today).Days)
                    .Take(5)
                    .ToList();


问:
tf.image.sample_distorted_bounding_box ValueError
I am trying to augment existing labeled bounding boxed image for making more object detection training data using the function tf.image.sample_distorted_bounding_box but I keep getting these errors found here.  I'm pretty sure my bounding box is set correctly because it works when I draw the bounding box.

```<code>img = mpimg.imread('bPawn0.jpg')
img = img.reshape(1,300,300,3)
boxes = [100,88,253,209]
box = np.ones([1,1,4])
for i in range(4):
    box[:,:,i] = boxes[i]/300
box = tf.convert_to_tensor(box, np.float32)

begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(tf.shape(img),bounding_boxes=box)

ValueError: Tried to convert 'min_object_covered' to a tensor and failed. Error: None values not supported.
</code>```

Any suggestions as to what I am doing wrong here?

答:
I'm wondering if this is a bug in the sample_distorted_bounding_box() code, since I don't see a test that doesn't specify that argument to the function explicitly.

Can you try setting that argument explicitly, something like this?

```<code>sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(
    tf.shape(image),
    bounding_boxes=bbox,
    min_object_covered=0.1,
    aspect_ratio_range=[0.75, 1.33],
    area_range=[0.05, 1.0],
    max_attempts=100,
    use_image_if_no_bounding_boxes=True)
</code>```

https://github.com/tensorflow/models/blob/master/research/inception/inception/image_processing.py#L235

Body:
I am trying to augment existing labeled bounding boxed image for making more object detection training data using the function tf.image.sample_distorted_bounding_box but I keep getting these errors found here.  I'm pretty sure my bounding box is set correctly because it works when I draw the bounding box.

img = mpimg.imread('bPawn0.jpg')
img = img.reshape(1,300,300,3)
boxes = [100,88,253,209]
box = np.ones([1,1,4])
for i in range(4):
    box[:,:,i] = boxes[i]/300
box = tf.convert_to_tensor(box, np.float32)

begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(tf.shape(img),bounding_boxes=box)

ValueError: Tried to convert 'min_object_covered' to a tensor and failed. Error: None values not supported.

Any suggestions as to what I am doing wrong here?

Body:
I'm wondering if this is a bug in the sample_distorted_bounding_box() code, since I don't see a test that doesn't specify that argument to the function explicitly.

Can you try setting that argument explicitly, something like this?

sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(
    tf.shape(image),
    bounding_boxes=bbox,
    min_object_covered=0.1,
    aspect_ratio_range=[0.75, 1.33],
    area_range=[0.05, 1.0],
    max_attempts=100,
    use_image_if_no_bounding_boxes=True)

https://github.com/tensorflow/models/blob/master/research/inception/inception/image_processing.py#L235


问:
Swift 4 Scrollview Constraints Issue
I added a scrollview to my viewController and anchored it to my view, like this:

```<code>class MainContainer: UIViewController {

    let mainScrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .lightGray
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.contentInsetAdjustmentBehavior = .never
        return scrollView
    }()

    override func viewDidLoad() {

        view.addSubview(mainScrollView)

        mainScrollView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)

    }
}
</code>```

The above code works great. Constraints work as expected
I then try to append a view to it by adding

mainScrollView.addSubview(cameraView.view)

That is when the constraints act weird on my scrollview. For some reason the width and height of the scrollview is doubled. Here is a screenshot of my view hierarchy to illustrate my issue

In the image I selected the scrollview and right clicked to "Show Constraints" which for some reason are doubled in width and height. Before adding the view controller the constraints where fine. The added view controller appears fine but the constraints on the scrollview are messed.

答: Make sure that cameraView.view's top , bottom , leading and trailing constraints are hooked to the scrollview (the superview) then give a height and width to cameraView.view , also don't forget to make translateAutoresizing.... equal to false for the scrollview . . .

Title: Swift 4 Scrollview Constraints Issue

Body:
I added a scrollview to my viewController and anchored it to my view, like this:

class MainContainer: UIViewController {

    let mainScrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .lightGray
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.contentInsetAdjustmentBehavior = .never
        return scrollView
    }()

    override func viewDidLoad() {

        view.addSubview(mainScrollView)

        mainScrollView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)

    }
}

The above code works great. Constraints work as expected
I then try to append a view to it by adding

mainScrollView.addSubview(cameraView.view)

That is when the constraints act weird on my scrollview. For some reason the width and height of the scrollview is doubled. Here is a screenshot of my view hierarchy to illustrate my issue

In the image I selected the scrollview and right clicked to "Show Constraints" which for some reason are doubled in width and height. Before adding the view controller the constraints where fine. The added view controller appears fine but the constraints on the scrollview are messed.


问:
Installing Pandas on Mac OSX
I'm having trouble installing the Python Pandas library on my Mac OSX computer.

I type the following in Terminal:

```<code>$ sudo easy_install pandas
</code>```

But then I get the following:

```<code>Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge.net
Best match: pandas 0.9.0
Downloading http://pypi.python.org/packages/source/p/pandas/pandas-
0.9.0.zip#md5=04b1d8e11cc0fc30ae777499d89003ec
Processing pandas-0.9.0.zip
Writing /tmp/easy_install-ixjbQO/pandas-0.9.0/setup.cfg
Running pandas-0.9.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ixjbQO/pandas-
0.9.0/egg-dist-tmp-EGREoT
warning: no files found matching 'setupegg.py'
no previously-included directories found matching 'doc/build'
warning: no previously-included files matching '*.so' found anywhere in distribution
warning: no previously-included files matching '*.pyd' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '.git*' found anywhere in distribution
warning: no previously-included files matching '.DS_Store' found anywhere in distribution
warning: no previously-included files matching '*.png' found anywhere in distribution
unable to execute gcc: No such file or directory
error: Setup script exited with error: command 'gcc' failed with exit status 1
</code>```

I do have Xcode and gcc installed, however, gcc is only found when I type:

```<code>$ gcc
-bash: gcc: command not found

$ gcc-4.2
i686-apple-darwin11-gcc-4.2.1: no input files
</code>```

What should I do?

答:
Try

```<code>pip3 install pandas
</code>```

from terminal. Maybe your original pip install pandas is referencing anaconda distribution

Title: Installing Pandas on Mac OSX

Body:
I'm having trouble installing the Python Pandas library on my Mac OSX computer.

I type the following in Terminal:

$ sudo easy_install pandas

But then I get the following:

Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge.net
Best match: pandas 0.9.0
Downloading http://pypi.python.org/packages/source/p/pandas/pandas-
0.9.0.zip#md5=04b1d8e11cc0fc30ae777499d89003ec
Processing pandas-0.9.0.zip
Writing /tmp/easy_install-ixjbQO/pandas-0.9.0/setup.cfg
Running pandas-0.9.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ixjbQO/pandas-
0.9.0/egg-dist-tmp-EGREoT
warning: no files found matching 'setupegg.py'
no previously-included directories found matching 'doc/build'
warning: no previously-included files matching '*.so' found anywhere in distribution
warning: no previously-included files matching '*.pyd' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '.git*' found anywhere in distribution
warning: no previously-included files matching '.DS_Store' found anywhere in distribution
warning: no previously-included files matching '*.png' found anywhere in distribution
unable to execute gcc: No such file or directory
error: Setup script exited with error: command 'gcc' failed with exit status 1

I do have Xcode and gcc installed, however, gcc is only found when I type:

$ gcc
-bash: gcc: command not found

$ gcc-4.2
i686-apple-darwin11-gcc-4.2.1: no input files

What should I do?

Body:
Try

pip3 install pandas

from terminal. Maybe your original pip install pandas is referencing anaconda distribution


问:
Display list of items from database based on hard coded dropdownlist selection in ASP.NET MVC
I am trying to display list of items from database based on dropdownlist selection which is hard coded in ASP.NET MVC application.

My Controller

```<code> public ActionResult ListofItems()
            {
                ListofClassClassHandle listofClassClassHandle = new ListofClassClassHandle ();
                return View(listofClassClassHandle.LeadingAll());
            }
</code>```

ListofClassClassHandle Class

```<code>public List<Leading> LeadingAll()
        {
            clsUtilities clsUtilities = new clsUtilities();
            DataSet ds;
            List<Leading> leading = new List<Leading>();
            string sSQL;
            sSQL = "exec GetLeading 'NZ'";
            ds = clsUtilities.GetDataSet(sSQL);
            DataTable dataTable = ds.Tables[0];
            foreach(DataRow dr in dataTable.Rows)
            {
                leading.Add(
                    new Leading
                    {
                        RankId = Convert.ToInt32(dr["RankId"]),
                        Name = Convert.ToString(dr["Name"]),

                    }
                    );
            }
</code>```

Leading Class

```<code>public class Leading
    {
        public int RankId { get; set; }
        public string Name{ get; set; }
        public Countries AllCountries { get; set; }

    }
public enum Countries
    {
        New_Zealand,
        Australia
    }
</code>```

Leading View

```<code> @Html.DropDownList("AllCountries",
        new SelectList(Enum.GetValues(typeof(Countries))),
        "Select Country",
         new { @class = "form-control", style = "width: 150px;" })

<table class="table">
    <tr>
        <th>
            @Html.DisplayName("Rank")
        </th>
        <th>
            @Html.DisplayName("Name")
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.RankId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>

        </tr>
    }

</table>
</code>```

I want to display the list based on dropdown country list selection. The dropdown list is hard coded where the list of data is populating from database.

Please guide me. I do not have any idea how to accomplish this? Any help or guidance is highly appreciated.

答:
You can pass the dropdown selection to your GET action method and from there to your data access method and use that to get the filtered set of data.

To start, add a parameter to your action method.

```<code>public ActionResult ListofItems(string AllCountries="")
{
    var h = new ListofClassClassHandle();
    return View(h.LeadingAll(AllCountries));
}
</code>```

And update the LeadingAll method to accept this parameter. Update your data access code to  use the value inside the country variable.

```<code>public List<Leading> LeadingAll(string country)
{
    // to do : use the value of country to call the stored procedure
    // to do : return list of Leading objects
}
</code>```

Now in your View, you can keep your dropdown list inside a form tag along with  a submit button. Set the form tag's action attribute value to your ListOfItems action method and set the form method attribute to GET.

```<code>@using (Html.BeginForm("ListOfItems", "Home", FormMethod.Get))
{
    @Html.DropDownList("AllCountries",
            new SelectList(Enum.GetValues(typeof(Countries))),
            "Select Country",
            new { @class = "form-control", style = "width: 150px;" })
    <input type="submit" value="Filter" />
}
</code>```

When the user selects an option from the SELECT element and click submit button it will make a GET call with the selection in the querystring ( Ex :/ListOfItems/?AllCountries=Australia) and your action method code will use this value to get the data for that country by passing that to your data access method.

Body:
I am trying to display list of items from database based on dropdownlist selection which is hard coded in ASP.NET MVC application.

My Controller

 public ActionResult ListofItems()
            {
                ListofClassClassHandle listofClassClassHandle = new ListofClassClassHandle ();
                return View(listofClassClassHandle.LeadingAll());
            }

ListofClassClassHandle Class

public List<Leading> LeadingAll()
        {
            clsUtilities clsUtilities = new clsUtilities();
            DataSet ds;
            List<Leading> leading = new List<Leading>();
            string sSQL;
            sSQL = "exec GetLeading 'NZ'";
            ds = clsUtilities.GetDataSet(sSQL);
            DataTable dataTable = ds.Tables[0];
            foreach(DataRow dr in dataTable.Rows)
            {
                leading.Add(
                    new Leading
                    {
                        RankId = Convert.ToInt32(dr["RankId"]),
                        Name = Convert.ToString(dr["Name"]),

                    }
                    );
            }

Leading Class

public class Leading
    {
        public int RankId { get; set; }
        public string Name{ get; set; }
        public Countries AllCountries { get; set; }

    }
public enum Countries
    {
        New_Zealand,
        Australia
    }

Leading View

 @Html.DropDownList("AllCountries",
        new SelectList(Enum.GetValues(typeof(Countries))),
        "Select Country",
         new { @class = "form-control", style = "width: 150px;" })

            @Html.DisplayName("Rank")

            @Html.DisplayName("Name")

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.RankId)

                @Html.DisplayFor(modelItem => item.Name)

    }

I want to display the list based on dropdown country list selection. The dropdown list is hard coded where the list of data is populating from database.

Please guide me. I do not have any idea how to accomplish this? Any help or guidance is highly appreciated.

Body:
You can pass the dropdown selection to your GET action method and from there to your data access method and use that to get the filtered set of data.

To start, add a parameter to your action method.

public ActionResult ListofItems(string AllCountries="")
{
    var h = new ListofClassClassHandle();
    return View(h.LeadingAll(AllCountries));
}

And update the LeadingAll method to accept this parameter. Update your data access code to  use the value inside the country variable.

public List<Leading> LeadingAll(string country)
{
    // to do : use the value of country to call the stored procedure
    // to do : return list of Leading objects
}

Now in your View, you can keep your dropdown list inside a form tag along with  a submit button. Set the form tag's action attribute value to your ListOfItems action method and set the form method attribute to GET.

@using (Html.BeginForm("ListOfItems", "Home", FormMethod.Get))
{
    @Html.DropDownList("AllCountries",
            new SelectList(Enum.GetValues(typeof(Countries))),
            "Select Country",
            new { @class = "form-control", style = "width: 150px;" })
    <input type="submit" value="Filter" />
}

When the user selects an option from the SELECT element and click submit button it will make a GET call with the selection in the querystring ( Ex :/ListOfItems/?AllCountries=Australia) and your action method code will use this value to get the data for that country by passing that to your data access method.


问:
Is there way to save trained model after overfitting occurs in CatBoost?
I am using CatBoostRegressor in Python version of the Catboost library.

According to documentation, it's possible to use overfitting detector, which I am doing, like this:

```<code>model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)

# this code didn't executed
model.save_model(model_name)
</code>```

However, after the overfitting occurs, I've got my Python script interrupted, prematurely stopped, pick any phrase you want, and save model part didn't get executed, which leads to a lot of waisted time and no results in the end. I didn't get any stacktrace.

Is there any possibility to handle it in CatBoost and save hours of fitting work?

答:
Use this code. It will save the model no matter what happens in the try block.</p>

```<code>try:
    model.fit(X, y)
finally:
    model.save_model()
</code>```

Body:
I am using CatBoostRegressor in Python version of the Catboost library.

According to documentation, it's possible to use overfitting detector, which I am doing, like this:

model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)

# this code didn't executed
model.save_model(model_name)

However, after the overfitting occurs, I've got my Python script interrupted, prematurely stopped, pick any phrase you want, and save model part didn't get executed, which leads to a lot of waisted time and no results in the end. I didn't get any stacktrace.

Is there any possibility to handle it in CatBoost and save hours of fitting work?

Body:
Use this code. It will save the model no matter what happens in the try block.

try:
    model.fit(X, y)
finally:
    model.save_model()


问:
How to edit the view of "The page has expired due to inactivity" in Laravel 5.5
In Laravel 5.5, When you are using CSRF protection (by default) and you send a post request after long inactivity you'll get this error page (Screenshot).

I'm ok with this error however, I need to change the view/text of this error to match my application style and my language for sure.

Any Ideas in how to edit this view?

答:
You can override the default view by placing a 419.blade.php file in the resources/views/errors folder.

If you're using an editor with global search capabilities, you can search for the error message inside your project. For example, in Visual Studio Code you can press Ctrl + Shift + F to search inside the project.

I use it all the time to find the files which are part of the framework that I need to customize.

More on overriding the error views in this section of the official docs.


问:
Bash script help, include sub-directories for processing files
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.  </p>

```<code>#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done
</code>```

答:
Since your script already understands one level of file expansion, perhaps running it on every directory containing a ./userfiles directory would be fast and simple...

```<code>$ find . -type d -a -name userfiles -a -exec sh /whatever/myscript {}/.. \;
</code>```

Body:
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.

#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done

Body:
Since your script already understands one level of file expansion, perhaps running it on every directory containing a ./userfiles directory would be fast and simple...

$ find . -type d -a -name userfiles -a -exec sh /whatever/myscript {}/.. \;


问:
installing an existing R packages on Linux server
Please explain how to install the following package on the Linux server.
(R package)
R is installed in /usr/bin/.
I'm not understanding the documentation I'm finding.

Thanks

答:
You can do it using  </p>

```<code>install.packages("ada", lib = "/usr/lib64/R/library", dependencies = T)
</code>```

Body:
You can do it using

install.packages("ada", lib = "/usr/lib64/R/library", dependencies = T)


问:
VBA Loop to Conditionally Format showing Type Mismatch bug
I have an excel sheet with 4 columns, and I want to loop through the column and if (Column D/Column C) <> (Column B/Column A), highlight all 4 cells. I'm getting a Type Mismatch running the following and not sure why?</p>

```<code>Sub Check()

Dim ValA as Variant
Dim ValB as Variant
Dim ValC as Variant
Dim ValD as Variant
Dim ColA as Long
Dim ColB as Long
Dim ColC as Long
Dim ColD as Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)
ColA = ValA.Column

 Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)
ColB = ValB.Column

 Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)
ColC = ValC.Column

 Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)
ColD = ValD.Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

For i = 2 to LastRow
    If ActiveSheet.Cells(i,ColD).Value/ActiveSheet.Cells(i,ColC).Value <> ActiveSheet.Cells(i, ColB).Value/ActiveSheet(i, ColA).Value Then
        ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3
    End If
Next i
End Sub
</code>```

答:
To do this with conditional formating, first select your data range (select the entire 4 columns):

Then, go to conditional formating > new rule...

Do a formula based condition (last option) and enter the following formula:

```<code>=($D1/$C1)<>($B1/$A1) 'in my case. Edit to fit your respective data columns.
</code>```

Click on "Format" to choose your highlight options and that should do it.

Body:
I have an excel sheet with 4 columns, and I want to loop through the column and if (Column D/Column C) <> (Column B/Column A), highlight all 4 cells. I'm getting a Type Mismatch running the following and not sure why?

Sub Check()

Dim ValA as Variant
Dim ValB as Variant
Dim ValC as Variant
Dim ValD as Variant
Dim ColA as Long
Dim ColB as Long
Dim ColC as Long
Dim ColD as Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)
ColA = ValA.Column

 Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)
ColB = ValB.Column

 Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)
ColC = ValC.Column

 Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)
ColD = ValD.Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

For i = 2 to LastRow
    If ActiveSheet.Cells(i,ColD).Value/ActiveSheet.Cells(i,ColC).Value <> ActiveSheet.Cells(i, ColB).Value/ActiveSheet(i, ColA).Value Then
        ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3
    End If
Next i
End Sub

Body:
To do this with conditional formating, first select your data range (select the entire 4 columns):

Then, go to conditional formating > new rule...

Do a formula based condition (last option) and enter the following formula:

=($D1/$C1)<>($B1/$A1) 'in my case. Edit to fit your respective data columns.

Click on "Format" to choose your highlight options and that should do it.


问:
How to convert "2012-03-04 00:00:00.0" to Date with Format "dd-mm-yyyy HH:mm:ss" Using Java
I have a date format that I am getting from the database and is a String type. It has a value stored that is like "2012-03-04 00:00:00.0" but I have declared a SimpleDateFormat as "dd-MMM-yyyy HH:mm:ss" which is needed in my project. Now whenever I am retrieving some data alsong with date from database I get a parse Exception with the log as below.

java.text.ParseException: Unparseable date: "2012-03-04 00:00:00.0"
          at java.text.DateFormat.parse(Unknown Source)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl$1.setValues(AepSelfProfileDaoImpl.java:1188)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614)
          at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl.insertDataIntoActionItems(AepSelfProfileDaoImpl.java:1174)
          at com.tcs.tool.iris.aep.selfProfile.service.AepSelfProfileServiceImpl.insertDataIntoActionItems(AepSelfProfileServiceImpl.java:214)
          at com.tcs.tool.iris.aep.selfProfile.controller.UpdateProgressController.onSubmit(UpdateProgressController.java:48)
          at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:675)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:275)
          at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
          at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
          at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
          at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
          at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
          at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
          at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
          at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
          at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
          at java.lang.Thread.run(Unknown Source)

Please help me to figure out whats wrong with this. And how to convert it into the correct format.

The code snippet where I get the exception is as follows:-

```<code>SimpleDateFormat sdf = new SimpleDateFormat(
                                "dd-MMM-yyyy HH:mm:ss");
                        Calendar currenttime = Calendar.getInstance();
                        java.util.Date currentdate = currenttime.getTime();
                        String currentDateInsert = sdf.format(currentdate);
                        CommentNActionItem commentAndAction = commentActionItem
                                .get(i);
                        java.util.Date datefromDb = null;
                        try {
                            @SuppressWarnings("unused")
                            Date dateF=sdf.parse(commentAndAction.getCreatedDate());
                            datefromDb = (java.sql.Date)sdf.parseObject(commentAndAction.getCreatedDate());
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
</code>```

}

答:
tl;dr

```<code>LocalDateTime.parse(
    "2012-03-04 00:00:00.0".replace( " " , "T" )
).format(
    DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )
)
</code>```

java.time

The other Answers use the troublesome old date-time classes that are now legacy, supplanted entirely by the modern java.time classes. For earlier Android, see the last bullets below.

Parse as a LocalDateTime object as your input lacks any indication of time zone or offset-from-UTC.

```<code>String input = "2012-03-04 00:00:00.0".replace( " " , "T" ) ;

LocalDateTime ldt = LocalDateTime.parse( input ) ;
</code>```

If you really do not care about the fractional second, chop it off.

```<code>LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ) ;
</code>```

Specify your custom format for use in generating a String to represent this value.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = ldtTruncated.format( f ) ;
</code>```

Dump to console.

```<code>System.out.println( "input: " + input ) ;
System.out.println( "ldt: " + ldt ) ;
System.out.println( "ldtTruncated: " + ldtTruncated ) ;
System.out.println( "output: " + output ) ;
</code>```

See this code run live at IdeOne.com.

input: 2012-03-04T00:00:00.0

ldt: 2012-03-04T00:00

ldtTruncated: 2012-03-04T00:00

output: 2012-03-04 00:00:00

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

ContentLicense: CC BY-SA 4.0

Body:
I have a date format that I am getting from the database and is a String type. It has a value stored that is like "2012-03-04 00:00:00.0" but I have declared a SimpleDateFormat as "dd-MMM-yyyy HH:mm:ss" which is needed in my project. Now whenever I am retrieving some data alsong with date from database I get a parse Exception with the log as below.

java.text.ParseException: Unparseable date: "2012-03-04 00:00:00.0"
          at java.text.DateFormat.parse(Unknown Source)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl$1.setValues(AepSelfProfileDaoImpl.java:1188)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892)
          at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
          at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614)
          at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883)
          at com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl.insertDataIntoActionItems(AepSelfProfileDaoImpl.java:1174)
          at com.tcs.tool.iris.aep.selfProfile.service.AepSelfProfileServiceImpl.insertDataIntoActionItems(AepSelfProfileServiceImpl.java:214)
          at com.tcs.tool.iris.aep.selfProfile.controller.UpdateProgressController.onSubmit(UpdateProgressController.java:48)
          at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:675)
          at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:275)
          at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
          at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
          at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
          at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
          at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
          at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
          at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
          at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
          at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
          at java.lang.Thread.run(Unknown Source)

Please help me to figure out whats wrong with this. And how to convert it into the correct format.

The code snippet where I get the exception is as follows:-

SimpleDateFormat sdf = new SimpleDateFormat(
                                "dd-MMM-yyyy HH:mm:ss");
                        Calendar currenttime = Calendar.getInstance();
                        java.util.Date currentdate = currenttime.getTime();
                        String currentDateInsert = sdf.format(currentdate);
                        CommentNActionItem commentAndAction = commentActionItem
                                .get(i);
                        java.util.Date datefromDb = null;
                        try {
                            @SuppressWarnings("unused")
                            Date dateF=sdf.parse(commentAndAction.getCreatedDate());
                            datefromDb = (java.sql.Date)sdf.parseObject(commentAndAction.getCreatedDate());
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();

}

Body:
tl;dr

LocalDateTime.parse(
    "2012-03-04 00:00:00.0".replace( " " , "T" )
).format(
    DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )
)

java.time

The other Answers use the troublesome old date-time classes that are now legacy, supplanted entirely by the modern java.time classes. For earlier Android, see the last bullets below.

Parse as a LocalDateTime object as your input lacks any indication of time zone or offset-from-UTC.

String input = "2012-03-04 00:00:00.0".replace( " " , "T" ) ;

LocalDateTime ldt = LocalDateTime.parse( input ) ;

If you really do not care about the fractional second, chop it off.

LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ) ;

Specify your custom format for use in generating a String to represent this value.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = ldtTruncated.format( f ) ;

Dump to console.

System.out.println( "input: " + input ) ;
System.out.println( "ldt: " + ldt ) ;
System.out.println( "ldtTruncated: " + ldtTruncated ) ;
System.out.println( "output: " + output ) ;

See this code run live at IdeOne.com.

input: 2012-03-04T00:00:00.0

ldt: 2012-03-04T00:00

ldtTruncated: 2012-03-04T00:00

output: 2012-03-04 00:00:00

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….


问:
AmbiguousMatchException exception in ServiceStack?
PFB my code.

```<code>namespace ManualCSharpe
{
    public class MyServices : Service
    {
        [Route("/L/hello/")] //RequestDTO one
        public class HelloL
        {
            public string Name { get; set; }
        }
        [Route("/H/hello/")] //RequestDTO two
        public class HelloH
        {
            public string Name1 { get; set; }
        }
        public class HelloResponse //ResponseDTO
        {
            public string Result { get; set; }
        }

        public class HelloServiceL : Service //Service One
        {
            public object Get(HelloL request)
            {
                return new HelloResponse { Result = "Low" };
            }
         }
        public class HelloServiceH : Service //Service
        {
            public object Get(HelloH request)
            {
                return new HelloResponse { Result = "High" };
            }
        }

        //Define the Web Services AppHost
        public class AppHost : AppSelfHostBase
        {
            public AppHost()
                : base("HttpListener Self-Host",new Assembly[] {typeof(HelloServiceL).Assembly, typeof(HelloServiceH).Assembly}) { }

            public override void Configure(Funq.Container container) { }
        }

        //Run it!
        static void Main(string[] args)
        {
            var listeningOn = args.Length == 0 ? "http://*:133/" : args[0];
            var appHost = new AppHost()
                .Init()
                .Start(listeningOn);

            Console.WriteLine("AppHost Created at {0}, listening on {1}",
                DateTime.Now, listeningOn);

            Console.ReadKey();
        }
    }
}
</code>```

When I am tring to added two service then it is show below exception.

```<code>An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in ServiceStack.dll

Additional information: Could not register Request 'ManualCSharpe.MyServices+HelloL' with service 'ManualCSharpe.MyServices+HelloServiceL' as it has already been assigned to another service.

Each Request DTO can only be handled by 1 service.
</code>```

I have below douts.

Here I have created two different DTO for Two Service. Why it is showing error like Each Request DTO can only be handled by 1 service. In simple word, Two route mapped with two DTO with two Service.

Can I create one route for multiple RequestDTO with multiple service? In Simple word, One Route/L/hello/ can be mapped with two DTO HelloL and HelloH.

答:
For those of you who come here from a google search, a AmbiguousMatchException exception in ServiceStack can sometimes be triggered within ServiceStack but handled internally.

You can change your exception setting so it doesn't break on this exception.

I had changed my exception setting to break on all exceptions and this had me stuck for a while.

Body:
PFB my code.

namespace ManualCSharpe
{
    public class MyServices : Service
    {
        [Route("/L/hello/")] //RequestDTO one
        public class HelloL
        {
            public string Name { get; set; }
        }
        [Route("/H/hello/")] //RequestDTO two
        public class HelloH
        {
            public string Name1 { get; set; }
        }
        public class HelloResponse //ResponseDTO
        {
            public string Result { get; set; }
        }

        public class HelloServiceL : Service //Service One
        {
            public object Get(HelloL request)
            {
                return new HelloResponse { Result = "Low" };
            }
         }
        public class HelloServiceH : Service //Service
        {
            public object Get(HelloH request)
            {
                return new HelloResponse { Result = "High" };
            }
        }

        //Define the Web Services AppHost
        public class AppHost : AppSelfHostBase
        {
            public AppHost()
                : base("HttpListener Self-Host",new Assembly[] {typeof(HelloServiceL).Assembly, typeof(HelloServiceH).Assembly}) { }

            public override void Configure(Funq.Container container) { }
        }

        //Run it!
        static void Main(string[] args)
        {
            var listeningOn = args.Length == 0 ? "http://*:133/" : args[0];
            var appHost = new AppHost()
                .Init()
                .Start(listeningOn);

            Console.WriteLine("AppHost Created at {0}, listening on {1}",
                DateTime.Now, listeningOn);

            Console.ReadKey();
        }
    }
}

When I am tring to added two service then it is show below exception.

An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in ServiceStack.dll

Additional information: Could not register Request 'ManualCSharpe.MyServices+HelloL' with service 'ManualCSharpe.MyServices+HelloServiceL' as it has already been assigned to another service.

Each Request DTO can only be handled by 1 service.

I have below douts.

Here I have created two different DTO for Two Service. Why it is showing error like Each Request DTO can only be handled by 1 service. In simple word, Two route mapped with two DTO with two Service.

Can I create one route for multiple RequestDTO with multiple service? In Simple word, One Route/L/hello/ can be mapped with two DTO HelloL and HelloH.


问:
How to remove extra left/right padding on AppCompatEditText inside ConstraintLayout
I have an AppCompatEditText inside a ConstraintLayout and as always the line at the bottom of the EditText is indented a bit. I usually fix that by using a negative padding but the ConstraintLayout doesn't allow that, so how do I fix it?

答:
Have you tried changing layout margins instead?
Plus could you also include some code as this will help determine problem.

As a side note:
https://developer.android.com/reference/android/support/v7/widget/AppCompatEditText.html

States:

This will automatically be used when you use EditText in your layouts and the top-level activity / dialog is provided by appcompat. You should only need to manually use this class when writing custom views.

I only point this at as it annoys me when my colleagues do it.


问:
Successive use of same method in block recalculates the method?
I've always assumed every time I call a method in Java the method is executed again. I've assumed the return value is not stored automatically unless I store it in a variable.

Then I ran across this code in Princeton's algs4.BST class where they call three methods twice each:

```<code>private boolean check() {
    if (!isBST())            StdOut.println("Not in symmetric order");
    if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
    if (!isRankConsistent()) StdOut.println("Ranks not consistent");
    return isBST() && isSizeConsistent() && isRankConsistent();
}
</code>```

Are they simply not concerned with performance? Or is the compiler smart enough keep the first return value of each method to use in the return statement?

Sorry if this is a duplicate seems like this answer should exist but I can't find it here or in Java docs. I found these (and others) but they don't answer my question:

Is this the cleanest way to repeat method call in Java?

How to call a method without repeat from other methods in java

答:
The Java Language Specification explicitly and unconditionally states that evaluation of a method invocation expression involves executing the designated method's code.  JLS 8 puts it this way:

At run time, method invocation requires five steps. First, a target
  reference may be computed. Second, the argument expressions are
  evaluated. Third, the accessibility of the method to be invoked is
  checked. Fourth, the actual code for the method to be executed is
  located. Fifth, a new activation frame is created, synchronization is
  performed if necessary, and control is transferred to the method code.

(JLS 8, 15.12.4; emphasis added)

Thus, invoking a method a second time incurs its cost a second time, regardless of whether the same value can be expected to be computed.  It is conceivable that JIT compilation could optimize that, but there are more considerations there than whether the same result is going to be computed, and you're anyway unlikely to see any JIT action triggered by just two invocations of a given method.

Bottom line: yes, the author of the code was simply not concerned with performance.  They may have considered the implementation presented to be clearer than one that avoided redundant method invocations, or they may have had some other personal reason for the choice.  This kind of disregard for practicalities is not uncommon in code serving academic purposes, such as that presented.

Body:
I've always assumed every time I call a method in Java the method is executed again. I've assumed the return value is not stored automatically unless I store it in a variable.

Then I ran across this code in Princeton's algs4.BST class where they call three methods twice each:

private boolean check() {
    if (!isBST())            StdOut.println("Not in symmetric order");
    if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
    if (!isRankConsistent()) StdOut.println("Ranks not consistent");
    return isBST() && isSizeConsistent() && isRankConsistent();
}

Are they simply not concerned with performance? Or is the compiler smart enough keep the first return value of each method to use in the return statement?

Sorry if this is a duplicate seems like this answer should exist but I can't find it here or in Java docs. I found these (and others) but they don't answer my question:

Is this the cleanest way to repeat method call in Java?

How to call a method without repeat from other methods in java


问:
How do I disable -u interpreter option in PyCharm?
I am configuring PyCharm to use remote python interpreter. PyCharm seems to execute the interpreter with -u option, and I can't find a way to disable that. The reason I need it disabled is that I am running nosetests command, so I get this:

```<code>ssh://xxx@xxx.xxx.xxx.xxx:22/path/to/bin/nosetests -s -a M_4439 -u /path/to/test_elf.py

Usage: nosetests [options]

nosetests: error: no such option: -u

Process finished with exit code 2
</code>```

I looked around, and could not find where -u is set. I checked:

Run -> Edit configurations. I have my options there: -s -a M_4439

Settings -> Project interpreter

Where is -u set?

答:
Answering my own question, as per comment above:

PyCharm has its helper script to run nose tests. I configured the interpreter to be remote python and now I get this (which is what I need): ssh://xxx@xxx.xxx.xxx.xxx:22/path/to/bin/python -u /path/to/.pycharm_helpers/pycharm/noserunner.py /path/to/test_elf.py .

Now I just need to figure out pre-test scripts that are usually sourced from .bashrc.
Edit configurations -> Before launch: Remote external tool does that

Body:
I am configuring PyCharm to use remote python interpreter. PyCharm seems to execute the interpreter with -u option, and I can't find a way to disable that. The reason I need it disabled is that I am running nosetests command, so I get this:

ssh://xxx@xxx.xxx.xxx.xxx:22/path/to/bin/nosetests -s -a M_4439 -u /path/to/test_elf.py

Usage: nosetests [options]

nosetests: error: no such option: -u

Process finished with exit code 2

I looked around, and could not find where -u is set. I checked:

Run -> Edit configurations. I have my options there: -s -a M_4439

Settings -> Project interpreter

Where is -u set?


问:
Laravel 3 - PHP Warning: in_array() expects parameter 2 to be array
I am working with a code that was not written by me. It is a Laravel 3 application, it is giving me the following error:

PHP Warning:  in_array() expects parameter 2 to be array, null given in /Users/use/Documents/project/laravel/error.php on line 87

Can you give me pointers on how to debug it? It is giving error in the file which was included in the framework. Also I using the php's inbuilt server to run the application. Does that cause problems? Any pointers are helpful.

PS: I am on a mac.

答:
You can get this also if you're using composer and the required files have not been installed after a fresh checkout of the project. To resolve:

$ composer install

Or similar. To actually get a head on this information I had to throw $exception in the error.php file around line 87, then I saw the reason in the Apache error logs.


问:
In C ,we use %x.ys for string manipulation. What it will be in C++?
How can I replace printf() with cout?
My Code In C++:

```<code>    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }
</code>```

The Code Prints:

```<code>United Kingdom

       United

United

Uni
</code>```

How can I manipulate like this in C++?

答:
The std::setw() I/O manipulator is the direct equivalent of printf()'s minimum width for strings, and the std::left and std::right I/O manipulators are the direct equivalent for justification within the output width.  But there is no direct equivilent of printf()'s precision (max length) for strings, you have to truncate the string data manually.

Try this:

```<code>#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    char st[15] = "United Kingdom";

    cout << setw(15) << st << '\n'; // prints " United Kingdom"
    cout << setw(5) << st << '\n'; // prints "United Kingdom"
    cout << setw(15) << string(st, 6) << '\n'; // prints "         United"
    cout << left << setw(15) << string(st, 6) << '\n'; // prints "United         "
    cout << setw(15) << string(st, 0) << '\n'; // prints "               "
    cout << string(st, 3) << '\n'; // prints "Uni"
    cout << st << '\n; // prints "United Kingdom"

    return 0;
}
</code>```

Live demo

Body:
How can I replace printf() with cout?
My Code In C++:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }

The Code Prints:

United Kingdom

       United

United

Uni

How can I manipulate like this in C++?

Body:
The std::setw() I/O manipulator is the direct equivalent of printf()'s minimum width for strings, and the std::left and std::right I/O manipulators are the direct equivalent for justification within the output width.  But there is no direct equivilent of printf()'s precision (max length) for strings, you have to truncate the string data manually.

Try this:

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    char st[15] = "United Kingdom";

    cout << setw(15) << st << '\n'; // prints " United Kingdom"
    cout << setw(5) << st << '\n'; // prints "United Kingdom"
    cout << setw(15) << string(st, 6) << '\n'; // prints "         United"
    cout << left << setw(15) << string(st, 6) << '\n'; // prints "United         "
    cout << setw(15) << string(st, 0) << '\n'; // prints "               "
    cout << string(st, 3) << '\n'; // prints "Uni"
    cout << st << '\n; // prints "United Kingdom"

    return 0;
}

Live demo


问:
hive function returning wrong date
```<code>hive> select from_unixtime(UNIX_TIMESTAMP('02/31/17', "mm/dd/yy"),'yyyy-MM-dd') from dual;
OK
2017-01-31
</code>```

It is returning wrond date.

答:
Found it.Date format is wrong.</p>

```<code>select   from_unixtime(unix_timestamp('12/31/17' ,'MM/dd/yy'), 'yyyy-MM-dd') from dual;
</code>```

Title: hive function returning wrong date

Body:
hive> select from_unixtime(UNIX_TIMESTAMP('02/31/17', "mm/dd/yy"),'yyyy-MM-dd') from dual;
OK
2017-01-31

It is returning wrond date.

Body:
Found it.Date format is wrong.

select   from_unixtime(unix_timestamp('12/31/17' ,'MM/dd/yy'), 'yyyy-MM-dd') from dual;


问:
show unit test success/failure count in sonarqube
I'm using an asp.net MVC project with VSTS and Sonar (5.6.3).
My unit test coverage is showing up on my Sonar Dashboard.

However, I didn't find a way to display number of unit test passed/failed on the dashboard.

Any help?

答: I am not sure my issue is relate to yours. I am using karma-sonarqube-unit-reporter to generate output.xml for sonar. The reason number of unit tests doesnt show on home page is in the output.xml all the file paths are not defined. Change all the file paths to test files paths solve the problem. Hope this helps.</p>


问:
Count the number of employees for every country
I have this task:

Count the number of employees for every country. Show only those countries, when works more than 20 employees

employee_id is dedicated for Employees table

country belongs to different table - Countries table and we need country_name from this table

I have no idea how to solve this task. Below what I was able to create. I think we should use Inner Join.

```<code>SELECT a.employee_id
    , b.country_name
    , COUNT(a.employee_id) AS count
FROM   employees a
      INNER JOIN countries b ON a.employee_id = b.country_name
GROUP BY b.country_name
WHERE employee_id >20;
</code>```

I think I need help from the beginning.
Thanks

答:
Your join doesn't seem correct but as I don't know the table structure, I can't say what the right column is (I'm going to assume that it should be country_name. Even so, try this:

```<code>SELECT b.country_name
    , COUNT(a.employee_id) AS count
FROM   employees a
      INNER JOIN countries b ON a.country_name = b.country_name
GROUP BY b.country_name
HAVING COUNT(employee_id) >20;
</code>```

When grouping you need to use the HAVING statement to filter.

Body:
I have this task:

Count the number of employees for every country. Show only those countries, when works more than 20 employees

employee_id is dedicated for Employees table

country belongs to different table - Countries table and we need country_name from this table

I have no idea how to solve this task. Below what I was able to create. I think we should use Inner Join.

SELECT a.employee_id
    , b.country_name
    , COUNT(a.employee_id) AS count
FROM   employees a
      INNER JOIN countries b ON a.employee_id = b.country_name
GROUP BY b.country_name
WHERE employee_id >20;

I think I need help from the beginning.
Thanks

Body:
Your join doesn't seem correct but as I don't know the table structure, I can't say what the right column is (I'm going to assume that it should be country_name. Even so, try this:

SELECT b.country_name
    , COUNT(a.employee_id) AS count
FROM   employees a
      INNER JOIN countries b ON a.country_name = b.country_name
GROUP BY b.country_name
HAVING COUNT(employee_id) >20;

When grouping you need to use the HAVING statement to filter.


问:
FSL doesn't install on Ubuntu 16.04 from NeuroDebian
I am trying to install FSL on Ubuntu 16.04 64-bit.

I followed procedure at neurodebian website, selected the correct package, specified ALL software.

When I copy-paste the commands in my terminal the pipe hangs without prompting for my sudo password:

```<code>wget -O- http://neuro.debian.net/lists/xenial.de-m.full | sudo tee /etc/apt/sources.list.d/neurodebian.sources.list
</code>```

I also tried to separate the pipe in the two commands. The first one runs, the second asks for my password and then hangs. I con't know how to connect their outputs though.

If I use CTRL+Z it stops (of course) and then I type

```<code>sudo apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9
sudo apt-get update
sudo apt-get install fsl-complete
</code>```

but the package is not found. Also the package fsl-5.0-complete is not found.

I tried the mirror in Japan and the mirror in Munich, with no success.
The advice posted in the comments on NeuroDebian just repeats the instructions, and it doesn't help.

答:
Are you missing the second line of the first command given in the instructions you linked?</p>

```<code>sudo apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9
</code>```

Body:
I am trying to install FSL on Ubuntu 16.04 64-bit.

I followed procedure at neurodebian website, selected the correct package, specified ALL software.

When I copy-paste the commands in my terminal the pipe hangs without prompting for my sudo password:

wget -O- http://neuro.debian.net/lists/xenial.de-m.full | sudo tee /etc/apt/sources.list.d/neurodebian.sources.list

I also tried to separate the pipe in the two commands. The first one runs, the second asks for my password and then hangs. I con't know how to connect their outputs though.

If I use CTRL+Z it stops (of course) and then I type

sudo apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9
sudo apt-get update
sudo apt-get install fsl-complete

but the package is not found. Also the package fsl-5.0-complete is not found.

I tried the mirror in Japan and the mirror in Munich, with no success.
The advice posted in the comments on NeuroDebian just repeats the instructions, and it doesn't help.

Body:
Are you missing the second line of the first command given in the instructions you linked?

sudo apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9


问:
Fixing render blocking CSS on WP

Hello I am trying to fix render blocking CSS recommendation from Google Page speed.

```<code><style>here goes critical path</style>
<link rel="preload" as="style" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" onload="this.rel='stylesheet'" />
<noscript id="aonoscrcss">
<link type="text/css" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" rel="stylesheet" />
</noscript>
</code>```

I use Autoptimize for this purpose, so I inserted critical path and checked defer CSS. However Google doesn't count this as a fixed recommendation.
From this code part, is there any issues that causing it, or it something else? Any hints on how to troubleshoot this issue?

And also Google shows 2 blocking css files with the same name and url.

答:
Well, to be honest, I've been dealing with these kind of stuff for ages. The only thing I manage to do is to add "inline" css to all pages... Yes, it's a pain in the *ss. but after all... google is ok with it..

the solution would be to get ALL css rules for EACH page and add it as an inline-css in your html (minimized of course.)

not sure if that's the best way to go, however, that's what solved the issue for me..

cheers

Title: Fixing render blocking CSS on WP

Body:
Hello I am trying to fix render blocking CSS recommendation from Google Page speed.

<link rel="preload" as="style" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" onload="this.rel='stylesheet'" />

<link type="text/css" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" rel="stylesheet" />

I use Autoptimize for this purpose, so I inserted critical path and checked defer CSS. However Google doesn't count this as a fixed recommendation.
From this code part, is there any issues that causing it, or it something else? Any hints on how to troubleshoot this issue?

And also Google shows 2 blocking css files with the same name and url.


问:
How To Append Javascript Date To Multiple Inputs With Same ClassName?
I'm trying to append today's date to multiple inputs generated with a while statement. But each one of them returns blank. Any way to make this work? Thanks

PHP

```<code>//rest of code here
while ($row = mysqli_fetch_array($result)) {
<input class="Paydate"  name="Paydate" value="" type="text">
}
</code>```

JS

```<code><script>
var mydate;
mydate = new Date();
document.getElementsByClassName('Paydate').value = mydate.toISOString().slice(0, 19).replace('T', ' ');
</script>
</code>```

答:
getElementsByClassName returns live HTMLCollection rather than a single element, you need to iterate the collection

```<code>var dateStr =  new Date().toISOString().slice(0, 19).replace('T', ' ');
Array.from( document.getElementsByClassName('Paydate') ).forEach( function(ele){
   ele.value = dateStr;
});
</code>```

Body:
I'm trying to append today's date to multiple inputs generated with a while statement. But each one of them returns blank. Any way to make this work? Thanks

PHP

//rest of code here
while ($row = mysqli_fetch_array($result)) {
<input class="Paydate"  name="Paydate" value="" type="text">
}

JS

Body:
getElementsByClassName returns live HTMLCollection rather than a single element, you need to iterate the collection

var dateStr =  new Date().toISOString().slice(0, 19).replace('T', ' ');
Array.from( document.getElementsByClassName('Paydate') ).forEach( function(ele){
   ele.value = dateStr;
});


问:
What is the CouchDB replication protocol? Is it like Git?
Is there technical documentation describing how replication between two Couches works?

What is the basic overview of CouchDB replication? What are some noteworthy characteristics about it?

答:
Unfortunately there is no detailed documentation describing the replication protocol. There is only the reference implementation built into CouchDB, and Filipe Manana's rewrite of the same which will probably become the new implmentation in the future.

However, this is the general idea:

Key points

If you know Git, then you know how Couch replication works. Replicating is very similar to pushing or pulling with distributed source managers like Git.

CouchDB replication does not have its own protocol. A replicator simply connects to two DBs as a client, then reads from one and writes to the other. Push replication is reading the local data and updating the remote DB; pull replication is vice versa.

Fun fact 1: The replicator is actually an independent Erlang application, in its own process. It connects to both couches, then reads records from one and writes them to the other.

Fun fact 2: CouchDB has no way of knowing who is a normal client and who is a replicator (let alone whether the replication is push or pull). It all looks like client connections. Some of them read records. Some of them write records.

Everything flows from the data model

The replication algorithm is trivial, uninteresting. A trained monkey could design it. It's simple because the cleverness is the data model, which has these useful characteristics:

Every record in CouchDB is completely independent of all others. That sucks if you want to do a JOIN or a transaction, but it's awesome if you want to write a replicator. Just figure out how to replicate one record, and then repeat that for each record.

Like Git, records have a linked-list revision history. A record's revision ID is the checksum of its own data. Subsequent revision IDs are checksums of: the new data, plus the revision ID of the previous.

In addition to application data ({"name": "Jason", "awesome": true}), every record stores the evolutionary timeline of all previous revision IDs leading up to itself.

Exercise: Take a moment of quiet reflection. Consider any two different records, A and B. If A's revision ID appears in B's timeline, then B definitely evolved from A. Now consider Git's fast-forward merges. Do you hear that? That is the sound of your mind being blown.

Git isn't really a linear list. It has forks, when one parent has multiple children. CouchDB has that too.

Exercise: Compare two different records, A and B. A's revision ID does not appear in B's timeline; however, one revision ID, C, is in both A's and B's timeline. Thus A didn't evolve from B. B didn't evolve from A. But rather, A and B have a common ancestor C. In Git, that is a "fork." In CouchDB, it's a "conflict."

In Git, if both children go on to develop their timelines independently, that's cool. Forks totally support that.

In CouchDB, if both children go on to develop their timelines independently, that cool too. Conflicts totally support that.

Fun fact 3: CouchDB "conflicts" do not correspond to Git "conflicts." A Couch conflict is a divergent revision history, what Git calls a "fork." For this reason the CouchDB community pronounces "conflict" with a silent n: "co-flicked."

Git also has merges, when one child has multiple parents. CouchDB sort of has that too.

In the data model, there is no merge. The client simply marks one timeline as deleted and continues to work with the only extant timeline.

In the application, it feels like a merge. Typically, the client merges the data from each timeline in an application-specific way. Then it writes the new data to the timeline. In Git, this is like copying and pasting the changes from branch A into branch B, then commiting to branch B and deleting branch A. The data was merged, but there was no git merge.

These behaviors are different because, in Git, the timeline itself is important; but in CouchDB, the data is important and the timeline is incidental—it's just there to support replication. That is one reason why CouchDB's built-in revisioning is inappropriate for storing revision data like a wiki page.

Final notes

At least one sentence in this writeup (possibly this one) is complete BS.


问:
Need Suggestion.
How to debug "NameError: global name 'X' is not defined" in Python? I am pretty much new in Python. I am using jupyter_notebook with Python 2.7 to execute code. I am facing following error.

My code:

```<code>logFile = "NASAlog.txt"

def parseLogs():
    parsed_logs=(sc
            .textFile(logFile)
            .map(parseApacheLogLine)
            .cache())

    access_logs = (parsed_logs
            .filter(lambda s: s[1] == 1)
            .map(lambda s: s[0])
            .cache())

    failed_logs = (parsed_logs
            .filter(lambda s: s[1] == 0)
            .map(lambda s: s[0]))
    failed_logs_count = failed_logs.count()
    if failed_logs_count > 0:
        print 'Number of invalid logline: %d' % failed_logs.count()
        for line in failed_logs.take(20):
            print 'Invalid logline: %s' % line

    print 'Read %d lines, successfully parsed %d lines, failed to parse %d lines' % (parsed_logs.count(), access_logs.count(), failed_logs.count())
    return parsed_logs, access_logs, failed_logs

parsed_logs, access_logs, failed_logs = parseLogs()
</code>```

ERROR

```<code>> NameError   Traceback (most recent call last)
>           <ipython-input-18-b365aa793252> in <module>()
>      24     return parsed_logs, access_logs, failed_logs
>      25
> ---> 26 parsed_logs, access_logs, failed_logs = parseLogs()
>
> <ipython-input-18-b365aa793252> in parseLogs()
>       2
>       3 def parseLogs():
> ----> 4     parsed_logs=(sc
>       5             .textFile(logFile)
>       6             .map(parseApacheLogLine)
>
> NameError: global name 'sc' is not defined
</code>```

答:
The problem is that you did never define sc. Therefore python can't find it. (Makes sense, doesn't it?)

Now there are several possible reasons:
- python is case-sensitive. Did you somewhere define SC instead of sc? ... Or Sc instead of sc?

You defined sc in another function (-> you defined it in a function outside parseLogs()). If you only define it there the variable will be local and just be available to the code inside the function. Add the line global sc to the first line of your function to make it accessible everywhere in you whole code.

You simply did not define sc.

Title: Need Suggestion.

Body:
How to debug "NameError: global name 'X' is not defined" in Python? I am pretty much new in Python. I am using jupyter_notebook with Python 2.7 to execute code. I am facing following error.

My code:

logFile = "NASAlog.txt"

def parseLogs():
    parsed_logs=(sc
            .textFile(logFile)
            .map(parseApacheLogLine)
            .cache())

    access_logs = (parsed_logs
            .filter(lambda s: s[1] == 1)
            .map(lambda s: s[0])
            .cache())

    failed_logs = (parsed_logs
            .filter(lambda s: s[1] == 0)
            .map(lambda s: s[0]))
    failed_logs_count = failed_logs.count()
    if failed_logs_count > 0:
        print 'Number of invalid logline: %d' % failed_logs.count()
        for line in failed_logs.take(20):
            print 'Invalid logline: %s' % line

    print 'Read %d lines, successfully parsed %d lines, failed to parse %d lines' % (parsed_logs.count(), access_logs.count(), failed_logs.count())
    return parsed_logs, access_logs, failed_logs

parsed_logs, access_logs, failed_logs = parseLogs()

ERROR

> NameError   Traceback (most recent call last)
>           <ipython-input-18-b365aa793252> in <module>()
>      24     return parsed_logs, access_logs, failed_logs
>      25
> ---> 26 parsed_logs, access_logs, failed_logs = parseLogs()
>
> <ipython-input-18-b365aa793252> in parseLogs()
>       2
>       3 def parseLogs():
> ----> 4     parsed_logs=(sc
>       5             .textFile(logFile)
>       6             .map(parseApacheLogLine)
>
> NameError: global name 'sc' is not defined