问:
No composer.json found in the current directory

Hi guys, really sorry if this has a basic answer as I'm quite new to this. I am following a YouTube tutorial Hyperledger Composer Development Tutorial (2/5) - Modeling Language (Mac OS X) https://www.youtube.com/watch?v=S2S5cEcmx7Q&t=100s.

Following all steps up to 3:22 (and tutorial 1/5) I try to command:

```<code>composer archive create -a /dist/perishables.bna --sourceType dir --sourceName
</code>```

Where the result should be:

```<code>Creating Business Network Archive

Looking for package.json of Business Network Definition
Input directory: /Users/joeheade/composer-sample-networks/packages/perishable-network

Found:
Description: Shipping Perishable Goods Business Network
Name: perishable-network
Identifier: perishable-network@0.1.11

Written Business Network Definition Archive file to
Output file: ./dist/perishable-network.bna

Command succeeded
</code>```

When I try, I get this:

```<code>Joe-Heades-MBP:perishable-network joeheade$ composer archive create -a /dist/perishables.bna --sourceType dir --sourceName

  [Symfony\Component\Console\Exception\RuntimeException]
  The "-a" option does not exist.

archive [-f|--format FORMAT] [--dir DIR] [--file FILE] [--ignore-filters] [--] [<package>] [<version>]
</code>```

If I check the version I get this:

```<code>Joe-Heades-MBP:perishable-network joeheade$ composer --version
Composer version 1.5.5 2017-12-01 14:42:57
</code>```

And for a generic command, I get this:

```<code>Joe-Heades-MBP:perishable-network joeheade$ composer archive create
Searching for the specified package.
No composer.json found in the current directory, searching packages from packagist.org
Could not find a package matching create.
</code>```

Please could somebody help? I'm also sorry if I'm following any Stack Overflow rules incorrectly; this is my first post.

Thank you in advance!

UPDATE: In addition if I take a step back I get this result for:

```<code>Joe-Heades-MacBook-Pro:dist joeheade$ compose archive create -a dist/perishables.bna --sourceType dir --sourceName
-bash: compose: command not found
</code>```

Following the steps https://github.com/composer/composer/issues/6303, I also get the following response:

```<code>Joe-Heades-MacBook-Pro:perishable-network joeheade$ composer update
Composer could not find a composer.json file in /Users/joeheade/composer-sample-networks/packages/perishable-network
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section
</code>```

答:
You've not installed Hyperledger Composer. You have installed something else called composer that also has a command line name of composer.
Please refer to the documentation website https://hyperledger.github.io/composer/ for information about Hyperledger Composer and please ensure you uninstall the dependency manager for php (called composer).

Body:
Hi guys, really sorry if this has a basic answer as I'm quite new to this. I am following a YouTube tutorial Hyperledger Composer Development Tutorial (2/5) - Modeling Language (Mac OS X) https://www.youtube.com/watch?v=S2S5cEcmx7Q&t=100s.

Following all steps up to 3:22 (and tutorial 1/5) I try to command:

composer archive create -a /dist/perishables.bna --sourceType dir --sourceName

Where the result should be:

Creating Business Network Archive

Looking for package.json of Business Network Definition
Input directory: /Users/joeheade/composer-sample-networks/packages/perishable-network

Found:
Description: Shipping Perishable Goods Business Network
Name: perishable-network
Identifier: perishable-network@0.1.11

Written Business Network Definition Archive file to
Output file: ./dist/perishable-network.bna

Command succeeded

When I try, I get this:

Joe-Heades-MBP:perishable-network joeheade$ composer archive create -a /dist/perishables.bna --sourceType dir --sourceName

  [Symfony\Component\Console\Exception\RuntimeException]
  The "-a" option does not exist.

archive [-f|--format FORMAT] [--dir DIR] [--file FILE] [--ignore-filters] [--] [<package>] [<version>]

If I check the version I get this:

Joe-Heades-MBP:perishable-network joeheade$ composer --version
Composer version 1.5.5 2017-12-01 14:42:57

And for a generic command, I get this:

Joe-Heades-MBP:perishable-network joeheade$ composer archive create
Searching for the specified package.
No composer.json found in the current directory, searching packages from packagist.org
Could not find a package matching create.

Please could somebody help? I'm also sorry if I'm following any Stack Overflow rules incorrectly; this is my first post.

Thank you in advance!

UPDATE: In addition if I take a step back I get this result for:

Joe-Heades-MacBook-Pro:dist joeheade$ compose archive create -a dist/perishables.bna --sourceType dir --sourceName
-bash: compose: command not found

Following the steps https://github.com/composer/composer/issues/6303, I also get the following response:

Joe-Heades-MacBook-Pro:perishable-network joeheade$ composer update
Composer could not find a composer.json file in /Users/joeheade/composer-sample-networks/packages/perishable-network
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section


来源: stackexchange

问:
Use WinDbg to Write Contents of Managed Byte[] to File
I have a crash dump from a production server that shows an OutOfMemoryException.  The exception itself is not relevant here.

I happened to run a !dso to view the stack objects:

```<code>0:042> !dso
OS Thread Id: 0x1014 (42)
ESP/REG  Object   Name
246eeb24 109a21bc System.UnhandledExceptionEventHandler
246eeb2c 39083998 System.Runtime.Remoting.Proxies.__TransparentProxy
246eeb34 39083b5c System.UnhandledExceptionEventArgs
246eeb48 39073280 System.Byte[]
246eec10 2e720050 System.OutOfMemoryException
[snip]
246ef250 0ac1c4d0 System.IO.MemoryStream <-- interesting
</code>```

I thought the MemoryStream might have something to do with the error, so I dumped it:

```<code>0:042> !do 0ac1c4d0
Name: System.IO.MemoryStream
MethodTable: 7932d5e4
EEClass: 790ec318
Size: 52(0x34) bytes
 (C:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
7933061c  400018a        4        System.Object  0 instance 00000000 __identity
7992cbcc  4001b6c        8 ...ream+ReadDelegate  0 instance 00000000 _readDelegate
7992cc58  4001b6d        c ...eam+WriteDelegate  0 instance 00000000 _writeDelegate
7931bd9c  4001b6e       10 ...ng.AutoResetEvent  0 instance 00000000 _asyncActiveEvent
79332c4c  4001b6f       14         System.Int32  1 instance        1 _asyncActiveCount
7932e6fc  4001b6b      574     System.IO.Stream  0   shared   static Null
    >> Domain:Value  000dc0f0:NotInit  00109d58:109b6abc <<
79333470  4001c16       18        System.Byte[]  0 instance 50710038 _buffer
79332c4c  4001c17       1c         System.Int32  1 instance        0 _origin
79332c4c  4001c18       20         System.Int32  1 instance 56071048 _position
79332c4c  4001c19       24         System.Int32  1 instance 56071048 _length
79332c4c  4001c1a       28         System.Int32  1 instance 67108864 _capacity
793044cc  4001c1b       2c       System.Boolean  1 instance        1 _expandable
793044cc  4001c1c       2d       System.Boolean  1 instance        1 _writable
793044cc  4001c1d       2e       System.Boolean  1 instance        1 _exposable
793044cc  4001c1e       2f       System.Boolean  1 instance        1 _isOpen
</code>```

Wow, a 56,071,048 byte buffer seems a bit large.  I'd like to see the contents of this buffer:

```<code>0:042> !do 50710038
Name: System.Byte[]
MethodTable: 79333470
EEClass: 790eeb6c
Size: 67108876(0x400000c) bytes
Array: Rank 1, Number of elements 67108864, Type Byte
Element Type: System.Byte
Fields:
None
</code>```

The first 10 elements of the array are below:

```<code>0:042> !dumparray -start 0 -length 10 50710038
Name: System.Byte[]
MethodTable: 79333470
EEClass: 790eeb6c
Size: 67108876(0x400000c) bytes
Array: Rank 1, Number of elements 67108864, Type Byte
Element Methodtable: 79333520
[0] 50710040
[1] 50710041
[2] 50710042
[3] 50710043
[4] 50710044
[5] 50710045
[6] 50710046
[7] 50710047
[8] 50710048
[9] 50710049
</code>```

This is a huge array.  I'd rather not !dumparray the whole thing.  I'd like to view the output in a file.

Question

Is it possible to dump the contents of this Byte[] to a file?

I am familiar with the .writemem command, but I can't seem to get this to work.  I've tried writing the entire length, but WinDbg didn't like that:

```<code>0:042> .writemem C:\LargeBuffer.bin 50710040 L56071048
                                                     ^ Range error in '.writemem C:\LargeBuffer.bin 50710040 l56071048'
</code>```

Did I format that .writemem command incorrectly?

答:
This is what worked for me:</p>

