问:
In Json4s why does an integer field in a JSON object get automatically converted to a String?
If I have a JSON object like:

```<code>{
  "test": 3
}
</code>```

Then I would expect that extracting the "test" field as a String would fail because the types don't line up:

import org.json4s._
import org.json4s.jackson.JsonMethods
import org.json4s.JsonAST.JValue

def getVal[T: Manifest](json: JValue, fieldName: String): Option[T] = {
  val field = json findField {
    case JField(name, _) if name == fieldName => true
    case _ => false
  }

  field.map {
    case (_, value) => value.extract[T]
  }
}

val json = JsonMethods.parse("""{"test":3}""")
val value: Option[String] = getVal[String](json, "test") // Was Some(3) but expected None
```

Is this automatic conversion from a JSON numeric to a String expected in Json4s? If so, are there any workarounds for this where the extracted field has to be of the same type that is specified in the type parameter to the extract method?

答:
One simple workaround is to create a custom serializer for cases where you want "strict" behavior. For example:

```<code>  import org.json4s._

  val stringSerializer = new CustomSerializer[String](_ => (
    {
      case JString(s) => s
      case JNull      => null
      case x          => throw new MappingException("Can't convert %s to String." format x)
    },
    {
      case s: String => JString(s)
    }
  ))
</code>```

Adding this serializer to your implicit formats ensures the strict behavior:

```<code>  implicit val formats = DefaultFormats + stringSerializer

  val js = JInt(123)
  val str = js.extract[String] // throws MappingException
</code>```

Body:
If I have a JSON object like:

{
  "test": 3
}

Then I would expect that extracting the "test" field as a String would fail because the types don't line up:

import org.json4s._
import org.json4s.jackson.JsonMethods
import org.json4s.JsonAST.JValue

def getVal[T: Manifest](json: JValue, fieldName: String): Option[T] = {
  val field = json findField {
    case JField(name, _) if name == fieldName => true
    case _ => false
  }

  field.map {
    case (_, value) => value.extract[T]
  }
}

val json = JsonMethods.parse("""{"test":3}""")
val value: Option[String] = getVal[String](json, "test") // Was Some(3) but expected None

Is this automatic conversion from a JSON numeric to a String expected in Json4s? If so, are there any workarounds for this where the extracted field has to be of the same type that is specified in the type parameter to the extract method?

Body:
One simple workaround is to create a custom serializer for cases where you want "strict" behavior. For example:

  import org.json4s._

  val stringSerializer = new CustomSerializer[String](_ => (
    {
      case JString(s) => s
      case JNull      => null
      case x          => throw new MappingException("Can't convert %s to String." format x)
    },
    {
      case s: String => JString(s)
    }
  ))

Adding this serializer to your implicit formats ensures the strict behavior:

  implicit val formats = DefaultFormats + stringSerializer

  val js = JInt(123)
  val str = js.extract[String] // throws MappingException


来源: stackexchange

问:
Asynch calls versus multi-threading
I have a Windows Service in VB.NET that makes calls to several long running processes (regular subroutines, not web svc, remoting, or anything fancy) in sequence. I'm leary about trying to implement multithreading just because we've never done it before and this is mission crticial code. I had the thought of calling the routines asynchronously instead. I'm familiar with that and use it as part of some web services. Am I missing something? It seems like asynch calls is a "poor mans" way to avoid multithreading issues.</p>

答:
I don't know what multithreading issues you expect to avoid by making asynchronous calls. Asynchronous calls are multithreading. The only real difference is that an async call is typically used for a relatively short-lived task whereas traditional multithreading (where you  explicitly create a thread and start it running) is typically used for long-running tasks.

Either way, you still have the same concurrency issues.

You can use asynchronous calls for long-running tasks. In fact, the Task class has a constructor that lets you specify creation options, including TaskCreationOptions.LongRunning.

Managing your own threads using the Thread class is a little bit more complicated than using something like Task or ThreadPool.QueueUserWorkItem, but it also gives you slightly more control. Any way you do it, you have to deal with concurrency issues like race conditions and thread-safe data structures (if multiple threads are modifying a data structure). I wouldn't call asynchronous calls a "poor man's multithreading." The differences aren't that large. They're just two different ways to accomplish the same thing.

ContentLicense: CC BY-SA 3.0

Title: Asynch calls versus multi-threading


问:
Javascript Prototype chaining change the target
I am a student studying programming.

I have a question.

```<code>    function a () {

    }

    a.prototype.prtSomething = function(arg) { console.log(arg); }

    function b () {

    }

    var myObj = new b();
</code>```

If I want to use the method of a in myObj, we use this code.

```<code>b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;
</code>```

That means changing the target of scope chaining.
But why don't we use this code?

```<code>b.prototype.__proto__ = a.prototype;
</code>```

I think there must be a reason to creating and using a new object.
but I don't know.
Please teach me.
Thank you.

答:
For at least one good reason: the __proto__ feature is deprecated, so you shouldn't use it for future compatibility.

I recommend reading MDN page on the topic, and also linked pages on inheritance if you are learning.

USEFUL ADDITIONAL NOTE:
using b.prototype = Object.create(a.prototype); is a way to simulate Class inheritance in a prototype way (b inherits from a) without the "parent" (a) constructor to be called. If you would rather prefer to simulate inheritance with "parent" constructor being called, you can use b.prototype = new a();

Of course it's a emulation of class behavior, it differs in details because prototypes are not classes, for example you can dynamically add functions to a's prototype after an instance of b has been created, and the new function will be available for the instance because it works by reference. In a similar way the second example doesn't execute a's constructor for every further instance, but only once when you assign it to b's prototype.

Actually I find prototypes really powerful when you get to know them, allows many combinations.

function a () {
    console.log('a constructor');
}

a.prototype.prtSomething = function(arg) { console.log(arg); }

function b () {
    console.log('b constructor');
}

b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;

var myObj = new b();```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function a () {
    console.log('a constructor');
}

a.prototype.prtSomething = function(arg) { console.log(arg); }

function b () {
    console.log('b constructor');
}

b.prototype = new a();
b.prototype.constructor = b;

var myObj = new b();</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a student studying programming.

I have a question.

    function a () {

    }

    a.prototype.prtSomething = function(arg) { console.log(arg); }

    function b () {

    }

    var myObj = new b();

If I want to use the method of a in myObj, we use this code.

b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;

That means changing the target of scope chaining.
But why don't we use this code?

b.prototype.__proto__ = a.prototype;

I think there must be a reason to creating and using a new object.
but I don't know.
Please teach me.
Thank you.

Body:
For at least one good reason: the __proto__ feature is deprecated, so you shouldn't use it for future compatibility.

I recommend reading MDN page on the topic, and also linked pages on inheritance if you are learning.

USEFUL ADDITIONAL NOTE:
using b.prototype = Object.create(a.prototype); is a way to simulate Class inheritance in a prototype way (b inherits from a) without the "parent" (a) constructor to be called. If you would rather prefer to simulate inheritance with "parent" constructor being called, you can use b.prototype = new a();

Of course it's a emulation of class behavior, it differs in details because prototypes are not classes, for example you can dynamically add functions to a's prototype after an instance of b has been created, and the new function will be available for the instance because it works by reference. In a similar way the second example doesn't execute a's constructor for every further instance, but only once when you assign it to b's prototype.

