问:
Load Angular components by router state change
in Angular all components packed in one file and loading all at once
so main.bundle.js getting bigger with any new component
is there any way to load needed components async, when router state changes?

答:
Yes you can

```<code>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { EagerComponent } from './eager.component';

const routes: Routes = [
   { path: '', redirectTo: 'eager', pathMatch: 'full' },
   { path: 'eager', component: EagerComponent },
   { path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

For further information look into Lazy Loading here:
https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

Body:
Yes you can

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { EagerComponent } from './eager.component';

const routes: Routes = [
   { path: '', redirectTo: 'eager', pathMatch: 'full' },
   { path: 'eager', component: EagerComponent },
   { path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

For further information look into Lazy Loading here:
https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html


来源: stackexchange

问:
Java integer convert to only 2 byte array missing extra 00
I have a stream of data which I have first read using this method.

```<code>int messageSerialNumber = r.readUnsignedShort();
</code>```

Next, I convert it into

```<code>byte[] byteMessageSerialNumber = new byte[2];
byteMessageSerialNumber[0] = (byte) messageSerialNumber;
byteMessageSerialNumber[1] = (byte) (messageSerialNumber >>> 8);
</code>```

Next I build a bigger buffer array and add other data into it.

```<code>ByteBuffer bufReply = ByteBuffer.allocate(10);
bufReply.put(replyMessageID);
bufReply.put(byteMessageSerialNumber);
byte[] fullMessageReply=bufReply.array();
</code>```

What I want is the byteMessageSerialNumber to have 2 bytes so what happens now is that it's without the extra 00.

So it becomes

```<code>05 01 00 27 36 81 82 01 2C
</code>```

It's supposed to be

```<code>05 01 00 27 36 81 82 01 00 2C
</code>```

答:
The solution is simple. Swap like this:

```<code>byteMessageSerialNumber[0] = (byte) (messageSerialNumber >>> 8);
byteMessageSerialNumber[1] = (byte) messageSerialNumber;
</code>```

The first byte should be the first, most significant part of messageSerialNumber, the second byte should be the last, least significant part of messageSerialNumber.

ContentLicense: CC BY-SA 3.0

Body:
I have a stream of data which I have first read using this method.

int messageSerialNumber = r.readUnsignedShort();

Next, I convert it into

byte[] byteMessageSerialNumber = new byte[2];
byteMessageSerialNumber[0] = (byte) messageSerialNumber;
byteMessageSerialNumber[1] = (byte) (messageSerialNumber >>> 8);

Next I build a bigger buffer array and add other data into it.

ByteBuffer bufReply = ByteBuffer.allocate(10);
bufReply.put(replyMessageID);
bufReply.put(byteMessageSerialNumber);
byte[] fullMessageReply=bufReply.array();

What I want is the byteMessageSerialNumber to have 2 bytes so what happens now is that it's without the extra 00.

So it becomes

05 01 00 27 36 81 82 01 2C

It's supposed to be

05 01 00 27 36 81 82 01 00 2C

Body:
The solution is simple. Swap like this:

byteMessageSerialNumber[0] = (byte) (messageSerialNumber >>> 8);
byteMessageSerialNumber[1] = (byte) messageSerialNumber;

The first byte should be the first, most significant part of messageSerialNumber, the second byte should be the last, least significant part of messageSerialNumber.


问:
How to tune the margin in victory?
Below is a general victory code.

```<code> <svg viewBox={viewBox}>
          <VictoryPie
            standalone={false}
            width={width} height={height}
            data={data}
            innerRadius={innerRadius}
            colorScale={colorScale}

          />
          <VictoryLegend x={width - 50} y={30}
            title="Totals"
            centerTitle
            orientation="vertical"
            gutter={20}
            style={{
              title: { fontSize: 15 }
            }}
            data={legendDataWithStyle}
            standalone={false}
          />
</svg>
</code>```

This is the corresponding Jsfiddle

I was using VictoryLegend x={width - 50} y={30} to regulate the distance of piechart and legend. But I found it's hard to precisely tune it. How can I increase the distance of the pie and legend?

答:
I can suggest you use g element with the appropriate value for transform attribute

The g SVG element is a container used to group other SVG elements.
  Transformations applied to the  element are performed on all of its
  child elements, and any of its attributes are inherited by its child
  elements.

And width and height attributes for svg element instead of viewBox.
I forked your fiddle, check please - https://jsfiddle.net/levsha/5tx2s8jj/
here the diff between your and my code.

```<code><svg width={width + 100} height={height}> // we add 100 here to legend fits in svg
</code>```

...

```<code><g transform="translate(40,0)"> // we move legend on 40px here
  <VictoryLegend x={width} y={30}
    title="Totals"
    centerTitle
    orientation="vertical"
    gutter={20}
    style={{
     title: { fontSize: 15 }
    }}
    data={legendDataWithStyle}
    standalone={false}
  />
</g>
</code>```

Title: How to tune the margin in victory?

Body:
Below is a general victory code.

 <svg viewBox={viewBox}>
          <VictoryPie
            standalone={false}
            width={width} height={height}
            data={data}
            innerRadius={innerRadius}
            colorScale={colorScale}

          />
          <VictoryLegend x={width - 50} y={30}
            title="Totals"
            centerTitle
            orientation="vertical"
            gutter={20}
            style={{
              title: { fontSize: 15 }
            }}
            data={legendDataWithStyle}
            standalone={false}
          />
</svg>

This is the corresponding Jsfiddle

I was using VictoryLegend x={width - 50} y={30} to regulate the distance of piechart and legend. But I found it's hard to precisely tune it. How can I increase the distance of the pie and legend?

Body:
I can suggest you use g element with the appropriate value for transform attribute

The g SVG element is a container used to group other SVG elements.
  Transformations applied to the  element are performed on all of its
  child elements, and any of its attributes are inherited by its child
  elements.

And width and height attributes for svg element instead of viewBox.
I forked your fiddle, check please - https://jsfiddle.net/levsha/5tx2s8jj/
here the diff between your and my code.

<svg width={width + 100} height={height}> // we add 100 here to legend fits in svg

...

<g transform="translate(40,0)"> // we move legend on 40px here
  <VictoryLegend x={width} y={30}
    title="Totals"
    centerTitle
    orientation="vertical"
    gutter={20}
    style={{
     title: { fontSize: 15 }
    }}
    data={legendDataWithStyle}
    standalone={false}
  />
</g>


问:
Generating a random number in Swift
I read in https://www.hackingwithswift.com/read/35/2/generating-random-numbers-in-ios-8-and-earlier that the best way to generate a random number is to use

```<code>    let r = arc4random_uniform(UInt32(_names.count))
    let name : String = _names[Int(r)]
</code>```

but it seems odd that I have to cast twice to be able to get a random number, what should I do to avoid casting?

答:
Modified answer from Luca written as extension in Swift 4

```<code>/// Returns random number within given range, upper bound included, eg. -1...0 = [-1, 0, 1]
extension CountableClosedRange where Bound == Int
{
    var random: Int
    {
        let range = self
        let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0
        let min = UInt32(range.lowerBound + offset)
        let max = UInt32(range.upperBound + offset)
        let randomNumber = Int(min + arc4random_uniform(max - min + 1)) - offset

        return randomNumber
    }
}

/// Returns random number within given range, upper bound not included, eg. -1...0 = [-1, 0]
extension CountableRange where Bound == Int
{
    var random: Int
    {
        let range = self
        let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0
        let min = UInt32(range.lowerBound + offset)
        let max = UInt32(range.upperBound + offset)
        let randomNumber = Int(min + arc4random_uniform(max - min)) - offset

        return randomNumber
    }
}
</code>```

Examples:

```<code>(0...10).random
(0..<10).random
</code>```

Title: Generating a random number in Swift

Body:
I read in https://www.hackingwithswift.com/read/35/2/generating-random-numbers-in-ios-8-and-earlier that the best way to generate a random number is to use

    let r = arc4random_uniform(UInt32(_names.count))
    let name : String = _names[Int(r)]

but it seems odd that I have to cast twice to be able to get a random number, what should I do to avoid casting?

Body:
Modified answer from Luca written as extension in Swift 4

/// Returns random number within given range, upper bound included, eg. -1...0 = [-1, 0, 1]
extension CountableClosedRange where Bound == Int
{
    var random: Int
    {
        let range = self
        let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0
        let min = UInt32(range.lowerBound + offset)
        let max = UInt32(range.upperBound + offset)
        let randomNumber = Int(min + arc4random_uniform(max - min + 1)) - offset

        return randomNumber
    }
}

/// Returns random number within given range, upper bound not included, eg. -1...0 = [-1, 0]
extension CountableRange where Bound == Int
{
    var random: Int
    {
        let range = self
        let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0
        let min = UInt32(range.lowerBound + offset)
        let max = UInt32(range.upperBound + offset)
        let randomNumber = Int(min + arc4random_uniform(max - min)) - offset

        return randomNumber
    }
}

Examples:

(0...10).random
(0..<10).random


问:
Initiating variables, of different types, in a way that I can iterate through them with a variable

'Declare variables for cell values attained from APR spreadsheet
    Dim orgSheetvalues(0) As String 'Project Title
    Dim orgSheetvalues(1) As String 'Circuit Tag
    Dim orgSheetvalues(2) As String 'District
    Dim orgSheetvalues(3) As String 'State
    Dim orgSheetvalues(4) As Date 'Date recieved
    Dim orgSheetvalues(5) As Currency  'Planned Capital Cost
    Dim orgSheetvalues(6) As Currency  'Actual Capital Cost
    Dim orgSheetvalues(7) As Date  'Capital work completed date
    Dim orgSheetvalues(8) As Currency  'Planned O&M Cost
    Dim orgSheetvalues(9) As Currency  'Actual O&M Cost
    Dim orgSheetvalues(10) As Date  'O&M work completed date
    Dim orgSheetvalues(11) As String 'RWP File Path
```

Clearly, this does not work.  Does anyone know of a way I can use the same variable name, for different variable types, in a way that can be iterated as the above would if it worked (eg. orgSheetvalue(iterating variable))?