```<code>.foreach($str {!DumpHeap /d -mt 00007ff890e96948 -min 0n126500 -short}){r@$t0=  dwo(${$str}+8)*2;.writemem e:\temp\str\${$str}.txt ${$str}+c L? @$t0}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a crash dump from a production server that shows an OutOfMemoryException.  The exception itself is not relevant here.

I happened to run a !dso to view the stack objects:

0:042> !dso
OS Thread Id: 0x1014 (42)
ESP/REG  Object   Name
246eeb24 109a21bc System.UnhandledExceptionEventHandler
246eeb2c 39083998 System.Runtime.Remoting.Proxies.__TransparentProxy
246eeb34 39083b5c System.UnhandledExceptionEventArgs
246eeb48 39073280 System.Byte[]
246eec10 2e720050 System.OutOfMemoryException
[snip]
246ef250 0ac1c4d0 System.IO.MemoryStream <-- interesting

I thought the MemoryStream might have something to do with the error, so I dumped it:

0:042> !do 0ac1c4d0
Name: System.IO.MemoryStream
MethodTable: 7932d5e4
EEClass: 790ec318
Size: 52(0x34) bytes
 (C:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
7933061c  400018a        4        System.Object  0 instance 00000000 __identity
7992cbcc  4001b6c        8 ...ream+ReadDelegate  0 instance 00000000 _readDelegate
7992cc58  4001b6d        c ...eam+WriteDelegate  0 instance 00000000 _writeDelegate
7931bd9c  4001b6e       10 ...ng.AutoResetEvent  0 instance 00000000 _asyncActiveEvent
79332c4c  4001b6f       14         System.Int32  1 instance        1 _asyncActiveCount
7932e6fc  4001b6b      574     System.IO.Stream  0   shared   static Null
    >> Domain:Value  000dc0f0:NotInit  00109d58:109b6abc <<
79333470  4001c16       18        System.Byte[]  0 instance 50710038 _buffer
79332c4c  4001c17       1c         System.Int32  1 instance        0 _origin
79332c4c  4001c18       20         System.Int32  1 instance 56071048 _position
79332c4c  4001c19       24         System.Int32  1 instance 56071048 _length
79332c4c  4001c1a       28         System.Int32  1 instance 67108864 _capacity
793044cc  4001c1b       2c       System.Boolean  1 instance        1 _expandable
793044cc  4001c1c       2d       System.Boolean  1 instance        1 _writable
793044cc  4001c1d       2e       System.Boolean  1 instance        1 _exposable
793044cc  4001c1e       2f       System.Boolean  1 instance        1 _isOpen

Wow, a 56,071,048 byte buffer seems a bit large.  I'd like to see the contents of this buffer:

0:042> !do 50710038
Name: System.Byte[]
MethodTable: 79333470
EEClass: 790eeb6c
Size: 67108876(0x400000c) bytes
Array: Rank 1, Number of elements 67108864, Type Byte
Element Type: System.Byte
Fields:
None

The first 10 elements of the array are below:

0:042> !dumparray -start 0 -length 10 50710038
Name: System.Byte[]
MethodTable: 79333470
EEClass: 790eeb6c
Size: 67108876(0x400000c) bytes
Array: Rank 1, Number of elements 67108864, Type Byte
Element Methodtable: 79333520
[0] 50710040
[1] 50710041
[2] 50710042
[3] 50710043
[4] 50710044
[5] 50710045
[6] 50710046
[7] 50710047
[8] 50710048
[9] 50710049

This is a huge array.  I'd rather not !dumparray the whole thing.  I'd like to view the output in a file.

Question

Is it possible to dump the contents of this Byte[] to a file?

I am familiar with the .writemem command, but I can't seem to get this to work.  I've tried writing the entire length, but WinDbg didn't like that:

0:042> .writemem C:\LargeBuffer.bin 50710040 L56071048
                                                     ^ Range error in '.writemem C:\LargeBuffer.bin 50710040 l56071048'

Did I format that .writemem command incorrectly?

Body:
This is what worked for me:

.foreach($str {!DumpHeap /d -mt 00007ff890e96948 -min 0n126500 -short}){r@$t0=  dwo(${$str}+8)*2;.writemem e:\temp\str\${$str}.txt ${$str}+c L? @$t0}

ContentLicense: CC BY-SA 3.0


问:
Vertically aligning a div and an input
After trying to get it right for hours I've finally found a way to align two divs perfectly on one line, but now I'm trying to get a button and an input box aligned and they're just slightly off. Note: I'm using Bootstrap with this!

Here's my code:

html:

```<code><input id="col1" type="text" class="form-control" placeholder="Enter activity" /><button id="col2" class="btn btn-outline-success my-2 my-sm-0" type = "button">Add</button>
</code>```

css:

```<code>body {
    margin: 10px;
}

#col1 {
    display: inline-block;
    width: 70%;
    height: 100px;

}

#col2 {
    display: inline-block;
    width: 30%;
    height: 100px;

}

button, input {
  height: 100%;
  width: 100%;
  line-height: 0;
  border: 0;
}
</code>```

http://jsfiddle.net/x1hphsvb/335/

Any help is appreciated!

答:
Just add vertical-align: baseline; to the button's CSS. (The default vertical alignment for buttons in bootstrap is "middle"):

http://jsfiddle.net/q3aarre2/1/

Title: Vertically aligning a div and an input

Body:
After trying to get it right for hours I've finally found a way to align two divs perfectly on one line, but now I'm trying to get a button and an input box aligned and they're just slightly off. Note: I'm using Bootstrap with this!

Here's my code:

html:

<input id="col1" type="text" class="form-control" placeholder="Enter activity" /><button id="col2" class="btn btn-outline-success my-2 my-sm-0" type = "button">Add</button>

css:

body {
    margin: 10px;
}

#col1 {
    display: inline-block;
    width: 70%;
    height: 100px;

}

#col2 {
    display: inline-block;
    width: 30%;
    height: 100px;

}

button, input {
  height: 100%;
  width: 100%;
  line-height: 0;
  border: 0;
}

http://jsfiddle.net/x1hphsvb/335/

Any help is appreciated!


问:
How to force a Java thread to close a thread-local database connection
When Using a thread-local database connection, closure of the connection is required when the thread exists.

This I can only do if I can override the run() method of the calling thread. Even that is not a great solution, since at time of exit, I don't know if a connection has ever been opened by that thread.

The problem is in fact more general: How to force a thread to call some finalisation method of a thread-local object when it exits.

I looked at the sources of java 1.5 and found that the thread local map is set to null, which will eventually cause the garbage collection to call finalize(), but I don't want to count on the garbage collector.

The following override seems inevitable to make sure that a database connection is closed:

```<code>@Override
public void remove() {
    get().release();
    super.remove();
}
</code>```

where release() closes the database connection, if it has been opened. But we don't know if the thread has ever used this thread-local. If get() has never been called by this thread, then there's quite a waste of effort here: ThreadLocal.initialValue() will be called, a map will be created on this thread, etc.

Further clarification and example as per Thorbjørn's comment:

java.lang.ThreadLocal is a type of factory for an object that is bound to a thread. This type has a getter for the object and a factory method (typically written by the user). When the getter is called it calls the factory method only if it has never been called before by this thread.

Using ThreadLocal allows a developer to bind a resource to a thread even if the thread code was written by a third party.

Example:
Say we have a resource Type called MyType and we want to have one and only one of it per thread.

Define in the using class:

```<code>private static ThreadLocal<MyType> resourceFactory = new ThreadLocal<MyType>(){
    @override
    protected MyType initialValue(){
        return new MyType();
    }
}
</code>```

Use in local context in this class:

```<code>public void someMethod(){
    MyType resource = resourceFactory.get();
    resource.useResource();
}
</code>```

get() can call initialValue() only once in the life cycle of the calling thread. At that point an instance of MyType gets instantiated and bound to this thread. Subsequent calls to get() by this thread refer again to this object.

The classic usage example is when MyType is some thread-unsafe text/date/xml formatter.

But such formatters usually don't need to be released or closed, database connections do and I am using java.lang.ThreadLocal to have a one database connection per thread.

The way I see it, java.lang.ThreadLocal is almost perfect for that. Almost because there's no way to guarantee closure of the resource if the calling thread belongs to a third party application.

I need your brains squires: By extending java.lang.ThreadLocal I managed to bind one database connection for every thread, for it's exclusive usage - including threads that I can not modify or override. I managed to make sure that the connections get closed in case the thread dies on uncaught exception.

In case of normal thread exit, the garbage collector closes the connection (because MyType overrides the finalize()). In actual fact it happens quite quickly, but this is not ideal.

If I had my way, there would have been another method on the java.lang.ThreadLocal:

```<code>protected void release() throws Throwable {}
</code>```

If this method existed on java.lang.ThreadLocal, called by JVM upon any thread exit/death, then in my own override of it I could close my connection (and the redeemer would have come to Zion).

In the absence of such method, I'm looking for another way to confirm closure. A way that won't rely on the JVM garbage collection.

答:
What we did was

```<code>@Override
public void run() {
  try {
    // ...
  } finally {
    resource.close();
  }
}
</code>```

Basically just always (possibly open and then) close it for all paths through the thread.  In case it helps anybody out there :)

ContentLicense: CC BY-SA 4.0

Body:
When Using a thread-local database connection, closure of the connection is required when the thread exists.

This I can only do if I can override the run() method of the calling thread. Even that is not a great solution, since at time of exit, I don't know if a connection has ever been opened by that thread.

The problem is in fact more general: How to force a thread to call some finalisation method of a thread-local object when it exits.

I looked at the sources of java 1.5 and found that the thread local map is set to null, which will eventually cause the garbage collection to call finalize(), but I don't want to count on the garbage collector.

The following override seems inevitable to make sure that a database connection is closed:

@Override
public void remove() {
    get().release();
    super.remove();
}

where release() closes the database connection, if it has been opened. But we don't know if the thread has ever used this thread-local. If get() has never been called by this thread, then there's quite a waste of effort here: ThreadLocal.initialValue() will be called, a map will be created on this thread, etc.

Further clarification and example as per Thorbjørn's comment:

java.lang.ThreadLocal is a type of factory for an object that is bound to a thread. This type has a getter for the object and a factory method (typically written by the user). When the getter is called it calls the factory method only if it has never been called before by this thread.

Using ThreadLocal allows a developer to bind a resource to a thread even if the thread code was written by a third party.

Example:
Say we have a resource Type called MyType and we want to have one and only one of it per thread.

Define in the using class:

private static ThreadLocal<MyType> resourceFactory = new ThreadLocal<MyType>(){
    @override
    protected MyType initialValue(){
        return new MyType();
    }
}

Use in local context in this class:

public void someMethod(){
    MyType resource = resourceFactory.get();
    resource.useResource();
}

get() can call initialValue() only once in the life cycle of the calling thread. At that point an instance of MyType gets instantiated and bound to this thread. Subsequent calls to get() by this thread refer again to this object.

The classic usage example is when MyType is some thread-unsafe text/date/xml formatter.

But such formatters usually don't need to be released or closed, database connections do and I am using java.lang.ThreadLocal to have a one database connection per thread.

The way I see it, java.lang.ThreadLocal is almost perfect for that. Almost because there's no way to guarantee closure of the resource if the calling thread belongs to a third party application.

I need your brains squires: By extending java.lang.ThreadLocal I managed to bind one database connection for every thread, for it's exclusive usage - including threads that I can not modify or override. I managed to make sure that the connections get closed in case the thread dies on uncaught exception.

In case of normal thread exit, the garbage collector closes the connection (because MyType overrides the finalize()). In actual fact it happens quite quickly, but this is not ideal.

If I had my way, there would have been another method on the java.lang.ThreadLocal:

protected void release() throws Throwable {}

If this method existed on java.lang.ThreadLocal, called by JVM upon any thread exit/death, then in my own override of it I could close my connection (and the redeemer would have come to Zion).

In the absence of such method, I'm looking for another way to confirm closure. A way that won't rely on the JVM garbage collection.

Body:
What we did was

@Override
public void run() {
  try {
    // ...
  } finally {
    resource.close();
  }
}

Basically just always (possibly open and then) close it for all paths through the thread.  In case it helps anybody out there :)


问:
How can I run a Windows executable from WSL (Ubuntu) Bash
Along with Windows 10 Anniversary update for summer 2016, came the possibility to run ubuntu binaries inside the new Windows Subsystem for Linux (WSL), a "lightweight" virtualized subsystem.

Unfortunately, launching C:\Windows\System32\bash.exe, another bash ELF binary starts a process inside the WSL, from where you cannot escape!  You may launch only other ELF binaries.

So how can I execute *.exe files from Windows Bash?[1]

[1] Question asked also in Microsoft's "official" GH support repo.

答:
In the Windows 10 Creators Update (build 1703, April 2017), this is natively supported. So you can now run Windows binaries from Linux...

notepad.exe or any other .exe (the extension is needed and it needs being on your path, some older versions need the whole path)

...and vice versa using one of the following:

bash.exe -c command_to_run i.e: bash.exe -c ls

bash -c command_to_run i.e: bash -c ls

wsl command_to_run i.e: wsl "ls"; or specify the distro you want to use to run it using:

ubuntu run ls

For more information, see the above linked article.


问:
Having Trouble Passing And Recieving Data From My Intent
I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.

So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.

The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".

CLASS 1:

```<code>public void ActivateAlarm(View view){
        Bundle myBundle = getIntent().getExtras();
        if(myBundle == null){
            Log.i("The bundle is empty!", "Smashing success!");
        }

        else{
            SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
            String NumberToCall = sharedPreferences.getString("CallNumber", "");
            String TextOne = sharedPreferences.getString("1Text", "");
            String TextTwo = sharedPreferences.getString("2Text", "");
            String TextThree = sharedPreferences.getString("3Text", "");

            Button myButton = (Button) findViewById(R.id.button);
            myButton.setText(TextOne);

            Log.i("MY NUMBER TO CALL", NumberToCall);
            /*Take in the data from the settings. Check it for consistency.
            1)Are the numbers empty?
            2)Is the number 911 or a 7 digit number?
            3)Do they have a passcode?
            4)Is the number real? No philisophical BS
             */
        }

    }