Actually I find prototypes really powerful when you get to know them, allows many combinations.

function a () {
    console.log('a constructor');
}

a.prototype.prtSomething = function(arg) { console.log(arg); }

function b () {
    console.log('b constructor');
}

b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;

var myObj = new b();

function a () {
    console.log('a constructor');
}

a.prototype.prtSomething = function(arg) { console.log(arg); }

function b () {
    console.log('b constructor');
}

b.prototype = new a();
b.prototype.constructor = b;

var myObj = new b();


问:
Iterating Ansible setup command
I want to use ansible setup module to retrieve hosts specs and I tried with  a bash for loop.

Ansible version: 2.4

My hosts inventory has been defined in a group of machines which I called rhelmachines

I would like to collect the following list of variables called "specs"

```<code>declare -a specs=("ansible_all_ipv4_addresses" "ansible_processor" "ansible_processor_cores" "ansible_uptime_seconds")
</code>```

I am then trying to include the ansible command in a for bash loop:

```<code>for i in "${specs[@]}"
do
    ansible rhelmachines -m setup -a 'filter='$i'
done
</code>```

how can I concatenate multiple filters in one connection only ?

Thanks!

答:
I took @Luigi Sambolino answer and make it better. His answer was failing on more than one host in the inventory. He proposed using lineinfile which has one con in this situation - every fact that was the same as other machines were omitted. Other drawback was that results wasn't sorted together, all was mixed.

I needed to take some basic information about systems, like IP, OS version, and so on. Here's my playbook:

```<code>- hosts: all
  gather_facts: true
  ignore_unreachable: true
  tasks:
  - name: get the facts
    setup:
      gather_subset=all
    register: facts
  - name: remove file
    local_action:
      module: file
      path: results
      state: absent
  - name: save results in file
    local_action:
      module: shell
      cmd: echo "{{ item }}" >> results
    with_together:
      - "{{ facts.ansible_facts.ansible_default_ipv4.address }}"
      - "{{ facts.ansible_facts.ansible_architecture }}"
      - "{{ facts.ansible_facts.ansible_distribution }}"
      - "{{ facts.ansible_facts.ansible_distribution_version }}"
      - "{{ facts.ansible_facts.ansible_hostname }}"
      - "{{ facts.ansible_facts.ansible_kernel }}"
</code>```

Now the results look like this:

```<code>...
['10.200.1.21', 'x86_64', 'Ubuntu', '18.04', 'bacula', '4.15.18-7-pve']
['10.200.2.53', 'x86_64', 'Ubuntu', '18.04', 'webserver', '4.15.18-27-pve']
...
</code>```

Square brackets can be deleted by sed and we have a nice CSV file that can be used with any spreadsheet, for example.

Title: Iterating Ansible setup command

Body:
I want to use ansible setup module to retrieve hosts specs and I tried with  a bash for loop.

Ansible version: 2.4

My hosts inventory has been defined in a group of machines which I called rhelmachines

I would like to collect the following list of variables called "specs"

declare -a specs=("ansible_all_ipv4_addresses" "ansible_processor" "ansible_processor_cores" "ansible_uptime_seconds")

I am then trying to include the ansible command in a for bash loop:

for i in "${specs[@]}"
do
    ansible rhelmachines -m setup -a 'filter='$i'
done

how can I concatenate multiple filters in one connection only ?

Thanks!

Body:
I took @Luigi Sambolino answer and make it better. His answer was failing on more than one host in the inventory. He proposed using lineinfile which has one con in this situation - every fact that was the same as other machines were omitted. Other drawback was that results wasn't sorted together, all was mixed.

I needed to take some basic information about systems, like IP, OS version, and so on. Here's my playbook:

- hosts: all
  gather_facts: true
  ignore_unreachable: true
  tasks:
  - name: get the facts
    setup:
      gather_subset=all
    register: facts
  - name: remove file
    local_action:
      module: file
      path: results
      state: absent
  - name: save results in file
    local_action:
      module: shell
      cmd: echo "{{ item }}" >> results
    with_together:
      - "{{ facts.ansible_facts.ansible_default_ipv4.address }}"
      - "{{ facts.ansible_facts.ansible_architecture }}"
      - "{{ facts.ansible_facts.ansible_distribution }}"
      - "{{ facts.ansible_facts.ansible_distribution_version }}"
      - "{{ facts.ansible_facts.ansible_hostname }}"
      - "{{ facts.ansible_facts.ansible_kernel }}"

Now the results look like this:

...
['10.200.1.21', 'x86_64', 'Ubuntu', '18.04', 'bacula', '4.15.18-7-pve']
['10.200.2.53', 'x86_64', 'Ubuntu', '18.04', 'webserver', '4.15.18-27-pve']
...

Square brackets can be deleted by sed and we have a nice CSV file that can be used with any spreadsheet, for example.


问:
C# if statement interpretation
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

```<code>1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false
</code>```

答:
The || operator applies the short-circuit evaluation.

So, for the || operator, if the first term of the expression is true there is no need to evaluate (execute) the second term.

The effect of this logic on your code is that the second part of the expression in line 5 is not executed and the variable b remains at 1 after the decrement.

This leads to the line 6 giving false as result

Title: C# if statement interpretation

Body:
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false


问:
Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Ok, so I decided to use selenium for some code, but it doesn't work. When I put the chromedriver in my path, manually, it still doesn't work. can anyone help. PS: I already pip installed selenium.

Also, I watch/read the other article on stack overflow about this problem, but it didn't help me.

答:
Well add change the code to this

import os

path = os.path.join(os.path.dirname(os.path.realpath(__file__)) + r'\chromedriver')
driver = webdriver.Chrome(executable_path = path)