答:
While the Variant array will work just fine, it's prone to errors as you will need to remember the datatype each position holds.

A custom Type in my opinion would be better approach.

```<code>Public Type MyCustomType
    ProjectTitle As String
    CircuitTag As String
    District As String
    State As String
    DateRecieved As Date
    PlannedCapitalCost As Currency
   '...
End Type

Sub T()
    Dim o As MyCustomType
        o.ProjectTitle = "abc"
        o.CircuitTag = "..."
        o.DateRecieved = Date
End Sub
</code>```

Body:
'Declare variables for cell values attained from APR spreadsheet
    Dim orgSheetvalues(0) As String 'Project Title
    Dim orgSheetvalues(1) As String 'Circuit Tag
    Dim orgSheetvalues(2) As String 'District
    Dim orgSheetvalues(3) As String 'State
    Dim orgSheetvalues(4) As Date 'Date recieved
    Dim orgSheetvalues(5) As Currency  'Planned Capital Cost
    Dim orgSheetvalues(6) As Currency  'Actual Capital Cost
    Dim orgSheetvalues(7) As Date  'Capital work completed date
    Dim orgSheetvalues(8) As Currency  'Planned O&M Cost
    Dim orgSheetvalues(9) As Currency  'Actual O&M Cost
    Dim orgSheetvalues(10) As Date  'O&M work completed date
    Dim orgSheetvalues(11) As String 'RWP File Path

Clearly, this does not work.  Does anyone know of a way I can use the same variable name, for different variable types, in a way that can be iterated as the above would if it worked (eg. orgSheetvalue(iterating variable))?

Body:
While the Variant array will work just fine, it's prone to errors as you will need to remember the datatype each position holds.

A custom Type in my opinion would be better approach.

Public Type MyCustomType
    ProjectTitle As String
    CircuitTag As String
    District As String
    State As String
    DateRecieved As Date
    PlannedCapitalCost As Currency
   '...
End Type

Sub T()
    Dim o As MyCustomType
        o.ProjectTitle = "abc"
        o.CircuitTag = "..."
        o.DateRecieved = Date
End Sub


问:
Android firebase authentication error in .java file
I am trying to authenticate login and signup with Firebase. I was following this article on android hive
but there was lot of errors, one was this,

import com.google.firebase.auth.FirebaseAuth;

for complete detail version of the code you can follow the above "android hive" link.

答:
You can use the Firebase Assistant for adding Firebase Authenitcation.

To open the Firebase Assistant in Android Studio:

Click Tools > Firebase to open the Assistant window.

Click to expand one of the listed features (for example,
Authentication), Click the Connect to Firebase button to connect to
Firebase Project.

Select your project from Firebase console.

It'll automatically add the correct dependencies for your project.


问:
What should I use for performance sensitive data access?
So I have an application which requires very fast access to large volumes of data and we're at the stage where we're undergoing a large re-design of the database, which gives a good opertunity to re-write the data access layer if nessersary!

Currently in our data access layer we use manually created entities along with plain SQL to fill them. This is pretty fast, but this technology is really getting old, and I'm concerned we're missing out on a newer framework or data access method which could be better in terms of neatness and maintainability.

We've seen the Entity Framework, but after some research it just seems that the benefit of the ORM it gives is not enough to justify the lower performance and as some of our queries are getting complex I'm sure performance with the EF would become more of an issue.

So it is a case of sticking with our current methods of data access, or is there something a bit neater than manually creating and maintaining entities?

I guess the thing that's bugging me is just opening our data layer solution and seeing lots of entities, all of which need to be maintained exactly in line with the database, which sometimes can be a lot of work, but then maybe this is the price we pay for performance?

Any ideas, comments and suggestions are very appreciated! :)

Thanks,

Andy.

** Update **

Forgot to mention that we really need to be able to handle using Azure (client requirements), which currently stops us from using stored procedures. ** Update 2 ** Actually we have an interface layer for our DAL which means we can created an Azure implementation which just override data access methods from the Local implementation which aren't suitable for Azure, so I guess we could just use stored procedures for performance sensitive local databases with EF for the cloud.

答:
Stored procedures for performance. ORMs for ease of development

Do you feel up to troubleshooting some opaque generated SQL when it runs badly...? That generates several round trips where one would do? Or insists on using wrong datatypes?

ContentLicense: CC BY-SA 2.5


问:
How to display output on different screen in c?
I want to display output on different screen, but how?
For example:
I want to display " hello world " on the first black screen, and when I press enter button, the old screen will disappear and another new black screen will display "thank you" .
Just how to do that in c?</p>

答:
This is platform-dependent.

In Unix you have to call the corresponding APIs, Qt or GTK, to create a new terminal console.

In Windows you have to call WinAPI such as CreateConsole and such.

It would be easier if you only want to clear your current console. Using ASCII CSI escape sequence works on most Unix & Linux systems, just

```<code>printf("\x1B[2J");
</code>```

Or in Windows, call

```<code>system("cls");
</code>```

There's actually a more native approach which calls FillConsoleOutputCharacter and FillConsoleOutputAttribute, which introduces extra code that I'm not talking about here.

Body:
This is platform-dependent.

In Unix you have to call the corresponding APIs, Qt or GTK, to create a new terminal console.

In Windows you have to call WinAPI such as CreateConsole and such.

It would be easier if you only want to clear your current console. Using ASCII CSI escape sequence works on most Unix & Linux systems, just

printf("\x1B[2J");

Or in Windows, call

system("cls");

There's actually a more native approach which calls FillConsoleOutputCharacter and FillConsoleOutputAttribute, which introduces extra code that I'm not talking about here.


问:
running multiple commands in parallel in bash
I want to run multiple scripts/commands in parallel in bash.
Here is the bash script :

```<code>python test_script.py &
docker stop process &
docker stop process1 &
sleep(1)
wait

docker start process1 &
docker start process &
wait
</code>```

Here, im running multiple dockers and want to start/stop docker when my script python test_script.py is running.

for ex: python script is running and on parallel i want to stop process & process1 docker. python script is still in-progress and then say wait or sleep for 1 min and start the process again.

How can i achieve it ?

答:
You can combine the following rules:

X; Y    Run X and then Y, regardless of success of X

X && Y  Run Y if X succeeded

X || Y  Run Y if X failed

X &     Run X in background.

Body:
I want to run multiple scripts/commands in parallel in bash.
Here is the bash script :

python test_script.py &
docker stop process &
docker stop process1 &
sleep(1)
wait

docker start process1 &
docker start process &
wait

Here, im running multiple dockers and want to start/stop docker when my script python test_script.py is running.

for ex: python script is running and on parallel i want to stop process & process1 docker. python script is still in-progress and then say wait or sleep for 1 min and start the process again.

How can i achieve it ?


问:
How to configure url-pattern under security domain in web.xml from java at runtime?
I have security domain configured in web.xml as:

```<code><security-constraint>
    <display-name>all</display-name>
        <web-resource-collection>
            <web-resource-name>all</web-resource-name>
            <url-pattern>${param-name</url-pattern>
            <http-method>POST</http-method>
            <http-method>GET</http-method>
            <http-method>PUT</http-method>
            <http-method>DELETE</http-method>
            <http-method>PATCH</http-method>
        </web-resource-collection>
        <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>
</security-constraint>
</code>```

Now I want to set url-pattern here at server startup from java at runtime. How can I do that?

答: refer java doc to set url-pattern</p>

Body:
I have security domain configured in web.xml as:

<security-constraint>
    <display-name>all</display-name>
        <web-resource-collection>
            <web-resource-name>all</web-resource-name>
            <url-pattern>${param-name</url-pattern>
            <http-method>POST</http-method>
            <http-method>GET</http-method>
            <http-method>PUT</http-method>
            <http-method>DELETE</http-method>
            <http-method>PATCH</http-method>
        </web-resource-collection>
        <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>
</security-constraint>

Now I want to set url-pattern here at server startup from java at runtime. How can I do that?

Body: refer java doc to set url-pattern


问:
How to detect touch on UIWebView
On UIWebview, how can I detect a touch?

But not when user clicks some URL or touching a control.

Is it possible to handle it?

答:
Everything that inherits from UIResponder can handle touches (so does UIWebView). Read the doc:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIResponder_Class/Reference/Reference.html

You'll have to use:

```<code>touchesBegan:withEvent:
</code>```

Edit: Adding the comment here for clarity-

I believe then there's no clean way of doing it, you can either override the hittest withEvent method like this  or do a hack like this: overriding UIView

Title: How to detect touch on UIWebView

Body:
Everything that inherits from UIResponder can handle touches (so does UIWebView). Read the doc:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIResponder_Class/Reference/Reference.html

You'll have to use:

touchesBegan:withEvent:

Edit: Adding the comment here for clarity-

I believe then there's no clean way of doing it, you can either override the hittest withEvent method like this  or do a hack like this: overriding UIView


问:
Partially deserialize json into POJO but keep some raw json as field
I have a json as follows:

```<code>"customer": {
     "personal": {
        "name": “jim johnson”,
        “miscellaneous”: {
            “active”: “true”,
            “addons”: {
              "location": “us”
            },
        “customer_id”: “1234”
        }
    },
    “source”: “main db”
}
</code>```

I can create an simple POJO mapping everything one to one but what I would like is the following:

I would like to have an object such as follows:

```<code>class Customer {
   Personal personal;
   String source;
}

class Personal {
    String name;
    String customer_id;
    String miscellaneous; // <—— This is the problem
    // JsonObject miscellaneous;
}
</code>```

How can I deserialize the json and have the miscellaneous kept as a string of raw json string? Or even have it as a raw json element?

答:
```<code>public class myClassName {
        public Customer customer;
        public class Customer {
            public Personal personal;
            public String source;
        }
        public class Personal {
            public String name;
           public Miscellaneous miscellaneous;
        }
        public class Miscellaneous {
            public String active;
           public Addons addons;
                   public String customerId;
        }
        public class Addons {
            public String location;
        }
    }
</code>```

Body:
I have a json as follows:

"customer": {
     "personal": {
        "name": “jim johnson”,
        “miscellaneous”: {
            “active”: “true”,
            “addons”: {
              "location": “us”
            },
        “customer_id”: “1234”
        }
    },
    “source”: “main db”
}

I can create an simple POJO mapping everything one to one but what I would like is the following:

I would like to have an object such as follows:

class Customer {
   Personal personal;
   String source;
}

class Personal {
    String name;
    String customer_id;
    String miscellaneous; // <—— This is the problem
    // JsonObject miscellaneous;
}

How can I deserialize the json and have the miscellaneous kept as a string of raw json string? Or even have it as a raw json element?


问:
Laravel resource route delete from axios
I would like to setup axios to delete a record using a resource route:

```<code>axios.delete('/job-management', this.deletedata).then((res)=>{
    console.log(res);
})
</code>```

For my routes I have:

```<code>Route::resource('job-management', "PositionsController", [ 'as' => 'jobs']);
</code>```

Now, in my PositionsController I have:

```<code>public function destroy(Positions $positions) {
    return $positions;
}
</code>```

But the above always returns "method not allowed". How can I handle a delete request with the axios delete() method?

答:
as I can see in your code above, you pass Positionseloquent as a parameter to destroy method but in your vueJS you don't pass this object. for that you would pass it like this :

```<code>axios.delete('/job-management/${id}').then((res)=>{
    console.log(res);
})
</code>```

and the id param inside the url of ur axios delete, it can object of data or any think.

i hope this help you

Body:
I would like to setup axios to delete a record using a resource route:

axios.delete('/job-management', this.deletedata).then((res)=>{
    console.log(res);
})

For my routes I have:

Route::resource('job-management', "PositionsController", [ 'as' => 'jobs']);

Now, in my PositionsController I have:

public function destroy(Positions $positions) {
    return $positions;
}

But the above always returns "method not allowed". How can I handle a delete request with the axios delete() method?

Body:
as I can see in your code above, you pass Positionseloquent as a parameter to destroy method but in your vueJS you don't pass this object. for that you would pass it like this :

axios.delete('/job-management/${id}').then((res)=>{
    console.log(res);
})

and the id param inside the url of ur axios delete, it can object of data or any think.

i hope this help you


问:
C#: calling C++ DLL with char** argument
I would like to call this C++ function from my C# code:

```<code>void GetArrayOfNames(char** names, int nbOfNames);
</code>```

To call it in C++, I just define an array of char*:

```<code>char* aNames[20];
</code>```

And allocate each name in a loop:

```<code>for(int i-0; i<20; i++)
{
    aNames[i] = new char[50];
}
</code>```

Then call:

```<code>GetArrayOfNames(aNames, 20);
</code>```

In my C# code, I have:

```<code>[DllImport("MyDLL.dll")]
unsafe static extern void GetArrayOfNames(char** ppNames, int nbOfNames);
</code>```

Now, how do I do the memory allocation and call GetArrayOfNames?  Also, any way of not having to declare my function as "unsafe"?

答:
As I understand char** is just a reference to string. I created a small test for myself and it worked fine:

```<code>class Program
{
    [DllImport("TestCppLib.dll", CharSet = CharSet.Ansi, EntryPoint = "?fnTestCppLib@@YAHPAPAD@Z", CallingConvention=CallingConvention.Cdecl)]
    extern static int fnTestCppLib(ref string s);
    static void Main(string[] args)
    {
        var s = "some";
        var t = fnTestCppLib(ref s);
        Debug.Assert(s == "test");
    }
}
</code>```

The implementation of function in C++ is:

```<code>TESTCPPLIB_API int fnTestCppLib(char ** str)
{
    *str = "test";
    return 42;
}
</code>```

Body:
I would like to call this C++ function from my C# code:

void GetArrayOfNames(char** names, int nbOfNames);

To call it in C++, I just define an array of char*:

char* aNames[20];

And allocate each name in a loop:

for(int i-0; i<20; i++)
{
    aNames[i] = new char[50];
}

Then call:

GetArrayOfNames(aNames, 20);

In my C# code, I have:

[DllImport("MyDLL.dll")]
unsafe static extern void GetArrayOfNames(char** ppNames, int nbOfNames);

Now, how do I do the memory allocation and call GetArrayOfNames?  Also, any way of not having to declare my function as "unsafe"?

Body:
As I understand char** is just a reference to string. I created a small test for myself and it worked fine:

class Program
{
    [DllImport("TestCppLib.dll", CharSet = CharSet.Ansi, EntryPoint = "?fnTestCppLib@@YAHPAPAD@Z", CallingConvention=CallingConvention.Cdecl)]
    extern static int fnTestCppLib(ref string s);
    static void Main(string[] args)
    {
        var s = "some";
        var t = fnTestCppLib(ref s);
        Debug.Assert(s == "test");
    }
}

The implementation of function in C++ is:

TESTCPPLIB_API int fnTestCppLib(char ** str)
{
    *str = "test";
    return 42;
}


问:
How to detect if a toggle is open it should be displayed on a larger screen jquery
this is my first post.I am working with different size screens.On a visible-sm screen such as an ipad/mobile when i click a button it toggles a div for me.However i would like to know if my toggle/div is opened while it is in visible-sm mode and i make the screen "responsive" how do i get it to toggle my div  over the entire screen.Only if its open.

code

```<code>function Toggle() {
          if  ($("#btn").click(function () {

                ($("#open").toggle());           //this will display my "#open div"
                ($("#open").css('display', 'block'));
                $("#div").hide();
            }))
            else if{
                    ($("#open").is(":visible"))
                {
                  alert("need a holiday!!!"); //this is what i tried to check if the div is open but it does not detect anything
                   }
             // so if #open is opened and the screen is now responsive it should fill the entire screen
           }
          }
</code>```

css

```<code><div id="open" class="visible-sm">// contents that are displayed</div>
</code>```

your guidance will be highly appreciated.

答:
Are you looking for something like this?</p>

```<code>if($('#open').css('display') == 'block')
{
//div is visible
}
else{
//not visible
]
</code>```

Body:
this is my first post.I am working with different size screens.On a visible-sm screen such as an ipad/mobile when i click a button it toggles a div for me.However i would like to know if my toggle/div is opened while it is in visible-sm mode and i make the screen "responsive" how do i get it to toggle my div  over the entire screen.Only if its open.

code

function Toggle() {
          if  ($("#btn").click(function () {

                ($("#open").toggle());           //this will display my "#open div"
                ($("#open").css('display', 'block'));
                $("#div").hide();
            }))
            else if{
                    ($("#open").is(":visible"))
                {
                  alert("need a holiday!!!"); //this is what i tried to check if the div is open but it does not detect anything
                   }
             // so if #open is opened and the screen is now responsive it should fill the entire screen
           }
          }

css

// contents that are displayed

your guidance will be highly appreciated.

Body:
Are you looking for something like this?

if($('#open').css('display') == 'block')
{
//div is visible
}
else{
//not visible
]


问:
Multiple galleries on the same page
I have these two galleries: https://jsfiddle.net/au254p1q/3/

When i'm on second image and i click "next", the slideshow proceeds on the second gallery (image three). How can i avoid this? I need two separated slideshow to each gallery. Thanks.

```<code>enter code here
</code>```

答: I'm not very familiar with highslide js, but as I see you are using same instance of hs for two galleries, so it toggles between all images provided. Only difference in your code is html, it doesn't make logical distinction between galleries, only visual. You should make separate instance for second gallery, if it isn't singleton. I guess that you're trying to do some lightbox, try this. As I see, it make possible to pass instance for different elements. You should pass your data attribute to element you want: [data-toggle="lightbox"] for one, [data-toggle="lightbox-2"] for second, and this should work. It requires jQuery on the other hand.

Title: Multiple galleries on the same page

Body:
I have these two galleries: https://jsfiddle.net/au254p1q/3/

When i'm on second image and i click "next", the slideshow proceeds on the second gallery (image three). How can i avoid this? I need two separated slideshow to each gallery. Thanks.

enter code here


问:
How do i change my layout text dynamically?
i'm trying to change the Text on the BUTTON dynamically which is in the panel:

the initial text i've given is: var gost = "HPCL Jan 20 Put,40 cents ..";

```<code>    var bottomdetail = new Ext.Panel({
    flex:1,
    padding: 1,
    layout : {
                type: 'vbox',
                pack: 'center',
                align: 'stretch'
             },
    stretchX: true,
    items:[{
           xtype: 'button',
           flex: 1,
           baseCls: 'round',
           html: '<table border="0" height="100%" width="100%"><tr><td width="100%" style="color:#fff; padding-left:5px;" valign="middle">'+ gost + '</td><td valign="middle" align="right" style="padding-right:5px;"><img src="resources/Images/rightarrow.png"></img></td></tr></table>',
           handler: function(){window.location='DetailsPanel.html';}
           }]
});
</code>```

here is the piont where i use it to change the text :

```<code>    var shakepanel = new Ext.Panel({
                                layout : {
                                            type: 'hbox',
                                            pack: 'center',
                                            align: 'stretch'
                                         },
                                stretchX: true,
                                flex:1,
                                disable: true,
                                items: [{
                                        xtype: 'button',
                                        disable: true,
                                        layout: 'fit',
                                        ui: 'decline',
                                        text: 'SHAKE',
                                        flex:1,
                                        handler: function(){
                                            gost="ola i changed it";
                                            alert(bottomdetail.getText());
                                            }
                                     }]
                        });
</code>```

when i click on the button "SHAKE" the value of the "gost" is updated but how to apply the updated gost text to the bottomdetail panel which has the button in it.............

答:
Add an id to the TD with your dynamic text in your layout table, say 'id=titleCell'.

Then call this function after you have updated your text, to remove the existing text node in this cell and add your new one.

```
function updateTitle() {
  var titleCell = document.getElementById('titleCell');
  var updatedTitleText = document.createTextNode(gost);

  titleCell.removeChild(titleCell.firstChild);
  titleCell.appendChild(updatedTitleText);
}
```

You can call it directly after you update your gost var

Body:
i'm trying to change the Text on the BUTTON dynamically which is in the panel:

the initial text i've given is: var gost = "HPCL Jan 20 Put,40 cents ..";

    var bottomdetail = new Ext.Panel({
    flex:1,
    padding: 1,
    layout : {
                type: 'vbox',
                pack: 'center',
                align: 'stretch'
             },
    stretchX: true,
    items:[{
           xtype: 'button',
           flex: 1,
           baseCls: 'round',
           html: '

'+ gost + '

',
           handler: function(){window.location='DetailsPanel.html';}
           }]
});

here is the piont where i use it to change the text :

    var shakepanel = new Ext.Panel({
                                layout : {
                                            type: 'hbox',
                                            pack: 'center',
                                            align: 'stretch'
                                         },
                                stretchX: true,
                                flex:1,
                                disable: true,
                                items: [{
                                        xtype: 'button',
                                        disable: true,
                                        layout: 'fit',
                                        ui: 'decline',
                                        text: 'SHAKE',
                                        flex:1,
                                        handler: function(){
                                            gost="ola i changed it";
                                            alert(bottomdetail.getText());
                                            }
                                     }]
                        });

when i click on the button "SHAKE" the value of the "gost" is updated but how to apply the updated gost text to the bottomdetail panel which has the button in it.............

Body:
Add an id to the TD with your dynamic text in your layout table, say 'id=titleCell'.

Then call this function after you have updated your text, to remove the existing text node in this cell and add your new one.

function updateTitle() {
  var titleCell = document.getElementById('titleCell');
  var updatedTitleText = document.createTextNode(gost);

  titleCell.removeChild(titleCell.firstChild);
  titleCell.appendChild(updatedTitleText);
}

You can call it directly after you update your gost var


问:
STM32F - SPI with DMA "ErrorCallback" and frames shifted
I am communicating 2 uC (an arduino display as MASTER and STM32F429 as slave).Its communication consists of 10 bytes in full duplex through SPI using DMA, every 150ms.

During some minutes the communication goes very good, both uC are sending their 10 bytes properly. During this time, I have noted that "HAL_SPI_ErrorCallback" function is called becasue I have added a counter within and it is increased little by little, but the comminication still goes well.

My first question is: Is it normal that sometimes ErrorCallback function is called randomly? due to noise or whatever the communication has an instantaneous error... I guess..

Here are a capture of the MISO signal in green, CLK in whie and CS in yellow

On the other hand, after a while (randomly 10 min, 1h ...) the communication is corrupted just in the MISO signal , the STM32 sends the 10 bytes frame but instead of sending Byte0 Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8 Byte9 Byte10, (LSB first)

it sends:

Byte10 Byte0 Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8 Byte9, IT IS MOVED TO RIGTH 1 byte!?!?

Attached you can see the capture "Working.jpg" with byte0 = 0x02 and the rest of the bytes = 0. In the other capture "NOT_working.jpg" is a capture with the problem. Both uC were working properly for a while and suddenly the STM32 uC started to send this frame all the time (the communication frame is byte = 0x02 and the rest of the bytes = 0 in order to see easily this error).

Working.jpg - which is MISO signal sending the frame properly

NOT_working.jpg - which is MISO signal sending the frame incorrectly

I have tried the communication in:
"Init.Mode = DMA_NORMAL" and "DMA_CIRCULAR", and both configuration have the same behaviour.
I have creaged the 2 variables in order to find out the problem:

```<code>    DMA_counter_RX = __HAL_DMA_GET_COUNTER(&hdma_spi6_rx);
    DMA_counter_TX = __HAL_DMA_GET_COUNTER(&hdma_spi6_tx);
</code>```

And the the comunications goes well, DMA_counter_RX = 10 BUT DMA_counter_TX = 9. This values are normal. But as soon as the shift error occurs, both DMA counters are = 10.

Also this problem always happens in debug mode when I click on "suspend" (pause) and "resume"(play) as soon as I click on "resume"  and the processor continues with the program, the MISO signal is shifted forever.

Additionally I am using TIM1, TIM5, TIM2, TIM3 and TIM4 for other things like PWM and interruptions but not related to SPI...

I have tried to solve this problem modifying all the NVIC priorities for all interruptions and so on but the problem get worst.

I am using System Workbench for STM32  latest version.

Any help is appreciate! Thanks in advance and best regards.

Alejandro

Sorry for long question... :(

Bellow you can see my configuration for SPI and DMA if it can help you:

```<code>void MX_DMA_Init(void)
{
  __HAL_RCC_DMA2_CLK_ENABLE();

  HAL_NVIC_SetPriority(DMA2_Stream5_IRQn, 2, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream5_IRQn);
  HAL_NVIC_SetPriority(DMA2_Stream6_IRQn, 2, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream6_IRQn);

}

void MX_SPI6_Init(void)
{

  hspi6.Instance = SPI6;
  hspi6.Init.Mode = SPI_MODE_SLAVE;
  hspi6.Init.Direction = SPI_DIRECTION_2LINES;
  hspi6.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi6.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi6.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi6.Init.NSS = SPI_NSS_HARD_INPUT;
  hspi6.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi6.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi6.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi6.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi6) != HAL_OK)
  {
    Error_Handler();
  }

}

void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{

      GPIO_InitTypeDef GPIO_InitStruct;
      if(hspi->Instance==SPI6)
      {
        __HAL_RCC_SPI6_CLK_ENABLE();

        /**SPI6 GPIO Configuration
        PG8     ------> SPI6_NSS
        PG12     ------> SPI6_MISO
        PG13     ------> SPI6_SCK
        PG14     ------> SPI6_MOSI
        */
        GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
        GPIO_InitStruct.Alternate = GPIO_AF5_SPI6;
        HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);

        hdma_spi6_rx.Instance = DMA2_Stream6;
        hdma_spi6_rx.Init.Channel = DMA_CHANNEL_1;
        hdma_spi6_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
        hdma_spi6_rx.Init.PeriphInc = DMA_PINC_DISABLE;
        hdma_spi6_rx.Init.MemInc = DMA_MINC_ENABLE;
        hdma_spi6_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
        hdma_spi6_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
        hdma_spi6_rx.Init.Mode = DMA_NORMAL;
        hdma_spi6_rx.Init.Priority = DMA_PRIORITY_MEDIUM;
        hdma_spi6_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
        if (HAL_DMA_Init(&hdma_spi6_rx) != HAL_OK)
        {
          Error_Handler();
        }

        __HAL_LINKDMA(hspi,hdmarx,hdma_spi6_rx);

        hdma_spi6_tx.Instance = DMA2_Stream5;
        hdma_spi6_tx.Init.Channel = DMA_CHANNEL_1;
        hdma_spi6_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
        hdma_spi6_tx.Init.PeriphInc = DMA_PINC_DISABLE;
        hdma_spi6_tx.Init.MemInc = DMA_MINC_ENABLE;
        hdma_spi6_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
        hdma_spi6_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
        hdma_spi6_tx.Init.Mode = DMA_NORMAL;
        hdma_spi6_tx.Init.Priority = DMA_PRIORITY_MEDIUM;
        hdma_spi6_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
        if (HAL_DMA_Init(&hdma_spi6_tx) != HAL_OK)
        {
          Error_Handler();
        }

        __HAL_LINKDMA(hspi,hdmatx,hdma_spi6_tx);

        /* Peripheral interrupt init */
        HAL_NVIC_SetPriority(SPI6_IRQn, 2, 0);
        HAL_NVIC_EnableIRQ(SPI6_IRQn);
      }
}
</code>```

During initialization code, I configure SPI6 and DMA as it is described before, just after that I enable communication using:

```<code>HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data, 10);
</code>```

Also it were added the following 2 functions related to SPI communication:

```<code>void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
    if(hspi -> Instance == SPI6)
    {
        HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data, 10);
    }
}

void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
{
    if(hspi -> Instance == SPI6)
    {

        HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data,10);
    }
}
</code>```

STM cube mx automatically created:

```<code>void DMA2_Stream5_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream5_IRQn 0 */

  /* USER CODE END DMA2_Stream5_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_spi6_tx);
  /* USER CODE BEGIN DMA2_Stream5_IRQn 1 */

  /* USER CODE END DMA2_Stream5_IRQn 1 */
}

/**
* @brief This function handles DMA2 stream6 global interrupt.
*/
void DMA2_Stream6_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream6_IRQn 0 */

  /* USER CODE END DMA2_Stream6_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_spi6_rx);
  /* USER CODE BEGIN DMA2_Stream6_IRQn 1 */

  /* USER CODE END DMA2_Stream6_IRQn 1 */
}

void SPI6_IRQHandler(void)
{
  /* USER CODE BEGIN SPI6_IRQn 0 */

  /* USER CODE END SPI6_IRQn 0 */
  HAL_SPI_IRQHandler(&hspi6);
  /* USER CODE BEGIN SPI6_IRQn 1 */

  /* USER CODE END SPI6_IRQn 1 */
}
</code>```

------------------------------EDITED----------------------------
I add 2 captures of the SPI register

SPI registers WORKING

SPI registers ERROR

答:
I finally got the solution, I found what the problem was!

Usually, the CS signal goes from 1 to 0, then MISO and MOSI communicates, and once the communication finishes CS signal goes from 0 to 1, and the STM32F429 continues with the rest of the tasks...

This was happening every 150 ms, that's the period of thime both uC are communicating. But the STM32 uC has another tasks with more priority than SPI communication.

When one of this higher priority starts during SPI communication, and once this higher priority is done then the uC continues with the task was doing ( it was SPI), obviouslythis frame is lost and "HAL_SPI_ErrorCallback" is executed, and then SPI is restarted.If SPI is restarted when CS signal is 1, (spi idle), then there is no problem, SPI is restarted properly and the next frame will be received without problem. BUT if SPI is restarted when CS signal is 0 (STM32 SPI is selected and ready to communicate) then the STM32 is waiting to send and receive an amount of bytes but it will receives less, so an a mismatch of communication bytes is the key of the PROBLEM.

I have solved this issue just adding:

```<code>void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
{
    if(hspi -> Instance == SPI6)
    {

        while(HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_8) != GPIO_PIN_SET) // CS signal
        {
        }

        HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data,10);
    }
}
</code>```

I have to modify "WHILE" in order to not stop the processor , but it is the first approximation.

Now the communication is working all the time, but some times a frame is lost (and " HAL_SPI_ErrorCallback" is called) due to higher priority task. But it is normal, a CRC is implemented to note that.

Thanks for helping me and support the support.

I hope this helps to other people.

Best regards.

Alejandro.

Body:
I am communicating 2 uC (an arduino display as MASTER and STM32F429 as slave).Its communication consists of 10 bytes in full duplex through SPI using DMA, every 150ms.

During some minutes the communication goes very good, both uC are sending their 10 bytes properly. During this time, I have noted that "HAL_SPI_ErrorCallback" function is called becasue I have added a counter within and it is increased little by little, but the comminication still goes well.

My first question is: Is it normal that sometimes ErrorCallback function is called randomly? due to noise or whatever the communication has an instantaneous error... I guess..

Here are a capture of the MISO signal in green, CLK in whie and CS in yellow

On the other hand, after a while (randomly 10 min, 1h ...) the communication is corrupted just in the MISO signal , the STM32 sends the 10 bytes frame but instead of sending Byte0 Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8 Byte9 Byte10, (LSB first)

it sends:

Byte10 Byte0 Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8 Byte9, IT IS MOVED TO RIGTH 1 byte!?!?

Attached you can see the capture "Working.jpg" with byte0 = 0x02 and the rest of the bytes = 0. In the other capture "NOT_working.jpg" is a capture with the problem. Both uC were working properly for a while and suddenly the STM32 uC started to send this frame all the time (the communication frame is byte = 0x02 and the rest of the bytes = 0 in order to see easily this error).

Working.jpg - which is MISO signal sending the frame properly

NOT_working.jpg - which is MISO signal sending the frame incorrectly

I have tried the communication in:
"Init.Mode = DMA_NORMAL" and "DMA_CIRCULAR", and both configuration have the same behaviour.
I have creaged the 2 variables in order to find out the problem:

    DMA_counter_RX = __HAL_DMA_GET_COUNTER(&hdma_spi6_rx);
    DMA_counter_TX = __HAL_DMA_GET_COUNTER(&hdma_spi6_tx);

And the the comunications goes well, DMA_counter_RX = 10 BUT DMA_counter_TX = 9. This values are normal. But as soon as the shift error occurs, both DMA counters are = 10.

Also this problem always happens in debug mode when I click on "suspend" (pause) and "resume"(play) as soon as I click on "resume"  and the processor continues with the program, the MISO signal is shifted forever.

Additionally I am using TIM1, TIM5, TIM2, TIM3 and TIM4 for other things like PWM and interruptions but not related to SPI...

I have tried to solve this problem modifying all the NVIC priorities for all interruptions and so on but the problem get worst.

I am using System Workbench for STM32  latest version.

Any help is appreciate! Thanks in advance and best regards.

Alejandro

Sorry for long question... :(

Bellow you can see my configuration for SPI and DMA if it can help you:

void MX_DMA_Init(void)
{
  __HAL_RCC_DMA2_CLK_ENABLE();

  HAL_NVIC_SetPriority(DMA2_Stream5_IRQn, 2, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream5_IRQn);
  HAL_NVIC_SetPriority(DMA2_Stream6_IRQn, 2, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream6_IRQn);

}

void MX_SPI6_Init(void)
{

  hspi6.Instance = SPI6;
  hspi6.Init.Mode = SPI_MODE_SLAVE;
  hspi6.Init.Direction = SPI_DIRECTION_2LINES;
  hspi6.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi6.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi6.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi6.Init.NSS = SPI_NSS_HARD_INPUT;
  hspi6.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi6.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi6.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi6.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi6) != HAL_OK)
  {
    Error_Handler();
  }

}

void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{

      GPIO_InitTypeDef GPIO_InitStruct;
      if(hspi->Instance==SPI6)
      {
        __HAL_RCC_SPI6_CLK_ENABLE();

        /**SPI6 GPIO Configuration
        PG8     ------> SPI6_NSS
        PG12     ------> SPI6_MISO
        PG13     ------> SPI6_SCK
        PG14     ------> SPI6_MOSI
        */
        GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
        GPIO_InitStruct.Alternate = GPIO_AF5_SPI6;
        HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);

        hdma_spi6_rx.Instance = DMA2_Stream6;
        hdma_spi6_rx.Init.Channel = DMA_CHANNEL_1;
        hdma_spi6_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
        hdma_spi6_rx.Init.PeriphInc = DMA_PINC_DISABLE;
        hdma_spi6_rx.Init.MemInc = DMA_MINC_ENABLE;
        hdma_spi6_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
        hdma_spi6_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
        hdma_spi6_rx.Init.Mode = DMA_NORMAL;
        hdma_spi6_rx.Init.Priority = DMA_PRIORITY_MEDIUM;
        hdma_spi6_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
        if (HAL_DMA_Init(&hdma_spi6_rx) != HAL_OK)
        {
          Error_Handler();
        }

        __HAL_LINKDMA(hspi,hdmarx,hdma_spi6_rx);

        hdma_spi6_tx.Instance = DMA2_Stream5;
        hdma_spi6_tx.Init.Channel = DMA_CHANNEL_1;
        hdma_spi6_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
        hdma_spi6_tx.Init.PeriphInc = DMA_PINC_DISABLE;
        hdma_spi6_tx.Init.MemInc = DMA_MINC_ENABLE;
        hdma_spi6_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
        hdma_spi6_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
        hdma_spi6_tx.Init.Mode = DMA_NORMAL;
        hdma_spi6_tx.Init.Priority = DMA_PRIORITY_MEDIUM;
        hdma_spi6_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
        if (HAL_DMA_Init(&hdma_spi6_tx) != HAL_OK)
        {
          Error_Handler();
        }

        __HAL_LINKDMA(hspi,hdmatx,hdma_spi6_tx);

        /* Peripheral interrupt init */
        HAL_NVIC_SetPriority(SPI6_IRQn, 2, 0);
        HAL_NVIC_EnableIRQ(SPI6_IRQn);
      }
}

