问:
C++ Classes: Christian Holiday Calculator
Basically, I'm trying to complete this exam-style question for exam practice. I know how to do everything but the last question, to do with classes. I kinda get them, but don't know how to apply it to the question. Could anybody give me some starting points or tips (or even possible answers) to how I would go about creating a C++ class? Any help is much appreciated. The question is below. Apologies about how long it is.

In 1800 the mathematician Carl Friedrich Gauss presented an algorithm for calculating the
date of the Easter holiday in the new Gregorian calendar (introduced in the British Empire in
the year 1752). For this a number of expressions need to be evaluated:
Two terms M and N, which for a given year y hold the values:

```<code>year      M N
1700-1799 23 3
1800-1899 23 4
1900-2099 24 5
2100-2199 24 6
The expressions are:
a = y mod 19
b = y mod 4
c = y mod 7
d = (19a + M) mod 30
e = (2b + 4c + 6d + N) mod 7
</code>```

If 22+d+e is smaller than 32 than this sum is the day of the Easter holiday in March.
Otherwise d+e-9 is the day of Easter in April unless:
- the result is the 26th April, in which case Easter is on the 19th April instead
- the result is the 25th April, in which case Easter is on the 18th of April if d is 28 and
a is greater than 10

a) Implement a C/C++ function that given a year as parameter will
print out the date for the Easter holiday. (10 marks)
Other Christian holidays can be calculated from the date of Easter:
Good Friday is the Friday before Easter Sunday.
Palm Sunday is the Sunday before Easter Sunday.
Whit Sunday is 7 weeks after Easter Sunday.
Ascension day is 10 days before Whit Sunday.
Note: April and June are 30 days long, whereas March and May are 31 days long.

b) Design/describe algorithms for identifying the date for the Christian
holidays "Good Friday", "Palm Sunday", "Ascension" and "Whit
Sunday". (no source code is required for this answer) (15 Marks)

The terms M and N in the Easter calculation algorithm described by Gauss can also
be calculated using the following expressions:

```<code>k = floor(y/100)
p = floor((13 + 8k)/25)
q = floor(k/4)
M = (15 − p + k − q) mod 30
N = (4 + k − q) mod 7
</code>```

The floor function rounds down a value – in the maths library math.h this is
available as a C function with the prototype double floor(double);

c) Produce a C++ class to implement a Christian Holiday calculator. It
should have private attributes (member variables) representing the
day, month and year of the date and a private method for
calculating the terms M and N. The default constructor should set
all attributes to 0. It should be possible to change the year using a
set() method and to retrieve day and month using get() methods.
The class should also contain compute methods for the different
holidays – example: computeEaster().

答:
...how I would go about creating a C++ class?

Creating a class is simple:

```<code>class foobar
{
public:
private:
};
</code>```

There! you now have a class foobar. That class can be whatever you want it to be. Fill in the public and private sections as appropriate.

Could anybody give me some starting points or tips...

As for how to use classes on how to solve a given problem, here are the general steps in roughly sequential order:

Identify the requirements of the problem. What needs solving?

Reform those requirements as a list of responsibilities. What does your program have to do to fulfill those requirements?

Group those responsibilities together to form a cohesive class object. How does this class object contribute to the overall solution of the problem? How will this object actually be used?

Express and capture that usage in a unit test for each of those objects. While doing this, you can pretend that that class is already implemented and whatever member functions you need from it is available.

Finally, implement that class so the unit test passes.

One last note, as David's comment already pointed out, copying and pasting the original problem verbatim into your question is a bad idea. People will be (substantially) less inclined to read it through. You can increase the likelihood for a response if you clarified exactly what trouble you're having and cutting out all the irrelevant parts.

Body:
Basically, I'm trying to complete this exam-style question for exam practice. I know how to do everything but the last question, to do with classes. I kinda get them, but don't know how to apply it to the question. Could anybody give me some starting points or tips (or even possible answers) to how I would go about creating a C++ class? Any help is much appreciated. The question is below. Apologies about how long it is.

In 1800 the mathematician Carl Friedrich Gauss presented an algorithm for calculating the
date of the Easter holiday in the new Gregorian calendar (introduced in the British Empire in
the year 1752). For this a number of expressions need to be evaluated:
Two terms M and N, which for a given year y hold the values:

year      M N
1700-1799 23 3
1800-1899 23 4
1900-2099 24 5
2100-2199 24 6
The expressions are:
a = y mod 19
b = y mod 4
c = y mod 7
d = (19a + M) mod 30
e = (2b + 4c + 6d + N) mod 7

If 22+d+e is smaller than 32 than this sum is the day of the Easter holiday in March.
Otherwise d+e-9 is the day of Easter in April unless:
- the result is the 26th April, in which case Easter is on the 19th April instead
- the result is the 25th April, in which case Easter is on the 18th of April if d is 28 and
a is greater than 10

a) Implement a C/C++ function that given a year as parameter will
print out the date for the Easter holiday. (10 marks)
Other Christian holidays can be calculated from the date of Easter:
Good Friday is the Friday before Easter Sunday.
Palm Sunday is the Sunday before Easter Sunday.
Whit Sunday is 7 weeks after Easter Sunday.
Ascension day is 10 days before Whit Sunday.
Note: April and June are 30 days long, whereas March and May are 31 days long.

b) Design/describe algorithms for identifying the date for the Christian
holidays "Good Friday", "Palm Sunday", "Ascension" and "Whit
Sunday". (no source code is required for this answer) (15 Marks)

The terms M and N in the Easter calculation algorithm described by Gauss can also
be calculated using the following expressions:

k = floor(y/100)
p = floor((13 + 8k)/25)
q = floor(k/4)
M = (15 − p + k − q) mod 30
N = (4 + k − q) mod 7

The floor function rounds down a value – in the maths library math.h this is
available as a C function with the prototype double floor(double);

c) Produce a C++ class to implement a Christian Holiday calculator. It
should have private attributes (member variables) representing the
day, month and year of the date and a private method for
calculating the terms M and N. The default constructor should set
all attributes to 0. It should be possible to change the year using a
set() method and to retrieve day and month using get() methods.
The class should also contain compute methods for the different
holidays – example: computeEaster().

Body:
...how I would go about creating a C++ class?

Creating a class is simple:

class foobar
{
public:
private:
};

There! you now have a class foobar. That class can be whatever you want it to be. Fill in the public and private sections as appropriate.

Could anybody give me some starting points or tips...

As for how to use classes on how to solve a given problem, here are the general steps in roughly sequential order:

Identify the requirements of the problem. What needs solving?

Reform those requirements as a list of responsibilities. What does your program have to do to fulfill those requirements?

Group those responsibilities together to form a cohesive class object. How does this class object contribute to the overall solution of the problem? How will this object actually be used?

Express and capture that usage in a unit test for each of those objects. While doing this, you can pretend that that class is already implemented and whatever member functions you need from it is available.

Finally, implement that class so the unit test passes.

One last note, as David's comment already pointed out, copying and pasting the original problem verbatim into your question is a bad idea. People will be (substantially) less inclined to read it through. You can increase the likelihood for a response if you clarified exactly what trouble you're having and cutting out all the irrelevant parts.


来源: stackexchange

问:
GraphQL Mutation is not letting me add data to mysql table with non null violation error
I am using GraphQL, Sequelize, and MySql to add data to Clients Table. In the GraphQl Mutation, I do the following:

```<code>const db = require("./models");

const Mutation = new GraphQLObjectType({
    name: "Mutation",
    fields: {
        addClient: {
            type: ClientType,
            args: {
                lastName: { type: new GraphQLNonNull(GraphQLString) },
                firstName: { type: new GraphQLNonNull(GraphQLString) },
                primaryPhoneNumber: { type: new GraphQLNonNull(GraphQLString) },
                cellphone: { type: GraphQLString },
                workPhone: { type: GraphQLString },
                email: { type: GraphQLString },
                UserId: { type: new GraphQLNonNull(GraphQLString) }
            },
            resolve(parentValue, args) {
                let newClient = new db.Client({
                    lastName: args.lastName,
                    firstName: args.firstName,
                    primaryPhoneNumber: args.primaryPhoneNumber,
                    cellphone: args.cellphone,
                    workPhone: args.workPhone,
                    email: args.email,
                    UserId: args.UserId
                });
                console.log(newClient);
                return db.Client.create(newClient);
            }
        }
    }
});
</code>```

But I receive this error back when testing it on GraphiQL:

```<code>{
  "errors": [
    {
      "message": "notNull Violation: Client.lastName cannot be null,\nnotNull Violation:
 Client.firstName cannot be null",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "addClient"
      ]
    }
  ],
  "data": {
    "addClient": null
  }
}
</code>```

I believe this error comes from sequelize as in my Model I define some Non-Null fields:

```<code>module.exports = function(sequelize, DataTypes) {
    var Client = sequelize.define(
        "Client",
        {
            lastName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            firstName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            primaryPhoneNumber: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            cellphone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            workPhone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            email: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            }
        },

        {
            timestamps: false
        }
    );

    Client.associate = function(models) {
        // Associating Clients with Pets
        // When a Client is deleted, also delete any associated Pets
        Client.belongsTo(models.User);
        Client.hasMany(models.Pet, {
            onDelete: "cascade"
        });
    };

    return Client;
};
</code>```

This is my query from the front end:

```<code>mutation {
  addClient(lastName: "ali", firstName: "muhamed",  primaryPhoneNumber:
"00990099009", email: "jalimaña@email.com", UserId: "14fb9610-4766-11ea-9a4e-
e130bc08c2aa") {
    lastName,
    firstName
  }
}
</code>```

Does anybody know why is this happening? Any help will be highly appreciated.

答:
Model.create takes a plain object with the values the Model instance should be initialized with. You shouldn't pass an existing instance of Model to it. Instead, just call the save method on the instance.

```<code>const instance = new SomeModel({ firstName: 'Bob' })
await instance.save()
</code>```

This is equivalent to

```<code>const instance = SomeModel.build({ firstName: 'Bob' })
await instance.save()
</code>```

and

```<code>await SomeModel.create({ firstName: 'Bob' })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using GraphQL, Sequelize, and MySql to add data to Clients Table. In the GraphQl Mutation, I do the following:

const db = require("./models");

const Mutation = new GraphQLObjectType({
    name: "Mutation",
    fields: {
        addClient: {
            type: ClientType,
            args: {
                lastName: { type: new GraphQLNonNull(GraphQLString) },
                firstName: { type: new GraphQLNonNull(GraphQLString) },
                primaryPhoneNumber: { type: new GraphQLNonNull(GraphQLString) },
                cellphone: { type: GraphQLString },
                workPhone: { type: GraphQLString },
                email: { type: GraphQLString },
                UserId: { type: new GraphQLNonNull(GraphQLString) }
            },
            resolve(parentValue, args) {
                let newClient = new db.Client({
                    lastName: args.lastName,
                    firstName: args.firstName,
                    primaryPhoneNumber: args.primaryPhoneNumber,
                    cellphone: args.cellphone,
                    workPhone: args.workPhone,
                    email: args.email,
                    UserId: args.UserId
                });
                console.log(newClient);
                return db.Client.create(newClient);
            }
        }
    }
});

But I receive this error back when testing it on GraphiQL:

{
  "errors": [
    {
      "message": "notNull Violation: Client.lastName cannot be null,\nnotNull Violation:
 Client.firstName cannot be null",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "addClient"
      ]
    }
  ],
  "data": {
    "addClient": null
  }
}

I believe this error comes from sequelize as in my Model I define some Non-Null fields:

module.exports = function(sequelize, DataTypes) {
    var Client = sequelize.define(
        "Client",
        {
            lastName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            firstName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            primaryPhoneNumber: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            cellphone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            workPhone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            email: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            }
        },

        {
            timestamps: false
        }
    );

    Client.associate = function(models) {
        // Associating Clients with Pets
        // When a Client is deleted, also delete any associated Pets
        Client.belongsTo(models.User);
        Client.hasMany(models.Pet, {
            onDelete: "cascade"
        });
    };

    return Client;
};

This is my query from the front end:

mutation {
  addClient(lastName: "ali", firstName: "muhamed",  primaryPhoneNumber:
"00990099009", email: "jalimaña@email.com", UserId: "14fb9610-4766-11ea-9a4e-
e130bc08c2aa") {
    lastName,
    firstName
  }
}

Does anybody know why is this happening? Any help will be highly appreciated.

Body:
Model.create takes a plain object with the values the Model instance should be initialized with. You shouldn't pass an existing instance of Model to it. Instead, just call the save method on the instance.

const instance = new SomeModel({ firstName: 'Bob' })
await instance.save()

This is equivalent to

const instance = SomeModel.build({ firstName: 'Bob' })
await instance.save()

and

await SomeModel.create({ firstName: 'Bob' })


问:
Can someone explain what is happening with this piece of micro python
Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

```<code>class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )
</code>```

which produces

```<code>python3 test.py
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
</code>```

Thanks

答: Your function invert isn't returning anything so when you try to multiply it you have None*float resulting in your described answer.

Body:
Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )

which produces

python3 test.py
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

Thanks


问:
Return resolved promise value
```<code>  const displayCharacters =  async () => {
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };

      const b = await fetch("/image",options).then(res => res.json())
      return b;

    }else{
      return "yikes";
    }
  }

  console.log(displayCharacters());
</code>```

I have this fetch request but when I log the results this is what i see :

```<code>Promise {<resolved>: "yikes"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "yikes"
</code>```

I just want the promiseValue and not this whole thing around it. How do i do this?

答:
the async function returns a promise instantly, without waiting for the promise to resolve. You may instead console.log inside the function:

```<code>  const displayCharacters =  async () => {
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };
      try {
        const b = await fetch("/image",options).then(res => res.json());
        console.log(b);

        //the better practice is however, to do like:
        const b = await fetch("/image",options)
        const result = await b.json();
        console.log(result );
      }
      catch(err) {
         console.log(err);
      }

    }else{
      console.log("yikes");
    }
  }

displayCharacters();
</code>```

Title: Return resolved promise value

Body:
  const displayCharacters =  async () => {
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };

      const b = await fetch("/image",options).then(res => res.json())
      return b;

    }else{
      return "yikes";
    }
  }

  console.log(displayCharacters());

I have this fetch request but when I log the results this is what i see :

Promise {<resolved>: "yikes"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "yikes"

I just want the promiseValue and not this whole thing around it. How do i do this?

Body:
the async function returns a promise instantly, without waiting for the promise to resolve. You may instead console.log inside the function:

  const displayCharacters =  async () => {
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };
      try {
        const b = await fetch("/image",options).then(res => res.json());
        console.log(b);

        //the better practice is however, to do like:
        const b = await fetch("/image",options)
        const result = await b.json();
        console.log(result );
      }
      catch(err) {
         console.log(err);
      }

    }else{
      console.log("yikes");
    }
  }

displayCharacters();


问:
Add client-side Blazor to existing Asp.Net Core 3.1 App
I'm trying to render a client-side Blazor App in a view of a controller of an existing Asp.Net Core 3.1 App.

I started following this guide and I created an empty app from the template.
I found out that what I need is:

These nuget packages:

<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />
```</li>
<li>This code in <code>Program.Main</code>:

<pre class="lang-cs prettyprint-override"><code>var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();
</code>```

This HTML code in the View for the Blazor App 'entry point':

<app>Loading...</app>

    An unhandled error has occurred.
    Reload

```</li>
<li>The <code>.razor</code> components:

<ul>
<li>App.razor</li>
<li>_Imports.razor</li>
<li>Shared/MainLayout.razor</li>
<li>Shared/NavMenu.razor</li>
</ul></li>
</ol>

<p>This should be it, but I get the error (can add full stack trace if you need):</p>

```---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Razor, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
```

<p>Where can I find that nuget package version? Do I need an assembly binding?
I tried without success with:</p>

```<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.0" />
```

<p><strong>EDIT</strong></p>

<p>Adding the following packages solved that issue:</p>

<pre class="lang-xml prettyprint-override"><code><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.RazorPages" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
</code>```

But now I have a different error:

```<code>C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk.Razor\build\netstandard2.0\Microsoft.NET.Sdk.Razor.Component.targets(106,5): error : rzc generate exited with code 1.
</code>```

And Visual Studio (16.4.4) crashes as soon as I open any .razor file

答:
Add the following packages in your project :

<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="3.2.0-preview1.20073.1" />
```
<p>In your <code>Startup.Configure</code> method add:</p>
<pre class="lang-cs prettyprint-override"><code>app.UseClientSideBlazorFiles<BlazorApp.Program>()
   .UseEndpoints(endpoints =>
   {
       endpoints.MapFallbackToClientSideBlazor<BlazorApp.Program>("blazor");
   });