```

So what is does is it add the chrome webdriver from path to selenium webdriver. Make sure to add the chromedriver.exe file in the root of the folder.

Body:
Well add change the code to this

import os

path = os.path.join(os.path.dirname(os.path.realpath(__file__)) + r'\chromedriver')
driver = webdriver.Chrome(executable_path = path)

So what is does is it add the chrome webdriver from path to selenium webdriver. Make sure to add the chromedriver.exe file in the root of the folder.


问:
How the node in Corda restore data in Enterprise Corda Version
I set up a network with 2 normal Node (NodeA and NodeB) and 1 Notary. If NodeA has shut down and lose apart of its database (about current states), how can We ensure that the network may run as well. And how does NodeA restore this data that loss? (Can Enterprise Corda Version help me in this case?)</p>

答:
When a database admin deletes your data, Corda will not be able to help you. You are responsible for your own database. You need to ensure that only authorized parties have permissions to access the database.
Let's say that PartyA now does not have latest states/ data for your custom tables. In this scenario, PartyA can request PartyB for this missing state if PartyB was also a participant to the state. It depends on PartyB whether to share this state to PartyA. </p>

<p>There is a built in flow to send the state from one party to other </p>

```<code>SendStateAndRefFlow(otherSideSession: FlowSession, stateAndRefs: List<StateAndRef<*>>)
</code>```

Body:
When a database admin deletes your data, Corda will not be able to help you. You are responsible for your own database. You need to ensure that only authorized parties have permissions to access the database.
Let's say that PartyA now does not have latest states/ data for your custom tables. In this scenario, PartyA can request PartyB for this missing state if PartyB was also a participant to the state. It depends on PartyB whether to share this state to PartyA.

There is a built in flow to send the state from one party to other

SendStateAndRefFlow(otherSideSession: FlowSession, stateAndRefs: List<StateAndRef<*>>)


问:
The call is ambiguous between the following methods: Identical.NameSpace.InitializeComponent() and Identical.NameSpace.InitializeComponent()
Ok, I suspect this might be a Visual Studio thing, but there must be some reason for this. I created from the list of default items a ListBox (Right Click on project, or folder in project -> Add -> New Item -> Xaml ListBox). Immediately I get a red squiggly line with the error:

"Error    2   The call is ambiguous between the following methods or
  properties: 'Identical.NameSpace.ListBox1.InitializeComponent()' and
  'Identical.NameSpace.ListBox1.InitializeComponent()'  C:\Documents and
  Settings\ouflak\My Documents\Visual Studio
  2010\Projects\Identical\NameSpace\ListBox1.xaml.cs   27"

All of the code in question is auto-generated and the reason for the error is because of a conflict between two auto-generated files: ListBox1.g.cs and ListBox1.designer.cs where public void InitializeComponent() is declared in both. Naturally the code cannot compile under this circumstance. It is simple enough to just delete the ListBox1.designer.cs and move on I suppose. But my question: Why is this code auto-generated with this error? I would expect anything auto-generated to be able to build and compile without having to touch the project or any code. For just about every other toobox item that you can add, this is the case. So why generate this code with the built-in error? Are we supposed to find some way to make this work? Is this code merely a suggestion and it is up to the IDE user/developer to hammer out the details?

Here is the generated code:
ListBox1.xaml:

```<code>< ?xml version="1.0" encoding="utf-8" ? >
< ListBox
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:xc="http://ns.neurospeech.com/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    x:Class="Identical.NameSpace.ListBox1"
    >
    <sys:String>Item 1</sys:String>
    <sys:String>Item 2</sys:String>
    <sys:String>Item 3</sys:String>
< /ListBox>
</code>```

ListBox1.g.cs:

```<code>namespace Identical.Namespace
{
    /// <summary>
    /// ListBox1
    /// </summary>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    public partial class ListBox1 : System.Windows.Controls.ListBox, System.Windows.Markup.IComponentConnector {

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
            return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/MyProject;component/namespace/listbox1.xaml", System.UriKind.Relative);

            #line 1 "..\..\..\namespace\ListBox1.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)     {
        this._contentLoaded = true;
        }
    }
}
</code>```

ListBox1.designer.cs:

```<code>namespace Identical.NameSpace
{
    using System;

    public partial class ListBox1 : System.Windows.Controls.ListBox
    {
        private void InitializeComponent()
        {
            // Pre Statements...
            string string1 = "Item 1";
            string string2 = "Item 2";
            string string3 = "Item 3";
            // Statements...
            this.BeginInit();
            this.Items.Add(string1);
            this.Items.Add(string2);
            this.Items.Add(string3);
            this.EndInit();
            // Post Statements...
        }
    }
}
</code>```

and lastly the ListBox1.xaml.cs (only modified to prevent XML documentation and Stylecop warnings):

```<code>namespace Identical.NameSpace
{
    /// <summary>
    /// ListBox1 class
    /// </summary>
    public partial class ListBox1 : ListBox
    {
        /// <summary>
        /// Initializes a new instance of the ListBox1 class
        /// </summary>
        public ListBox1()
        {
            this.InitializeComponent();
        }
    }
}
</code>```

That's it. This is the code entirely in its virgin auto-generated state with the exception of the comments I put into the xaml.cs file.

I've searched this site and the internet a bit, but no one seems to have explained this behavior. I will probably just delete the designer.cs code and move on. But if anybody knows why this is here in the first place, or if it is indeed a bug in Visual Studio 2010 professional, I'd really like to know.

答:
I had the same problem after changing a bunch of files at once, here's how I fixed it:

Find the solution in Solution Explorer (View -> Solution Explorer)

Right-click on the solution and click "Clean Solution"

.. and that's it! Visual Studio can be weird sometimes..

Body:
Ok, I suspect this might be a Visual Studio thing, but there must be some reason for this. I created from the list of default items a ListBox (Right Click on project, or folder in project -> Add -> New Item -> Xaml ListBox). Immediately I get a red squiggly line with the error:

"Error    2   The call is ambiguous between the following methods or
  properties: 'Identical.NameSpace.ListBox1.InitializeComponent()' and
  'Identical.NameSpace.ListBox1.InitializeComponent()'  C:\Documents and
  Settings\ouflak\My Documents\Visual Studio
  2010\Projects\Identical\NameSpace\ListBox1.xaml.cs   27"

All of the code in question is auto-generated and the reason for the error is because of a conflict between two auto-generated files: ListBox1.g.cs and ListBox1.designer.cs where public void InitializeComponent() is declared in both. Naturally the code cannot compile under this circumstance. It is simple enough to just delete the ListBox1.designer.cs and move on I suppose. But my question: Why is this code auto-generated with this error? I would expect anything auto-generated to be able to build and compile without having to touch the project or any code. For just about every other toobox item that you can add, this is the case. So why generate this code with the built-in error? Are we supposed to find some way to make this work? Is this code merely a suggestion and it is up to the IDE user/developer to hammer out the details?

Here is the generated code:
ListBox1.xaml:

< ?xml version="1.0" encoding="utf-8" ? >
< ListBox
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:xc="http://ns.neurospeech.com/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    x:Class="Identical.NameSpace.ListBox1"
    >
    <sys:String>Item 1</sys:String>
    <sys:String>Item 2</sys:String>
    <sys:String>Item 3</sys:String>
< /ListBox>

ListBox1.g.cs:

namespace Identical.Namespace
{
    ///
    /// ListBox1
    ///
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    public partial class ListBox1 : System.Windows.Controls.ListBox, System.Windows.Markup.IComponentConnector {

        private bool _contentLoaded;

        ///
        /// InitializeComponent
        ///
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
            return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/MyProject;component/namespace/listbox1.xaml", System.UriKind.Relative);

            #line 1 "..\..\..\namespace\ListBox1.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)     {
        this._contentLoaded = true;
        }
    }
}

ListBox1.designer.cs:

namespace Identical.NameSpace
{
    using System;

    public partial class ListBox1 : System.Windows.Controls.ListBox
    {
        private void InitializeComponent()
        {
            // Pre Statements...
            string string1 = "Item 1";
            string string2 = "Item 2";
            string string3 = "Item 3";
            // Statements...
            this.BeginInit();
            this.Items.Add(string1);
            this.Items.Add(string2);
            this.Items.Add(string3);
            this.EndInit();
            // Post Statements...
        }
    }
}

and lastly the ListBox1.xaml.cs (only modified to prevent XML documentation and Stylecop warnings):

namespace Identical.NameSpace
{
    ///
    /// ListBox1 class
    ///
    public partial class ListBox1 : ListBox
    {
        ///
        /// Initializes a new instance of the ListBox1 class
        ///
        public ListBox1()
        {
            this.InitializeComponent();
        }
    }
}

That's it. This is the code entirely in its virgin auto-generated state with the exception of the comments I put into the xaml.cs file.

I've searched this site and the internet a bit, but no one seems to have explained this behavior. I will probably just delete the designer.cs code and move on. But if anybody knows why this is here in the first place, or if it is indeed a bug in Visual Studio 2010 professional, I'd really like to know.


问:
How to use clock() in C++
How do I call clock() in C++?

For example, I want to test how much time a linear search takes to find a given element in an array.

答:
You can measure how long your program works. The following functions help measure the CPU time since the start of the program:

C++ (double)clock() / CLOCKS_PER_SEC with ctime included.

Python time.clock() returns floating-point value in seconds.

Java System.nanoTime() returns long value in nanoseconds.

My reference: algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

So you can add this line of code after your algorithm:

```<code>cout << (double)clock() / CLOCKS_PER_SEC;
</code>```

Expected Output: the output representing the number of clock ticks per second

ContentLicense: CC BY-SA 2.5

Title: How to use clock() in C++

Body:
You can measure how long your program works. The following functions help measure the CPU time since the start of the program:

C++ (double)clock() / CLOCKS_PER_SEC with ctime included.

Python time.clock() returns floating-point value in seconds.

Java System.nanoTime() returns long value in nanoseconds.

My reference: algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

So you can add this line of code after your algorithm:

cout << (double)clock() / CLOCKS_PER_SEC;

Expected Output: the output representing the number of clock ticks per second


问:
Make POST request from HTML
I want to make an HTTP POST request from an HTML anchor tag that has the URL in its href attribute.

How can I make it use POST instead of GET?

```<code><a href='http:/test_url:5002/api/GetFile'></a>
</code>```

I also want to set parameters in the body of the request. How can I do that?

I want to find a way to include them in the HTML tag itself, not in a JavaScript file.

答:
there's only one way for you to POST data with a link... you would need to wrap the code in a <form> and use that link to submit the form, for example:

<form id="frm" ation="http:/test_url:5002/api/GetFile">
  <input type="hidden" name="param1" value="value_for_param1" />
  ...

  ...
</form>
```