</code>```

CLASS 2:

```<code>public void GoToAlarm(View view){

        EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
        EditText text1 = (EditText) findViewById(R.id.textNumOne);
        EditText text2 = (EditText) findViewById(R.id.textNumTwo);
        EditText text3 = (EditText) findViewById(R.id.textNumThree);

        Intent intent = new Intent(this, AlarmActive.class);

        intent.putExtra("callNumber", NumberToCall.getText().toString());
        intent.putExtra("1Text", text1.getText().toString());
        intent.putExtra("2Text", text2.getText().toString());
        intent.putExtra("3Text", text3.getText().toString());

        startActivity(intent);

    }
</code>```

答:
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.

An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:

```<code>        String NumberToCall = intent.getStringExtra("CallNumber");
        String TextOne = intent.getStringExtra("1Text");
        String TextTwo = intent.getStringExtra("2Text");
        String TextThree = intent.getStringExtra("3Text");
</code>```

SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:

```<code>SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();

editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());

editor.apply();
</code>```

You can retrieve the values with the code you were using in Class 1.

Body:
I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.

So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.

The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".

CLASS 1:

public void ActivateAlarm(View view){
        Bundle myBundle = getIntent().getExtras();
        if(myBundle == null){
            Log.i("The bundle is empty!", "Smashing success!");
        }

        else{
            SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
            String NumberToCall = sharedPreferences.getString("CallNumber", "");
            String TextOne = sharedPreferences.getString("1Text", "");
            String TextTwo = sharedPreferences.getString("2Text", "");
            String TextThree = sharedPreferences.getString("3Text", "");

            Button myButton = (Button) findViewById(R.id.button);
            myButton.setText(TextOne);

            Log.i("MY NUMBER TO CALL", NumberToCall);
            /*Take in the data from the settings. Check it for consistency.
            1)Are the numbers empty?
            2)Is the number 911 or a 7 digit number?
            3)Do they have a passcode?
            4)Is the number real? No philisophical BS
             */
        }

    }

CLASS 2:

public void GoToAlarm(View view){

        EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
        EditText text1 = (EditText) findViewById(R.id.textNumOne);
        EditText text2 = (EditText) findViewById(R.id.textNumTwo);
        EditText text3 = (EditText) findViewById(R.id.textNumThree);

        Intent intent = new Intent(this, AlarmActive.class);

        intent.putExtra("callNumber", NumberToCall.getText().toString());
        intent.putExtra("1Text", text1.getText().toString());
        intent.putExtra("2Text", text2.getText().toString());
        intent.putExtra("3Text", text3.getText().toString());

        startActivity(intent);

    }

Body:
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.

An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:

        String NumberToCall = intent.getStringExtra("CallNumber");
        String TextOne = intent.getStringExtra("1Text");
        String TextTwo = intent.getStringExtra("2Text");
        String TextThree = intent.getStringExtra("3Text");

SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:

SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();

editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());

editor.apply();

You can retrieve the values with the code you were using in Class 1.


问:
Angular if screen is above a certain breakpoint, show one div, else show another
On my html I have two divs with different layouts.
One is a table, and the other one is a several divs

```<code> <div class="firstView>
   <table class="table table-bordered">.....
     ..
    <tr *ngFor="let data of Data">
     <td>data.name</td>
    </tr>
   </table>
 </div>

 <div class="secondView">
  <div class="col-md-12" *ngFor="let data of Data">
     insert data here
  </div>
</code>```

I can use show and hidden to display or hide them at certain screen sizes.
But since I load data in both of them, I think it would be best if I could have an If statement, that displays and renders firstView if screensize > 992px
and the secondView if it's less than that.

How can I have an ngIf statement with breakpoints as values?

答:
Actually used an old account for the answer before, so using the chance to detail it out with the correct account here!

So if you want to save the window width to a variable, you can set up your component code like this

```<code>class FooComponent implements OnInit {

  public currentWindowWidth: number;

  // ...

  ngOnInit() {
    this.currentWindowWidth = window.innerWidth;
  }

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

In your markup you can then simply check as follows:

```<code><div class="first" *ngIf="currentWindowWidth < 992">
  ...
</div>
<div class="second" *ngIf="currentWindowWidth >= 992" >
  ...
</div>
</code>```

Edit:

If you then want to also react to resizing you can do it as follows:

```<code>@HostListener('window:resize')
onResize() {
  this.currentWindowWidth = window.innerWidth
}
</code>```

Body:
On my html I have two divs with different layouts.
One is a table, and the other one is a several divs

.....
     ..

     data.name

     insert data here

I can use show and hidden to display or hide them at certain screen sizes.
But since I load data in both of them, I think it would be best if I could have an If statement, that displays and renders firstView if screensize > 992px
and the secondView if it's less than that.

How can I have an ngIf statement with breakpoints as values?

Body:
Actually used an old account for the answer before, so using the chance to detail it out with the correct account here!

So if you want to save the window width to a variable, you can set up your component code like this

class FooComponent implements OnInit {

  public currentWindowWidth: number;

  // ...

  ngOnInit() {
    this.currentWindowWidth = window.innerWidth;
  }

  // ...
}

In your markup you can then simply check as follows:

<div class="first" *ngIf="currentWindowWidth < 992">
  ...
</div>
<div class="second" *ngIf="currentWindowWidth >= 992" >
  ...
</div>

Edit:

If you then want to also react to resizing you can do it as follows:

@HostListener('window:resize')
onResize() {
  this.currentWindowWidth = window.innerWidth
}


问:
Finding correlation coefficient from 2 lists
I am working on a project which has many functions when given a couple lists of data. I've already seperated the lists and I have defined some functions which I know for certain work correctly, that being a mean function and standard deviation function. My issue is when testing my lists I get a correct mean, correct standard deviation, but incorrect correlation coefficient. Could my math be off here? I need to find the correlation coefficient with only Python's standard library.

MY CODE:

```<code>def correlCo(someList1, someList2):

    # First establish the means and standard deviations for both lists.
    xMean = mean(someList1)
    yMean = mean(someList2)
    xStandDev = standDev(someList1)
    yStandDev = standDev(someList2)
    zList1 = []
    zList2 = []

    # Create 2 new lists taking (a[i]-a's Mean)/standard deviation of a
    for x in someList1:
        z1 = ((float(x)-xMean)/xStandDev)
        zList1.append(z1)

    for y in someList2:
        z2 = ((float(y)-yMean)/yStandDev)
        zList2.append(z2)

    # Mapping out the lists to be float values instead of string
    zList1 = list(map(float,zList1))
    zList2 = list(map(float,zList2))
    # Multiplying each value from the lists
    zFinal = [a*b for a,b in zip(zList1,zList2)]
    totalZ = 0
    # Taking the sum of all the products
    for a in zFinal:
        totalZ += a
    # Finally calculating correlation coefficient
    r = (1/(len(someList1) - 1)) * totalZ

    return r
</code>```

SAMPLE RUN:

I have a list of [1,2,3,4,4,8] and [3,3,4,5,8,9]

I expect the correct answer of r = 0.8848, but get r = .203727

EDIT: To include the mean and standard deviation functions I have made.

```<code>def mean(someList):
    total = 0
    for a in someList:
        total += float(a)
    mean = total/len(someList)
    return mean

def standDev(someList):
    newList = []
    sdTotal = 0
    listMean = mean(someList)
    for a in someList:
        newNum = (float(a) - listMean)**2
        newList.append(newNum)

    for z in newList:
        sdTotal += float(z)

    standardDeviation = sdTotal/(len(newList))

    return standardDeviation
</code>```

答:
Normally according to the standard deviation formula, you should have divided the dev to the sample number (length of the list) before sqrrt it.Right?
I mean:
dev += ((someList[i]-listMean)**2)/len(someList)

enter image description here

Body:
I am working on a project which has many functions when given a couple lists of data. I've already seperated the lists and I have defined some functions which I know for certain work correctly, that being a mean function and standard deviation function. My issue is when testing my lists I get a correct mean, correct standard deviation, but incorrect correlation coefficient. Could my math be off here? I need to find the correlation coefficient with only Python's standard library.

MY CODE:

def correlCo(someList1, someList2):

    # First establish the means and standard deviations for both lists.
    xMean = mean(someList1)
    yMean = mean(someList2)
    xStandDev = standDev(someList1)
    yStandDev = standDev(someList2)
    zList1 = []
    zList2 = []

    # Create 2 new lists taking (a[i]-a's Mean)/standard deviation of a
    for x in someList1:
        z1 = ((float(x)-xMean)/xStandDev)
        zList1.append(z1)

    for y in someList2:
        z2 = ((float(y)-yMean)/yStandDev)
        zList2.append(z2)

    # Mapping out the lists to be float values instead of string
    zList1 = list(map(float,zList1))
    zList2 = list(map(float,zList2))
    # Multiplying each value from the lists
    zFinal = [a*b for a,b in zip(zList1,zList2)]
    totalZ = 0
    # Taking the sum of all the products
    for a in zFinal:
        totalZ += a
    # Finally calculating correlation coefficient
    r = (1/(len(someList1) - 1)) * totalZ

    return r

SAMPLE RUN:

I have a list of [1,2,3,4,4,8] and [3,3,4,5,8,9]

I expect the correct answer of r = 0.8848, but get r = .203727

EDIT: To include the mean and standard deviation functions I have made.

def mean(someList):
    total = 0
    for a in someList:
        total += float(a)
    mean = total/len(someList)
    return mean

def standDev(someList):
    newList = []
    sdTotal = 0
    listMean = mean(someList)
    for a in someList:
        newNum = (float(a) - listMean)**2
        newList.append(newNum)

    for z in newList:
        sdTotal += float(z)

    standardDeviation = sdTotal/(len(newList))

    return standardDeviation


问:
Setting different component template according to condition Angular
I created a component and I need to have two different templates depending on some condition. For example, I have a "testApp" component and if condition is true, the parent tag needs to be an anchor tag, otherwise parent tag has to be a div. The html content inside the parent container will be the same inside both templates.
I am trying to figure out a way to do this, but I cannot find how and where to write the condition to choose the template.

angular.module('testApp').component('testCard', {
templateUrl: 'testCard', // inlined template
controller: [TestCardController]
});

```

答: You should be able to supply a function for templateUrl instead of a string.  See More than one template in same component in AngularJS 1.5</p>


问:
swift3 firebase update and get error for FIRAuth.auth().currentUser?.email
Before firebase update, this code is working well for email login and print out the user email.
But after I update firebase today, the below code has an error.
Please kindly help to fix it.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    print(FIRAuth.auth().currentUser?.email)
}
</code>```

after change the code FIRAuth to Auth and run the app.
I input the email and password and press the login button, it shows the below error.

答:
This way worked for me:

```<code>let email = emailText.text!
let password = passwordText.text!

Auth.auth().signIn(withEmail: email, password: password) { (user, error) in

if error == nil {

/* user is signed in */

} else {

/* email or password is taken OR error connecting to Firebase */

}

}
</code>```

To get the current user email try this:

```<code>print(Auth.auth().currentUser?.email as String!)
</code>```

Body:
Before firebase update, this code is working well for email login and print out the user email.
But after I update firebase today, the below code has an error.
Please kindly help to fix it.

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    print(FIRAuth.auth().currentUser?.email)
}