During initialization code, I configure SPI6 and DMA as it is described before, just after that I enable communication using:

HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data, 10);

Also it were added the following 2 functions related to SPI communication:

void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
    if(hspi -> Instance == SPI6)
    {
        HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data, 10);
    }
}

void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
{
    if(hspi -> Instance == SPI6)
    {

        HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data,10);
    }
}

STM cube mx automatically created:

void DMA2_Stream5_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream5_IRQn 0 */

  /* USER CODE END DMA2_Stream5_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_spi6_tx);
  /* USER CODE BEGIN DMA2_Stream5_IRQn 1 */

  /* USER CODE END DMA2_Stream5_IRQn 1 */
}

/**
* @brief This function handles DMA2 stream6 global interrupt.
*/
void DMA2_Stream6_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream6_IRQn 0 */

  /* USER CODE END DMA2_Stream6_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_spi6_rx);
  /* USER CODE BEGIN DMA2_Stream6_IRQn 1 */

  /* USER CODE END DMA2_Stream6_IRQn 1 */
}

void SPI6_IRQHandler(void)
{
  /* USER CODE BEGIN SPI6_IRQn 0 */

  /* USER CODE END SPI6_IRQn 0 */
  HAL_SPI_IRQHandler(&hspi6);
  /* USER CODE BEGIN SPI6_IRQn 1 */

  /* USER CODE END SPI6_IRQn 1 */
}