</code>```

Where "blazor" is the relative uri to your razor view hosting the blazor app.

and BlazorApp.Program the type of your blazor app Program

If you want it in 2 separates projects then the Blazor app project must have those packages :

<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />
```
<p>and the server project this one :</p>
<pre class="lang-xml prettyprint-override"><code><PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="3.2.0-preview1.20073.1" />
</code>```

Body:
I'm trying to render a client-side Blazor App in a view of a controller of an existing Asp.Net Core 3.1 App.

I started following this guide and I created an empty app from the template.
I found out that what I need is:

These nuget packages:

<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />

This code in Program.Main:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();

This HTML code in the View for the Blazor App 'entry point':

<app>Loading...</app>

    An unhandled error has occurred.
    Reload

The .razor components:

App.razor

_Imports.razor

Shared/MainLayout.razor

Shared/NavMenu.razor

This should be it, but I get the error (can add full stack trace if you need):

---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Razor, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

Where can I find that nuget package version? Do I need an assembly binding?
I tried without success with:

<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.0" />

EDIT

Adding the following packages solved that issue:

<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.RazorPages" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />

But now I have a different error:

C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk.Razor\build\netstandard2.0\Microsoft.NET.Sdk.Razor.Component.targets(106,5): error : rzc generate exited with code 1.

And Visual Studio (16.4.4) crashes as soon as I open any .razor file

Body:
Add the following packages in your project :

<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="3.2.0-preview1.20073.1" />

In your Startup.Configure method add:

app.UseClientSideBlazorFiles<BlazorApp.Program>()
   .UseEndpoints(endpoints =>
   {
       endpoints.MapFallbackToClientSideBlazor<BlazorApp.Program>("blazor");
   });

Where "blazor" is the relative uri to your razor view hosting the blazor app.

and BlazorApp.Program the type of your blazor app Program

If you want it in 2 separates projects then the Blazor app project must have those packages :

<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.2.0-preview1.20073.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />

and the server project this one :

<PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="3.2.0-preview1.20073.1" />


问:
Recursive parse JSON with c#
I try to do a recursive parse but it doesn't work, it only parse the first title.

I already tried that: C# parse recursive json but it didn't work.

I also tried a parse with Regex but it didn't work either, it only captures the first title.

So I'm hoping you can help me solve the problem that's been blocking my progress :/

My Json

```<code>{
   "data":{
      "count":[

      ],
      "list":[
         {
            "title":"new doc 4",
            "rotate":0,
            "sort_key":"new doc 4",
            "tag_ids":"",
            "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
            "co_token":"",
            "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
            "t":"1474932063",
            "c":"2",
            "updated":"1474932063"
         },
         {
            "title":"new doc 5",
            "rotate":0,
            "sort_key":"new doc 5",
            "tag_ids":"",
            "doc_id":"Xy67QdRhTR9XS159WLyCCTbK",
            "co_token":"",
            "p":"XadS23UUQbQRQt9gLPWDWTAQ",
            "t":"1474932060",
            "c":"1",
            "updated":"1474932061"
         },
         {
            "title":"new doc 6",
            "rotate":0,
            "sort_key":"new doc 6",
            "tag_ids":"",
            "doc_id":"Q4W55XLA1AeERUJHaVN7EF80",
            "co_token":"",
            "p":"T6BYAMKXNa086Tb4FaYd4rV1",
            "t":"1474932059",
            "c":"1",
            "updated":"1474932059"
         },
         {
            "title":"new doc 7",
            "rotate":0,
            "sort_key":"new doc 7",
            "tag_ids":"",
            "doc_id":"9heQFfeYFUFXb536VTyHLhKL",
            "co_token":"",
            "p":"BeFULN12QL6H9L5HXCAYfH1S",
            "t":"1474932056",
            "c":"2",
            "updated":"1474932056"
         },
         {
            "title":"new doc 8",
            "rotate":0,
            "sort_key":"new doc 8",
            "tag_ids":"",
            "doc_id":"H7eXd1yTfFAY2V8ha3a6FS9K",
            "co_token":"",
            "p":"LJVyNVCPMbXH2abMMbb6BRYN",
            "t":"1474932053",
            "c":"1",
            "updated":"1474932053"
         },
         {
            "title":"new doc 9",
            "rotate":0,
            "sort_key":"new doc 9",
            "tag_ids":"",
            "doc_id":"3VVL56tQDXf73V8UKXrNX0d0",
            "co_token":"",
            "p":"rV2H7WWCRy1Vrb0PaU1TQKTD",
            "t":"1474932047",
            "c":"3",
            "updated":"1474932049"
         },
         {
            "title":"new doc 10",
            "rotate":0,
            "sort_key":"new doc 10",
            "tag_ids":"",
            "doc_id":"4TBabHAKNRXdREJXNdWfQEWF",
            "co_token":"",
            "p":"TR7Dt89gV3hfSJBTDQ1JQP72",
            "t":"1474402937",
            "c":"1",
            "updated":"1474402937"
         },
         {
            "title":"new doc 11",
            "rotate":0,
            "sort_key":"new doc 11",
            "tag_ids":"",
            "doc_id":"TV4fBdehY4fFHN00g082QDKX",
            "co_token":"",
            "p":"SCUPQ9bW6BgTT9JAP4K2WCYU",
            "t":"1474402932",
            "c":"3",
            "updated":"1474402932"
         },
         {
            "title":"new doc 12",
            "rotate":0,
            "sort_key":"new doc 12",
            "tag_ids":"",
            "doc_id":"M8fHK8gQB3FWUEeLKQMdUaFB",
            "co_token":"",
            "p":"BPDTg3aTTDELyFUA1WK0M2rA",
            "t":"1474402911",
            "c":"7",
            "updated":"1474402913"
         },
         {
            "title":"new doc",
            "rotate":0,
            "sort_key":"new doc",
            "tag_ids":"",
            "doc_id":"ayCK8RrHSe796g4PSNRgMD5N",
            "co_token":"",
            "p":"Y46RWJFb0XJRHtKy6B077Me1",
            "t":"1389379718",
            "c":"1",
            "updated":"1389379718"
         }
      ],
   }
}
</code>```

答:
Parse the string into an object that c# can use to iterate through.

then use the foreach loop to access the items of the list.

Add title to a stringbuilder

Save the collected titles to a file.

```<code>var obj = JObject.Parse(jsonString);
var list = obj["data"]["list"];

StringBuilder sb = new StringBuilder();
foreach(var item in list)
    sb.AppendLine(item["title"].ToString());

File.WriteAllText(@"c:\temp\titles.txt", sb.ToString());

</code>```

Title: Recursive parse JSON with c#

Body:
I try to do a recursive parse but it doesn't work, it only parse the first title.

I already tried that: C# parse recursive json but it didn't work.

I also tried a parse with Regex but it didn't work either, it only captures the first title.

So I'm hoping you can help me solve the problem that's been blocking my progress :/

My Json

{
   "data":{
      "count":[

      ],
      "list":[
         {
            "title":"new doc 4",
            "rotate":0,
            "sort_key":"new doc 4",
            "tag_ids":"",
            "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
            "co_token":"",
            "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
            "t":"1474932063",
            "c":"2",
            "updated":"1474932063"
         },
         {
            "title":"new doc 5",
            "rotate":0,
            "sort_key":"new doc 5",
            "tag_ids":"",
            "doc_id":"Xy67QdRhTR9XS159WLyCCTbK",
            "co_token":"",
            "p":"XadS23UUQbQRQt9gLPWDWTAQ",
            "t":"1474932060",
            "c":"1",
            "updated":"1474932061"
         },
         {
            "title":"new doc 6",
            "rotate":0,
            "sort_key":"new doc 6",
            "tag_ids":"",
            "doc_id":"Q4W55XLA1AeERUJHaVN7EF80",
            "co_token":"",
            "p":"T6BYAMKXNa086Tb4FaYd4rV1",
            "t":"1474932059",
            "c":"1",
            "updated":"1474932059"
         },
         {
            "title":"new doc 7",
            "rotate":0,
            "sort_key":"new doc 7",
            "tag_ids":"",
            "doc_id":"9heQFfeYFUFXb536VTyHLhKL",
            "co_token":"",
            "p":"BeFULN12QL6H9L5HXCAYfH1S",
            "t":"1474932056",
            "c":"2",
            "updated":"1474932056"
         },
         {
            "title":"new doc 8",
            "rotate":0,
            "sort_key":"new doc 8",
            "tag_ids":"",
            "doc_id":"H7eXd1yTfFAY2V8ha3a6FS9K",
            "co_token":"",
            "p":"LJVyNVCPMbXH2abMMbb6BRYN",
            "t":"1474932053",
            "c":"1",
            "updated":"1474932053"
         },
         {
            "title":"new doc 9",
            "rotate":0,
            "sort_key":"new doc 9",
            "tag_ids":"",
            "doc_id":"3VVL56tQDXf73V8UKXrNX0d0",
            "co_token":"",
            "p":"rV2H7WWCRy1Vrb0PaU1TQKTD",
            "t":"1474932047",
            "c":"3",
            "updated":"1474932049"
         },
         {
            "title":"new doc 10",
            "rotate":0,
            "sort_key":"new doc 10",
            "tag_ids":"",
            "doc_id":"4TBabHAKNRXdREJXNdWfQEWF",
            "co_token":"",
            "p":"TR7Dt89gV3hfSJBTDQ1JQP72",
            "t":"1474402937",
            "c":"1",
            "updated":"1474402937"
         },
         {
            "title":"new doc 11",
            "rotate":0,
            "sort_key":"new doc 11",
            "tag_ids":"",
            "doc_id":"TV4fBdehY4fFHN00g082QDKX",
            "co_token":"",
            "p":"SCUPQ9bW6BgTT9JAP4K2WCYU",
            "t":"1474402932",
            "c":"3",
            "updated":"1474402932"
         },
         {
            "title":"new doc 12",
            "rotate":0,
            "sort_key":"new doc 12",
            "tag_ids":"",
            "doc_id":"M8fHK8gQB3FWUEeLKQMdUaFB",
            "co_token":"",
            "p":"BPDTg3aTTDELyFUA1WK0M2rA",
            "t":"1474402911",
            "c":"7",
            "updated":"1474402913"
         },
         {
            "title":"new doc",
            "rotate":0,
            "sort_key":"new doc",
            "tag_ids":"",
            "doc_id":"ayCK8RrHSe796g4PSNRgMD5N",
            "co_token":"",
            "p":"Y46RWJFb0XJRHtKy6B077Me1",
            "t":"1389379718",
            "c":"1",
            "updated":"1389379718"
         }
      ],
   }
}

Body:
Parse the string into an object that c# can use to iterate through.

then use the foreach loop to access the items of the list.

Add title to a stringbuilder

Save the collected titles to a file.

var obj = JObject.Parse(jsonString);
var list = obj["data"]["list"];

StringBuilder sb = new StringBuilder();
foreach(var item in list)
    sb.AppendLine(item["title"].ToString());

File.WriteAllText(@"c:\temp\titles.txt", sb.ToString());


问:
How to save and download text file in Flutter web application
I am new to Flutter and working in a flutter web application, My requirement is to create and download a text file. like below.

void getData() {
    List<int> bytes = utf8.encode('this is the text file');
    print(bytes); // Need to download this with txt file.
}
```