any input can be used to append parameters to the <form>, as an example, the hidden is used

now, remember that you shouldn't use http:/test_url:5002 just minimize to /api/getfile or you would most likely get caught into CORS issues

Title: Make POST request from HTML

Body:
I want to make an HTTP POST request from an HTML anchor tag that has the URL in its href attribute.

How can I make it use POST instead of GET?

I also want to set parameters in the body of the request. How can I do that?

I want to find a way to include them in the HTML tag itself, not in a JavaScript file.

Body:
there's only one way for you to POST data with a link... you would need to wrap the code in a <form> and use that link to submit the form, for example:

<form id="frm" ation="http:/test_url:5002/api/GetFile">
  <input type="hidden" name="param1" value="value_for_param1" />
  ...
  <a href="#" onclick="document.querySelector('#frm').submit()"></a>
  ...
</form>

any input can be used to append parameters to the <form>, as an example, the hidden is used

now, remember that you shouldn't use http:/test_url:5002 just minimize to /api/getfile or you would most likely get caught into CORS issues


问:
Can I do an IF statement / Ternary Operator within an ?
Okay, I know this might seem a little off but I am trying to achieve a solution where an image URL is used only when the image URL is valid and exists.

```<code>$imglink = URL . 'public/uploads/profile/' . $value['image'];  //valid to be used if image exists
$defaultLink = URL . 'public/images/profile-img.jpg';   // To be used if $imglink is not available
</code>```

What I have tried is:

```<code>$loki = $imglink ? $imglink : $defaultLink;

$imageURL = "<img src='$loki'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";
</code>```

ALSO Tried this:

```<code>$imageURL = "<img src='<?php echo $imglink ? $imglink : $defaultLink />'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";
</code>```

I have tried using different approaches but it isn't working. Also, this is being done in a Codeigniter Controller file.

答:
You could first check the value in ternary operator and then assign it properly-

```<code>// check if $value['image'] is set and not empty; assign value accordingly.
$img = ( !empty($value['image']) ) ? ( URL . 'public/uploads/profile/' . $value['image'] ) : ( URL . 'public/images/profile-img.jpg' );

// give that value in src of img tag
$imageURL = "<img src='" .$img. "'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";
</code>```

See if it helps you. :)

Title: Can I do an IF statement / Ternary Operator within an <img src' ' >?

Body:
Okay, I know this might seem a little off but I am trying to achieve a solution where an image URL is used only when the image URL is valid and exists.

$imglink = URL . 'public/uploads/profile/' . $value['image'];  //valid to be used if image exists
$defaultLink = URL . 'public/images/profile-img.jpg';   // To be used if $imglink is not available

What I have tried is:

$loki = $imglink ? $imglink : $defaultLink;

$imageURL = "";

ALSO Tried this:

$imageURL = "<img src='<?php echo $imglink ? $imglink : $defaultLink />'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";

I have tried using different approaches but it isn't working. Also, this is being done in a Codeigniter Controller file.

Body:
You could first check the value in ternary operator and then assign it properly-

// check if $value['image'] is set and not empty; assign value accordingly.
$img = ( !empty($value['image']) ) ? ( URL . 'public/uploads/profile/' . $value['image'] ) : ( URL . 'public/images/profile-img.jpg' );

// give that value in src of img tag
$imageURL = "<img src='" .$img. "'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";

See if it helps you. :)


问:
wp core install cannot connect to database with WP-CLI
I don't know why it's doing this but for some reason, when I try to install WordPress with WP CLI with wp core install, it cannot complete and throws the Error: Error establishing a database connection error.

I've checked everything and I'm not sure what the issue is. I'm using MAMP PRO and all of the settings in the wp-config.php file are correct.

I'm connecting via localhost and the database is created just fine and I can see that there.

I've tried changing localhost to 127.0.0.1 in the wp-config file, but that borks outright.

Username and Password to connect are the default of root and root.

If I go to the local URL directly, I can see the WP install screen and then after I select the language, it redirects me to the setup where I can name the site, username, password, etc. I never see the DB connection info at all.

I did have to set this in my .zshrc file:
export PATH=$PATH:/Applications/MAMP/Library/bin/ cause it was having an issue when creating the wp-config file with wp config create, but once I added that, it was able to create the wp-config file without errors, so maybe that might be an issue?  But overall, I'm stumped. I had a bash script that was working to generate all of this automatically, but now I'm not sure what the issue could be since it appears everything is setup correctly.

答:
If you're running on Mac and using MAMP, update hostname in wp-config.php </p>

```<code>define( 'DB_HOST', 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock' );
</code>```

Body:
If you're running on Mac and using MAMP, update hostname in wp-config.php