------------------------------EDITED----------------------------
I add 2 captures of the SPI register

SPI registers WORKING

SPI registers ERROR

Body:
I finally got the solution, I found what the problem was!

Usually, the CS signal goes from 1 to 0, then MISO and MOSI communicates, and once the communication finishes CS signal goes from 0 to 1, and the STM32F429 continues with the rest of the tasks...

This was happening every 150 ms, that's the period of thime both uC are communicating. But the STM32 uC has another tasks with more priority than SPI communication.

When one of this higher priority starts during SPI communication, and once this higher priority is done then the uC continues with the task was doing ( it was SPI), obviouslythis frame is lost and "HAL_SPI_ErrorCallback" is executed, and then SPI is restarted.If SPI is restarted when CS signal is 1, (spi idle), then there is no problem, SPI is restarted properly and the next frame will be received without problem. BUT if SPI is restarted when CS signal is 0 (STM32 SPI is selected and ready to communicate) then the STM32 is waiting to send and receive an amount of bytes but it will receives less, so an a mismatch of communication bytes is the key of the PROBLEM.

I have solved this issue just adding:

void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
{
    if(hspi -> Instance == SPI6)
    {

        while(HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_8) != GPIO_PIN_SET) // CS signal
        {
        }

        HAL_SPI_TransmitReceive_DMA(&hspi6, (uint8_t*)HMI_slave_TX_data, (uint8_t*)HMI_slave_RX_data,10);
    }
}

I have to modify "WHILE" in order to not stop the processor , but it is the first approximation.

Now the communication is working all the time, but some times a frame is lost (and " HAL_SPI_ErrorCallback" is called) due to higher priority task. But it is normal, a CRC is implemented to note that.

Thanks for helping me and support the support.

I hope this helps to other people.

Best regards.

Alejandro.


答:
hi, are you trying to like this

```<code>  function Toggle() {
          if  ($("#btn").click(function () {

                if ($(window).width() < 991) {
                $("#open").toggle();//this will display my "#open div"
                $("#open").css('display', 'block');
                $("#div").hide();
                 }
                 else {
                   alert('More than 991');
                      }
                }))

          }
</code>```

Title: How to detect if a toggle is open it should be displayed on a larger screen jquery

Body:
hi, are you trying to like this

  function Toggle() {
          if  ($("#btn").click(function () {

                if ($(window).width() < 991) {
                $("#open").toggle();//this will display my "#open div"
                $("#open").css('display', 'block');
                $("#div").hide();
                 }
                 else {
                   alert('More than 991');
                      }
                }))

          }