Can anyone help me to achieve this

答:
Got another way to do it, via popular JS library called FileSaver

First, update your ProjectFolder/web/index.html file to include the library and define the webSaveAs function like so:

```<code>...

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js">
</script>

<script>
function webSaveAs(blob, name) {
  saveAs(blob, name);
}
</script>

<script src="main.dart.js" type="application/javascript"></script>

...
</code>```

Then you can call this function from Dart code like so:

```<code>import 'dart:js' as js;
import 'dart:html' as html;

...

js.context.callMethod("webSaveAs", [html.Blob([bytes]), "test.txt"])
</code>```

Body:
I am new to Flutter and working in a flutter web application, My requirement is to create and download a text file. like below.

void getData() {
    List<int> bytes = utf8.encode('this is the text file');
    print(bytes); // Need to download this with txt file.
}

Can anyone help me to achieve this

Body:
Got another way to do it, via popular JS library called FileSaver

First, update your ProjectFolder/web/index.html file to include the library and define the webSaveAs function like so:

...

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js">
</script>

<script>
function webSaveAs(blob, name) {
  saveAs(blob, name);
}
</script>

<script src="main.dart.js" type="application/javascript"></script>

...

Then you can call this function from Dart code like so:

import 'dart:js' as js;
import 'dart:html' as html;

...

js.context.callMethod("webSaveAs", [html.Blob([bytes]), "test.txt"])


问:
npm run fails because IntelliJ can't find npm even though it is installed
On my windows 10, in my build.sbt in Intellij IDE, I have a function def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build")). When I run it, I get error 'npm' is not recognized as an internal or external command, operable program or batch file.. npm is installed and I have added it in the PATH variable.

```<code>C:\Users\surface>where npm
C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd
</code>```

I have also added paths to npm and node in Intellij settings.

Why is the script not running?

答: It seems the issue was that I had to restart the IntelliJ IDE. Enterinng node and npm in IntelliJ seem to have worked

Body:
On my windows 10, in my build.sbt in Intellij IDE, I have a function def runDevBuild(implicit dir: File): Int = ifUiInstalled(runScript("npm run build")). When I run it, I get error 'npm' is not recognized as an internal or external command, operable program or batch file.. npm is installed and I have added it in the PATH variable.

C:\Users\surface>where npm
C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd

I have also added paths to npm and node in Intellij settings.

Why is the script not running?


问:
Android Camera Hardware Information
While we can get physical manufacturer information programmatically through android.os.* components, I haven't seen references to checking in on the camera details.

Specifically, I was curious if there was a way to detect what camera sensor was being used in a specific device so that adjustments could be made as necessary?  With some Samsung Galaxy S6 devices having different camera sensors found in them sporadically, I can't rely on just the device itself and it would be best if I did it based on the physical hardware for the camera.

reference: Camera Sensor Discrepencies

This is in reference of course to correcting and detecting the appearance of colors properly within an application.

答:
If you are looking for an Android App there are many in market now. Camera2 API probe is one of the best (I have no affiliations with this, but I use this in my work).

Alternatively you can very easily probe information using Camera2 APIs like:

CameraCharacteristics

CONTROL_AE_AVAILABLE_MODES - for AE modes

CONTROL_AF_AVAILABLE_MODES - for AF modes

And more available on Android documentation - just look for Camera2

ContentLicense: CC BY-SA 3.0

Title: Android Camera Hardware Information


问:
Unable to create a react app using "create-react-app"
I have installed "create-react-app" globally on my pc using "npm install create-react-app -g". And it worked just fine for months. I had previously created a lot of react app using the "create-react-app app-name" command. And it worked flawlessly. Until a few days ago when it sudden stopped working and started giving errors. I have tried various things suggested but with no luck. So after days of trying to solve the issue I am asking this question.

I have tried doing the following things:

```<code>1> using the "npm cache clean --force" and then "npm cache verify".
2> I also unabled my antivirus (norton) and then ran the commands.
3> I installed the latest node version
4> I intalled the latest npm version and updated it using the command "npm install npm@latest -g"
5> I followed the instructions on this stackoverflow link https://stackoverflow.com/questions/50189096/installing-create-react-app-gives-npm-err-shasum-check-failed-and-npm-err-unex/50191315#50191315 to change the registry.
And a few other things. But nothing has worked.
</code>```

The error that I get is as follows:

```<code>D:\codes\react\maximilianUdemy\project1>create-react-app react-mytest-app

Creating a new React app in D:\codes\react\maximilianUdemy\project1\react-mytest-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...HqQqP7Ky/f49Ar0oPZ\n4'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\vaibh\AppData\Roaming\npm-cache\_logs\2019-07-20T10_24_27_969Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting react-mytest-app/ from D:\codes\react\maximilianUdemy\project1
Done.
</code>```

Below is an excerpt from the C:\Users\vaibh\AppData\Roaming\npm-cache\_logs\2019-07-20T10_24_27_969Z-debug.log. Since the log is really big (664 lines), I have only noted from when the error started showing.

```<code>471 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...HqQqP7Ky/f49Ar0oPZ\n4'
471 verbose stack     at JSON.parse (<anonymous>)
471 verbose stack     at parseJson (D:\Program_Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)
471 verbose stack     at D:\Program_Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50
471 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:85:5)
472 verbose cwd D:\codes\react\maximilianUdemy\project1\react-mytest-app
473 verbose Windows_NT 10.0.17134
474 verbose argv "D:\\Program_Files\\nodejs\\node.exe" "D:\\Program_Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--save" "--save-exact" "--loglevel" "error" "react" "react-dom" "react-scripts"
475 verbose node v12.6.0
476 verbose npm  v6.9.0
477 error Unexpected end of JSON input while parsing near '...HqQqP7Ky/f49Ar0oPZ\n4'
478 verbose exit [ 1, true ]
</code>```

答:
Try to use npx create-react-app my-app

I think also information in this link will help you.

Body:
I have installed "create-react-app" globally on my pc using "npm install create-react-app -g". And it worked just fine for months. I had previously created a lot of react app using the "create-react-app app-name" command. And it worked flawlessly. Until a few days ago when it sudden stopped working and started giving errors. I have tried various things suggested but with no luck. So after days of trying to solve the issue I am asking this question.

I have tried doing the following things:

1> using the "npm cache clean --force" and then "npm cache verify".
2> I also unabled my antivirus (norton) and then ran the commands.
3> I installed the latest node version
4> I intalled the latest npm version and updated it using the command "npm install npm@latest -g"
5> I followed the instructions on this stackoverflow link https://stackoverflow.com/questions/50189096/installing-create-react-app-gives-npm-err-shasum-check-failed-and-npm-err-unex/50191315#50191315 to change the registry.
And a few other things. But nothing has worked.

The error that I get is as follows:

D:\codes\react\maximilianUdemy\project1>create-react-app react-mytest-app

Creating a new React app in D:\codes\react\maximilianUdemy\project1\react-mytest-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...HqQqP7Ky/f49Ar0oPZ\n4'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\vaibh\AppData\Roaming\npm-cache\_logs\2019-07-20T10_24_27_969Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting react-mytest-app/ from D:\codes\react\maximilianUdemy\project1
Done.