after change the code FIRAuth to Auth and run the app.
I input the email and password and press the login button, it shows the below error.

Body:
This way worked for me:

let email = emailText.text!
let password = passwordText.text!

Auth.auth().signIn(withEmail: email, password: password) { (user, error) in

if error == nil {

/* user is signed in */

} else {

/* email or password is taken OR error connecting to Firebase */

}

}

To get the current user email try this:

print(Auth.auth().currentUser?.email as String!)


问:
Using google drive file picker on mobile sites
We allow our users to upload pdf files via google drive. The google drive file picker works well on desktop but on our mobile responsive site we still get the standard file picker and the user experience is not ideal.  It's obviously optimized for desktops.

Is there a better way to do this for responsive mobile sites?

Using the https://apis.google.com/js/api.js library and the google file picker https://developers.google.com/picker/

```<code>$(function($){ $(document).ready(function () {  pdfPicker = new GoogleFilePicker({
    apiKey: 'XXXXXXXXX',
    clientId: 'XXXXXXX',
    scope: ['https://www.googleapis.com/auth/drive.readonly'],
    viewId: 'pdfs',
    onLoad: function () {
    },
    onSuccess: function (data) {
      var element = $('#resume_url');
      element.val(data.downloadUrl + '&token=' + data.token);
      element.change();
    },
    onCancel: function () {
    },
    load: true
  });

$('#btn_pdfPicker_gdrive').on('click', function(event){
  $('#resume').empty();
  pdfPicker.createPicker();
  //Close modal so we can see the google drive picker.
  $("div[data-vet-upload-resume]").modal('hide');
});

<a href="javascript:void(0)" id="btn_pdfPicker_gdrive" class="btn btn-block">
    <di>
        Upload with<br>Google Drive
    </div>
</a>

<input type="text" name="data[Resume][resume_url]" id="resume_url" style="display:block;position:absolute;top:0;left:-9999px;" />
</code>```

答:
We adjust the popup style after load to optimise it.

CSS

```<code>.google_picker_popup{
  height: 100% !important;
  width: 100% !important;

}

.google_picker_container{
  height: 80% !important;
  width: 80% !important;
  max-height: 1024px;
  min-width:250px;
  max-width: 1039px;
  top:0 !important;
  right: 0 !important;
  bottom: 0 !important;
  left: 0 !important;
  margin: auto;
}
</code>```

and add the classes in the JS right after building the picker

```<code>function createPicker() {
    //the rest of your function here
      build();
      picker.setVisible(true);
    //adjust picker size
    $(".picker.shr-q-shr-r-shr-td.picker-dialog-content").addClass("google_picker_popup");
    $(".picker.shr-q-shr-r.picker-dialog").addClass("google_picker_container");
}
</code>```

And that's the outcome

Hope that helps

Body:
We allow our users to upload pdf files via google drive. The google drive file picker works well on desktop but on our mobile responsive site we still get the standard file picker and the user experience is not ideal.  It's obviously optimized for desktops.

Is there a better way to do this for responsive mobile sites?

Using the https://apis.google.com/js/api.js library and the google file picker https://developers.google.com/picker/