问:
Docker pull images from private repository and pulling changes on images
I want to manage a docker private repository in order of pull images using insecure protocol (http), my question is: It is possible to pull changes on images when something changes on the image I have in the repository or I have to pull all the images again??

For example when something changes on the code that I have in the images in the repository and then I rebuild it on my server I would like to pull that changes from any pc... Something like git I mean

Thank you all!

答:
It is possible to pull changes on images when something changes on the image I have in the repository or I have to pull all the images again?? For example when something changes on the code that I have in the images in the repository and then I rebuild it on my server I would like to pull that changes from any pc... Something like git I mean

You can't pull only the changes like git. Docker pulls images and this means that you will have to run new containers after the image is updated. As it is described here: How to upgrade docker container after its image changed, your workflow/setup should allow you to:

pull the new image

stop your running container

remove it

run it again with the new version

I think you should also do some research on tags which might help you. Since your are updating code, you can use images with different tags. I have found this question: How to update a Docker Image which has many useful things you may wanna use.

Also, if you are using the :latest tag, you should keep in mind the following:

If you are shipping Docker images to a production environment, you should just ignore the latest tag. Don’t use it. Don’t be tempted by it. It’s easy to look at it and think that your deployment script should just pull “latest” and your build process will ensure that’s valid. It takes a lot of discipline to make that work. Just version your tags. Every time.

mentioned here: The misunderstood Docker tag: latest


问:
If distinct count reaches 10 in column then just return true/false instead checking laks of rows in spark
//Actually it iterates through laks of columns for distinct rows it is costlier approach because I need to check if distinct count reaches 10 then return true/false.  </p>

```<code>    val distcnt = dfFilter.select(dfFilter.col("colName")).distinct().count()

    if (distcnt > 10) {
      //I need to do stuff here if it greater than 10 distinct rows
    }
</code>```

答:
If your count condition is always 10, then you can limit the rows returned before count function,</p>

```<code>val distcnt = dfFilter.select(dfFilter.col("colName")).distinct().limit(11).count()
</code>```

Body:
//Actually it iterates through laks of columns for distinct rows it is costlier approach because I need to check if distinct count reaches 10 then return true/false.

    val distcnt = dfFilter.select(dfFilter.col("colName")).distinct().count()

    if (distcnt > 10) {
      //I need to do stuff here if it greater than 10 distinct rows
    }

Body:
If your count condition is always 10, then you can limit the rows returned before count function,

val distcnt = dfFilter.select(dfFilter.col("colName")).distinct().limit(11).count()


问:
How do you become an expert in a programming language?
Assuming you have basic to intermediate knowledge of a particular language, how can you become an expert in that language in a short amount of time?</p>

答: Refer to this 21 Days by Peter Norvig</p>

Body: Refer to this 21 Days by Peter Norvig


问:
Trying to fix MISRA Violation Rule 10.4: unsigned 32-bit int and signed 32-bit int, which do not match
```<code>#define INIT_VALUE 1u
typedef unsigned int uint32_t;
typedef signed int int32_t;
void do_test(uint32_t var1, int32_t var2);

void do_test(uint32_t var1, int32_t var2)
{  uint32_t m_var = INIT_VALUE;
   m_var = (m_var << 1) + (var1 + var2);
}
</code>```

This code resulted in violation of Rule 10.4 which is due to unsigned var1 and signed var2.

I have tried in casting one of the variable to other. But that is not a generic way.

Is there any way to do that ?

答:
Rule 10.4 is a sound one, as it prevents implicit type conversions that can lead to a change of signedness. This is what is happening in your code, var1 + var2 leads to var2 getting silently promoted to an unsigned type. This is not good, since there must be a reason why this variable was signed in the first place.

Simply make sure that you keep track of signedness in your algorithm. If the signed variable will have a negative value, then an implicit conversion to unsigned is a bug. Or otherwise, if you know that the value is always positive and therefore signedness does not matter, then simply cast the signed variable to uint32_t.

Body:
#define INIT_VALUE 1u
typedef unsigned int uint32_t;
typedef signed int int32_t;
void do_test(uint32_t var1, int32_t var2);

void do_test(uint32_t var1, int32_t var2)
{  uint32_t m_var = INIT_VALUE;
   m_var = (m_var << 1) + (var1 + var2);
}

This code resulted in violation of Rule 10.4 which is due to unsigned var1 and signed var2.

I have tried in casting one of the variable to other. But that is not a generic way.

Is there any way to do that ?


问:
Meaning of flags in PROCESS_EXTENDED_BASIC_INFORMATION struct?
Can someone explain what all those bits stand for in PROCESS_EXTENDED_BASIC_INFORMATION?

```<code>typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION {
    SIZE_T Size;    // Ignored as input, written with structure size on output
    PROCESS_BASIC_INFORMATION BasicInfo;
    union {
        ULONG Flags;
        struct {
            ULONG IsProtectedProcess : 1;
            ULONG IsWow64Process : 1;
            ULONG IsProcessDeleting : 1;
            ULONG IsCrossSessionCreate : 1;
            ULONG IsFrozen : 1;
            ULONG IsBackground : 1;
            ULONG IsStronglyNamed : 1;
            ULONG IsSecureProcess : 1;
            ULONG IsSubsystemProcess : 1;
            ULONG SpareBits : 23;
        } DUMMYSTRUCTNAME;
    } DUMMYUNIONNAME;
} PROCESS_EXTENDED_BASIC_INFORMATION, *PPROCESS_EXTENDED_BASIC_INFORMATION;
</code>```

Microsoft showed this struct in this article but gave no explanation for what those flags stand for.

答:
The following is a highly undocumented stuff that Microsoft probably doesn't want you to use. Do so at your own risk.

PS. But, you actually had an interesting question. So just for general education:

IsProtectedProcess (0x001) System protected process: other processes can't read/write its VM or inject a remote thread into it. (Old style. If I'm not mistaking, it was available since XP SP3.)

IsWow64Process (0x002) WOW64 process, or 32-bit process running on a 64-bit Windows.

IsProcessDeleting (0x004) Process was terminated, but there're open handles to it -- a very transient stage. (That should be of any interest to you only if you're a kernel driver.)

IsCrossSessionCreate (0x008) Process was created across terminal sessions. Ex: Read CreateProcessAsUser for details.

IsFrozen (0x010) Immersive process is suspended (applies only to UWP processes.) For example, Immersive process can be suspended if a user moves it to the background or minimizes it. Used mostly for power saving. More info.

IsBackground (0x020) Immersive process is in the Background task mode. UWP process may temporarily switch into performing a background task. Used mostly for power saving.

IsStronglyNamed (0x040) UWP Strongly named process. The UWP package is digitally signed. Any modifications to files inside the package can be tracked. This usually means that if the package signature is broken the UWP app will not start.

IsSecureProcess (0x080) Isolated User Mode process -- new security mode in Windows 10, with more stringent restrictions on what can "tap" into this process.

IsSubsystemProcess (0x100) Set when the type of the process subsystem is other than Win32 (like *NIX, such as Ubuntu.) Yes, you read it right, you can run Linux natively on Windows 10. (Ref1, Ref2.)

PS2. I'm open for corrections, if any ...

Body:
Can someone explain what all those bits stand for in PROCESS_EXTENDED_BASIC_INFORMATION?

typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION {
    SIZE_T Size;    // Ignored as input, written with structure size on output
    PROCESS_BASIC_INFORMATION BasicInfo;
    union {
        ULONG Flags;
        struct {
            ULONG IsProtectedProcess : 1;
            ULONG IsWow64Process : 1;
            ULONG IsProcessDeleting : 1;
            ULONG IsCrossSessionCreate : 1;
            ULONG IsFrozen : 1;
            ULONG IsBackground : 1;
            ULONG IsStronglyNamed : 1;
            ULONG IsSecureProcess : 1;
            ULONG IsSubsystemProcess : 1;
            ULONG SpareBits : 23;
        } DUMMYSTRUCTNAME;
    } DUMMYUNIONNAME;
} PROCESS_EXTENDED_BASIC_INFORMATION, *PPROCESS_EXTENDED_BASIC_INFORMATION;

Microsoft showed this struct in this article but gave no explanation for what those flags stand for.


问:
saving gameObject layer always ends up as default (Unity + VS)
So, I've been following this guide: https://www.youtube.com/watch?v=RQyfHmf7v9s
To make a space shooter game.

The idea is that two objects under layer "Enemy" won't collide, But when the object under layer "Player" collides with "Enemy" it becomes part of "invulnerable" layer that doesn't collide with anything.

but it seems that one line at the code (this one:)

```<code>            gameObject.layer = correctLayer;
</code>```