Below is an excerpt from the C:\Users\vaibh\AppData\Roaming\npm-cache\_logs\2019-07-20T10_24_27_969Z-debug.log. Since the log is really big (664 lines), I have only noted from when the error started showing.

471 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...HqQqP7Ky/f49Ar0oPZ\n4'
471 verbose stack     at JSON.parse (<anonymous>)
471 verbose stack     at parseJson (D:\Program_Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)
471 verbose stack     at D:\Program_Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50
471 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:85:5)
472 verbose cwd D:\codes\react\maximilianUdemy\project1\react-mytest-app
473 verbose Windows_NT 10.0.17134
474 verbose argv "D:\\Program_Files\\nodejs\\node.exe" "D:\\Program_Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--save" "--save-exact" "--loglevel" "error" "react" "react-dom" "react-scripts"
475 verbose node v12.6.0
476 verbose npm  v6.9.0
477 error Unexpected end of JSON input while parsing near '...HqQqP7Ky/f49Ar0oPZ\n4'
478 verbose exit [ 1, true ]


问:
The below error occurred after running the command ionic(5) serve
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:112:11)
    at Object.join (path.js:375:7)
    at noopServiceWorkerMiddleware (D:\Learning of React+ReactNative\myApp\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
    at Layer.handle [as handle_request] (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:317:13)
    at D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:275:10)
    at launchEditorMiddleware (D:\Learning of React+ReactNative\myApp\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
    at Layer.handle [as handle_request] (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:317:13)
    at D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\index.js:275:10)
    at handleWebpackInternalMiddleware (D:\Learning of React+ReactNative\myApp\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
    at Layer.handle [as handle_request] (D:\Learning of React+ReactNative\myApp\node_modules\express\lib\router\layer.js:95:5) </p>

答:
I found a fix, seems the problem stems from react-scripts 3.3.x series. In package.json I changed

```<code>"react-scripts":"3.3.0"
</code>```

to

```<code>"react-scripts":"^3.4.0"
</code>```

then run npm i and ionic serve and it works.

More info here https://github.com/facebook/create-react-app/issues/8490

Body:
I found a fix, seems the problem stems from react-scripts 3.3.x series. In package.json I changed

"react-scripts":"3.3.0"

to

"react-scripts":"^3.4.0"

then run npm i and ionic serve and it works.

More info here https://github.com/facebook/create-react-app/issues/8490


问:
How to get text from URLs using regexp_extract in data studio
Example URLs:

/en/current-season/abc-note-book/2018-abc-note-book-arun-1

/en/current-season/xyz-note-book/2018-xyz-note-book-kumar-2

/en/current-season/pqr-note-book/2018-pqr-note-book-rahul-3

I want to extract 'abc-note-book' section as column 1 from all the URLs

Expected Result:

abc note book

xyz note book

pqr note book

And also need to extract 'arun-1' section as column 2 from all the URLs

Expected Result

arun-1

kumar-2

rahul-3

Please suggest how to extract using regexp_extract in data studio? Or is there any other formula to extract it.

Thanks.

答:
Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate. The required text can be extracted using the REGEXP_EXTRACT function, and in the case of Column 1, REGEXP_REPLACE can be used to replace the - with a space:

Column 1 (e.g. abc note book)

```<code>REGEXP_REPLACE(REGEXP_EXTRACT(URL, "/\\d+-(\\w+-\\w+-\\w+)"), "-", " ")
</code>```

Column 2 (e.g. arun-1)

```<code>REGEXP_EXTRACT(URL, "(\\w+-\\d+)$")
</code>```

Body:
Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate. The required text can be extracted using the REGEXP_EXTRACT function, and in the case of Column 1, REGEXP_REPLACE can be used to replace the - with a space:

Column 1 (e.g. abc note book)

REGEXP_REPLACE(REGEXP_EXTRACT(URL, "/\\d+-(\\w+-\\w+-\\w+)"), "-", " ")

Column 2 (e.g. arun-1)

REGEXP_EXTRACT(URL, "(\\w+-\\d+)$")


问:
How to use values from the WITH table in my insert?
After last answer I realized that I did things that was not needed. So I tried to rewrite it as following, but get error

```<code>CREATE OR REPLACE FUNCTION piljetter_system.update_search() RETURNS trigger AS $func_table$
BEGIN
    INSERT INTO piljetter_system.search(consertid, document_tsvector)
SELECT  new.consertid,
        setweight(to_tsvector('english', coalesce(new.consertname, '')), 'A')
    || setweight(to_tsvector('english', coalesce(b.bandname , '')), 'B') -- Get bandname from id
    || setweight(to_tsvector('english', coalesce(s.stagename, '')), 'C') -- GET stagename from id
    || setweight(to_tsvector('english', coalesce(s.stagecountry, '')), 'D') -- GET stagecountry from id
    || setweight(to_tsvector('english', coalesce(s.stagecity, '')), 'E') -- GET stagecity from id
    || setweight(to_tsvector('english', coalesce(s.stagestreet, '')), 'F')
    -- GET stagestreet from id
FROM    piljetter_system.bands b, piljetter_system.stages s
WHERE   b.bandid = new.bandid AND s.stageid = new.stageid;
RETURN NEW.document_tsvector;
END
$func_table$ LANGUAGE plpgsql;
</code>```

I'm triggering the function at insert and update at my conserts table.

The result I want is to insert a new line at search(consertid, document_tsvector) where the consertid = new.consertid and document_tsvector = new.consertname,  bandname from the new.bandid in the consert stagename, stagecountry, stagecity, stagestreet from the new.stageid.

ERROR:

ERROR:  FEL:  unrecognized weight: 69 CONTEXT:  SQL-sats: "INSERT INTO
  piljetter_system.search(consertid, document_tsvector)
      SELECT  new.consertid,
            setweight(to_tsvector('english', coalesce(new.consertname, '')), 'A')
          || setweight(to_tsvector('english', coalesce(b.bandname , '')), 'B') -- Get bandname from id
          || setweight(to_tsvector('english', coalesce(s.stagename, '')), 'C') -- GET stagename from id
          || setweight(to_tsvector('english', coalesce(s.stagecountry, '')), 'D') -- GET stagecountry from id
          || setweight(to_tsvector('english', coalesce(s.stagecity, '')), 'E') -- GET stagecity from id
          || setweight(to_tsvector('english', coalesce(s.stagestreet, '')), 'F')        -- GET stagestreet from id  FROM

  piljetter_system.bands b, piljetter_system.stages s   WHERE   b.bandid
  = new.bandid AND s.stageid = new.stageid" PL/pgSQL-funktion piljetter_system.update_search() rad 3 vid SQL-sats

// OLD POST
I'm kinda new to functions and triggers and I'm doing a project at school. I want to make a trigger function that update another table based on what I insert into my conserts table.

My problem is that I need the stagename, stagecountry, stagecity, stagestreet from the stageid and also the bandname from the bandid and insert it into search colum document_tsvector. Below you can see the code I need to fix. I dont manage to get the info from the WITH tables inside my insert.

```<code>CREATE FUNCTION piljetter_system.update_search() RETURNS trigger AS $func_table$
BEGIN
    WITH band AS (
        SELECT bandname FROM piljetter_system.bands WHERE bandid = new.bandid
    ), stage AS (
        SELECT stagename, stagecountry, stagecity, stagestreet FROM piljetter_system.stages WHERE stageid = new.stageid
    )

    INSERT INTO piljetter_system.search(consertid, document_tsvector)
    VALUES (new.consertid,
        setweight(to_tsvector('english', coalesce(new.consertname, '')), 'A')
        || setweight(to_tsvector('english', coalesce(band.bandname , '')), 'B') -- Get bandname from id
        || setweight(to_tsvector('english', coalesce(stage.stagename, '')), 'C') -- GET stagename from id
        || setweight(to_tsvector('english', coalesce(stage.stagecountry, '')), 'D') -- GET stagecountry from id
        || setweight(to_tsvector('english', coalesce(stage.stagecity, '')), 'E') -- GET stagecity from id
        || setweight(to_tsvector('english', coalesce(stage.stagestreet, '')), 'F')    -- GET stagestreet from id
    );
    RETURN NEW;
END
$func_table$ LANGUAGE plpgsql;
</code>```

Pictures of the tables;
bands

conserts

stages

search

Thank you for any help!

答:
Why are you doing it with WITH?  Why not just run two queries storing the values into variables, and then use the variables in the INSERT?

Anyway, you would just select from the CTE tables.

```<code>INSERT INTO piljetter_system.search(consertid, document_tsvector)
select new.consertid, ...
    from band, stage
</code>```

But it looks like your trigger is inserting into the same table it was just called for. That is wrong. If your goal is to set document_tsvector, you should just assign a value to NEW.document_tsvector before you RETURN NEW.

Body:
After last answer I realized that I did things that was not needed. So I tried to rewrite it as following, but get error

CREATE OR REPLACE FUNCTION piljetter_system.update_search() RETURNS trigger AS $func_table$
BEGIN
    INSERT INTO piljetter_system.search(consertid, document_tsvector)
SELECT  new.consertid,
        setweight(to_tsvector('english', coalesce(new.consertname, '')), 'A')
    || setweight(to_tsvector('english', coalesce(b.bandname , '')), 'B') -- Get bandname from id
    || setweight(to_tsvector('english', coalesce(s.stagename, '')), 'C') -- GET stagename from id
    || setweight(to_tsvector('english', coalesce(s.stagecountry, '')), 'D') -- GET stagecountry from id
    || setweight(to_tsvector('english', coalesce(s.stagecity, '')), 'E') -- GET stagecity from id
    || setweight(to_tsvector('english', coalesce(s.stagestreet, '')), 'F')
    -- GET stagestreet from id
FROM    piljetter_system.bands b, piljetter_system.stages s
WHERE   b.bandid = new.bandid AND s.stageid = new.stageid;
RETURN NEW.document_tsvector;
END
$func_table$ LANGUAGE plpgsql;

I'm triggering the function at insert and update at my conserts table.

The result I want is to insert a new line at search(consertid, document_tsvector) where the consertid = new.consertid and document_tsvector = new.consertname,  bandname from the new.bandid in the consert stagename, stagecountry, stagecity, stagestreet from the new.stageid.

ERROR:

ERROR:  FEL:  unrecognized weight: 69 CONTEXT:  SQL-sats: "INSERT INTO
  piljetter_system.search(consertid, document_tsvector)
      SELECT  new.consertid,
            setweight(to_tsvector('english', coalesce(new.consertname, '')), 'A')
          || setweight(to_tsvector('english', coalesce(b.bandname , '')), 'B') -- Get bandname from id
          || setweight(to_tsvector('english', coalesce(s.stagename, '')), 'C') -- GET stagename from id
          || setweight(to_tsvector('english', coalesce(s.stagecountry, '')), 'D') -- GET stagecountry from id
          || setweight(to_tsvector('english', coalesce(s.stagecity, '')), 'E') -- GET stagecity from id
          || setweight(to_tsvector('english', coalesce(s.stagestreet, '')), 'F')        -- GET stagestreet from id  FROM

  piljetter_system.bands b, piljetter_system.stages s   WHERE   b.bandid
  = new.bandid AND s.stageid = new.stageid" PL/pgSQL-funktion piljetter_system.update_search() rad 3 vid SQL-sats

// OLD POST
I'm kinda new to functions and triggers and I'm doing a project at school. I want to make a trigger function that update another table based on what I insert into my conserts table.

My problem is that I need the stagename, stagecountry, stagecity, stagestreet from the stageid and also the bandname from the bandid and insert it into search colum document_tsvector. Below you can see the code I need to fix. I dont manage to get the info from the WITH tables inside my insert.

CREATE FUNCTION piljetter_system.update_search() RETURNS trigger AS $func_table$
BEGIN
    WITH band AS (
        SELECT bandname FROM piljetter_system.bands WHERE bandid = new.bandid
    ), stage AS (
        SELECT stagename, stagecountry, stagecity, stagestreet FROM piljetter_system.stages WHERE stageid = new.stageid
    )

    INSERT INTO piljetter_system.search(consertid, document_tsvector)
    VALUES (new.consertid,
        setweight(to_tsvector('english', coalesce(new.consertname, '')), 'A')
        || setweight(to_tsvector('english', coalesce(band.bandname , '')), 'B') -- Get bandname from id
        || setweight(to_tsvector('english', coalesce(stage.stagename, '')), 'C') -- GET stagename from id
        || setweight(to_tsvector('english', coalesce(stage.stagecountry, '')), 'D') -- GET stagecountry from id
        || setweight(to_tsvector('english', coalesce(stage.stagecity, '')), 'E') -- GET stagecity from id
        || setweight(to_tsvector('english', coalesce(stage.stagestreet, '')), 'F')    -- GET stagestreet from id
    );
    RETURN NEW;
END
$func_table$ LANGUAGE plpgsql;

Pictures of the tables;
bands

conserts

stages

search

Thank you for any help!

Body:
Why are you doing it with WITH?  Why not just run two queries storing the values into variables, and then use the variables in the INSERT?

Anyway, you would just select from the CTE tables.

INSERT INTO piljetter_system.search(consertid, document_tsvector)
select new.consertid, ...
    from band, stage

But it looks like your trigger is inserting into the same table it was just called for. That is wrong. If your goal is to set document_tsvector, you should just assign a value to NEW.document_tsvector before you RETURN NEW.


问:
looping+enviroments in R: assigning new variable name to column value
I am attempting to create an environment to store information for each row of a CSV file.  I need some help in making a loop assigning the variable name in the new environment to be the same as the value of a specific column.  I don't care as much about what its value is as much as what it is called (I'll modify the value later).  How would I go about doing this?