define( 'DB_HOST', 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock' );


问:
PHP timezone not set
First of all, i don't have access to the php.ini in the webserver.

In my local server I put date.timezone = "Europe/Lisbon" in my php.ini.

Is it possible to change this in .htaccess? or, what is the alternative?

At the moment I get this error in web server for phpmailer():

```<code>Strict Standards:  date(): It is not safe to rely on the system's timezone settings. ....
</code>```

答:
Try ini_set at the top of your script.

```<code>ini_set("date.timezone", "Europe/Lisbon");
</code>```

Title: PHP timezone not set

Body:
First of all, i don't have access to the php.ini in the webserver.

In my local server I put date.timezone = "Europe/Lisbon" in my php.ini.

Is it possible to change this in .htaccess? or, what is the alternative?

At the moment I get this error in web server for phpmailer():

Strict Standards:  date(): It is not safe to rely on the system's timezone settings. ....

Body:
Try ini_set at the top of your script.

ini_set("date.timezone", "Europe/Lisbon");


问:
MongoDB $match $group query slow
So I have the following query for about 500k documents and it is really slow on the database side:

```<code>db.collection('news').aggregate(
    [
      {
        $match: {
          feeds: { $in: feeds },
          createdAt: { $lte: lastPostDate },
          deleted: {
            $exists: false
          }
        }
      },
      {
        $group: {
          _id: { title: '$title' },
          id: { $first: '$_id' },
          title: { $addToSet: '$title' },
          source: { $first: '$source' },
          shortid: { $first: '$shortid' },
          stats: { $first: '$stats' },
          log: { $first: '$log' },
          createdAt: { $first: '$createdAt' },
          feedUpdated: { $first: '$feedUpdated' },
          media: { $first: '$media' },
          title: { $first: '$title' }
        }
      },
      { $sort: sort },
      {
        $skip: limit * (page - 1)
      },
      {
        $limit: limit * 1
      }
    ],
    {
      allowDiskUse: true,
      cursor: {}
    }
)
</code>```

I know the allowDiskUse is making it slow, but if I disable it I get:

MongoError: Exceeded memory limit for $group, but didn't allow
  external sort. Pass allowDiskUse:true to opt in.

答:
```<code>let aggregation = MongoSchemaModel.aggregate([]);
aggregation.options = { allowDiskUse: true };
aggregation.exec((err, data) => {});
</code>```

OR

```<code>let aggregation = MongoSchemaModel.aggregate([], { allowDiskUse: true });
aggregation.exec((err, data) => {});
</code>```

Reference:-
https://mkyong.com/mongodb/mongodb-sort-exceeded-memory-limit-of-104857600-bytes/

Title: MongoDB $match $group query slow

Body:
So I have the following query for about 500k documents and it is really slow on the database side:

db.collection('news').aggregate(
    [
      {
        $match: {
          feeds: { $in: feeds },
          createdAt: { $lte: lastPostDate },
          deleted: {
            $exists: false
          }
        }
      },
      {
        $group: {
          _id: { title: '$title' },
          id: { $first: '$_id' },
          title: { $addToSet: '$title' },
          source: { $first: '$source' },
          shortid: { $first: '$shortid' },
          stats: { $first: '$stats' },
          log: { $first: '$log' },
          createdAt: { $first: '$createdAt' },
          feedUpdated: { $first: '$feedUpdated' },
          media: { $first: '$media' },
          title: { $first: '$title' }
        }
      },
      { $sort: sort },
      {
        $skip: limit * (page - 1)
      },
      {
        $limit: limit * 1
      }
    ],
    {
      allowDiskUse: true,
      cursor: {}
    }
)

I know the allowDiskUse is making it slow, but if I disable it I get:

MongoError: Exceeded memory limit for $group, but didn't allow
  external sort. Pass allowDiskUse:true to opt in.

Body:
let aggregation = MongoSchemaModel.aggregate([]);
aggregation.options = { allowDiskUse: true };
aggregation.exec((err, data) => {});

OR

let aggregation = MongoSchemaModel.aggregate([], { allowDiskUse: true });
aggregation.exec((err, data) => {});

Reference:-
https://mkyong.com/mongodb/mongodb-sort-exceeded-memory-limit-of-104857600-bytes/


问:
Filter an array taking into account that the filtered options are optional
I have a code that should filter the array depending on some condition. One time it could be 1 condition or 2, depending on how many user are inserted.

const arr = [
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
  {
    name: 'Bill',
    age: 47,
    old: 'No'
  },
]
const filteredData = [4, "John", "No"];

var find = arr.filter(function(result) {
  return filteredData.includes(result.name) && filteredData.includes(result.age) && filteredData.includes(result.old);
})

console.log(find)```
</div>
</div>
</p>

<p>In this case the code works, but if I add just one value in <code>const filteredData = [4, "John", "No" ];</code>, like: <code>const filteredData = ["John"];</code>, I should get:</p>

```[
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
]
```

...but now I don't get anything, because in filteredData all 3 conditions should be mandatory. How to change the code to make the number of condition optional?

答:
May be I can help you.

```<code>const arr = [
  {
    name:'John',
    age:44,
    old:'No'
  },
   {
    name:'John',
    age:4,
    old:'No'
  },
  {
    name:'Bill',
    age:47,
    old:'No'
  },
]
const filteredData = ["John"];

const newArr = arr.filter((it) => !filteredData.indexOf(it.name))

display.log(JSON.stringify(newArr))
</code>```

And now You can see this objects which consists of name John.

Body:
I have a code that should filter the array depending on some condition. One time it could be 1 condition or 2, depending on how many user are inserted.

const arr = [
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
  {
    name: 'Bill',
    age: 47,
    old: 'No'
  },
]
const filteredData = [4, "John", "No"];

var find = arr.filter(function(result) {
  return filteredData.includes(result.name) && filteredData.includes(result.age) && filteredData.includes(result.old);
})

console.log(find)

In this case the code works, but if I add just one value in const filteredData = [4, "John", "No" ];, like: const filteredData = ["John"];, I should get:

[
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
]

...but now I don't get anything, because in filteredData all 3 conditions should be mandatory. How to change the code to make the number of condition optional?

Body:
May be I can help you.

const arr = [
  {
    name:'John',
    age:44,
    old:'No'
  },
   {
    name:'John',
    age:4,
    old:'No'
  },
  {
    name:'Bill',
    age:47,
    old:'No'
  },
]
const filteredData = ["John"];

const newArr = arr.filter((it) => !filteredData.indexOf(it.name))

display.log(JSON.stringify(newArr))

And now You can see this objects which consists of name John.


问:
How can I prevent Chromium from writing to the console?
I'm making a very simple Delphi console application ({$APPTYPE CONSOLE}) with a single TChromiumWindow on the main form. The purpose of the application is to retrieve a webpage, process the HTML and output some JSON to the console. This can not be done using plain HTTP requests due to the nature of the webpage, which requires running some javascript as well.

Everything works as expected, except for one problem. The chromium components output some error messages to the console as well, which makes my JSON invalid! For example, I always get the following two error messages on startup:

```<code>[0529/133941.811:ERROR:gpu_process_transport_factory.cc(990)] Lost UI shared context.
[0529/133941.832:ERROR:url_request_context_getter_impl.cc(130)] Cannot use V8 Proxy resolver in single process mode.
</code>```

Of course the best solution would be to not get any error messages in the first place, but for several reasons (which mostly have to do with company legacy code) I can't for example disable single process mode.

So the next best thing would be to keep these error messages from being printed to the console. I've tried setting

```<code>GlobalCEFApp.LogSeverity := LOGSEVERITY_DISABLE;
</code>```

but that didn't help. Specifying a logfile using GlobalCEFApp.LogFile doesn't help either.

So how can I prevent the Chromium components from writing to the console at all?

答:
The TChromium component provides an OnConsoleMessage event with signature :

```<code> TOnConsoleMessage = procedure(Sender: TObject; const browser: ICefBrowser;
                               const message, source: ustring; line: Integer;
                               out Result: Boolean) of object;
</code>```

If you handle this event and set the Result variable to true the message output to the console is suppressed.

Body:
I'm making a very simple Delphi console application ({$APPTYPE CONSOLE}) with a single TChromiumWindow on the main form. The purpose of the application is to retrieve a webpage, process the HTML and output some JSON to the console. This can not be done using plain HTTP requests due to the nature of the webpage, which requires running some javascript as well.

Everything works as expected, except for one problem. The chromium components output some error messages to the console as well, which makes my JSON invalid! For example, I always get the following two error messages on startup:

[0529/133941.811:ERROR:gpu_process_transport_factory.cc(990)] Lost UI shared context.
[0529/133941.832:ERROR:url_request_context_getter_impl.cc(130)] Cannot use V8 Proxy resolver in single process mode.

Of course the best solution would be to not get any error messages in the first place, but for several reasons (which mostly have to do with company legacy code) I can't for example disable single process mode.

So the next best thing would be to keep these error messages from being printed to the console. I've tried setting

GlobalCEFApp.LogSeverity := LOGSEVERITY_DISABLE;

but that didn't help. Specifying a logfile using GlobalCEFApp.LogFile doesn't help either.

So how can I prevent the Chromium components from writing to the console at all?

Body:
The TChromium component provides an OnConsoleMessage event with signature :

 TOnConsoleMessage = procedure(Sender: TObject; const browser: ICefBrowser;
                               const message, source: ustring; line: Integer;
                               out Result: Boolean) of object;

If you handle this event and set the Result variable to true the message output to the console is suppressed.


问:
git mv rename all files and folders to capitalize first letter
I am renaming all my component names and folders. All of them start with a small letter. I am capitalizing them. The way I am currently doing is for the folder names I am writing

```<code>git mv folder test
git mv test Folder
</code>```

as for the files directyl

```<code>git mv file File
</code>```

I have a folder that contains around 50 folders and 200 sub-files. Can I automate this? I need to capitalize all them with git mv so that Github detects the changes. I use windows 10.

答:
Of course there are ways to automate it. Since you're apparently a JavaScript dev, you could look into the Node.js APIs;

fs.readdir to read each name in a directory

child_process.spawn to run git mv ... ...

Body:
I am renaming all my component names and folders. All of them start with a small letter. I am capitalizing them. The way I am currently doing is for the folder names I am writing

git mv folder test
git mv test Folder

as for the files directyl

git mv file File

I have a folder that contains around 50 folders and 200 sub-files. Can I automate this? I need to capitalize all them with git mv so that Github detects the changes. I use windows 10.


问:
Loop Iteration Efficient
You have a loop that iterates over 1,000 items. You want to add a newline to every four items. The items are in an array structure that have numeric index starting at 0. How do you do it?</p>

答:
FWIW:</p>

```<code>for (int i = 0; i < list.size(); ++i) {
    // you want to 'do it' with list[i] here

    if (0 == (i+1)%4))
    {
           // 'you want to add a new line' here
    }
}
</code>```

Title: Loop Iteration Efficient

Body:
FWIW:

for (int i = 0; i < list.size(); ++i) {
    // you want to 'do it' with list[i] here

    if (0 == (i+1)%4))
    {
           // 'you want to add a new line' here
    }
}


问:
i18n find in associated model with cakephp
I have two models (Posts and Categories), those two model have i18n properties. I need to do something like this:

```<code>$posts->find('all')
</code>```

and return the Post with Category both translated.
How can I achieve this on cakephp 1.3?

答:
How are you storing the properties? That would help answer.

If you do not have a lot, you could create a translator component that stores the key value pairs and then pass your data to a function in the component after you have retrieved your data.

```<code>$posts = $this->Post->find('all');
$posts = $this->Translator->translatePost($post, 'language');
</code>```

Unless you are storing the translations within the Model data, then this is probably a better solution so that you don't break the MVC paradigm.

There are tons of ways to do it, but you need to be more specific with your question in order to hone in on the issue.

Body:
I have two models (Posts and Categories), those two model have i18n properties. I need to do something like this:

$posts->find('all')

and return the Post with Category both translated.
How can I achieve this on cakephp 1.3?

Body:
How are you storing the properties? That would help answer.

If you do not have a lot, you could create a translator component that stores the key value pairs and then pass your data to a function in the component after you have retrieved your data.

$posts = $this->Post->find('all');
$posts = $this->Translator->translatePost($post, 'language');

Unless you are storing the translations within the Model data, then this is probably a better solution so that you don't break the MVC paradigm.

There are tons of ways to do it, but you need to be more specific with your question in order to hone in on the issue.


问:
Sudoku solver in JS
I'm trying to write an algorithm that can solve sudoku. For now, my code works till supplyGrid is out of numbers. When it happens it should go back and try another number, right? To be honest I have no clue how to achive that.

var grid = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0]
],
    supplyGrid = [1, 2, 3, 4, 5, 6, 7, 8, 9],
    row = 0,
    col = 0,
    value = 0,
    index = 0;

var solveSudoku = function (grid, row, col) {
    if (col > 8) {
        row++;
        col = 0;
        if (row > 8 && col > 8) {
            console.log(grid);
            return;
        }
    }
    if (grid[row][col] === 0) { //
        index = Math.floor(Math.random() * supplyGrid.length);
        value = supplyGrid[index];
        if (isValid(row, col, value)) {
            grid[row][col] = value;
            col++;
            supplyGrid = [1, 2, 3, 4, 5, 6, 7, 8, 9];
            solveSudoku(grid, row, col);
        } else {
            supplyGrid.splice(index, 1);
            console.log(supplyGrid);
            if (supplyGrid.length < 1) {
                //backtrack();
                console.log('Out of numbers');
                return;
            }
            solveSudoku(grid, row, col);
        }
    } else { //row = 3, col = 5
        solveSudoku(grid, row, ++col);
    }
    return this;
}

function isValid(row, col, value) {
    if ((validateColumn(row, col, value)) || (validateRow(row, col, value)) || (validateBox(row, col, value))) {
        return false;
    } else {
        return true;
    }
}

function validateBox(row, col, value) {
    row = Math.floor(row / 3) * 3;
    col = Math.floor(col / 3) * 3;
    var isFound = false;
    for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
            if (grid[row + i][col + j] == value) isFound = true;
        }
    }
    return isFound;
}

function validateRow(row, col, value) {
    var isFound = false;
    for (var i = 0; i < 9; i++) {
        if (grid[row][i] === value) isFound = true;
    }
    return isFound;
}

function validateColumn(row, col, value) {
    var isFound = false;
    for (var i = 0; i < 9; i++) {
        if (grid[i][col] === value) isFound = true;
    }
    return isFound;
}```