$(function($){ $(document).ready(function () {  pdfPicker = new GoogleFilePicker({
    apiKey: 'XXXXXXXXX',
    clientId: 'XXXXXXX',
    scope: ['https://www.googleapis.com/auth/drive.readonly'],
    viewId: 'pdfs',
    onLoad: function () {
    },
    onSuccess: function (data) {
      var element = $('#resume_url');
      element.val(data.downloadUrl + '&token=' + data.token);
      element.change();
    },
    onCancel: function () {
    },
    load: true
  });

$('#btn_pdfPicker_gdrive').on('click', function(event){
  $('#resume').empty();
  pdfPicker.createPicker();
  //Close modal so we can see the google drive picker.
  $("div[data-vet-upload-resume]").modal('hide');
});

    <di>
        Upload with
Google Drive

<input type="text" name="data[Resume][resume_url]" id="resume_url" style="display:block;position:absolute;top:0;left:-9999px;" />

Body:
We adjust the popup style after load to optimise it.

CSS

.google_picker_popup{
  height: 100% !important;
  width: 100% !important;

}

.google_picker_container{
  height: 80% !important;
  width: 80% !important;
  max-height: 1024px;
  min-width:250px;
  max-width: 1039px;
  top:0 !important;
  right: 0 !important;
  bottom: 0 !important;
  left: 0 !important;
  margin: auto;
}

and add the classes in the JS right after building the picker

function createPicker() {
    //the rest of your function here
      build();
      picker.setVisible(true);
    //adjust picker size
    $(".picker.shr-q-shr-r-shr-td.picker-dialog-content").addClass("google_picker_popup");
    $(".picker.shr-q-shr-r.picker-dialog").addClass("google_picker_container");
}

And that's the outcome

Hope that helps


问:
Referencing an Array outside its range
this program creates an image with 100 boxes, after the box is created, it's 4 coordinates are stored in the index of the class array Tile so I can refernce each tile later in my code. This works fine, excpect that I can not reference the Tile array in my main function, only in the Draw() function where it is created. Any solutions would be appreciated.

EDIT: Making Tiles* Tile[100] global does not seem to solve the issue.

Simplified Code:

```<code>#include <iostream>
class Tiles {
public:
    Tiles() : mA (1){}
    double mA;
};

void Function1() {
    Tiles Tile[5];
    Tile[1].mA = 10;
}

int main(int iArgc, char** cppArgv) {
    Function1();
    Tile[1].mA = 2;  // ERROR "Tile" is unidentified.
    return 0;
}
</code>```

Full Code:

```<code>#include <iostream>
#include <glut.h>
class Tiles {
public:
 Tiles() : mA () , mB() , mC() , mD() , mCP(){}
 double mA[2] , mB[2] , mC[2] , mD[2]  , mCP[2];
};

void Draw() {
 glClear(GL_COLOR_BUFFER_BIT);
 glColor3f(1.0, 1.0, 1.0);
 double dX1 = 0.0, dY1 = 0.0, dMidX = 0.0, dMidY = 0.0, dXC = 0.0, dYC = 0.0;
 int sq = 0, row = 1, CoordMap = 0;
 Tiles Tile[100];
   //Tiles* Tile = new Tiles[100]; doesnt seem to be any different..
     for (int i=0; i < 10;i++ ) { // ROWS
     for (int i2=0; i2 < 10; i2++) { // BOXES
      glBegin(GL_LINE_STRIP);
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mA[1] = dX1;
      Tile[sq].mA[2] = dY1;// Bottom Left
      dX1 = dX1 + .1;
      dXC = dX1;
      dYC = dY1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mB[1] = dX1;
      Tile[sq].mB[2] = dY1;// Bottom Right
      dY1 = dY1 + .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mC[1] = dX1;
      Tile[sq].mC[2] = dY1;// Top Left
      dX1 = dX1 - .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mD[1] = dX1;
      Tile[sq].mD[2] = dY1;// Top Right
      glEnd();
      glBegin(GL_POINTS);
      glVertex3f((dX1 + .05) , (dY1 - .05), 0.0);
      glEnd();
      ++sq;
      dX1 = dXC;
      dY1 = dYC;
        }
      row++;
      dX1 = 0.0;
      dY1 = ((row * .1) - .1);
        }
     glFlush();
    }

void Initialize() {
 glClearColor(0.0, 0.0, 0.0, 0.0);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int iArgc, char** cppArgv) {
 glutInit(&iArgc, cppArgv);
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize(250, 250);
 glutInitWindowPosition(200, 200);
 glutCreateWindow("XoaX.net");
 Initialize();
 glutDisplayFunc(Draw);
 glutMainLoop();
 //Tile[2].mA[1] = 2; //
 return 0;
}
</code>```

This code is modified from it's orginal version written by XoaX - Michael Hall.

Thank you

答:
If you want to make it accessible from main, the answer is to move it to global scope, but..

You're using openGL and glut here, and you're calling glutMainLoop just before accessing Tile in main().. as written in the specification, glutMainLoop never return once called..

if by chances, you're trying to cout the value before the call to glutMainLoop, the draw method will not have been called, since it was called from within glutMainLoop.. which make the value to still be 0..

references : http://www.opengl.org/documentation/specs/glut/spec3/node14.html

Title: Referencing an Array outside its range

Body:
this program creates an image with 100 boxes, after the box is created, it's 4 coordinates are stored in the index of the class array Tile so I can refernce each tile later in my code. This works fine, excpect that I can not reference the Tile array in my main function, only in the Draw() function where it is created. Any solutions would be appreciated.

EDIT: Making Tiles* Tile[100] global does not seem to solve the issue.

Simplified Code:

#include <iostream>
class Tiles {
public:
    Tiles() : mA (1){}
    double mA;
};

void Function1() {
    Tiles Tile[5];
    Tile[1].mA = 10;
}

int main(int iArgc, char** cppArgv) {
    Function1();
    Tile[1].mA = 2;  // ERROR "Tile" is unidentified.
    return 0;
}

Full Code:

#include <iostream>
#include <glut.h>
class Tiles {
public:
 Tiles() : mA () , mB() , mC() , mD() , mCP(){}
 double mA[2] , mB[2] , mC[2] , mD[2]  , mCP[2];
};

void Draw() {
 glClear(GL_COLOR_BUFFER_BIT);
 glColor3f(1.0, 1.0, 1.0);
 double dX1 = 0.0, dY1 = 0.0, dMidX = 0.0, dMidY = 0.0, dXC = 0.0, dYC = 0.0;
 int sq = 0, row = 1, CoordMap = 0;
 Tiles Tile[100];
   //Tiles* Tile = new Tiles[100]; doesnt seem to be any different..
     for (int i=0; i < 10;i++ ) { // ROWS
     for (int i2=0; i2 < 10; i2++) { // BOXES
      glBegin(GL_LINE_STRIP);
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mA[1] = dX1;
      Tile[sq].mA[2] = dY1;// Bottom Left
      dX1 = dX1 + .1;
      dXC = dX1;
      dYC = dY1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mB[1] = dX1;
      Tile[sq].mB[2] = dY1;// Bottom Right
      dY1 = dY1 + .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mC[1] = dX1;
      Tile[sq].mC[2] = dY1;// Top Left
      dX1 = dX1 - .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mD[1] = dX1;
      Tile[sq].mD[2] = dY1;// Top Right
      glEnd();
      glBegin(GL_POINTS);
      glVertex3f((dX1 + .05) , (dY1 - .05), 0.0);
      glEnd();
      ++sq;
      dX1 = dXC;
      dY1 = dYC;
        }
      row++;
      dX1 = 0.0;
      dY1 = ((row * .1) - .1);
        }
     glFlush();
    }

void Initialize() {
 glClearColor(0.0, 0.0, 0.0, 0.0);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int iArgc, char** cppArgv) {
 glutInit(&iArgc, cppArgv);
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize(250, 250);
 glutInitWindowPosition(200, 200);
 glutCreateWindow("XoaX.net");
 Initialize();
 glutDisplayFunc(Draw);
 glutMainLoop();
 //Tile[2].mA[1] = 2; //
 return 0;
}

This code is modified from it's orginal version written by XoaX - Michael Hall.

Thank you


问:
Is there a difference between nested parallelism and collapsed for loops?
I know that enabling nested parallelism will allow for a nested omp parallel for loop to also be parallelized.  But I use collapse(2) in my nested for loops (for inside of for) instead.

Is there a difference?  Why or why not?  Assume the best case scenario: no dependence between the loop indices and other things equal.

答:
Yes there is a huge difference - use collapse (not collapsed). Do not use nested parallelism.

Nested parallelism means that there are independent teams of threads working on the different levels of worksharing. You can run into all sorts of trouble either with oversubscribing CPU cores to too many threads - or not utilizing CPU cores because some threads are in the wrong team which has no work right now. It's rather hard to get decent performance out of nested parallelism. This is why you usually need to explicitly enable it.

Collapsing loops on the other hand means that the different loops are joint on a work-sharing level. This allows one team of threads (usually with as many threads as available CPU cores) to efficiently work the different iterations of the loops.


问:
sending multiple files in a single fax
I have global api for Sending fax as shown in below code,currently i am able to send fax just single file as attachments, but i have another case of sending multiple files in a single fax request and files names are in this sequence as available in database

Here is Complete Code for Sending fax

```<code>package oracle.apps.print;

import com.softlinx.replixfax.*;
import javax.xml.ws.*;
import org.apache.commons.codec.binary.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.io.File;

public class Fax {

public String Fax(String Filepath,String faxno,String flg) {

        try {

            ReplixFaxService service = new ReplixFaxService();
            ReplixFaxPort port = service.getReplixFaxPort();
            ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "user");
            if (flg.toString().equals("N")) {
                ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://api.rpxfax.com/softlinx/replixfax/wsapi");
        } else {
                ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://api.rpxtest.com:8083/softlinx/replixfax/wsapi");
        }

            Authentication auth = new Authentication();
            auth.setLogin("user");
            String password="pwd";

            auth.setPassword(org.apache.commons.codec.binary.Base64.encodeBase64String(password.getBytes()));
            auth.setRealm("MTBC");
            auth.setPasswordSecurity("base64");

            SendFaxInput sendFaxInput = new SendFaxInput();
            sendFaxInput.setAuthentication(auth);

            FaxRecipient recipient = new FaxRecipient();
            recipient.setFaxNumber(faxno.toString());

            Attachment attachment = new Attachment();
            File f = new File(Filepath.toString());
            attachment.setFileName(f.getName());

            Path path = Paths.get(Filepath.toString());
            byte[] data = Files.readAllBytes(path);
            attachment.setAttachmentContent(data);

            sendFaxInput.getFaxRecipient().add(recipient);
            sendFaxInput.getAttachment().add(attachment);

        SendFaxOutput result = port.sendFax(sendFaxInput);
            System.out.println("Status Code= " + result.getRequestStatus().getStatusCode());

        if(result.getFaxInfo() != null){
             System.out.println("Fax ID = " + result.getFaxInfo().get(0).getFaxId());

            }
        return result.getRequestStatus().getStatusCode();
    //return "a";

        } catch (Exception ex) {
            System.out.println("Exception: " + ex.getMessage());
        return ex.getMessage();

        }
    }
 }
</code>```

I am attaching file at

```<code>Attachment attachment = new Attachment();
File f = new File(Filepath.toString());
attachment.setFileName(f.getName());

Path path = Paths.get(Filepath.toString());
byte[] data = Files.readAllBytes(path);
attachment.setAttachmentContent(data);

sendFaxInput.getFaxRecipient().add(recipient);
sendFaxInput.getAttachment().add(attachment);
</code>```

Can i parse my Above Files string to multiple attachments manner ,
need help to consider all files as attachments

答:
I have resolved this by myself adding the code for help

```<code>String[] f_paths = Filepath.split("///");
            for (int i = 0; i < f_paths.length; i++) {

                Attachment attachment = new Attachment();
                File f = new File(f_paths[i].toString());
                attachment.setFileName(f.getName());

                Path path = Paths.get(f_paths[i].toString());
                byte[] data = Files.readAllBytes(path);
                attachment.setAttachmentContent(data);
                sendFaxInput.getAttachment().add(attachment);
            }
</code>```

Just Split the Files String by separator and iterate via loop

Title: sending multiple files in a single fax

Body:
I have global api for Sending fax as shown in below code,currently i am able to send fax just single file as attachments, but i have another case of sending multiple files in a single fax request and files names are in this sequence as available in database

Here is Complete Code for Sending fax

package oracle.apps.print;

import com.softlinx.replixfax.*;
import javax.xml.ws.*;
import org.apache.commons.codec.binary.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.io.File;

public class Fax {

public String Fax(String Filepath,String faxno,String flg) {

        try {

            ReplixFaxService service = new ReplixFaxService();
            ReplixFaxPort port = service.getReplixFaxPort();
            ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "user");
            if (flg.toString().equals("N")) {
                ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://api.rpxfax.com/softlinx/replixfax/wsapi");
        } else {
                ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://api.rpxtest.com:8083/softlinx/replixfax/wsapi");
        }

            Authentication auth = new Authentication();
            auth.setLogin("user");
            String password="pwd";

            auth.setPassword(org.apache.commons.codec.binary.Base64.encodeBase64String(password.getBytes()));
            auth.setRealm("MTBC");
            auth.setPasswordSecurity("base64");

            SendFaxInput sendFaxInput = new SendFaxInput();
            sendFaxInput.setAuthentication(auth);

            FaxRecipient recipient = new FaxRecipient();
            recipient.setFaxNumber(faxno.toString());

            Attachment attachment = new Attachment();
            File f = new File(Filepath.toString());
            attachment.setFileName(f.getName());

            Path path = Paths.get(Filepath.toString());
            byte[] data = Files.readAllBytes(path);
            attachment.setAttachmentContent(data);

            sendFaxInput.getFaxRecipient().add(recipient);
            sendFaxInput.getAttachment().add(attachment);

        SendFaxOutput result = port.sendFax(sendFaxInput);
            System.out.println("Status Code= " + result.getRequestStatus().getStatusCode());

        if(result.getFaxInfo() != null){
             System.out.println("Fax ID = " + result.getFaxInfo().get(0).getFaxId());

            }
        return result.getRequestStatus().getStatusCode();
    //return "a";

        } catch (Exception ex) {
            System.out.println("Exception: " + ex.getMessage());
        return ex.getMessage();

        }
    }
 }

I am attaching file at

Attachment attachment = new Attachment();
File f = new File(Filepath.toString());
attachment.setFileName(f.getName());

Path path = Paths.get(Filepath.toString());
byte[] data = Files.readAllBytes(path);
attachment.setAttachmentContent(data);

sendFaxInput.getFaxRecipient().add(recipient);
sendFaxInput.getAttachment().add(attachment);

Can i parse my Above Files string to multiple attachments manner ,
need help to consider all files as attachments

Body:
I have resolved this by myself adding the code for help

String[] f_paths = Filepath.split("///");
            for (int i = 0; i < f_paths.length; i++) {

                Attachment attachment = new Attachment();
                File f = new File(f_paths[i].toString());
                attachment.setFileName(f.getName());

                Path path = Paths.get(f_paths[i].toString());
                byte[] data = Files.readAllBytes(path);
                attachment.setAttachmentContent(data);
                sendFaxInput.getAttachment().add(attachment);
            }

Just Split the Files String by separator and iterate via loop


问:
how to retrieve ajax data in "multiple" drop box?
I have 2 multiple select drop box.. form one I want to inflate the other multiple select drop box.. can anyone help me with this?
When I get result from the jQuery or ajax i want that result to display in 2nd number multiple select drop box...

this is my ajax..

```<code>function demo1() {
    var emp_id = document.getElementById("employeeName").value;
    alert(emp_id);
    var datastring = "emp_id=" + emp_id;
    //alert (emp_id);

    $.ajax({
        type: "POST",
        url: "search_emp.php",
        data: datastring,
        dataType: "text",
        //async: false,
        success: function (data) {
            //$("#clname").append(data);
            $('#clname').html(data);
            //document.getElementById("clname").innerHTML=data;
        }
    });
}
</code>```

This are 2 multiple drop box..

```<code> <label>Select Employee </label>
     <select multiple="multiple" class="w300" name="employeeName[]" id="employeeName" >

 <?php $result = $conn->query("SELECT id,first_name,last_name,employee_id FROM employees");
                while ($row = $result->fetch_assoc()){ ?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['id']; ?><?php echo $row['first_name']; ?>
                    <?php echo $row['last_name'] ?></option>

                <?php } ?>
 <!--<?php echo $option;?>-->
<!--<?php echo $option2;?>-->
 </select>
 </br>
 <label>Select Client</label>
 <select multiple="multiple" class="w300" name="clname[]" id="clname">

 <!--<?php echo $c;?>-->
 </select>
</code>```

答:
.html() will set the innerHTML content of a DOM element, you can't do that on a <select>. There are two ways to solve it:

1) Quick & dirty: replace HTML

Make your search_emp.php also return the HTML code for the <select>, like this:

```<code>echo '<select multiple="multiple" class="w300" name="clname[]" id="clname">';
while($row = mysqli_fetch_assoc($ress)) {
    echo '<option value="'.$row['gn_id'].'">'.$row['gamename'].'</option>';
}
echo '</select>';
</code>```

Then you can use  jQuery.replaceWith() to replace the whole DOM element:

```<code>$('#clname').replaceWith(data);
</code>```

2) Much nicer: Build DOM from JSON

Instead of returning HTML code, your search_emp.php should return JSON, something like

```<code>[
    {
        "gn_id": "123",
        "gamename": "superduper client"
    },
    {
        "gn_id": "234",
        "gamename": "another client"
    }
]
</code>```

You can easily do this by passing the client array to PHP's json_encode() and add a JSON content type header (Note that you will have to change the dataType attribute of $.ajax to "json" or you could use the shortcut function $.json():

```<code>// identify the content as JSON
header('Content-Type: application/json');

// put your MySQL query here.
// if errors occur, send a HTTP 500 header and return a useful error message as JSON

// collect results in an array
$rows = array();
while($row = mysqli_fetch_assoc($ress)) {
    $rows[] = $row;
}

// return the results as a JSON list
echo json_encode($rows);
</code>```

Before you make the AJAX call, you would want to remove all existing options from the select. In the success function of the AJAX call, you can loop through the results and append them to the select:

```<code>// reset the select options
$('#clname').empty();

// make the ajax call
$.ajax({
    type: "POST",
    url: "search_emp.php",
    data: datastring,
    dataType: "json",
    success: function (data) {
        // build the options from the JSON data
        for (let client of data) {
            $('#clname').append('<option value="' + client.gn_id + '">' + client.gamename + '</option>');
        }
    },
    // optional, but good to have: error handling
    error: function (data) {
        alert("An error occurred:\n" + data.error)
    }
});
</code>```

jsfiddle

Note: let client of data only works in modern browsers (ES2015 compatible). If you want to support older browsers, do an old-fashioned for (len=data.length, i=0; i<len; ++i) loop. Or use jQuery.each() (although this might be slower)

Body:
I have 2 multiple select drop box.. form one I want to inflate the other multiple select drop box.. can anyone help me with this?
When I get result from the jQuery or ajax i want that result to display in 2nd number multiple select drop box...

this is my ajax..

function demo1() {
    var emp_id = document.getElementById("employeeName").value;
    alert(emp_id);
    var datastring = "emp_id=" + emp_id;
    //alert (emp_id);

    $.ajax({
        type: "POST",
        url: "search_emp.php",
        data: datastring,
        dataType: "text",
        //async: false,
        success: function (data) {
            //$("#clname").append(data);
            $('#clname').html(data);
            //document.getElementById("clname").innerHTML=data;
        }
    });
}

This are 2 multiple drop box..

 Select Employee
     <select multiple="multiple" class="w300" name="employeeName[]" id="employeeName" >

 <?php $result = $conn->query("SELECT id,first_name,last_name,employee_id FROM employees");
                while ($row = $result->fetch_assoc()){ ?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['id']; ?><?php echo $row['first_name']; ?>
                    <?php echo $row['last_name'] ?></option>

                <?php } ?>

 </select>

 Select Client
 <select multiple="multiple" class="w300" name="clname[]" id="clname">

 </select>

Body:
.html() will set the innerHTML content of a DOM element, you can't do that on a <select>. There are two ways to solve it:

1) Quick & dirty: replace HTML