turns my object into "Default" layer every time.
this is the code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("WaterEffects/ForCamera")]
public class HitHandler : MonoBehaviou {

public int health = 1; //Object health

float invulnTimer = 0.25f; //Time in which the gameObject is invulnerable
int correctLayer; // save the original layer of the object

void start()
{
    correctLayer = gameObject.layer;
    gameObject.SetActive(true);
}

void OnTriggerEnter2D()
{
    Debug.Log("Trigger!");
    health--;
    invulnTimer = 2f;
    gameObject.layer = 10; //put object in invulnerable layer
}
// Update is called once per frame
void Update()
{
    invulnTimer -= Time.deltaTime;
    if (invulnTimer <= 0)
    {
        gameObject.layer = correctLayer; //returns object to original layer (doesnt work)
    }
    if (health <= 0)
    {
        Die();
    }
}
void Die()
{
    Destroy(gameObject); // Destroys object
}
}
</code>```

I have no idea why the start function doesn't save the right layer, even though in unity i have defined the objects as their reflective layers.

Note: I have made the objects Kinematic and checked IsTrigger. When the first mentioned line of code is not in use it does work.

答:
It should be void Start() not void start().

Be aware of those capital letters.

Body:
So, I've been following this guide: https://www.youtube.com/watch?v=RQyfHmf7v9s
To make a space shooter game.

The idea is that two objects under layer "Enemy" won't collide, But when the object under layer "Player" collides with "Enemy" it becomes part of "invulnerable" layer that doesn't collide with anything.

but it seems that one line at the code (this one:)

            gameObject.layer = correctLayer;

turns my object into "Default" layer every time.
this is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("WaterEffects/ForCamera")]
public class HitHandler : MonoBehaviou {

public int health = 1; //Object health

float invulnTimer = 0.25f; //Time in which the gameObject is invulnerable
int correctLayer; // save the original layer of the object

void start()
{
    correctLayer = gameObject.layer;
    gameObject.SetActive(true);
}

void OnTriggerEnter2D()
{
    Debug.Log("Trigger!");
    health--;
    invulnTimer = 2f;
    gameObject.layer = 10; //put object in invulnerable layer
}
// Update is called once per frame
void Update()
{
    invulnTimer -= Time.deltaTime;
    if (invulnTimer <= 0)
    {
        gameObject.layer = correctLayer; //returns object to original layer (doesnt work)
    }
    if (health <= 0)
    {
        Die();
    }
}
void Die()
{
    Destroy(gameObject); // Destroys object
}
}

I have no idea why the start function doesn't save the right layer, even though in unity i have defined the objects as their reflective layers.

Note: I have made the objects Kinematic and checked IsTrigger. When the first mentioned line of code is not in use it does work.


问:
My app restarted itself, log shows ChimeraModuleLdr: Module config changed, forcing restart due to module
I was testing my app and I saw it restart itself, was really weird. I looked and looked on the logs and I couldn't find anything odd except for this line ChimeraModuleLdr: Module config changed, forcing restart due to module. This is on a Pixel XL with Oreo.

Here are the last few lines of the log and the start up of the app after it was killed.

```<code>10-18 22:49:31.262  8379  8379 I ChimeraModuleLdr: Module config changed, forcing restart due to module
10-18 22:49:31.262  8379  8379 I Process : Sending signal. PID: 8379 SIG: 9
--------- beginning of main
10-18 22:49:31.641 13717 13717 I MultiDex: VM with version 2.1.0 has multidex support
10-18 22:49:31.641 13717 13717 I MultiDex: install
10-18 22:49:31.641 13717 13717 I MultiDex: VM has multidex support, MultiDex support library is disabled.
</code>```

Any idea about what triggered this?

答:
It seems that the ChimeraModule (or Dynamite) is the dynamic module loading system used by the Google Play Services (more details here).

I guess that, if your app is using a specific module from the Google Play Services, when that specific module is updated your app is restarted as well.

Body:
I was testing my app and I saw it restart itself, was really weird. I looked and looked on the logs and I couldn't find anything odd except for this line ChimeraModuleLdr: Module config changed, forcing restart due to module. This is on a Pixel XL with Oreo.

Here are the last few lines of the log and the start up of the app after it was killed.

10-18 22:49:31.262  8379  8379 I ChimeraModuleLdr: Module config changed, forcing restart due to module
10-18 22:49:31.262  8379  8379 I Process : Sending signal. PID: 8379 SIG: 9
--------- beginning of main
10-18 22:49:31.641 13717 13717 I MultiDex: VM with version 2.1.0 has multidex support
10-18 22:49:31.641 13717 13717 I MultiDex: install
10-18 22:49:31.641 13717 13717 I MultiDex: VM has multidex support, MultiDex support library is disabled.

Any idea about what triggered this?


问:
Why do I get wrong, doubled input value on keyup when typing fast?
```<code>$("#input").keyup(function(){
 console.log($(this).val());
})
</code>```

When one is typing slowly "a" & "b" the above code will result in "a", "b" in the console log. But the problem is when somebody does it quickly. The result then is "ab", "ab". It's easier to repeat this situation with letters which are near on a keyboard e.g. "e" & "r". How to avoid it?

Events keydown and keypress does not suffer from this problem of quick-typist, but they are also fire to early. Result: returned value of an input does not contain the last typed letter when they occur. Or maybe there is a way to get this last letter somehow?

答:
I had a similar problem and found a workaround. Basically, I created an array with the timeStamp of the event (e.timeStamp) for every time the keyup fired. Then I compared the last two values in the array (the two most recent) and stopped the event if the difference in time wasn't at least 100ms.

This is my code inside the function called by the keyup listener:

```<code>timeArray.push(e.timeStamp); // add new timeStamp to array
if (timeArray.length >= 2) {
        var diff = (timeArray[timeArray.length - 1] - timeArray[timeArray.length - 2]);
        if (diff > 100) {   // 1 second
                // perform desired action
        } else { return false; }
} else {
            // still perform desired action if array only has one timestamp
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
$("#input").keyup(function(){
 console.log($(this).val());
})

When one is typing slowly "a" & "b" the above code will result in "a", "b" in the console log. But the problem is when somebody does it quickly. The result then is "ab", "ab". It's easier to repeat this situation with letters which are near on a keyboard e.g. "e" & "r". How to avoid it?

Events keydown and keypress does not suffer from this problem of quick-typist, but they are also fire to early. Result: returned value of an input does not contain the last typed letter when they occur. Or maybe there is a way to get this last letter somehow?

Body:
I had a similar problem and found a workaround. Basically, I created an array with the timeStamp of the event (e.timeStamp) for every time the keyup fired. Then I compared the last two values in the array (the two most recent) and stopped the event if the difference in time wasn't at least 100ms.

This is my code inside the function called by the keyup listener:

timeArray.push(e.timeStamp); // add new timeStamp to array
if (timeArray.length >= 2) {
        var diff = (timeArray[timeArray.length - 1] - timeArray[timeArray.length - 2]);
        if (diff > 100) {   // 1 second
                // perform desired action
        } else { return false; }
} else {
            // still perform desired action if array only has one timestamp
        }


问:
Redirecting to specified controller and action in asp.net mvc action filter
I have written an action filter which detects a new session and attempts to redirect the user to a page informing them that this has happened.  The only problem is I can not figure out how to make it redirect to a controller/action combo in an action filter.  I can instead only figure out how to redirect to a specified url.  Is there a direct way to redirect to a controller/action combo in an action filter in mvc2?</p>

答:
Rather than getting a reference to HttpContent and redirecting directly in the ActionFilter you can set the Result of the filter context to be a RedirectToRouteResult. It's a bit cleaner and better for testing.

Like this:

```<code>public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(something)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary {{ "Controller", "YourController" },
                                      { "Action", "YourAction" } });
    }

    base.OnActionExecuting(filterContext);
}
</code>```

Body:
Rather than getting a reference to HttpContent and redirecting directly in the ActionFilter you can set the Result of the filter context to be a RedirectToRouteResult. It's a bit cleaner and better for testing.

Like this:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(something)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary {{ "Controller", "YourController" },
                                      { "Action", "YourAction" } });
    }

    base.OnActionExecuting(filterContext);
}


问:
Set some class object to Local Storage
I'm using Angular CLI. Actually, I have registration component:
ts

```<code>...
export class User {
  first_name: string;
  second_name: string;
  email: string;
  password: string;
}
...
export class RegistrationComponent implements OnInit {
  saveValue(storageValue) {
  localStorage.setItem(`user`, new User(storageValue.first_name, storageValue.second_name));
</code>```

html

```<code><input type="text" name="first_name" [(ngModel)]="first_name">
<input type="text" name="second_name" [(ngModel)]="second_name">
</code>```

So I'm trying to set User object to Local storage but there is an error:  Supplied parameters do not match any signature of call target.
I have tryed yet:

```<code>...
saveValue(storageValue) {
      localStorage.setItem(`user`, new User(String(storageValue.first_name), String(storageValue.second_name));
...
</code>```

and

```<code>...
saveValue(storageValue) {
      localStorage.setItem(`user`, JSON.stringify(new User(storageValue.first_name, storageValue.second_name));
..
</code>```

however, it doesn't work. Could anyone help me please?

答:
You can only set a string to local storage, so you need to figure out a way to serialize/deserialize your User object.

Serialize

```<code>localStorage.setItem('user', JSON.stringify({
  first_name: storageValue.first_name,
  second_name: storageValue.second_name
}));
</code>```

Deserialize

```<code>const raw = JSON.parse(localStorage.getItem('user'));
const user = new User(raw.first_name, raw.second_name);
</code>```

Title: Set some class object to Local Storage

Body:
I'm using Angular CLI. Actually, I have registration component:
ts