Title: Sudoku solver in JS

Body:
Here is a simpler way. You basically use a hash object to keep track of the rows, columns and sub-boxes.

const _board = [
    ['.', '9', '.', '.', '4', '2', '1', '3', '6'],
    ['.', '.', '.', '9', '6', '.', '4', '8', '5'],
    ['.', '.', '.', '5', '8', '1', '.', '.', '.'],
    ['.', '.', '4', '.', '.', '.', '.', '.', '.'],
    ['5', '1', '7', '2', '.', '.', '9', '.', '.'],
    ['6', '.', '2', '.', '.', '.', '3', '7', '.'],
    ['1', '.', '.', '8', '.', '4', '.', '2', '.'],
    ['7', '.', '6', '.', '.', '.', '8', '1', '.'],
    ['3', '.', '.', '.', '9', '.', '.', '.', '.'],
];

function isValidSudoku(grid) {
    let seenRow = {},
        seenCol = {},
        seenSubBox = {},
        seen = {}

    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            let value = grid[row][col];
            if (!(value === '.')) {
                let rowKey = `${row}-${value}`,
                    colKey = `${col}-${value}`,
                    boxKey = `${Math.floor(row/3)}-${value}-${Math.floor(col/3)}`

                if (seenRow[rowKey] || seenCol[colKey] || seenSubBox[boxKey]) {
                    return false;
                }
                seenRow[rowKey] = true;
                seenCol[colKey] = true;
                seenSubBox[boxKey] = true;
            }
        }
    }

    return true;
}