Make your search_emp.php also return the HTML code for the <select>, like this:

echo '<select multiple="multiple" class="w300" name="clname[]" id="clname">';
while($row = mysqli_fetch_assoc($ress)) {
    echo '<option value="'.$row['gn_id'].'">'.$row['gamename'].'</option>';
}
echo '</select>';

Then you can use  jQuery.replaceWith() to replace the whole DOM element:

$('#clname').replaceWith(data);

2) Much nicer: Build DOM from JSON

Instead of returning HTML code, your search_emp.php should return JSON, something like

[
    {
        "gn_id": "123",
        "gamename": "superduper client"
    },
    {
        "gn_id": "234",
        "gamename": "another client"
    }
]

You can easily do this by passing the client array to PHP's json_encode() and add a JSON content type header (Note that you will have to change the dataType attribute of $.ajax to "json" or you could use the shortcut function $.json():

// identify the content as JSON
header('Content-Type: application/json');

// put your MySQL query here.
// if errors occur, send a HTTP 500 header and return a useful error message as JSON

// collect results in an array
$rows = array();
while($row = mysqli_fetch_assoc($ress)) {
    $rows[] = $row;
}

// return the results as a JSON list
echo json_encode($rows);

Before you make the AJAX call, you would want to remove all existing options from the select. In the success function of the AJAX call, you can loop through the results and append them to the select:

// reset the select options
$('#clname').empty();

// make the ajax call
$.ajax({
    type: "POST",
    url: "search_emp.php",
    data: datastring,
    dataType: "json",
    success: function (data) {
        // build the options from the JSON data
        for (let client of data) {
            $('#clname').append('<option value="' + client.gn_id + '">' + client.gamename + '</option>');
        }
    },
    // optional, but good to have: error handling
    error: function (data) {
        alert("An error occurred:\n" + data.error)
    }
});

jsfiddle

Note: let client of data only works in modern browsers (ES2015 compatible). If you want to support older browsers, do an old-fashioned for (len=data.length, i=0; i<len; ++i) loop. Or use jQuery.each() (although this might be slower)


问:
Function argument as key to array
I need find a value in associative array by it key. Is it possible to do something like this?</p>

```<code>$.fn.array_search = function(what, where, array_key){

    for (var key in where) {
        if (where[key].array_key == what) return true;
    }
    return false;
}
</code>```

答:
How about using .hasOwnProperty()  when working with objects and trying to find a key, the hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property. This method can be used to determine whether an object has the specified property as a direct property of that object unlike the in operator, this method does not check down the object's prototype chain.

Then you can use Array.prototype, to define your prototype for your array. The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects.

I updated your function as follows, hope it helps.

var arrayC = [{
    name: "omer",
    age: 16,
    city: "pakistan"
  },
  {
    name: "ali",
    age: 26,
    city: "pakistan"
  }
];

// If JavaScript doesn't provide a assoc_search() method natively,
if (!Array.prototype.assoc_search) {

  // returns after finding the first match for the given key => value pair and return the value
  Array.prototype.assoc_search = function(what, array_key) {

    let where = this;

    for (var key in where) {
      if (where[key].hasOwnProperty(array_key) && where[key][array_key] == what) {
        return where[key][array_key];
      }
    }
    return false;

  };
}

var result = arrayC.assoc_search("omer", "name");
(result) ? console.log('found ' + result): console.log('not found ');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Function argument as key to array

Body:
I need find a value in associative array by it key. Is it possible to do something like this?

$.fn.array_search = function(what, where, array_key){

    for (var key in where) {
        if (where[key].array_key == what) return true;
    }
    return false;
}

Body:
How about using .hasOwnProperty()  when working with objects and trying to find a key, the hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property. This method can be used to determine whether an object has the specified property as a direct property of that object unlike the in operator, this method does not check down the object's prototype chain.

Then you can use Array.prototype, to define your prototype for your array. The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects.

I updated your function as follows, hope it helps.

var arrayC = [{
    name: "omer",
    age: 16,
    city: "pakistan"
  },
  {
    name: "ali",
    age: 26,
    city: "pakistan"
  }
];

// If JavaScript doesn't provide a assoc_search() method natively,
if (!Array.prototype.assoc_search) {

  // returns after finding the first match for the given key => value pair and return the value
  Array.prototype.assoc_search = function(what, array_key) {

    let where = this;

    for (var key in where) {
      if (where[key].hasOwnProperty(array_key) && where[key][array_key] == what) {
        return where[key][array_key];
      }
    }
    return false;

  };
}

var result = arrayC.assoc_search("omer", "name");
(result) ? console.log('found ' + result): console.log('not found ');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Open visual studio project in its respective version instead of Visual Studio 2017
Ever since I installed Visual Studio 2017, it now wants to be the one to open all of my projects. Before installing 2017, if I double clicked a VS 2010 .csproj or .sln in Explorer (Windows 10), it would open in VS 2010. But now opening a project for all previous versions opens in 2017. Even if I right-click and choose Open With > Microsoft Visual Studio Version Selector it always chooses 2017. To open it in the correct version of Visual Studio, I have to first open VS and then browse to the project to open. This is a pain when I don't remember which version the project should open with and just want to click it and open it. Can I reset it to open a project in the version of visual studio it belongs with?</p>