ex., lets say that in csvFile$Names, the value is 'Blargh'.  I want to make a loop that would create a variable dataEnv$Blargh which holds ANYTHING as its value.

What I have so far which is definitely wrong:

```<code>dataEnv <-  new.env()
for (value in csvFile$Names) {
  dataEnv$Names <-  c(Names)
}
</code>```

答:
If I understand correctly you have a vector of character strings, Names, and want to create an environment e containing objects corresponding to each element of Names having that element as its name and containing an arbitrary value.  Using NULL as that value we have:

```<code>Names <- c("Blarg", "foo")
e <- new.env()
for(nm in Names) e[[nm]] <- NULL
</code>```

or in one line:

```<code>e <- list2env(Map(function(x) NULL, Names))
</code>```

or using the components of Names for both the names and the values:

```<code>e <- list2env(as.list(setNames(Names, Names)))
</code>```

Body:
I am attempting to create an environment to store information for each row of a CSV file.  I need some help in making a loop assigning the variable name in the new environment to be the same as the value of a specific column.  I don't care as much about what its value is as much as what it is called (I'll modify the value later).  How would I go about doing this?

ex., lets say that in csvFile$Names, the value is 'Blargh'.  I want to make a loop that would create a variable dataEnv$Blargh which holds ANYTHING as its value.

What I have so far which is definitely wrong:

dataEnv <-  new.env()
for (value in csvFile$Names) {
  dataEnv$Names <-  c(Names)
}

Body:
If I understand correctly you have a vector of character strings, Names, and want to create an environment e containing objects corresponding to each element of Names having that element as its name and containing an arbitrary value.  Using NULL as that value we have:

Names <- c("Blarg", "foo")
e <- new.env()
for(nm in Names) e[[nm]] <- NULL

or in one line:

e <- list2env(Map(function(x) NULL, Names))

or using the components of Names for both the names and the values:

e <- list2env(as.list(setNames(Names, Names)))


问:
Format text box to accept only numbers and white spaces and plus sign
I am trying to make a text-box which will only accept numbers, white spaces and plus sign.

Currently I have done something like this in KeyPressEvent of the textbox

```<code>if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) &&!char.IsWhiteSpace(e.KeyChar))
    {
                e.Handled = true;
    }
</code>```

I want to accept the + sign as well

Update

I did handle the !char.IsSymbol(e.KeyChar) but it will accept the = sign as well with the +

Any help!!!

Thanks

答:
This works fine for me:

```<code>if (!(char.IsLetter(e.KeyChar) && (!char.IsControl(e.KeyChar)
    && !char.IsDigit(e.KeyChar) && !(e.KeyChar == '.'))
{
    e.Handled = true;
}
</code>```

I added the char.IsControl because it allows you to use Backspace in a typeerror case.

Body:
I am trying to make a text-box which will only accept numbers, white spaces and plus sign.

Currently I have done something like this in KeyPressEvent of the textbox

if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) &&!char.IsWhiteSpace(e.KeyChar))
    {
                e.Handled = true;
    }

I want to accept the + sign as well

Update

I did handle the !char.IsSymbol(e.KeyChar) but it will accept the = sign as well with the +

Any help!!!

Thanks

Body:
This works fine for me:

if (!(char.IsLetter(e.KeyChar) && (!char.IsControl(e.KeyChar)
    && !char.IsDigit(e.KeyChar) && !(e.KeyChar == '.'))
{
    e.Handled = true;
}

I added the char.IsControl because it allows you to use Backspace in a typeerror case.


问:
NET Framework to .NET Core 3.1 - ResourceDictionary in external library
i'm trying to convert my application wpf application from .net framework 4.8 to .net core.
I have a a class library .net core 3.1, where i put all my themes, styles, languages and other resources, when i try to run it breaks because itcan't find my resource

IOException: Cannot locate resource 'windows/vulpesaccesswindow.xaml'.

in my app.xaml i have this:

```<code><Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/System.Windows.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Input.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Data.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.DataVisualization.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Diagrams.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Diagrams.Extensions.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Docking.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.GanttView.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.GridView.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Pivot.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.PivotFieldList.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.ScheduleView.xaml" />
            <!--TELERIK-->
            <!--UIX-->
            <ResourceDictionary Source="/UIX;component/Windows/VulpesAccessWindow.xaml" />
            <ResourceDictionary Source="/UIX;component/Windows/VulpesShellWindow.xaml" />
            <ResourceDictionary Source="/UIX;component/Windows/VulpesDialogWindow.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/ThemeLight.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/BaseColors.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Icons.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/VulpesTelerik.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Labels.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Navigation.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Validation.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Templates.xaml" />

            <ResourceDictionary>
                <local:ShellBootstrapper x:Key="bootstrapper" />
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</code>```

i try to set my resource VulpesAccessWindow.xaml Build Action to Resource and Embedded Resource, but nothing, when i run it breaks..

Any advice?

Thank you

答:
Using the full pack notation works in a solution I have:

```<code> <ResourceDictionary  Source="pack://application:,,,/UILib;component/Resources/FontResources.xaml"/>
</code>```

In the library, this is Build Action Page.

Body:
i'm trying to convert my application wpf application from .net framework 4.8 to .net core.
I have a a class library .net core 3.1, where i put all my themes, styles, languages and other resources, when i try to run it breaks because itcan't find my resource

IOException: Cannot locate resource 'windows/vulpesaccesswindow.xaml'.

in my app.xaml i have this:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/System.Windows.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Input.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Data.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.DataVisualization.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Diagrams.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Diagrams.Extensions.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Docking.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.GanttView.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.GridView.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.Pivot.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.PivotFieldList.xaml" />
            <ResourceDictionary Source="/Telerik.Windows.Themes.VisualStudio2013;component/Themes/Telerik.Windows.Controls.ScheduleView.xaml" />

            <ResourceDictionary Source="/UIX;component/Windows/VulpesAccessWindow.xaml" />
            <ResourceDictionary Source="/UIX;component/Windows/VulpesShellWindow.xaml" />
            <ResourceDictionary Source="/UIX;component/Windows/VulpesDialogWindow.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/ThemeLight.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/BaseColors.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Icons.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/VulpesTelerik.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Labels.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Navigation.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Validation.xaml" />
            <ResourceDictionary Source="/UIX;component/Resources/Templates.xaml" />

            <ResourceDictionary>
                <local:ShellBootstrapper x:Key="bootstrapper" />
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

i try to set my resource VulpesAccessWindow.xaml Build Action to Resource and Embedded Resource, but nothing, when i run it breaks..

Any advice?

Thank you

Body:
Using the full pack notation works in a solution I have:

 <ResourceDictionary  Source="pack://application:,,,/UILib;component/Resources/FontResources.xaml"/>

In the library, this is Build Action Page.


问:
fading in and fading out a dropdown an unordered list
I am trying to fade in and fade out a
 on a click. I know the method I am using is wrong because it doesn't work, but also because I am pretty sure it's because I need to use $(this) instead of the current $('#innerList') but I am just not sure what I have to do.

http://jsfiddle.net/kyllle/tfZXE/

答: Here you go: http://jsfiddle.net/tfZXE/13/ (only needed to use toggle, and not click, cause click doesn't take 2 methods. And also, you forgot to add # in front of one of the id's)</p>


问:
Why the first Thread.activeCount() return 1 but another return 2 in my code?
Here is my application:

```<code>public class NamedThread extends Thread {
    /* This will store name of the thread */

    String name;

    @Override
    public void run() {
//Will store the number of threads
        int count = 0;
        while (count <= 3) {
//Display the number of threads
            System.out.println(Thread.activeCount());
//Display the name of the currently running thread
            name = Thread.currentThread().getName();
            count++;
            System.out.println(name);
            if (name.equals("Thread1")) {
                System.out.println("Marimba");
            } else {
                System.out.println("Jini");
            }
        }
    }

    public static void main(String args[]) {
        NamedThread objNamedThread = new NamedThread();
        objNamedThread.setName("Thread1");
//Display the status of the thread, whether alive or not
        System.out.println(Thread.currentThread().isAlive());
        System.out.println(objNamedThread.isAlive());
        /*invokes the start method which in turn will call
         * run and begin thread execution
         */
        objNamedThread.start();
        System.out.println(Thread.currentThread().isAlive());
        System.out.println(objNamedThread.isAlive());
    }
}
</code>```

And the output is:

```<code>true
false
true
true
1
Thread1
Marimba
2
Thread1
Marimba
2
Thread1
Marimba
2
Thread1
Marimba
</code>```

What wrong with my application and why?Thank you!

答:
InteliJ generates another thread that is called Monitor Ctrl-Break thread.

The following code (took it from https://www.tutorialspoint.com/java/lang/thread_activecount.htm):

```<code>public static void main(String[] args) {

            Thread t = Thread.currentThread();
            t.setName("Admin Thread");

            // set thread priority to 1
            t.setPriority(1);

            // prints the current thread
            System.out.println("Thread = " + t);

            int count = Thread.activeCount();
            System.out.println("currently active threads = " + count);

            Thread th[] = new Thread[count];
            // returns the number of threads put into the array
            Thread.enumerate(th);

            // prints active threads
        for (int i = 0; i < count; i++) {
            System.out.println(i + ": " + th[i]);
        }
    }
</code>```

will generate the following output in inteliJ:

```<code>Thread = Thread[Admin Thread,1,main]
currently active threads = 2
0: Thread[Admin Thread,1,main]
1: Thread[Monitor Ctrl-Break,5,main]
</code>```

You can run it in debug and notice that this thread isnt created. Therefore, this thread is only added during normal run.

Body:
Here is my application:

public class NamedThread extends Thread {
    /* This will store name of the thread */

    String name;

    @Override
    public void run() {
//Will store the number of threads
        int count = 0;
        while (count <= 3) {
//Display the number of threads
            System.out.println(Thread.activeCount());
//Display the name of the currently running thread
            name = Thread.currentThread().getName();
            count++;
            System.out.println(name);
            if (name.equals("Thread1")) {
                System.out.println("Marimba");
            } else {
                System.out.println("Jini");
            }
        }
    }

    public static void main(String args[]) {
        NamedThread objNamedThread = new NamedThread();
        objNamedThread.setName("Thread1");
//Display the status of the thread, whether alive or not
        System.out.println(Thread.currentThread().isAlive());
        System.out.println(objNamedThread.isAlive());
        /*invokes the start method which in turn will call
         * run and begin thread execution
         */
        objNamedThread.start();
        System.out.println(Thread.currentThread().isAlive());
        System.out.println(objNamedThread.isAlive());
    }
}

And the output is:

true
false
true
true
1
Thread1
Marimba
2
Thread1
Marimba
2
Thread1
Marimba
2
Thread1
Marimba

What wrong with my application and why?Thank you!

Body:
InteliJ generates another thread that is called Monitor Ctrl-Break thread.

The following code (took it from https://www.tutorialspoint.com/java/lang/thread_activecount.htm):

public static void main(String[] args) {

            Thread t = Thread.currentThread();
            t.setName("Admin Thread");

            // set thread priority to 1
            t.setPriority(1);

            // prints the current thread
            System.out.println("Thread = " + t);

            int count = Thread.activeCount();
            System.out.println("currently active threads = " + count);

            Thread th[] = new Thread[count];
            // returns the number of threads put into the array
            Thread.enumerate(th);

            // prints active threads
        for (int i = 0; i < count; i++) {
            System.out.println(i + ": " + th[i]);
        }
    }

will generate the following output in inteliJ:

Thread = Thread[Admin Thread,1,main]
currently active threads = 2
0: Thread[Admin Thread,1,main]
1: Thread[Monitor Ctrl-Break,5,main]

You can run it in debug and notice that this thread isnt created. Therefore, this thread is only added during normal run.


问:
Django SearchFilter is displaying all the data when the search field is empty
I have implemented search feature using Django SearchFilter DRF which is perfectly working but the issue is I don't want to display all the query when I pass nothing in the search field. It is by default returning all the query. I don't know how to handle it.

views.py

```<code>    class EventSearchView(generics.ListAPIView):
          permission_classes = (AllowAny,)
          queryset = Event.objects.all()
          search_fields = ["name", "description","content"]
          filter_backends = (filters.SearchFilter,)
          serializer_class = EventSearchSerializer
          pagination_class = LargeResultsSetPagination
</code>```

When I search for fields "name", "description" it is working fine but when I search nothing and hit the url without search fields by default it is returning all the query, but I want to display nothing.

How can I achieve that?

答:
The other way its use Filter class. Just define it anywhere.

```<code>from django_filters import rest_framework as filters

class ContentFilter(filters.FilterSet):
    name = filters.CharFilter(required=True)

    class Meta:
    model = <your_model>
    fields = ['name']
</code>```

Than you can add it in your view:

```<code>filterset_class = ContentFilter
</code>```

Now your name parameter will be required and no one can fetch you request without it.
This is better way because if User forget to send parameter he get the error message and not a blank response.

Body:
I have implemented search feature using Django SearchFilter DRF which is perfectly working but the issue is I don't want to display all the query when I pass nothing in the search field. It is by default returning all the query. I don't know how to handle it.

views.py

    class EventSearchView(generics.ListAPIView):
          permission_classes = (AllowAny,)
          queryset = Event.objects.all()
          search_fields = ["name", "description","content"]
          filter_backends = (filters.SearchFilter,)
          serializer_class = EventSearchSerializer
          pagination_class = LargeResultsSetPagination

When I search for fields "name", "description" it is working fine but when I search nothing and hit the url without search fields by default it is returning all the query, but I want to display nothing.

How can I achieve that?

Body:
The other way its use Filter class. Just define it anywhere.

from django_filters import rest_framework as filters

class ContentFilter(filters.FilterSet):
    name = filters.CharFilter(required=True)

    class Meta:
    model = <your_model>
    fields = ['name']

Than you can add it in your view:

filterset_class = ContentFilter

Now your name parameter will be required and no one can fetch you request without it.
This is better way because if User forget to send parameter he get the error message and not a blank response.


问:
Return Months & days from TimeSpan asp.net
I want to return in Seconds, Minuites, Hours, Days, Months et Years from Datetime created.

I wrote this snippet of code

```<code>public static string ReturnCreatedSince(DateTime createdOn)
    {
        //Get current datetime
        var today = DateTime.Now;

        // Get days in current month
        var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

        double seconds = 60;
        double minutes = seconds * 60;
        double hours = minutes * 60;
        double days = hours * 24;
        //double weeks = days * 7;
        double months = days * daysInMonth;
        double years = months * 12;

        //Convert created datetime to seconds
        var datetimeInSeconds = (today - createdOn).TotalSeconds;

        var createdSince = string.Empty;

        if (datetimeInSeconds <= seconds) //seconds between 1 to 60
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Seconds.ToString() + " sec";
        }
        else if (datetimeInSeconds <= minutes)// Minuites between 1 to 60
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Minutes.ToString() + " mins";
        }
        else if (datetimeInSeconds <= hours)// Hours between 1 to 24
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Hours.ToString() + " hrs";
        }
        else if (datetimeInSeconds <= days)// Days between 1 to 24
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Days.ToString() + " jrs";
        }
        else if (datetimeInSeconds <= months)// Months between 1 to 24
        {
           return (datetimeInSeconds / months).ToString() + " m";
        }
        else if (datetimeInSeconds <= years)// Years between 1 to 12
        {
            return (datetimeInSeconds / years).ToString() + " yrs";
        }
        else
        {
            return createdOn.ToShortDateString();
        }
    }
</code>```

I tested the code with the following values

Edited

For a given datetime

if the number of second is less than 60 then it should return the value in second.
if the number of second is less greater 60 and less than (60 * 60) secs then it should return the value in mins , the same apply for hours, days months and years

Now i have this date "createdOn": "2017-10-16T14:41:16.557" and return 41 days instead of 1 month expected.

how can i fix it

答:
@Tarik solution for months will get you the total number of months between the startDate and endDate.

To get the last remaining months, include this while loop statement.

```<code>DateTime startDate = new DateTime(2003, 1, 1);
DateTime endDate = new DateTime(2007, 12, 1);
int nbYears = endDate.Year - startDate.Year;
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
while (nbMonths > 12)
{
    nbMonths = nbMonths % 12;
}
Console.WriteLine($"{nbYears} year(s) and {nbMonths} month(s)");
</code>```

Without the while loop, it prints: 4 year(s) and 59 month(s)
With the while loop, it prints: 4 year(s) and 11 month(s)

Body:
I want to return in Seconds, Minuites, Hours, Days, Months et Years from Datetime created.

I wrote this snippet of code

public static string ReturnCreatedSince(DateTime createdOn)
    {
        //Get current datetime
        var today = DateTime.Now;

        // Get days in current month
        var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

        double seconds = 60;
        double minutes = seconds * 60;
        double hours = minutes * 60;
        double days = hours * 24;
        //double weeks = days * 7;
        double months = days * daysInMonth;
        double years = months * 12;

        //Convert created datetime to seconds
        var datetimeInSeconds = (today - createdOn).TotalSeconds;

        var createdSince = string.Empty;

        if (datetimeInSeconds <= seconds) //seconds between 1 to 60
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Seconds.ToString() + " sec";
        }
        else if (datetimeInSeconds <= minutes)// Minuites between 1 to 60
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Minutes.ToString() + " mins";
        }
        else if (datetimeInSeconds <= hours)// Hours between 1 to 24
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Hours.ToString() + " hrs";
        }
        else if (datetimeInSeconds <= days)// Days between 1 to 24
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Days.ToString() + " jrs";
        }
        else if (datetimeInSeconds <= months)// Months between 1 to 24
        {
           return (datetimeInSeconds / months).ToString() + " m";
        }
        else if (datetimeInSeconds <= years)// Years between 1 to 12
        {
            return (datetimeInSeconds / years).ToString() + " yrs";
        }
        else
        {
            return createdOn.ToShortDateString();
        }
    }