console.log(isValidSudoku(_board));


问:
pine-script function returns different value than expected
I am struggling with the understanding of function executions in pine-script. Please see the short script below, it should compile as it is:

```<code>//@version=4
study("My Script")
a = 100.
d = 100.

d:=nz(d[1]) + 10

f_(_src) => nz(_src[1]) + 10
a := f_(a)

plot(a, "a", color.red, 5)
plot(d, "d", color.yellow, 5)
</code>```

I would expect, that the value of  a and d are the same, as the function "f_" executes the same code as in the assignment for d.
But a has always a constant value of 110 from the 2nd cycle, when d increases each cycle linearly +10.

What is the reason it behaves like this? I would be very happy about some reference.

Thank you a lot for your help, Seb.

答:
Your variables are initialized to 100. on every bar.

For variable a:

The value passed to f_() is always the a variable which has just been initialized to 100., as it's initialized on every bar, but once inside the function, that current value isn't used. Because you use nz(_src[1]), the value used is the value of the parameter the last time the function was called, all this from the function's perspective—not the global scope's perpective.

On the function's first call, the nz() call replaces the value with 0 as there is no previous value. The function returns 10.

On the second bar and all subsequent ones, you are still calling the function with the a=100 argument, but from thereon a previous value exists for the argument inside the function. It is always 100. because that's what you are calling the function with every time, so nz(_src[1]) always returns 100., and the function always returns 110.

For variable d:

On the first bar there is no previous value so nz(d[1]) returns 0 and the value 0 + 10 = 10 is assigned to d.

On the second bar, nz(d[1]) returns 10 and the value 10 + 10 = 20 is assigned to d, and so on.

In the case of d, the recently initialized value of 100. on each bar is, in fact, never used.

Body:
I am struggling with the understanding of function executions in pine-script. Please see the short script below, it should compile as it is:

//@version=4
study("My Script")
a = 100.
d = 100.

d:=nz(d[1]) + 10

f_(_src) => nz(_src[1]) + 10
a := f_(a)

plot(a, "a", color.red, 5)
plot(d, "d", color.yellow, 5)

I would expect, that the value of  a and d are the same, as the function "f_" executes the same code as in the assignment for d.
But a has always a constant value of 110 from the 2nd cycle, when d increases each cycle linearly +10.

What is the reason it behaves like this? I would be very happy about some reference.

Thank you a lot for your help, Seb.


问:
Decimal arithmetic in shell shows as command not found
My intention is to reduce or increase brightness levels using code

The following is my code

```<code>BRIGHTNESS=`xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' '`
z=$($BRIGHTNESS-0.1)
echo "$z"
</code>```

I get the error adjust_brightness.sh: line 4: 1.0-0.1: command not found

答:
$(...) is a command substitution. Command substitution executes the commands inside it. Here it tries to execute 1.0-0.1 as a command.

The $((...)) does arithmetic expansion, note the double braces.

While the following will trigger arithmetic expansion:

```<code>z=$(($brightness-0.1))
</code>```

No, shell does not support floating point arithmetic, only whole numbers. Research other questions on this site how to do floating point arithmetic in shell. Because arithmetic expansion expands also variables, you can remove the $ from inside. For example pipe the string to be calculated to bc (<<< is a here string):

```<code>z=$(bc <<<"$brightness - 0.1")
</code>```

Notes:

And while were at it, do not use backticks `...` at all. Use $(...) instead. brightness=$(xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' ')

UPPER CASE VARIABLES are by convention reserved for exported variables, like IFS, LINES, COLUMNS etc. Use lower case variables in your scripts.

Body:
My intention is to reduce or increase brightness levels using code

The following is my code

BRIGHTNESS=`xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' '`
z=$($BRIGHTNESS-0.1)
echo "$z"

I get the error adjust_brightness.sh: line 4: 1.0-0.1: command not found

Body:
$(...) is a command substitution. Command substitution executes the commands inside it. Here it tries to execute 1.0-0.1 as a command.

The $((...)) does arithmetic expansion, note the double braces.

While the following will trigger arithmetic expansion:

z=$(($brightness-0.1))

No, shell does not support floating point arithmetic, only whole numbers. Research other questions on this site how to do floating point arithmetic in shell. Because arithmetic expansion expands also variables, you can remove the $ from inside. For example pipe the string to be calculated to bc (<<< is a here string):

z=$(bc <<<"$brightness - 0.1")

Notes:

And while were at it, do not use backticks `...` at all. Use $(...) instead. brightness=$(xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' ')

UPPER CASE VARIABLES are by convention reserved for exported variables, like IFS, LINES, COLUMNS etc. Use lower case variables in your scripts.


问:
How to delay an image appearing while using a CSS animation on another part
I'm creating a web page. In it, I have CSS animations that move images, and when you click on these images, and a larger version of the image with a paragraph shows up in their place. I was trying to have it so the large version of the image and paragraph is delayed, so it shows up after the other images move. I had this working individually, but when I put it together, the large version of the image and paragraph is no longer delayed, and I can't figure out why. Here is my code:    https://jsfiddle.net/rfradkin/eq2h50kg/1/

var click = 0;
function checkClicks(imgs) {

 if(click == 0) {
  setTimeout(function(){
   myFunction(imgs);
  }, 10000);
 } else {
  myFunction(imgs);
 }

 click = 1;
}
function myFunction(imgs) {

 var expandImg = document.getElementById("expandedImg");
 expandImg.src = imgs.src;
 var imgParagraph = document.getElementById('img-paragraph');
 imgParagraph.innerHTML = imgs.getAttribute("yeep");

 expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  document.getElementById('column1').classList.add('animate')
  document.getElementById('column2').classList.add('animate')
  document.getElementById('column3').classList.add('animate')
  document.getElementById('column4').classList.add('animate');

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}

@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

Please take a look. I'm new to programming and any help I can get would be useful. Thanks and let me know if you need more info.

答:
OK, so quick explanation of this code ... we have the onclick of the HTML elements calling the function handleClick and passing it this aka the img that was clicked.