答:
I confirmed how this is meant to work with the team. The only requirement is that you set Microsoft Visual Studio Version Selector as the Default App for .SLN files in Windows. That app launches the version of Visual Studio specified in the solution file. If you crack open a .sln file in an editor, you'll see a section that specifies the version of VS that should be used. It'll look something like this:

```<code>Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.25909.2
</code>```

One thing to keep in mind though is that value will change whenever a different version of Visual Studio writes to the solution file. E.g., if you create a solution in VS 2010, close VS 2010, launch VS 2017, open the same solution, add a project to it (this is what forces VS to make a change to the .sln file), the version in the solution file will then change to VS 2017. I.e., the last version of VS to write to the solution file, will be set as the version to be used when opening it.

If you're finding it's not working as described, we likely have a bug here. Let me know if that's what you think is happening.

Body:
I confirmed how this is meant to work with the team. The only requirement is that you set Microsoft Visual Studio Version Selector as the Default App for .SLN files in Windows. That app launches the version of Visual Studio specified in the solution file. If you crack open a .sln file in an editor, you'll see a section that specifies the version of VS that should be used. It'll look something like this:

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.25909.2

One thing to keep in mind though is that value will change whenever a different version of Visual Studio writes to the solution file. E.g., if you create a solution in VS 2010, close VS 2010, launch VS 2017, open the same solution, add a project to it (this is what forces VS to make a change to the .sln file), the version in the solution file will then change to VS 2017. I.e., the last version of VS to write to the solution file, will be set as the version to be used when opening it.

If you're finding it's not working as described, we likely have a bug here. Let me know if that's what you think is happening.


问:
Wordpress commenting system with Facebook/Open ID/Twitter login?
Is there any Wordpress commenting system with Facebook/Open ID/Twitter login?
I know Disqus or Intense Debate but I don't like them because the comments aren't hosted on my server. I want full control.
I can find plugins for Facebook and Twitter separately, but not together.
Is there any way to do what Intense Debate can do without a 3rd party hosting involved?</p>

答:
I use a combination of both twitter and facebook plugins that work in harmony on my site, they are made by the same developer.

Simple Twitter Connect

Simple Facebook Connect

You can see them working in tandem on my blog.

(No longer using WordPress)

Back to using wordpress!

This does what you want and more, pretty slick.

Social Plugin for Wordpress


问:
getting a 502 gateway error when deploying hapijs to google app engine
The logs tell me the favicon is not being served

```<code>"GET /favicon.ico" 502
</code>```

app.yaml

```<code>runtime: nodejs
env: flex
</code>```

server.js

```<code>const Hapi = require('hapi');
const Vision = require('vision');
const Inert = require('inert');
const Path = require('path');
const Handlebars = require('handlebars');

async function start() {
  const server = new Hapi.Server({ host: 'localhost', port: process.env.PORT || 8080 });

  await server.register([Inert, Vision]);

  server.views({ engines: { html: Handlebars }, path: `${__dirname}/templates` });

  const rootHandler = (request, h) => {
    return h.view('index', {
      title: "Data Controller",
      message: "All hail the DC Dashboard",
      meta: `Hapi ${request.server.version}`
    });
  };

  server.route({ method: 'GET', path: '/', handler: rootHandler });
  server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: `${__dirname}/public` }}});
  server.route({ method: 'GET', path: '/favicon.ico', handler: { file: `${__dirname}/public/favicon.ico` }, config: { cache: { expiresIn: 86400000 }}});

  try {
    await server.start();
  }
  catch (err) {
    console.log(err);
    process.exit(1);
  }

  console.log('Server running at:', server.info.uri);
};

start();
</code>```

folder structure:

```<code>/
- public
 - css
 - js
 favicon.ico
server.js
</code>```

I'm just not sure how to resolve this! Any help appreciated.

答:
ok I resolved this by setting the host to </p>

```<code>0.0.0.0
</code>```

Body:
The logs tell me the favicon is not being served

"GET /favicon.ico" 502

app.yaml

runtime: nodejs
env: flex

server.js

const Hapi = require('hapi');
const Vision = require('vision');
const Inert = require('inert');
const Path = require('path');
const Handlebars = require('handlebars');

async function start() {
  const server = new Hapi.Server({ host: 'localhost', port: process.env.PORT || 8080 });

  await server.register([Inert, Vision]);

  server.views({ engines: { html: Handlebars }, path: `${__dirname}/templates` });

  const rootHandler = (request, h) => {
    return h.view('index', {
      title: "Data Controller",
      message: "All hail the DC Dashboard",
      meta: `Hapi ${request.server.version}`
    });
  };

  server.route({ method: 'GET', path: '/', handler: rootHandler });
  server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: `${__dirname}/public` }}});
  server.route({ method: 'GET', path: '/favicon.ico', handler: { file: `${__dirname}/public/favicon.ico` }, config: { cache: { expiresIn: 86400000 }}});

  try {
    await server.start();
  }
  catch (err) {
    console.log(err);
    process.exit(1);
  }

  console.log('Server running at:', server.info.uri);
};

start();

folder structure:

/
- public
 - css
 - js
 favicon.ico
server.js

I'm just not sure how to resolve this! Any help appreciated.

Body:
ok I resolved this by setting the host to

0.0.0.0


问:
MS Web Deploy: configuration section `system.webServer/management/delegation` is missing
I have Windows server 2012 R2 with installed Web Deploy 3.5.

I try to deploy my application, but got next error:

Log file contains next:

Is there any solution?

答:
In my case, it was the sequence of installation for management service and web deployment.

You need to install management service first and then install web deployment.

if you mess up the order like I did, uninstall web deployment and reinstall it.


问:
How to split cell array values into two columns in MATLAB?
I have data in a cell array as shown in the variable viewer here:

```<code>{[2.13949546690144;56.9515770543056],
 [1.98550875192835;50.4110852121618],
 ...}
</code>```

I want to split it into two columns with two decimal-point numbers as:

```<code>2.13   56.95
1.98   50.41
</code>```

by removing opening and closing braces and semicolons such as [;]
(to do as like "Text to columns" in Excel).

答:
```<code>% let's build a matching example...
c = cell(2,1);
c{1} = [2.13949546690144; 56.9515770543056];
c{2} = [1.98550875192835; 50.4110852121618];

% convert your cell array to a double array...
m = cell2mat(c);

% take the odd rows and place them to the left
% take the even rows and place them to the right
m = [m(1:2:end,:) m(2:2:end,:)];

% round the whole matrix to two decimal digits
m = round(m,2);
</code>```

Depending on your environment settings, you may still see a lot of trailing zeros after the first two decimal digits... but don't worry, everything is ok (on the precision point of view). If you want to display only the "real" digits of your numbers, use this command:

```<code>format short g;
</code>```

Body:
I have data in a cell array as shown in the variable viewer here:

{[2.13949546690144;56.9515770543056],
 [1.98550875192835;50.4110852121618],
 ...}

I want to split it into two columns with two decimal-point numbers as:

2.13   56.95
1.98   50.41

by removing opening and closing braces and semicolons such as [;]
(to do as like "Text to columns" in Excel).

Body:
% let's build a matching example...
c = cell(2,1);
c{1} = [2.13949546690144; 56.9515770543056];
c{2} = [1.98550875192835; 50.4110852121618];

% convert your cell array to a double array...
m = cell2mat(c);

% take the odd rows and place them to the left
% take the even rows and place them to the right
m = [m(1:2:end,:) m(2:2:end,:)];

% round the whole matrix to two decimal digits
m = round(m,2);

Depending on your environment settings, you may still see a lot of trailing zeros after the first two decimal digits... but don't worry, everything is ok (on the precision point of view). If you want to display only the "real" digits of your numbers, use this command:

format short g;


问:
SQL: Count items by day (where day must be converted)
Thank you in advance for reading my question. I have data like this:

```<code>| Date_Time               | City | Vehicle_ID |
'2017-01-01 00:00:00.000'   'A'       1159
'2017-01-01 13:12:00.000'   'A'       1159
'2017-01-02 01:00:34.000'   'B'       1323
'2017-01-02 02:00:25.000'   'A'       1159
</code>```

I would like to calculate a new column 'Day_Number' which represents the interval of days from min(Date_Time) + 1, and then count the unique(Vehicle_IDs) by 'City' and by 'Day_Number'.

Example:

```<code>| City | Day | count_unique_vehicles |
  'A'     1             2
  'A'     2             1
  'B'     2             1
</code>```

I have written some terrible sql like

```<code> select date_time, city, count(distinct Vehicle_ID) as unique_vehicle
 from X
 where date_time >= '2017-12-01 00:00:00.000'
 group by DATEADD(DAY, DATEDIFF(DAY,'2017-12-01', date_time), date_time), Division
</code>```

which doesn't work. What should my query look like?

答:
Try this:  </p>

```<code>SELECT
A.CITY, DATEDIFF(DAY, B.DAY_0, A.DATE_TIME) AS DAY, COUNT(DISTINCT A.VEHICLE_ID) AS UNIQUE_VEHICLE
FROM
YOUR_TABLE A, (SELECT MIN(DATE_TIME) AS DAY_0 FROM YOUR_TABLE) B
GROUP BY A.CITY, DATEDIFF(DAY, B.DAY_0, A.DATE_TIME)
ORDER BY A.CITY;
</code>```

Body:
Thank you in advance for reading my question. I have data like this:

| Date_Time               | City | Vehicle_ID |
'2017-01-01 00:00:00.000'   'A'       1159
'2017-01-01 13:12:00.000'   'A'       1159
'2017-01-02 01:00:34.000'   'B'       1323
'2017-01-02 02:00:25.000'   'A'       1159

I would like to calculate a new column 'Day_Number' which represents the interval of days from min(Date_Time) + 1, and then count the unique(Vehicle_IDs) by 'City' and by 'Day_Number'.

Example:

| City | Day | count_unique_vehicles |
  'A'     1             2
  'A'     2             1
  'B'     2             1

I have written some terrible sql like

 select date_time, city, count(distinct Vehicle_ID) as unique_vehicle
 from X
 where date_time >= '2017-12-01 00:00:00.000'
 group by DATEADD(DAY, DATEDIFF(DAY,'2017-12-01', date_time), date_time), Division

which doesn't work. What should my query look like?

Body:
Try this:

SELECT
A.CITY, DATEDIFF(DAY, B.DAY_0, A.DATE_TIME) AS DAY, COUNT(DISTINCT A.VEHICLE_ID) AS UNIQUE_VEHICLE
FROM
YOUR_TABLE A, (SELECT MIN(DATE_TIME) AS DAY_0 FROM YOUR_TABLE) B
GROUP BY A.CITY, DATEDIFF(DAY, B.DAY_0, A.DATE_TIME)
ORDER BY A.CITY;


问:
Force two cards to be on the same line
I've been working on a website. (Resize the output to get the effect)

.header {
  text-align: center;
  color: #ffffff;
  font-family: Trebuchet MS;
}

body {
  background: linear-gradient(to top right, #FFE259, #FFA751, #FFAF7B);
  background-attachment: fixed;
}

.img {
  text-align: center;
  width: 50%;
  height: 50%;
}

a:link {
  text-decoration: none;
  color: #0645AD;
}

a:visited {
  text-decoration: none;
  color: #0645AD;
}

a:active {
  text-decoration: none;
  color: #0B0080;
}

a:hover {
  text-decoration: none;
  color: #0B0080;
}

.cardPlain {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  width: 70%;
  margin: auto;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  width=70%;
  margin: auto;
}

.control-width {
  width: 70%;
  margin: auto;
}

.card,
.control-width.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  margin: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>&nbsp</h1>
<div class="control-width">

    <div class="card">
      <p>&nbsp</p>
      <p style="text-align: center;"><img src="rappaticFull.jpg" alt="I haven't uploaded the image :-)"></p>
      <div class="container" style="text-align:center">
        <h2 class="header">Hi, I'm rappatic.</h2>
        <p class="header">I code when I feel like it.</p>
        <p>&nbsp</p>
      </div>
    </div>

</div>

<h1>&nbsp</h1>

<div class="cardPlain">
  <div class="container" style="text-align:center">
    <h3 class="header">My Stuff</h3>
    <p class="header">&nbspStack Exchange</p>
    <p class="header">Downloads</p>
    <p class="header">Github</p>
    <p class="header">Twitter&nbsp|&nbspHuggles</p>
  </div>
</div>

<div class="cardPlain">
  <div class="container" style="text-align:center">
    <h3 class="header">Foo</h3>
    <p>bar</p>
    <p>Some content</p></code>```

So the idea is to force the Downloads div to display on the same line as the placeholder (foo), like this:

Everything I've tried (this, this, this and this) doesn't actually work. When I try to do the display: inline-block thing it just forces the two divs over to the left.

What can I do to make the two divs appear on the same line?

答:
Wrap your cardPlain divs in a parent div something like this and style the parent div with display: flex. This will align them horizontally, but you need to adjust the heights of each containers to match heights.

FLEX for more on flexbox tricks.

```<code><div style="display: flex">
  <div class="cardPlain">
  </div>
  <div class="cardPlain">
  </div>
<div>
</code>```

.header {
  text-align: center;
  color: #ffffff;
  font-family: Trebuchet MS;
}

body {
  background: linear-gradient(to top right, #FFE259, #FFA751, #FFAF7B);
  background-attachment: fixed;
}

.img {
  text-align: center;
  width: 50%;
  height: 50%;
}

a:link {
  text-decoration: none;
  color: #0645AD;
}

a:visited {
  text-decoration: none;
  color: #0645AD;
}

a:active {
  text-decoration: none;
  color: #0B0080;
}

a:hover {
  text-decoration: none;
  color: #0B0080;
}

.cardPlain {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  width: 70%;
  margin: auto;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  width=70%;
  margin: auto;
}

.control-width {
  width: 70%;
  margin: auto;
}

.card,
.control-width.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  margin: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>&nbsp</h1>
<div class="control-width">

    <div class="card">
      <p>&nbsp</p>
      <p style="text-align: center;"><img src="rappaticFull.jpg" alt="I haven't uploaded the image :-)"></p>
      <div class="container" style="text-align:center">
        <h2 class="header">Hi, I'm rappatic.</h2>
        <p class="header">I code when I feel like it.</p>
        <p>&nbsp</p>
      </div>
    </div>

</div>

<h1>&nbsp</h1>

<div style="display: flex;">
  <div class="cardPlain">
    <div class="container" style="text-align:center">
      <h3 class="header">My Stuff</h3>
      <p class="header">&nbspStack Exchange</p>
      <p class="header">Downloads</p>
      <p class="header">Github</p>
      <p class="header">Twitter&nbsp|&nbspHuggles</p>
    </div>
  </div>

  <div class="cardPlain">
    <div class="container" style="text-align:center">
      <h3 class="header">Foo</h3>
      <p>bar</p>
      <p>Some content</p>
    </div>
  </div>
</div></code>```

Title: Force two cards to be on the same line

Body:
I've been working on a website. (Resize the output to get the effect)

.header {
  text-align: center;
  color: #ffffff;
  font-family: Trebuchet MS;
}

body {
  background: linear-gradient(to top right, #FFE259, #FFA751, #FFAF7B);
  background-attachment: fixed;
}

.img {
  text-align: center;
  width: 50%;
  height: 50%;
}

a:link {
  text-decoration: none;
  color: #0645AD;
}

a:visited {
  text-decoration: none;
  color: #0645AD;
}

a:active {
  text-decoration: none;
  color: #0B0080;
}

a:hover {
  text-decoration: none;
  color: #0B0080;
}

.cardPlain {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  width: 70%;
  margin: auto;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  width=70%;
  margin: auto;
}

.control-width {
  width: 70%;
  margin: auto;
}

.card,
.control-width.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  margin: auto;
  width: 100%;
}

&nbsp

&nbsp

Hi, I'm rappatic.

I code when I feel like it.

&nbsp

&nbsp

My Stuff

&nbspStack Exchange

Downloads

Github

Twitter&nbsp|&nbspHuggles

Foo

bar

Some content

So the idea is to force the Downloads div to display on the same line as the placeholder (foo), like this:

Everything I've tried (this, this, this and this) doesn't actually work. When I try to do the display: inline-block thing it just forces the two divs over to the left.

What can I do to make the two divs appear on the same line?

Body:
Wrap your cardPlain divs in a parent div something like this and style the parent div with display: flex. This will align them horizontally, but you need to adjust the heights of each containers to match heights.

FLEX for more on flexbox tricks.

<div style="display: flex">
  <div class="cardPlain">
  </div>
  <div class="cardPlain">
  </div>
<div>

.header {
  text-align: center;
  color: #ffffff;
  font-family: Trebuchet MS;
}

body {
  background: linear-gradient(to top right, #FFE259, #FFA751, #FFAF7B);
  background-attachment: fixed;
}

.img {
  text-align: center;
  width: 50%;
  height: 50%;
}

a:link {
  text-decoration: none;
  color: #0645AD;
}

a:visited {
  text-decoration: none;
  color: #0645AD;
}

a:active {
  text-decoration: none;
  color: #0B0080;
}

a:hover {
  text-decoration: none;
  color: #0B0080;
}

.cardPlain {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  width: 70%;
  margin: auto;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  width=70%;
  margin: auto;
}

.control-width {
  width: 70%;
  margin: auto;
}

.card,
.control-width.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius: 10px;
  margin: auto;
  width: 100%;
}

<h1>&nbsp</h1>
<div class="control-width">
  <a href="bio.html">
    <div class="card">
      <p>&nbsp</p>
      <p style="text-align: center;"><img src="rappaticFull.jpg" alt="I haven't uploaded the image :-)"></p>
      <div class="container" style="text-align:center">
        <h2 class="header">Hi, I'm rappatic.</h2>
        <p class="header">I code when I feel like it.</p>
        <p>&nbsp</p>
      </div>
    </div>
  </a>
</div>

<h1>&nbsp</h1>

<div style="display: flex;">
  <div class="cardPlain">
    <div class="container" style="text-align:center">
      <h3 class="header">My Stuff</h3>
      <p class="header"><a href="https://stackexchange.com/users/7808413/pagie" target="_blank">&nbspStack Exchange</a></p>
      <p class="header"><a href="downloads.html">Downloads</a></p>
      <p class="header"><a href="https://github.com/rappatic" target="_blank">Github</a></p>
      <p class="header"><a href="https://twitter.com/rappatic_" target="_blank">Twitter</a>&nbsp|&nbsp<a href="https://huggle.jdf2.org/hug/rappatic/" target="_blank">Huggles</a></p>
    </div>
  </div>

  <div class="cardPlain">
    <div class="container" style="text-align:center">
      <h3 class="header">Foo</h3>
      <p>bar</p>
      <p>Some content</p>
    </div>
  </div>
</div>


问:
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
I recently discovered metaclasses in python.

Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.

But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:

a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages).

a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)

a meta-meta-metaclass is a pattern factory, which corresponds to the GOF pattern groupings, e.g. Creational,  Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.

a meta-meta-meta-metaclass (as far as I could go), is a pattern factory factory, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.

I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.

Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?

I'd very much like to research it further.

答:
To answer your question: no.

Feel free to research it further.

Note, however, that you've conflated design patterns (which are just ideas) with code (which is an implementation.)

Good code often reflects a number of interlocking design patterns.  There's no easy way for formalize this.  The best you can do is a nice picture, well-written docstrings, and method names that reflect the various design patterns.

Also note that a meta-class is a class.  That's a loop.  There's no higher level of abstractions.  At that point, it's just intent.  The idea of meta-meta-class doesn't mean much -- it's a meta-class for meta-classes, which is silly but technically possible.  It's all just a class, however.

Edit

"Are classes that create metaclasses really so silly? How does their utility suddenly run out?"

A class that creates a class is fine.  That's pretty much it.  The fact that the target class is a meta class or an abstract superclass or a concrete class doesn't matter.  Metaclasses make classes.  They might make other metaclasses, which is weird, but they're still just metaclasses making classes.

The utility "suddenly" runs out because there's no actual thing you need (or can even write) in a metaclass that makes another metaclass.  It isn't that it "suddenly" becomes silly.  It's that there's nothing useful there.

As I seed, feel free to research it.  For example, actually write a metaclass that builds another metaclass.  Have fun.  There might be something useful there.

The point of OO is to write class definitions that model real-world entities.  As such, a metaclass is sometimes handy to define cross-cutting aspects of several related classes.  (It's a way to do some Aspect-Oriented Programming.)  That's all a metaclass can really do; it's a place to hold a few functions, like __new__(), that aren't proper parts of the class itself.