I tested the code with the following values

Edited

For a given datetime

if the number of second is less than 60 then it should return the value in second.
if the number of second is less greater 60 and less than (60 * 60) secs then it should return the value in mins , the same apply for hours, days months and years

Now i have this date "createdOn": "2017-10-16T14:41:16.557" and return 41 days instead of 1 month expected.

how can i fix it

Body:
@Tarik solution for months will get you the total number of months between the startDate and endDate.

To get the last remaining months, include this while loop statement.

DateTime startDate = new DateTime(2003, 1, 1);
DateTime endDate = new DateTime(2007, 12, 1);
int nbYears = endDate.Year - startDate.Year;
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
while (nbMonths > 12)
{
    nbMonths = nbMonths % 12;
}
Console.WriteLine($"{nbYears} year(s) and {nbMonths} month(s)");

Without the while loop, it prints: 4 year(s) and 59 month(s)
With the while loop, it prints: 4 year(s) and 11 month(s)


问:
Issue with a skiping of first row
I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.

File contains: Rabbit, Pig, Dog, Horse, Bird

```<code>try:
    file = open("file.txt")
    line = file.readline()

    animals = []
    for line in file:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    file.close()
</code>```

Output is ['Bird', 'Dog', 'Horse', 'Pig']

答:
Every time readline() is called, it reads a line from a file and moves the cursor to the beggining of the next line.

In your code, line = file.readline() reads the first line and moves the cursor to the second line. As a result, your for loop starts from the second line of the file. If there is no particular reason you need it, just delete it. If you do need it, just append the line variable in the list and then do the sorting.

Title: Issue with a skiping of first row

Body:
I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.

File contains: Rabbit, Pig, Dog, Horse, Bird

try:
    file = open("file.txt")
    line = file.readline()

    animals = []
    for line in file:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    file.close()

Output is ['Bird', 'Dog', 'Horse', 'Pig']


问:
docker-compose: how to keep showing logs in 'follow' mode even when container is down?
If you run docker-compose logs -f service in one terminal and try to restart service in other, then logging will be stopped and you will need to start dkc logs again. How to keep dkc logs running?

The only solution I've found so far is to run additional noop service which will not allow dkc logs to shut down. If this is the only solution then do you have any suggestion for simplest noop service which already exists on docker hub?

My workaround:

add new noop service to the docker-compose.override.yml (I picked redis because it was already installed and is quite lightweight):

```<code>services:
  noop:
    image: redis:5-alpine
</code>```

run docker-compose logs -f service noop instead of with just service.

run docker-compose stop/restart service. logs process will be kept alive by noop service.

Con:

extra stuff to run

cannot use dkc stop and dkc restart without specifying the service

答:
Maybe some information about what you are logging. For example on nginx or php containers we simply move logfiles outside of container just using volume to mount them to host machine, then you can parse them as you want.

    volumes:
      - /var/log/mysql/error_service_xy.log:/var/log/mysql/error.log
```

Body:
If you run docker-compose logs -f service in one terminal and try to restart service in other, then logging will be stopped and you will need to start dkc logs again. How to keep dkc logs running?

The only solution I've found so far is to run additional noop service which will not allow dkc logs to shut down. If this is the only solution then do you have any suggestion for simplest noop service which already exists on docker hub?

My workaround:

add new noop service to the docker-compose.override.yml (I picked redis because it was already installed and is quite lightweight):

services:
  noop:
    image: redis:5-alpine

run docker-compose logs -f service noop instead of with just service.

run docker-compose stop/restart service. logs process will be kept alive by noop service.

Con:

extra stuff to run

cannot use dkc stop and dkc restart without specifying the service