Inside our handler we grab the source of the image from the src attribute, and the p element that is contained in the yeep attribute.   Then we loop through each column setting the animations in motion, and when we get to the final column we create a variable for the animation and add an event handler with a callback (which needed to be wrapped in an anonymous function or it wouldn't work correctly).   We pass the callback our column4 (or last) element along with the src and yeep attribute contents as parameters.

Once our animations finish, our callback fires, which then sets the larger image source and the paragraph contents to their respective elements, and then sets their displays to make them visible.

var click = 0;
function checkClicks(imgs) {

 if(click == 0) {
  setTimeout(function(){
   myFunction(imgs);
  }, 10000);
 } else {
  myFunction(imgs);
 }

 click = 1;
}

function whichAnimationEvent(){
  var t,
      el = document.createElement("fakeelement");

  var animations = {
    "animation"      : "animationend",
    "OAnimation"     : "oAnimationEnd",
    "MozAnimation"   : "animationend",
    "WebkitAnimation": "webkitAnimationEnd"
  }

  for (t in animations){
    if (el.style[t] !== undefined){
      return animations[t];
    }
  }
}

const customCallback = (e, s, y) => {
  let p = document.getElementById("img-paragraph");
  p.innerHTML = y;
  var expImg = document.getElementById("expandedImg");
  expImg.src = s;
  expImg.parentElement.style.display = "table-cell";
  p.style.display = "table-cell";
  let ele = document.getElementById("column4");
  ele.removeEventListener(window.animationEvent, customCallback);
}

const handleClick = (e) => {
  let yeep = e.getAttribute("yeep");
  let eleArr = ["column1", "column2", "column3", "column4"];
  for (ele in eleArr) {
    let thisEle = document.getElementById(eleArr[ele]);
    if (thisEle.classList) thisEle.classList.add('animate')
      else thisEle.className += " " + "animate";
    if (eleArr[ele] === "column4") {
      var animationEvent = whichAnimationEvent();
      thisEle.addEventListener(animationEvent, () => customCallback(thisEle, e.src, yeep));
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}

@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

Body:
I'm creating a web page. In it, I have CSS animations that move images, and when you click on these images, and a larger version of the image with a paragraph shows up in their place. I was trying to have it so the large version of the image and paragraph is delayed, so it shows up after the other images move. I had this working individually, but when I put it together, the large version of the image and paragraph is no longer delayed, and I can't figure out why. Here is my code:    https://jsfiddle.net/rfradkin/eq2h50kg/1/

var click = 0;
function checkClicks(imgs) {

 if(click == 0) {
  setTimeout(function(){
   myFunction(imgs);
  }, 10000);
 } else {
  myFunction(imgs);
 }

 click = 1;
}
function myFunction(imgs) {

 var expandImg = document.getElementById("expandedImg");
 expandImg.src = imgs.src;
 var imgParagraph = document.getElementById('img-paragraph');
 imgParagraph.innerHTML = imgs.getAttribute("yeep");

 expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  document.getElementById('column1').classList.add('animate')
  document.getElementById('column2').classList.add('animate')
  document.getElementById('column3').classList.add('animate')
  document.getElementById('column4').classList.add('animate');

}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}

@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

Please take a look. I'm new to programming and any help I can get would be useful. Thanks and let me know if you need more info.

Body:
OK, so quick explanation of this code ... we have the onclick of the HTML elements calling the function handleClick and passing it this aka the img that was clicked.

Inside our handler we grab the source of the image from the src attribute, and the p element that is contained in the yeep attribute.   Then we loop through each column setting the animations in motion, and when we get to the final column we create a variable for the animation and add an event handler with a callback (which needed to be wrapped in an anonymous function or it wouldn't work correctly).   We pass the callback our column4 (or last) element along with the src and yeep attribute contents as parameters.

Once our animations finish, our callback fires, which then sets the larger image source and the paragraph contents to their respective elements, and then sets their displays to make them visible.

var click = 0;
function checkClicks(imgs) {

 if(click == 0) {
  setTimeout(function(){
   myFunction(imgs);
  }, 10000);
 } else {
  myFunction(imgs);
 }

 click = 1;
}

function whichAnimationEvent(){
  var t,
      el = document.createElement("fakeelement");

  var animations = {
    "animation"      : "animationend",
    "OAnimation"     : "oAnimationEnd",
    "MozAnimation"   : "animationend",
    "WebkitAnimation": "webkitAnimationEnd"
  }

  for (t in animations){
    if (el.style[t] !== undefined){
      return animations[t];
    }
  }
}

const customCallback = (e, s, y) => {
  let p = document.getElementById("img-paragraph");
  p.innerHTML = y;
  var expImg = document.getElementById("expandedImg");
  expImg.src = s;
  expImg.parentElement.style.display = "table-cell";
  p.style.display = "table-cell";
  let ele = document.getElementById("column4");
  ele.removeEventListener(window.animationEvent, customCallback);
}

const handleClick = (e) => {
  let yeep = e.getAttribute("yeep");
  let eleArr = ["column1", "column2", "column3", "column4"];
  for (ele in eleArr) {
    let thisEle = document.getElementById(eleArr[ele]);
    if (thisEle.classList) thisEle.classList.add('animate')
      else thisEle.className += " " + "animate";
    if (eleArr[ele] === "column4") {
      var animationEvent = whichAnimationEvent();
      thisEle.addEventListener(animationEvent, () => customCallback(thisEle, e.src, yeep));
    }
  }
}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}

@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
}

.animate {
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!-- I'm trying to have the images move to the bottom using a CSS animation after they are clicked. After I do this by adding the code that works for this, the function you wrote stopped working. I can't figure out why. Can you help me?-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />
    <script src='../Javascript/script.js'></script>
    <script src='../Javascript/fix.js'></script>
    <script src='../Javascript/jquery-3.5.1.min.js'></script>
    <title>Projects</title>
</head>
<body class='totalbody'>

  <header class="topnav" id="topnav">
    <a class="link" href="../index.html">Home</a>
    <a class="link" href="#Academics">Academics</a>
    <a class="active-menu" href="projects.html">Projects</a>
    <a class="link" href="communityservice.html">Community Service</a>
  </header>

  <div>
    <div id="expanded-wrapper">
      <img id="expandedImg">
      <p id="img-paragraph"></p>
    </div>
  </div>

  <div class="row">
    <div class="column" id='column1'>
      <img src="https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" alt="Nature" style="width:100%" yeep="<p class='yeep1'> Parapraph #1 </p>" onclick="handleClick(this);">
    </div>
    <div class="column" id='column2'>
      <img src="https://s.yimg.com/ny/api/res/1.2/Petngc9GmDGVfvqWtZW1uw--/YXBwaWQ9aGlnaGxhbmRlcjt3PTcwNTtoPTM4MC43/https://s.yimg.com/uu/api/res/1.2/p2FH9i2oATkHA6O0ucuC9A--~B/aD0yMTY7dz00MDA7c209MTthcHBpZD15dGFjaHlvbg--/https://media.zenfs.com/en/prnewswire.com/d908212583d777d158af74cb171ec897"
        alt="Snow" style="width:100%" yeep="<p class='yeep2'> Parapraph #2 </p>" onclick="handleClick(this);">
    </div>
    <div class="column" id='column3'>
      <img src="https://engineering.wustl.edu/news/PublishingImages/141020_jwb_brookings_007-1915x768.jpg?RenditionID=1" alt="Mountains" style="width:100%" yeep="<p class='yeep3'> Parapraph #3 </p>" onclick="handleClick(this);">
    </div>
    <div class="column" id='column4'>
      <img src="https://techcrunch.com/wp-content/uploads/2019/01/McKelvey-courtyard.jpg" alt="Lights" style="width:100%" yeep="<p class='yeep4'> Parapraph #4 </p>" onclick="handleClick(this);">

    </div>
  </div>
</body>
</html>