...
export class User {
  first_name: string;
  second_name: string;
  email: string;
  password: string;
}
...
export class RegistrationComponent implements OnInit {
  saveValue(storageValue) {
  localStorage.setItem(`user`, new User(storageValue.first_name, storageValue.second_name));

html

<input type="text" name="first_name" [(ngModel)]="first_name">
<input type="text" name="second_name" [(ngModel)]="second_name">

So I'm trying to set User object to Local storage but there is an error:  Supplied parameters do not match any signature of call target.
I have tryed yet:

...
saveValue(storageValue) {
      localStorage.setItem(`user`, new User(String(storageValue.first_name), String(storageValue.second_name));
...

and

...
saveValue(storageValue) {
      localStorage.setItem(`user`, JSON.stringify(new User(storageValue.first_name, storageValue.second_name));
..

however, it doesn't work. Could anyone help me please?

Body:
You can only set a string to local storage, so you need to figure out a way to serialize/deserialize your User object.

Serialize

localStorage.setItem('user', JSON.stringify({
  first_name: storageValue.first_name,
  second_name: storageValue.second_name
}));

Deserialize

const raw = JSON.parse(localStorage.getItem('user'));
const user = new User(raw.first_name, raw.second_name);


问:
ScrollView constraint doesn't scrolls if soft keyboard is visible
I'm using a Constaint layout for a login screen which contains a some EditTextView.I have tried many types of fixes but cant seem to get one working. I would like to be able to scroll through my page when an editText is selected and the keyboard takes up half the screen.i added "thisandroid:windowSoftInputMode="adjustResize" to my mainfest file but i still have the same problem.
this my code</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:weightSum="1"
    android:background="@drawable/background"
    android:fillViewport="true"
    tools:context="com.activities.NewAccount" >

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="0dp"
            android:layout_height="200dp"
            android:scaleType="centerCrop"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/coversignup"
            android:layout_marginTop="5dp" />

        <com.etc.abdlhadi_etc.pro_latrattoria_android.utilites.MyTextView
            android:id="@+id/textView6"
            android:layout_width="237dp"
            android:layout_height="55dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:gravity="center"
            android:textColor="@color/dore"
            android:textSize="36dp"
            android:text="Créer votre compte"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="31dp"
            app:layout_constraintTop_toBottomOf="@+id/imageView2" />

        <EditText
            android:id="@+id/name"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:inputType="textPersonName"
            android:hint="Nom"
            android:background="@drawable/border"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="24dp"
            app:layout_constraintTop_toBottomOf="@+id/password" />

        <EditText
            android:id="@+id/email"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:inputType="textPersonName"
            android:hint="E-mail"
            android:background="@drawable/border"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="27dp"
            app:layout_constraintTop_toBottomOf="@+id/textView6" />
        <EditText
            android:id="@+id/password"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:background="@drawable/border"
            android:inputType="textPersonName"
            android:hint="Mot de passe"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="23dp"
            app:layout_constraintTop_toBottomOf="@+id/email" />
        <EditText
            android:id="@+id/tel"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:background="@drawable/border"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:inputType="textPersonName"
            android:hint="Tél"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="26dp"
            app:layout_constraintTop_toBottomOf="@+id/name" />
        <Button
            android:id="@+id/signup"
            android:layout_width="353dp"
            android:layout_height="48dp"
            android:text="Créer votre compte"
            android:textColor="@color/white"
            android:background="@color/dore"
            android:layout_marginRight="24dp"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginLeft="24dp"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="46dp"
            app:layout_constraintTop_toBottomOf="@+id/tel" />

    </android.support.constraint.ConstraintLayout>
</ScrollView>
</code>```

答: It looks like there is a bug in ConstraintLayout implementation. I've reported it in Google Issue Tracker.</p>

Body:
I'm using a Constaint layout for a login screen which contains a some EditTextView.I have tried many types of fixes but cant seem to get one working. I would like to be able to scroll through my page when an editText is selected and the keyboard takes up half the screen.i added "thisandroid:windowSoftInputMode="adjustResize" to my mainfest file but i still have the same problem.
this my code

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:weightSum="1"
    android:background="@drawable/background"
    android:fillViewport="true"
    tools:context="com.activities.NewAccount" >

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="0dp"
            android:layout_height="200dp"
            android:scaleType="centerCrop"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/coversignup"
            android:layout_marginTop="5dp" />

        <com.etc.abdlhadi_etc.pro_latrattoria_android.utilites.MyTextView
            android:id="@+id/textView6"
            android:layout_width="237dp"
            android:layout_height="55dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:gravity="center"
            android:textColor="@color/dore"
            android:textSize="36dp"
            android:text="Créer votre compte"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="31dp"
            app:layout_constraintTop_toBottomOf="@+id/imageView2" />

        <EditText
            android:id="@+id/name"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:inputType="textPersonName"
            android:hint="Nom"
            android:background="@drawable/border"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="24dp"
            app:layout_constraintTop_toBottomOf="@+id/password" />

        <EditText
            android:id="@+id/email"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:inputType="textPersonName"
            android:hint="E-mail"
            android:background="@drawable/border"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="27dp"
            app:layout_constraintTop_toBottomOf="@+id/textView6" />
        <EditText
            android:id="@+id/password"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:background="@drawable/border"
            android:inputType="textPersonName"
            android:hint="Mot de passe"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="23dp"
            app:layout_constraintTop_toBottomOf="@+id/email" />
        <EditText
            android:id="@+id/tel"
            android:layout_width="357dp"
            android:layout_height="47dp"
            android:background="@drawable/border"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:ems="10"
            android:textColor="@color/white"
            android:inputType="textPersonName"
            android:hint="Tél"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="26dp"
            app:layout_constraintTop_toBottomOf="@+id/name" />
        <Button
            android:id="@+id/signup"
            android:layout_width="353dp"
            android:layout_height="48dp"
            android:text="Créer votre compte"
            android:textColor="@color/white"
            android:background="@color/dore"
            android:layout_marginRight="24dp"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginLeft="24dp"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="46dp"
            app:layout_constraintTop_toBottomOf="@+id/tel" />

    </android.support.constraint.ConstraintLayout>
</ScrollView>


问:
How to build a 'release' APK in Android Studio?
I am trying to build an APK that I can upload to the Play Store.

When I select Build|Generate Signed APK... in Android Studio (version 0.3.1), I am directed to a link on how to properly set up the signing process in the "gradle build scripts":

http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Signing-Configurations

Unfortunately, after checking that page I'm at a loss as to what file to edit and what to put in it - I'm coming from a Visual Studio background, so lazily expect stuff to 'just work' :).

(After OK'ing Android Studio's warning message, A.S. brings up a Generate Signed APK Wizard, which I went through, passing my key's details. The resulting APK was rejected by the Play Store for having a key with a too-soon expiry-date).

I also tried bringing up the Android Studio Terminal window and running 'gradle', as instructed in the above message, but this command was not found. So as an aside, since perhaps running the command might do something useful, how would I run gradle?

I found a 'Gradle' window in the A.S. IDE, and tried building the assembleRelease target found in that window. However, the Run window output just shows "Executing external task 'assembleRelease'...".

答:
Click \Build\Select Build Variant... in Android Studio.
And choose release.


问:
multiple ways to update javascript object using map
functional programming has introduced immutable, so es6's map is quite a popular approach when working with data, specifically in arrays and object.

I have a reducer of redux below

```<code>const todos = (state = [], action) => {
    switch(action.type) {
        case 'TOGGLE_TODO': {
            return state.map(todo =>
                todo.id !== action.id ? todo
                : {
                ...todo, checked: !todo.checked
                }
            )
        }
        default:
           return state
    }

}
</code>```

What's the alternative to change the checked property besides above approach? Is the code even readable at all?

someone prefer this

```<code>switch (action.type) {
        case "TOGGLE_TODO":
            return [
                ...state.slice(0, action.id),
                {...state[action.id], isCompleted: !state[action.id].isCompleted},
                ...state.slice(action.id + 1)
            ]
        default:
            return state;
    }
</code>```

答:
Here's what I would do;

```<code>const todos = (state = [], action) => {
  switch(action.type) {
    case 'TOGGLE_TODO': {
      let newState = state.concat([]);
      newState.any((item) =>
        item.id == action.id &&
          (item = { ...item, checked: !item.checked })
      );

      return newState;
    }
    default:
       return state;
  }
}
</code>```

If you can change the data structure of your todo list to a map, then I think the following looks more readable.

```<code>const todos = (state = {}, action) => {
  switch(action.type) {
    case 'TOGGLE_TODO': {
      let itemToChange = state[action.id];
      return {
        ...state,
        [action.id]: {
          ...itemToChange,
          checked: !itemToChange.checked
        }
      };
    }
    default:
       return state
  }
}
</code>```

Body:
functional programming has introduced immutable, so es6's map is quite a popular approach when working with data, specifically in arrays and object.

I have a reducer of redux below

const todos = (state = [], action) => {
    switch(action.type) {
        case 'TOGGLE_TODO': {
            return state.map(todo =>
                todo.id !== action.id ? todo
                : {
                ...todo, checked: !todo.checked
                }
            )
        }
        default:
           return state
    }

}

What's the alternative to change the checked property besides above approach? Is the code even readable at all?

someone prefer this

switch (action.type) {
        case "TOGGLE_TODO":
            return [
                ...state.slice(0, action.id),
                {...state[action.id], isCompleted: !state[action.id].isCompleted},
                ...state.slice(action.id + 1)
            ]
        default:
            return state;
    }

Body:
Here's what I would do;

const todos = (state = [], action) => {
  switch(action.type) {
    case 'TOGGLE_TODO': {
      let newState = state.concat([]);
      newState.any((item) =>
        item.id == action.id &&
          (item = { ...item, checked: !item.checked })
      );

      return newState;
    }
    default:
       return state;
  }
}

If you can change the data structure of your todo list to a map, then I think the following looks more readable.

const todos = (state = {}, action) => {
  switch(action.type) {
    case 'TOGGLE_TODO': {
      let itemToChange = state[action.id];
      return {
        ...state,
        [action.id]: {
          ...itemToChange,
          checked: !itemToChange.checked
        }
      };
    }
    default:
       return state
  }
}


问:
Is there a way to reset IIS 7.5 to factory settings?
I modified a lot of options in IIS, and would like to reset its settings to default.

I already tried installing/reinstalling it. After the reinstall, it still had the site I created. It was still breaking on the setting I made to the DefaultWebSite.

People suggested uninstalling Windows Process Activation Service first, but it seems like it wasn't installed anyway, so I can't really uninstall it.

How can I reset this installation of IIS back to an out-of-the-box state?

答:
Resetting IIS

On the computer that is running Microsoft Dynamics NAV Web Server components, open a command prompt as an administrator as follows:

a. From the Start menu, choose All Programs, and then choose Accessories.
b. Right-click Command Prompt, and then choose Run as administrator.

At the command prompt, type the following command to change to the Microsoft.NET\Framework64\v4.0.30319 folder, and then press Enter.

cd\Windows\Microsoft.NET\Framework64\v4.0.30319

At the command prompt, type the following command, and then press Enter.

aspnet_regiis.exe -iru

At the command prompt, type the following command, and then press Enter.
iisreset


问:
what is the SQL query to get all dates list from specific date to today date
I need to get all dates from 01-01-2016 to todays date.

Example:

```<code>01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017
</code>```

Any help would be appreciated.

答:
```<code> SELECT *FROM Table_Name
 WHERE CONVERT(NVARCHAR,date_column,111) >=CONVERT(NVARCHAR,@From_Date,111) and  CONVERT(NVARCHAR,date_column,111) <=CONVERT( NVarchar, @TO_Date, 111)
</code>```

Body:
I need to get all dates from 01-01-2016 to todays date.

Example:

01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017

Any help would be appreciated.