问:
Is there an efficient way of deleting already allocated but empty Eigen rows without reallocation?
I am trying to write runtime efficient code using Eigen::Matrix class. To improve runtime I know that resizing the Eigen::Matrix is recommended such that sufficient memory is allocated and thus avoiding reallocation. However, I don't know the number of rows at compiletime nor at initialization of the matrix. What I want to do is to use a matrix of dynamic size, allocate memory with a known upper limit, then fill some data into the matrix and finally "cutoff/reshape" the lowerend rows that I didn't need.

So my problem looks like thus, except for the memory I allocate is way larger than (5,3)

```<code>    Eigen::MatrixXi M;
    M.resize(5,3);
    std::cout << "M size: (" << M.rows() << "x" << M.cols()<< " ) with Entries:\n"<< M << std::endl;
    M.row(0) = Eigen::RowVector3i(1, 1, 1);
    M.row(1) = Eigen::RowVector3i(2, 2, 2);
    M.row(2) = Eigen::RowVector3i(3, 3, 3);
    //M.reshape(3, 3); ??
    std::cout << "M size: (" << M.rows() << "x" << M.cols() << " ) with Entries:\n" << M << std::endl;
</code>```

I know that the following code would work but this snippet includes reallocation of new memory instead of just "freeing" the lower rows of M or remapping the memory of M;

```<code>    // works but inefficient
    Eigen::MatrixXi M2;
    M2.resize(3, 3);
    M2 = M.topRows(3);
</code>```

Do you have any ideas on how I can implement this idea more efficiently?

答:
First of all, if you are adding entries row-by-row, it could be more efficient to use a row-major matrix. Also, if the number of columns is known at compile-time to be 3, you can express this in the type:

```<code>typedef Eigen::Matrix<int, Eigen::Dynamic, 3, Eigen::RowMajor> MatrixRX3i;
MatrixRX3i M;
M.resize(5,3);
</code>```

If you don't mind that the entire memory of M is kept all the time, you can define M2 as an Eigen::Ref object:

```<code>Eigen::Ref<MatrixRX3i> M2(M.topRows(3));
</code>```

If you want to deallocate unnecessary memory, you should use conservativeResize():

```<code>M.conservativeResize(3,3);
</code>```

Ideally, this should just call std::realloc (in case the inner dimension does not change), though there might be some alignment related corner-cases.

Body:
I am trying to write runtime efficient code using Eigen::Matrix class. To improve runtime I know that resizing the Eigen::Matrix is recommended such that sufficient memory is allocated and thus avoiding reallocation. However, I don't know the number of rows at compiletime nor at initialization of the matrix. What I want to do is to use a matrix of dynamic size, allocate memory with a known upper limit, then fill some data into the matrix and finally "cutoff/reshape" the lowerend rows that I didn't need.

So my problem looks like thus, except for the memory I allocate is way larger than (5,3)

    Eigen::MatrixXi M;
    M.resize(5,3);
    std::cout << "M size: (" << M.rows() << "x" << M.cols()<< " ) with Entries:\n"<< M << std::endl;
    M.row(0) = Eigen::RowVector3i(1, 1, 1);
    M.row(1) = Eigen::RowVector3i(2, 2, 2);
    M.row(2) = Eigen::RowVector3i(3, 3, 3);
    //M.reshape(3, 3); ??
    std::cout << "M size: (" << M.rows() << "x" << M.cols() << " ) with Entries:\n" << M << std::endl;

I know that the following code would work but this snippet includes reallocation of new memory instead of just "freeing" the lower rows of M or remapping the memory of M;

    // works but inefficient
    Eigen::MatrixXi M2;
    M2.resize(3, 3);
    M2 = M.topRows(3);

Do you have any ideas on how I can implement this idea more efficiently?

Body:
First of all, if you are adding entries row-by-row, it could be more efficient to use a row-major matrix. Also, if the number of columns is known at compile-time to be 3, you can express this in the type:

typedef Eigen::Matrix<int, Eigen::Dynamic, 3, Eigen::RowMajor> MatrixRX3i;
MatrixRX3i M;
M.resize(5,3);

If you don't mind that the entire memory of M is kept all the time, you can define M2 as an Eigen::Ref object:

Eigen::Ref<MatrixRX3i> M2(M.topRows(3));

If you want to deallocate unnecessary memory, you should use conservativeResize():

M.conservativeResize(3,3);

Ideally, this should just call std::realloc (in case the inner dimension does not change), though there might be some alignment related corner-cases.


来源: stackexchange

问:
Selection field options in odoo
I have to create a new field in one of my forms which is a selection field. How do i make the options in the selection field, entries from another model( like selecting a place from list of places). Do i have to create a new module for such a field? I am using odoo 12.

NB: odoo newbie!

答:
Instead of Selection field you have to create a Many2one field.You can define a Many2one field like ,

```<code>from odoo import fields

   field_name = fields.Many2one('your.model', string="Field  Name")
</code>```

In your case, consider you have the places in the model place.place, then you can create the Many2one field in your form like ,

```<code>   place_id = fields.Many2one('place.place', string="Place")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Selection field options in odoo

Body:
Instead of Selection field you have to create a Many2one field.You can define a Many2one field like ,

from odoo import fields

   field_name = fields.Many2one('your.model', string="Field  Name")

In your case, consider you have the places in the model place.place, then you can create the Many2one field in your form like ,

   place_id = fields.Many2one('place.place', string="Place")


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答:
current is not a char* pointer, it is a path so it might lead to complication

also, sprintf can't print to string variables like you are trying to do.

ContentLicense: CC BY-SA 3.0

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release


问:
Why does Console.ReadKey().Key.ToString get lower and uppercase Letter by pressing once?
This snipet Outputs two Letters when i press one Key (r).

```<code>string key = string.Empty;
key = Console.ReadKey().Key.ToString();
Console.WriteLine(key);
Console.ReadKey();
// Output: rR
</code>```

Why does it output lower 'r' and Upercase 'R'  when i only press once the lowercase 'r'?

答:
Old question, but thought this may be useful to add.

As others have noted, Console.ReadKey() does the job of both reading your inputted key and also writing it to screen (before your Console.WriteLine() takes effect).

If you just wanted to read the input and not write it, you can use the optional bool intercept argument of Console.ReadKey() to hide the user input, and then write it later:

```<code>ConsoleKeyInfo cki = Console.ReadKey(true); // hiding input
Console.Write($"You pressed: {cki.Key}");

// press letter "a" (lower case)
// Output: You pressed: A
// i.e. no duplicated letter

Console.ReadLine();
</code>```

Link to MSDN section

If you needed lowercase output, just needs a slight modification:

```<code>ConsoleKeyInfo cki = Console.ReadKey(true); // hiding input
Console.Write($"You pressed: {cki.Key.ToString().ToLower()}");
// press letter "a" (lower case)
// Output: You pressed: a

Console.ReadLine();
</code>```

Body:
This snipet Outputs two Letters when i press one Key (r).

string key = string.Empty;
key = Console.ReadKey().Key.ToString();
Console.WriteLine(key);
Console.ReadKey();
// Output: rR

Why does it output lower 'r' and Upercase 'R'  when i only press once the lowercase 'r'?

Body:
Old question, but thought this may be useful to add.

As others have noted, Console.ReadKey() does the job of both reading your inputted key and also writing it to screen (before your Console.WriteLine() takes effect).

If you just wanted to read the input and not write it, you can use the optional bool intercept argument of Console.ReadKey() to hide the user input, and then write it later:

ConsoleKeyInfo cki = Console.ReadKey(true); // hiding input
Console.Write($"You pressed: {cki.Key}");

// press letter "a" (lower case)
// Output: You pressed: A
// i.e. no duplicated letter

Console.ReadLine();

Link to MSDN section

If you needed lowercase output, just needs a slight modification:

ConsoleKeyInfo cki = Console.ReadKey(true); // hiding input
Console.Write($"You pressed: {cki.Key.ToString().ToLower()}");
// press letter "a" (lower case)
// Output: You pressed: a

Console.ReadLine();


问:
Create a new .txt file for each .pdf files in a directory in python
My code is supposed to take each pdf from a directory, OCR it and return a .txt file for each OCR'd pdf. The name of the pdf and the .txt file should be the same except .pdf being changed to .txt. I am stuck in the part of splitting the input pdf name to generate the same name with a .txt extension for a OCR'd file. A sample file in the directory looks like this : "000dbf9d-d53f-465f-a7ce-722722136fb7465.pdf". I need output as "000dbf9d-d53f-465f-a7ce-722722136fb7465.txt". Also my code doesn't create new .txt files but overwrites on one file for each iteration. I need a new .txt file for each OCR'd .pdf files. Code till now:</p>

```<code>import io
import glob
from PIL import Image
import pytesseract
from wand.image import Image as wi

files = glob.glob(r"D:\files\**")
for file in files:
    #print(file)
    pdf = wi(filename = file, resolution = 300)

    pdfImg = pdf.convert('jpeg')

    imgBlobs = []

    for img in pdfImg.sequence:
        page = wi(image = img)
        imgBlobs.append(page.make_blob('jpeg'))

    extracted_texts = []

    for imgBlob in imgBlobs:
            im = Image.open(io.BytesIO(imgBlob))
            text = pytesseract.image_to_string(im, lang = 'eng')
            extracted_texts.append(text)
    with open("D:\\extracted_text\\"+ "\\file1.txt", 'w') as f:
        f.write(str(extracted_texts))
</code>```

答:
You just need to keep track of your file name and re-use it in the last two lines:</p>

```<code># ...
import os

files = glob.glob(r"D:\files\**")
for file in files:
    #print(file)

    # Get the name of the file less any suffixes
    name = os.path.basename(file).split('.')[0]

    # ...

    # Use `name` from above to name your text file
    with open("D:\\extracted_text\\" + name + ".txt", 'w') as f:
        f.write(str(extracted_texts))
</code>```

Body:
My code is supposed to take each pdf from a directory, OCR it and return a .txt file for each OCR'd pdf. The name of the pdf and the .txt file should be the same except .pdf being changed to .txt. I am stuck in the part of splitting the input pdf name to generate the same name with a .txt extension for a OCR'd file. A sample file in the directory looks like this : "000dbf9d-d53f-465f-a7ce-722722136fb7465.pdf". I need output as "000dbf9d-d53f-465f-a7ce-722722136fb7465.txt". Also my code doesn't create new .txt files but overwrites on one file for each iteration. I need a new .txt file for each OCR'd .pdf files. Code till now:

import io
import glob
from PIL import Image
import pytesseract
from wand.image import Image as wi

files = glob.glob(r"D:\files\**")
for file in files:
    #print(file)
    pdf = wi(filename = file, resolution = 300)

    pdfImg = pdf.convert('jpeg')

    imgBlobs = []

    for img in pdfImg.sequence:
        page = wi(image = img)
        imgBlobs.append(page.make_blob('jpeg'))

    extracted_texts = []

    for imgBlob in imgBlobs:
            im = Image.open(io.BytesIO(imgBlob))
            text = pytesseract.image_to_string(im, lang = 'eng')
            extracted_texts.append(text)
    with open("D:\\extracted_text\\"+ "\\file1.txt", 'w') as f:
        f.write(str(extracted_texts))

Body:
You just need to keep track of your file name and re-use it in the last two lines:

# ...
import os

files = glob.glob(r"D:\files\**")
for file in files:
    #print(file)

    # Get the name of the file less any suffixes
    name = os.path.basename(file).split('.')[0]

    # ...

    # Use `name` from above to name your text file
    with open("D:\\extracted_text\\" + name + ".txt", 'w') as f:
        f.write(str(extracted_texts))


问:
Read URL parameters
I have a very basic app and I want to read the request parameter values

http://localhost:3000/submission?issueId=1410&score=3

Page:

```<code>const Submission = () => {
    console.log(this.props.location); // error

    return ();
}

export default Submission;
</code>```

App

```<code>const App = () => (
   <Router>
       <div className='App'>
           <Switch>
               <Route path="/" exact component={Dashboard} />
               <Route path="/submission" component={Submission} />
               <Route path="/test" component={Test} />
           </Switch>
       </div>
   </Router>
);

export default App;
</code>```

答:
When you use a functional component you will need the props as a parameter of the function declaration. Then the props should be used within this function without this.

const Submission = (props) => {
  console.log(props.location);
  return (

  );
};
```

Title: Read URL parameters

Body:
I have a very basic app and I want to read the request parameter values

http://localhost:3000/submission?issueId=1410&score=3

Page:

const Submission = () => {
    console.log(this.props.location); // error

    return ();
}

export default Submission;

App

const App = () => (
   <Router>

           <Switch>
               <Route path="/" exact component={Dashboard} />
               <Route path="/submission" component={Submission} />
               <Route path="/test" component={Test} />
           </Switch>

   </Router>
);

export default App;

Body:
When you use a functional component you will need the props as a parameter of the function declaration. Then the props should be used within this function without this.

const Submission = (props) => {
  console.log(props.location);
  return (
    <div />
  );
};


问:
How to save a reference to a previous version of an object in mongo DB
I am trying to get started with MongoDB. I am used to working with relational database engines but now I have to work with MongoDB per requirement.

I am trying to explain my general problem as simplified as possible. Imagine being a Person. You have some traits like a  name or some friends. Now you have died of old age and been born as a new human. You now could have a different name and different friends.

Now you don't like your new "You" and want to return to a previous version of yourself, maybe because you liked the name or the friends more.

To allow this, a Person is bound to a Soul which just stores the current Person as well as all your previous ones.

Now when you store this object in MongoDB you get pretty fast a very huge document (More than 13k Lines in my case). I have created a similar JSON structure to highlight the problem.

```<code>    "Souls:" {
        "UniqueId": {
            "CurrentPerson": {
                "Name": "Jane Doe",
                "PreviousLifePerson": {
                    "Name": "John Doe",
                    "PreviousLifePerson": {
                        "Name": "Max Mustermann",
                        "PreviousLifePerson": {
                            "Name": "Erika Mustermann",
                            "PreviousLifePerson": null
                        }
                    }
                }
            }
        }
    }
</code>```

I have read that MongoDB saves related objects as embedded document by default.
The solution to this problem will probably be to save relations by the id of an object. However I am still unsure on if this is really the best solution and additionally I have some questions about general best practices for the .NET MongoDB Driver.

In C# I would propably have a class like this then:

    public class Person
    {
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("Name")]
        public string Name { get; set; }

        [BsonElement("Friends")]
        public List<ObjectId> FriendIds { get; set; }
        [BsonIgnore]
        public List<Person> Friends { get; set; }

        [BsonElement("Reincarnation")]
        public int Reincarnation { get; set; }

        [BsonElement("PreviousLifePerson")]
        public ObjectId PreviousLifePersonId { get; set; }
        [BsonIgnore]
        public Person PreviousLifePerson { get; set; }
    }
```

For each Ignored Element I'd have to send an additionally query to the database and retrieve those elements. Is this right?

Would I have for Soul and Person an individual collection then, even if a person is always assigned to a soul?

There surely is no built-in way to deserialize an object from the database without explicitly specifying the object id as a property, is it?

答:
since this is a highly relational problem domain, i would do it with MongoDB.Entities convenience library. here's a full program covering all the bases you mentioned.

using MongoDB.Entities;
using System.Linq;

namespace StackOverflow
{
    public class Program
    {
        public class Soul : Entity
        {
            public Many<Person> Incarnations { get; set; }
            public One<Person> CurrentIncarnation { get; set; }

            public Soul() => this.InitOneToMany(() => Incarnations);
        }

        public class Person : Entity
        {
            public string Name { get; set; }
            public One<Soul> Soul { get; set; }
            public One<Person> PreviousLife { get; set; }
            public Many<Person> Friends { get; set; }
            public bool IsDead { get; set; } = false;

            public Person() => this.InitOneToMany(() => Friends);
        }

        static void Main(string[] args)
        {
            new DB("test");

            //big bang
            var god = new Soul();
            god.Save();

            //first man is born
            var adam = new Person
            {
                Name = "Adam",
                Soul = god.ToReference()
            };
            adam.Save();
            god.Incarnations.Add(adam);
            god.CurrentIncarnation = adam.ToReference();

            //first woman is born (without a soul ;p)
            var eve = new Person
            {
                Name = "Eve",
            };
            eve.Save();

            //adam and eve become friends under an apple tree
            adam.Friends.Add(eve);
            eve.Friends.Add(adam);

            //adam dies and comes back as sally
            adam.IsDead = true; adam.Save();
            var sally = new Person
            {
                Name = "Sally",
                Soul = god.ToReference(),
                PreviousLife = adam.ToReference()
            };
            sally.Save();
            god.CurrentIncarnation = sally.ToReference();
            god.Incarnations.Add(sally);

            //sally and eve feel a deep connection
            sally.Friends.Add(eve);

            //sally feels stuck in a mans body, so she goes back to being adam
            sally.IsDead = true;
            sally.Save();
            god.CurrentIncarnation = adam.ToReference();
            god.Save();
            adam.IsDead = false;
            adam.PreviousLife = sally.ToReference();
            adam.Save();

            //invite sally's friends to the funeral
            var guestlist = DB.Find<Person>().One(sally.ID)
                                             .Friends.Collection()
                                             .ToList();
        }
    }
}
```

the library stores relationships by using special join collections which are automatically indexed which makes queries extremely fast.

my personal rule of thumb is to not embed an object inside another if there's gonna be more than a handful of them in there. but it all depends on how your app queries the data, what data is needed by your apps views. with MongoDB.Entities you have the freedom to do both quite easily.

Body:
I am trying to get started with MongoDB. I am used to working with relational database engines but now I have to work with MongoDB per requirement.

I am trying to explain my general problem as simplified as possible. Imagine being a Person. You have some traits like a  name or some friends. Now you have died of old age and been born as a new human. You now could have a different name and different friends.

Now you don't like your new "You" and want to return to a previous version of yourself, maybe because you liked the name or the friends more.

To allow this, a Person is bound to a Soul which just stores the current Person as well as all your previous ones.

Now when you store this object in MongoDB you get pretty fast a very huge document (More than 13k Lines in my case). I have created a similar JSON structure to highlight the problem.

    "Souls:" {
        "UniqueId": {
            "CurrentPerson": {
                "Name": "Jane Doe",
                "PreviousLifePerson": {
                    "Name": "John Doe",
                    "PreviousLifePerson": {
                        "Name": "Max Mustermann",
                        "PreviousLifePerson": {
                            "Name": "Erika Mustermann",
                            "PreviousLifePerson": null
                        }
                    }
                }
            }
        }
    }

I have read that MongoDB saves related objects as embedded document by default.
The solution to this problem will probably be to save relations by the id of an object. However I am still unsure on if this is really the best solution and additionally I have some questions about general best practices for the .NET MongoDB Driver.

In C# I would propably have a class like this then:

    public class Person
    {
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("Name")]
        public string Name { get; set; }

        [BsonElement("Friends")]
        public List<ObjectId> FriendIds { get; set; }
        [BsonIgnore]
        public List<Person> Friends { get; set; }

        [BsonElement("Reincarnation")]
        public int Reincarnation { get; set; }

        [BsonElement("PreviousLifePerson")]
        public ObjectId PreviousLifePersonId { get; set; }
        [BsonIgnore]
        public Person PreviousLifePerson { get; set; }
    }

For each Ignored Element I'd have to send an additionally query to the database and retrieve those elements. Is this right?

Would I have for Soul and Person an individual collection then, even if a person is always assigned to a soul?

There surely is no built-in way to deserialize an object from the database without explicitly specifying the object id as a property, is it?

Body:
since this is a highly relational problem domain, i would do it with MongoDB.Entities convenience library. here's a full program covering all the bases you mentioned.

using MongoDB.Entities;
using System.Linq;

namespace StackOverflow
{
    public class Program
    {
        public class Soul : Entity
        {
            public Many<Person> Incarnations { get; set; }
            public One<Person> CurrentIncarnation { get; set; }

            public Soul() => this.InitOneToMany(() => Incarnations);
        }

        public class Person : Entity
        {
            public string Name { get; set; }
            public One<Soul> Soul { get; set; }
            public One<Person> PreviousLife { get; set; }
            public Many<Person> Friends { get; set; }
            public bool IsDead { get; set; } = false;

            public Person() => this.InitOneToMany(() => Friends);
        }

        static void Main(string[] args)
        {
            new DB("test");

            //big bang
            var god = new Soul();
            god.Save();

            //first man is born
            var adam = new Person
            {
                Name = "Adam",
                Soul = god.ToReference()
            };
            adam.Save();
            god.Incarnations.Add(adam);
            god.CurrentIncarnation = adam.ToReference();

            //first woman is born (without a soul ;p)
            var eve = new Person
            {
                Name = "Eve",
            };
            eve.Save();

            //adam and eve become friends under an apple tree
            adam.Friends.Add(eve);
            eve.Friends.Add(adam);

            //adam dies and comes back as sally
            adam.IsDead = true; adam.Save();
            var sally = new Person
            {
                Name = "Sally",
                Soul = god.ToReference(),
                PreviousLife = adam.ToReference()
            };
            sally.Save();
            god.CurrentIncarnation = sally.ToReference();
            god.Incarnations.Add(sally);

            //sally and eve feel a deep connection
            sally.Friends.Add(eve);

            //sally feels stuck in a mans body, so she goes back to being adam
            sally.IsDead = true;
            sally.Save();
            god.CurrentIncarnation = adam.ToReference();
            god.Save();
            adam.IsDead = false;
            adam.PreviousLife = sally.ToReference();
            adam.Save();

            //invite sally's friends to the funeral
            var guestlist = DB.Find<Person>().One(sally.ID)
                                             .Friends.Collection()
                                             .ToList();
        }
    }
}

the library stores relationships by using special join collections which are automatically indexed which makes queries extremely fast.

my personal rule of thumb is to not embed an object inside another if there's gonna be more than a handful of them in there. but it all depends on how your app queries the data, what data is needed by your apps views. with MongoDB.Entities you have the freedom to do both quite easily.


问:
how to be sure in Linq to SQL that record has been added successfully or not?
I am just learning Linq to SQL and don't know much. Kindly guide and help me.

I am adding a new record by using a SubmitChanges();  How I can be confirmed that record has been added? For example, in using stored procedures we use to send a flag back to application but how is it done in LINQ to SQL? Please guide me.

答:
See: MSDN, How to: Submit Changes to the Database

Note that there is an overload of SubmitChanges() that will let you specidy how to handle conflicts.


问:
How to fix the bot from asking for id in DM , discord bot in JavaScript
Am coding a discord bot, the bot works fine if run inside the server but I want to add some commands that will also work inside DM, I have some code that set prefix for every server and when I run the bot and try commands in DM it produce error because it looking for guild id which DM doesn't have, how can I go around this.

```<code>//the code from line index.js:63:30 in the error message

if(message.author.bot) return;

let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]){
  prefixes[message.guild.id] = {
    prefixes: botconfig.prefix
  };
}
</code>```

I have tried using if statement but when I run command in DM the command still doesn't work but it doesn't produce any error.

```<code>bot.on("message", async message => {
  if (message.channel.type === "dm") {
      let prefix = "!";
} else (message.guild) {
      let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
  if(!prefixes[message.guild.id]){
    prefixes[message.guild.id] = {
      prefixes: botconfig.prefix
    };
  let prefix = prefixes[message.guild.id].prefixes;
  if(!message.content.startsWith(prefix)) return;

    let messageArray = message.content.split(" ");
  let cmd = messageArray[0];
  let args = messageArray.slice(1);

  let commandfile = bot.commands.get(cmd.slice(prefix.length));
  if(commandfile) commandfile.run(bot,message,args);
  }
}
}
</code>```

Below is the error am getting which is pointing me to line 63 in my code which is the code I posted above

```<code>    at Client.bot.on (C:\Users\Milan\Desktop\episode-18-code\index.js:63:30)
    at Client.emit (events.js:198:13)
    at MessageCreateHandler.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
    at WebSocketConnection.onPacket (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:198:13)
    at Receiver.receiverOnMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\websocket.js:789:20)
    at Receiver.emit (events.js:198:13)
(node:2912) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2912) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
```

答:
You can run certain things based on what type of channel it is.

if (message.channel.type === 'text') {
  // Server text channel commands
}

if (message.channel.type === 'dm') {
  // DM channel commands
}
```

All types of channels, according to the docs

dm direct message channel

group group DM channel

text server text channel

voice server voice channel

category server category channel

news server news channel

store server store channel

Body:
Am coding a discord bot, the bot works fine if run inside the server but I want to add some commands that will also work inside DM, I have some code that set prefix for every server and when I run the bot and try commands in DM it produce error because it looking for guild id which DM doesn't have, how can I go around this.

//the code from line index.js:63:30 in the error message

if(message.author.bot) return;

let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]){
  prefixes[message.guild.id] = {
    prefixes: botconfig.prefix
  };
}

I have tried using if statement but when I run command in DM the command still doesn't work but it doesn't produce any error.

bot.on("message", async message => {
  if (message.channel.type === "dm") {
      let prefix = "!";
} else (message.guild) {
      let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
  if(!prefixes[message.guild.id]){
    prefixes[message.guild.id] = {
      prefixes: botconfig.prefix
    };
  let prefix = prefixes[message.guild.id].prefixes;
  if(!message.content.startsWith(prefix)) return;

    let messageArray = message.content.split(" ");
  let cmd = messageArray[0];
  let args = messageArray.slice(1);

  let commandfile = bot.commands.get(cmd.slice(prefix.length));
  if(commandfile) commandfile.run(bot,message,args);
  }
}
}

Below is the error am getting which is pointing me to line 63 in my code which is the code I posted above

    at Client.bot.on (C:\Users\Milan\Desktop\episode-18-code\index.js:63:30)
    at Client.emit (events.js:198:13)
    at MessageCreateHandler.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
    at WebSocketConnection.onPacket (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:198:13)
    at Receiver.receiverOnMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\websocket.js:789:20)
    at Receiver.emit (events.js:198:13)
(node:2912) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2912) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

Body:
You can run certain things based on what type of channel it is.

if (message.channel.type === 'text') {
  // Server text channel commands
}

if (message.channel.type === 'dm') {
  // DM channel commands
}

All types of channels, according to the docs

dm direct message channel

group group DM channel

text server text channel

voice server voice channel

category server category channel

news server news channel

store server store channel


答:
Did you setup correctly react-router-dom with the HOC in your Submission component ?

Example :

```<code>import { withRouter } from 'react-router-dom'

const Submission = ({ history, location }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Submission)
</code>```

If you already did that you can access the params like that :

```<code>const queryString = require('query-string');

const parsed = queryString.parse(props.location.search);
</code>```

You can also use new URLSearchParams if you want something native and it works for your needs

```<code>const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar
</code>```

Be careful, i noticed that you have a functional component and you try to access the props with this.props. It's only for class component.

Title: Read URL parameters

Body:
Did you setup correctly react-router-dom with the HOC in your Submission component ?

Example :

import { withRouter } from 'react-router-dom'

const Submission = ({ history, location }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Submission)

If you already did that you can access the params like that :

const queryString = require('query-string');

const parsed = queryString.parse(props.location.search);

You can also use new URLSearchParams if you want something native and it works for your needs

const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar

Be careful, i noticed that you have a functional component and you try to access the props with this.props. It's only for class component.


问:
Multiple set wise where
I want to change two fields in one table with one query. It's looks like this

```<code>UPDATE SavedStoreModel
SET storePosition =:secondItemPosition
WHERE storePosition =:firstItemPosition,
storePosition =:firstItemPosition
WHERE storePosition =:secondItemPosition
</code>```

But this query is don't executable because of coma. A query like this works fine without where condition, but how to do this with multiple where?

答:
```<code>UPDATE SavedStoreModel
SET storePosition = case when storePosition = :firstItemPosition
                         then :secondItemPosition
                         else :firstItemPosition
                    end
WHERE storePosition in (:firstItemPosition, :secondItemPosition)
</code>```

Title: Multiple set wise where

Body:
I want to change two fields in one table with one query. It's looks like this

UPDATE SavedStoreModel
SET storePosition =:secondItemPosition
WHERE storePosition =:firstItemPosition,
storePosition =:firstItemPosition
WHERE storePosition =:secondItemPosition

But this query is don't executable because of coma. A query like this works fine without where condition, but how to do this with multiple where?


问:
Android application with camera2 library crash on start for SDK19
I use androidx.camera.camera2 library in my application. This library for SDK 21 and greater. But i want allow users start application for SDK 19 without camera2 support. I check SDK version in my code, but application crash on start. Can i exclude camera2 from dependencies for old SDK?</p>

```<code>05-30 12:13:42.318 2000-2000/com.myapp.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.android, PID: 2000
java.lang.NoClassDefFoundError: android.util.Size
    at androidx.camera.camera2.impl.Camera2DeviceSurfaceManager.<clinit>(Camera2DeviceSurfaceManager.java:53)
    at androidx.camera.camera2.Camera2AppConfig.create(Camera2AppConfig.java:58)
    at androidx.camera.camera2.impl.Camera2Initializer.onCreate(Camera2Initializer.java:44)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
    at android.app.ActivityThread.installProvider(ActivityThread.java:4790)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4385)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4325)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I recently stumbled into the same issue.
Diving deep into the CameraX code I found that CameraX is initialized in app startup through a content provider. Here is the content provider code where CameraX is being initialized.

```<code>public final class Camera2Initializer extends ContentProvider {
    private static final String TAG = "Camera2Initializer";
    @Override
    public boolean onCreate() {
        Log.d(TAG, "CameraX initializing with Camera2 ...");
        CameraX.init(getContext(), Camera2AppConfig.create(getContext()));
        return false;
    }
}
</code>```

Im not very familiar with content providers but my first taught was, this is add at the manifest level? And indeed I was right.
Looking at there manifest I found this

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidx.camera.camera2">
    <application>
        <provider
            android:name=".Camera2Initializer"
            android:authorities="${applicationId}.camerax-init"
            android:exported="false"
            android:initOrder="100"
            android:multiprocess="true" />
    </application>
</manifest>
</code>```

There manifest gets merged into ours which will include this content provider which in the other hand initializes CameraX, we want to avoid this. So one possible way of doing so is creating our own empty content provider and adding it to our manifest with the same name. This will override there content provider.
You can look into
https://developer.android.com/studio/build/manifest-merge
 for more detail about manifest merging.

So now with there content provider overriden hopefully you can call
CameraX.init(getContext(), Camera2AppConfig.create(getContext()));
only when the feature gets called and not on app startup.

Im hoping this gets fixed in later versions and allows us to initialize cameraX when we want to.

Body:
I use androidx.camera.camera2 library in my application. This library for SDK 21 and greater. But i want allow users start application for SDK 19 without camera2 support. I check SDK version in my code, but application crash on start. Can i exclude camera2 from dependencies for old SDK?

05-30 12:13:42.318 2000-2000/com.myapp.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.android, PID: 2000
java.lang.NoClassDefFoundError: android.util.Size
    at androidx.camera.camera2.impl.Camera2DeviceSurfaceManager.<clinit>(Camera2DeviceSurfaceManager.java:53)
    at androidx.camera.camera2.Camera2AppConfig.create(Camera2AppConfig.java:58)
    at androidx.camera.camera2.impl.Camera2Initializer.onCreate(Camera2Initializer.java:44)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
    at android.app.ActivityThread.installProvider(ActivityThread.java:4790)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4385)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4325)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

Body:
I recently stumbled into the same issue.
Diving deep into the CameraX code I found that CameraX is initialized in app startup through a content provider. Here is the content provider code where CameraX is being initialized.

public final class Camera2Initializer extends ContentProvider {
    private static final String TAG = "Camera2Initializer";
    @Override
    public boolean onCreate() {
        Log.d(TAG, "CameraX initializing with Camera2 ...");
        CameraX.init(getContext(), Camera2AppConfig.create(getContext()));
        return false;
    }
}

Im not very familiar with content providers but my first taught was, this is add at the manifest level? And indeed I was right.
Looking at there manifest I found this

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidx.camera.camera2">
    <application>
        <provider
            android:name=".Camera2Initializer"
            android:authorities="${applicationId}.camerax-init"
            android:exported="false"
            android:initOrder="100"
            android:multiprocess="true" />
    </application>
</manifest>

There manifest gets merged into ours which will include this content provider which in the other hand initializes CameraX, we want to avoid this. So one possible way of doing so is creating our own empty content provider and adding it to our manifest with the same name. This will override there content provider.
You can look into
https://developer.android.com/studio/build/manifest-merge
 for more detail about manifest merging.

So now with there content provider overriden hopefully you can call
CameraX.init(getContext(), Camera2AppConfig.create(getContext()));
only when the feature gets called and not on app startup.

Im hoping this gets fixed in later versions and allows us to initialize cameraX when we want to.


问:
Use AsyncStorage for loading user data in react native
I'm new with react native and I'm trying to write a to do application. I'm using AsyncStorage to store the tasks and then I want to load them each time user opens the app. Here you may see some of my codes:

//Main.js

```<code>import React from 'react';
import {
    StyleSheet ,
     Text,
     View,
     TextInput,
     ScrollView,
     TouchableOpacity,
     KeyboardAvoidingView,
     AsyncStorage
    } from 'react-native'
import Note from './Note'
   export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: '',
      dueDate: ''
    }
  }
  async saveUserTasks(value) {
    try {
      await AsyncStorage.setItem('@MySuperStore:userTask',JSON.stringify(value));
    } catch (error) {
      console.log("Error saving data" + error);
    }
  }
   getUserTasks = async() =>{
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:userTask');
      if (value !== null){
        this.state.noteArray = JSON.parse(value)
     }
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

render() {
  this.getUserTasks()
  // This is where I handle each item for my scrollview which I copied from a toturial and I have issues here.
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      deleteMethod={ () => this.deleteNote(key)}
      goToDetailPage= {() => this.goToNoteDetail(key)}
       />
    });
    const { navigation } = this.props;
    return(
      <KeyboardAvoidingView behavior='padding' style={styles.keyboard}>
        <View style={styles.container}>
            <ScrollView style={styles.scrollContainer}>
                {notes}
            </ScrollView>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
   </KeyboardAvoidingView>
      );
    }
    addNote(){
      if (this.state.noteText){
        var d = new Date();
        this.state.noteArray.push({
        'creationDate': d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDay(), 'taskName': this.state.noteText,'dueDate':'YYYY/MM/DD'
        });
        this.setState({noteArray:this.state.noteArray})
        this.setState({noteText: ''});
        this.saveUserTasks(this.state.noteArray)
      }
    }
    deleteNote(key){
      this.state.noteArray.splice(key,1);
      this.setState({noteArray: this.state.noteArray})
      this.saveUserTasks(this.state.noteArray)
    }
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('DetailsScreen', {
        selectedTask: this.state.noteArray[key],
      });
    }
}
//Styles goes here
</code>```

My problem is that when I open the app I can't see the list from storage until I try to type something in my textInput, even without adding it. which I don't understand why.

答:
You need to use setState not this.state.noteArray</p>

```<code>if (value !== null){
    this.setState({ noteArray: JSON.parse(value)});
 }
</code>```

Body:
I'm new with react native and I'm trying to write a to do application. I'm using AsyncStorage to store the tasks and then I want to load them each time user opens the app. Here you may see some of my codes:

//Main.js

import React from 'react';
import {
    StyleSheet ,
     Text,
     View,
     TextInput,
     ScrollView,
     TouchableOpacity,
     KeyboardAvoidingView,
     AsyncStorage
    } from 'react-native'
import Note from './Note'
   export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: '',
      dueDate: ''
    }
  }
  async saveUserTasks(value) {
    try {
      await AsyncStorage.setItem('@MySuperStore:userTask',JSON.stringify(value));
    } catch (error) {
      console.log("Error saving data" + error);
    }
  }
   getUserTasks = async() =>{
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:userTask');
      if (value !== null){
        this.state.noteArray = JSON.parse(value)
     }
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

render() {
  this.getUserTasks()
  // This is where I handle each item for my scrollview which I copied from a toturial and I have issues here.
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      deleteMethod={ () => this.deleteNote(key)}
      goToDetailPage= {() => this.goToNoteDetail(key)}
       />
    });
    const { navigation } = this.props;
    return(
      <KeyboardAvoidingView behavior='padding' style={styles.keyboard}>
        <View style={styles.container}>
            <ScrollView style={styles.scrollContainer}>
                {notes}
            </ScrollView>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
   </KeyboardAvoidingView>
      );
    }
    addNote(){
      if (this.state.noteText){
        var d = new Date();
        this.state.noteArray.push({
        'creationDate': d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDay(), 'taskName': this.state.noteText,'dueDate':'YYYY/MM/DD'
        });
        this.setState({noteArray:this.state.noteArray})
        this.setState({noteText: ''});
        this.saveUserTasks(this.state.noteArray)
      }
    }
    deleteNote(key){
      this.state.noteArray.splice(key,1);
      this.setState({noteArray: this.state.noteArray})
      this.saveUserTasks(this.state.noteArray)
    }
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('DetailsScreen', {
        selectedTask: this.state.noteArray[key],
      });
    }
}
//Styles goes here

My problem is that when I open the app I can't see the list from storage until I try to type something in my textInput, even without adding it. which I don't understand why.

Body:
You need to use setState not this.state.noteArray

if (value !== null){
    this.setState({ noteArray: JSON.parse(value)});
 }


问:
New valid date without time in javascript
I am using google charts and they require real dates for zoom in out etc.

So I have new Date('31/05/2019') that converts into same date with 02AM.

Is there a way to force 00:00:00 as time or to even use just date without time?

Now you may ask myself why would I do that when they have format option, well I need to use SteppedAreaChart that has problem with first day as it it showing that point on 0 axis.

To fix that I needed to add type="category", but now format doesn't work. It skips format option and puts the default one.

```<code>hAxis: {
  format: 'dd/MM/yy',
  type: 'category'
}
</code>```

I am getting this date from backend: 2019-05-31, And from that I get: May 31, 2019, 2:00:00 AM

答:
You can change the date to new Date('05/31/2019').

Or can you change the date to a timestamp like this and plot it

```<code>var date = new Date('05/31/2019');
timestamp = date.getTime();
</code>```

Body:
I am using google charts and they require real dates for zoom in out etc.

So I have new Date('31/05/2019') that converts into same date with 02AM.

Is there a way to force 00:00:00 as time or to even use just date without time?

Now you may ask myself why would I do that when they have format option, well I need to use SteppedAreaChart that has problem with first day as it it showing that point on 0 axis.

To fix that I needed to add type="category", but now format doesn't work. It skips format option and puts the default one.

hAxis: {
  format: 'dd/MM/yy',
  type: 'category'
}

I am getting this date from backend: 2019-05-31, And from that I get: May 31, 2019, 2:00:00 AM

Body:
You can change the date to new Date('05/31/2019').

Or can you change the date to a timestamp like this and plot it

var date = new Date('05/31/2019');
timestamp = date.getTime();


问:
How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?
I am new to the whole nodejs/reactjs world so apologies if my question sounds silly. I am currently playing around with reactabular.js.

Whenever I do a npm start it always runs on localhost:8080.

How do I change it to run on 0.0.0.0:8080 to make it publicly accessible? I have been trying to read the source code in the above repo but failed to find the file which sets this setting.

Also, to add to that - how do I make it run on port 80 if that is at all possible?

答:
I tried this to easily use another port:</p>

```<code>PORT=80 npm run dev
</code>```

Body:
I tried this to easily use another port:

PORT=80 npm run dev


问:
Access element
 with jQuery
I've this code:

```<code><div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="#" data-action="copy-link">Copy link</a>
    </div>
    ```
        Lorem ipsum...
    ```
</div>
</code>```

How can I access to ```</code> tag ?</p>

<p>What I've tried:</p>

```$('[data-action="copy-link"]').on('click', function(event) {
    var code = $(this).find('pre').css('color', 'red');
});
```

Thanks.

答:
Below code is working, try this</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
    $('[data-action="copy-link"]').on('click', function(event) {
        var code = $('.modal-body pre').css('color', 'red');
    });
    })
</script>
<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="javascript:void(0);" data-action="copy-link">Copy link</a>
    </div>
    ```
        Lorem ipsum...
    ```
</div>
</code>```

Title: Access element <pre> with jQuery

Body:
I've this code:

...

        Copy link

        Lorem ipsum...

How can I access to
 tag ?

What I've tried:

$('[data-action="copy-link"]').on('click', function(event) {
    var code = $(this).find('pre').css('color', 'red');
});

Thanks.

Body:
Below code is working, try this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
    $('[data-action="copy-link"]').on('click', function(event) {
        var code = $('.modal-body pre').css('color', 'red');
    });
    })
</script>
<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="javascript:void(0);" data-action="copy-link">Copy link</a>
    </div>
    <pre>
        Lorem ipsum...
    </pre>
</div>


问:
How to merger this sql server query?
I have this query

```<code>select count(*) as COUNT_A, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NOT NULL
group by datepart(yyyy, [Tgl_Perolehan])
</code>```

and this

```<code>select count(*) as COUNT_B, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NULL
group by datepart(yyyy, [Tgl_Perolehan])
</code>```

The difference is only IS NOT NULL and IS NULL and the result is

+---------+--------+
| COUNT_A  |  year  |
+----------+--------+
| 12       | 1991   |
| 15       | 1993   |
| 24       | 1998   |
+----------+--------+

I want make like this

+---------+---------+--------+
| COUNT_A  | COUNT_B |  year  |
+----------+---------+--------+
| 12       | 23      | 1991   |
| 15       | 33      | 1993   |
| 24       | 13      | 1998   |
+----------+---------+--------+

and I try like this

```<code>select (select count(*) as COUNT_A, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NOT NULL
group by datepart(yyyy, [Tgl_Perolehan])),
(select count(*) as COUNT_B, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NULL
group by datepart(yyyy, [Tgl_Perolehan]))
</code>```

But didn't fix my problem.
I have use CASE WHEN, but still didn't fix the problem.
How to merge and fix their?
Thanks.

答:
Try this-</p>

```<code>SELECT
SUM(CASE WHEN ertifikat_Nomor IS NOT NULL THEN 1 ELSE 0 END) AS COUNT_A,
SUM(CASE WHEN Sertifikat_Nomor IS NULL THEN 1 ELSE 0 END)AS COUNT_B,
DATEPART(yyyy, [Tgl_Perolehan]) AS [year]
FROM[table_name]
GROUP BY DATEPART(yyyy, [Tgl_Perolehan])
</code>```

Title: How to merger this sql server query?

Body:
I have this query

select count(*) as COUNT_A, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NOT NULL
group by datepart(yyyy, [Tgl_Perolehan])

and this

select count(*) as COUNT_B, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NULL
group by datepart(yyyy, [Tgl_Perolehan])

The difference is only IS NOT NULL and IS NULL and the result is

+---------+--------+
| COUNT_A  |  year  |
+----------+--------+
| 12       | 1991   |
| 15       | 1993   |
| 24       | 1998   |
+----------+--------+

I want make like this

+---------+---------+--------+
| COUNT_A  | COUNT_B |  year  |
+----------+---------+--------+
| 12       | 23      | 1991   |
| 15       | 33      | 1993   |
| 24       | 13      | 1998   |
+----------+---------+--------+

and I try like this

select (select count(*) as COUNT_A, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NOT NULL
group by datepart(yyyy, [Tgl_Perolehan])),
(select count(*) as COUNT_B, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name]
where Sertifikat_Nomor IS NULL
group by datepart(yyyy, [Tgl_Perolehan]))

But didn't fix my problem.
I have use CASE WHEN, but still didn't fix the problem.
How to merge and fix their?
Thanks.

Body:
Try this-

SELECT
SUM(CASE WHEN ertifikat_Nomor IS NOT NULL THEN 1 ELSE 0 END) AS COUNT_A,
SUM(CASE WHEN Sertifikat_Nomor IS NULL THEN 1 ELSE 0 END)AS COUNT_B,
DATEPART(yyyy, [Tgl_Perolehan]) AS [year]
FROM[table_name]
GROUP BY DATEPART(yyyy, [Tgl_Perolehan])


答:
In the standard sprintf() function (and the other printf()-like functions), the %s specifier doesn't work with C++ stringss; it only works with C-style strings. Try _UserDir.c_str(), which gives you a const char * that points to the internal array of the string and can therefore be used with many C functions.

If current_path() returns something that is not a (possibly const) pointer to char or unsigned char, you need to convert that value too.

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release


问:
How to make first row have specific name and image?
I have application which populate uitableview with some properties received from an api call. So my question is how i can make first cell for example have name "Back" and some image and after that start populate other cells with properties received from api call? If someone can post some example it would be awesome.

答:
Maybe what you want is not a first cell that can be scrolled out together with the other cells, but a header that stays at its place while the other cells scroll. If this is the case, you could use:

```<code>override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Section \(section)"
}
</code>```

This creates a simple text header.

If you want to use a custom header, you had to define a header view:

```<code>override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView() // Here you had to use a view that you set up earlier
    return view
}
</code>```

These headers can be created for every section of your table.

EDIT:

I implemented a simple tableView project, and added the code provided by Simke in his/her comments.

```<code>import Foundation
import UIKit

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
        cell.textLabel?.text = "Title"
        return cell
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?  {
        let vw = UIView()
        vw.frame.size.height = 40
        let btnBk = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: vw.frame.height))
        btnBk.backgroundColor = .blue
        btnBk.setTitle("back", for: .normal)
        btnBk.addTarget(self, action: #selector(btnAct), for: .touchUpInside)
        vw.addSubview(btnBk)
        return vw
    }

    @objc func btnAct(sender: UIButton!){
        print("a")
    }
}
</code>```

Here, the button in the header view works, i.e. "a" is printed in the logs.

Body:
Maybe what you want is not a first cell that can be scrolled out together with the other cells, but a header that stays at its place while the other cells scroll. If this is the case, you could use:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Section \(section)"
}

This creates a simple text header.

If you want to use a custom header, you had to define a header view:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView() // Here you had to use a view that you set up earlier
    return view
}

These headers can be created for every section of your table.

EDIT:

I implemented a simple tableView project, and added the code provided by Simke in his/her comments.

import Foundation
import UIKit

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
        cell.textLabel?.text = "Title"
        return cell
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?  {
        let vw = UIView()
        vw.frame.size.height = 40
        let btnBk = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: vw.frame.height))
        btnBk.backgroundColor = .blue
        btnBk.setTitle("back", for: .normal)
        btnBk.addTarget(self, action: #selector(btnAct), for: .touchUpInside)
        vw.addSubview(btnBk)
        return vw
    }

    @objc func btnAct(sender: UIButton!){
        print("a")
    }
}

Here, the button in the header view works, i.e. "a" is printed in the logs.


问:
How to fix my layout so my nav bar doesn´t hide some content after linking to the desired section
my navbar is set to fixed, but everytime i press on e.g. home, it doesnt scroll to the most top, the site is just a little under the maximum you can possibly scroll to the top, this makes my H1 beeing covered partly by my navbar.

I've tried different settings for my nav bar like static etc.

I've tried to change the padding of my nav bar which didnt helped either.

I've tried to achieve better results with different min heights for the sections, currently its set to 85%

```<code><!-- Header -->
<header>

<div id="logo">
    <img src="img/111.jpg"="Kurzwarenmobil">
</div>

<nav>

    <ul>
        <a href="#home"><li>home</li></a>
        <a href="#about"><li>Über mich</li></a>
        <a href="#DasKurzwarenmobil"><li>Das Kurzwarenmobil</li></a>
        <a href="#Kontakt"><li>Kontakt</li></a>
    </ul>
</nav>
</code>```

Kurzwarenmobil

H.S. Schneiderbedarf

html, body{margin: 0; padding: 0; height: 100%; text-align: center;}
section { min-height: 85%}
a {text-decoration: none;}
li {list-style-type: none;}

header { width: 100%; height: 65px; position: fixed; top:0; left: 0;

background: #FEFCFB; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) ; z-index:
1; }

logo {

width: 140px;
float: left;
margin: 10px 0 0 -10px
}

home{

background: url(../img/landing.jpg);
background-position: center center;
background-size: cover;
background-attachment:  fixed;
}

home h1 {

margin: 62px auto 0 auto;
font-size: 110px}

home h2 {

margin: 50 auto 0 auto;
font-size: 25px;

}

home img  {

width: 32px;
margin-top: 150px;
opacity: 0.7;
}

home img:hover {

opacity: 1;
}

home {min-height: 100%}

I want my Nav bar to Navigate to the most top part of the site, which means that there is no more space to scroll to the top. right now when i click on "home" on the nav bar, half of my H1 is covered by the navbar because it´s not scrolled up enough

答:
html, body{margin: 0; padding: 0; height: 100%; text-align: center;}
section { min-height: 85%}
a {text-decoration: none;}
li {list-style-type: none;}

h1, h2, h3,a { font-family: "Roboto Slab", sans-serif ; font-weight: 500; color: #494949;text-transform: uppercase;}
h1, h2 {color: white;
text-shadow: 0 -1px #999999, 1px 0 #999999, 0 1px #999999, -1px 0 #999999;}
h3 {font-size: 40px; padding-top: 0%;margin-bottom: 5px;}
h4, p {font-family: "Roboto Slab", serif; color:#494949;}

/* h1 padding as solution for the "jump to home" problem :h1 {padding-top: 2.5%} *******/

hr {width: 100px;height: 3px;background: #494949;border: 0;margin: 0 auto 40px auto;}
#logo,li,img,.button {transition: all 300ms; -webkit-transition: all 300ms; -moz-transition: all 300ms; -o-transition: all 300ms}

/* HEADER ********************************/
header { width: 100%; height: 65px; position: fixed; top:0; left: 0; background: #FEFCFB; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) ; z-index: 1; }

 #logo {

 width: 140px;
 float: left;
 margin: 10px 0 0 -10px
 }

#logo img{

 width: 56%;

}

#logo:hover {
 opacity: 0.5;
}

header nav {

 float:right;
 margin:6px 50px 0 0;
}

header nav ul li {
 float:left;
 margin-left: 25px;
}

header nav ul li a {
 font-size: 16px
}

header nav ul li:hover {
 padding-top: 5px;
}
/* Header

#headerino {
 min-height: 10%
}
 ********************************/

/* Home ********************************/

#home{
 background: url(../img/landing.jpg);
 background-position: center center;
 background-size: cover;
 background-attachment:  fixed;
 }

#home h1 {
 margin: 0;
  padding-top:60px;
 font-size: 110px}

#home h2 {
 margin: 0 auto 0 auto;
 font-size: 25px;

}

#home img  {
 width: 32px;
 margin-top: 150px;
 opacity: 0.7;
}
#home img:hover {
 opacity: 1;
}
#home {min-height: 100%}
/* About ********************************/

#about img {
 width: 240px;
}

#about h4{
 font-size: 15px;
}

#about p{
 width: 70%;
 margin:0 auto 0 auto;

}

#about img:hover {
 transform: scale(1.1);
}

/* Kurzwarenmobil ********************************/

#DasKurzwarenmobil img {
 width: 400px;
 border-radius: 3px;

}
#DasKurzwarenmobil {
 background-color: #D3D3D3;
 opacity: 1;
}
#DasKurzwarenmobil p{
 width: 70%;
 margin:0 auto 0 auto;
 }

#DasKurzwarenmobil img:hover {
 transform: scale(1.1);
}

/* Ich bringe den Großhandel zu ihnen ********************************/
#Großhandel img {
 width: 400px;
 border-radius: 3px;}

 #Großhandel img:hover {
 transform: scale(1.1);
}

#Großhandel p{
 width: 70%;
 margin:0 auto 0 auto;
}
/* Service ********************************/
#service img {
 width: 400px;
 border-radius: 3px;
}

#service {
 background-color: #D3D3D3;
 opacity: 1;
}
#service img:hover {
 transform: scale(1.1);}

#service p{
 width: 70%;
 margin:0 auto 0 auto;
 }

/* Contact  ********************************/

form input, textarea {
font-family: "Roboto Slab", serif;
font-size: 15px;
margin-bottom: 10px;
border-radius: 10px;
border: 2px solid;
border-color: #494949;
outline: none;
}

form input {

 width: 552px;
 height: 30px

}

form textarea {
 width: 552px;
 height: 200px;
 resize: none;
 border-color: #494949;
}

.input_text {
 color:#494949 ;
 padding-left: 10px;
}

.button {

 width: 566px;
 height: 50px;
 background-color: #f0f0f0;
 color: #494949;
}

.button:hover {

 background-color: #494949;
 color: #f0f0f0;

}

/* Footer  ********************************/

footer {

width: 100%;
height: 70px;
background-color: #3f3f3f;
}

footer p {
 font-size: 12px;
 color: #f0f0f0;
 padding-top:30px;
}

/* Media Queries ********************************/

/* Tablets ********************************/

@media screen and (max-width:1024px){

#logo {
 width: 100px;
 margin-top: 5px;
}

header nav {
 margin-top: 10px;

}
header nav ul li {
 font-size: 12px;
}

#home h1 {
 font-size: 65px;

}

#home h2 {
 font-size: 22px;
}
h3 {padding-top: 12%
}

}
/* Mobile********************************/

@media screen and (max-width:480px) {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>H.S. Schneiderbedarf &#124 Kurzwarenmobil</title>
  <link rel="stylesheet" type="text/css" href="css/fontawesome.min.css">
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">

  </head>

 <!-- Header -->
   <header>

    <div id="logo">
    <img src="img/111.jpg"="Kurzwarenmobil">
    </div>

    <nav>

     <ul>
      <li>home</li>
      <li>Über mich</li>
      <li>Das Kurzwarenmobil</li>
      <li>Kontakt</li>
     </ul>
    </nav>
   </header>

   <!-- Home -->
<section id="home">
     <h1>Kurzwarenmobil</h1>
     <h2>H.S. Schneiderbedarf</h2>

     <img src="img/pfeil.png" alt="arrow">

</section>

    <!-- Über mich -->

<section id="about">
    <h3>Über mich</h3>
    <hr>
    <img src="img/avatar.png" alt="Hüllis face">
    <h4>H.S Schneiderbedarf<h4>
    <p>
     Ich Bin Hülya S. und habe mittlerweile mehr als ein Jahrzent Erfahrung im Schneider- sowie Kurzwarengeschäft angesammelt.
    Meine Leidenschaft und Faszinierung der Branche gegenüber brachten mich
    nach jahrelangem arbeiten als Näherin in verschiedenen Unternehmen dazu, mich in dieser Branche selbstständig zu machen

    Nachdem die Entscheidung der Selbstständigkeit gefällt war, fing die Arbeit erst richtig an. Nach langem Konzeptionieren, Umsetzen, Verfeinern, Scheitern und wieder aufstehen war letzendlich die Idee des "Kurzwarenmobils" geboren.
    <br>

    Mittlerweile erstreckt sich mein Kundenstamm weit über die Grenzen Hannovers, den Heimatort des Kurzwarenmobils aus. Mittlerweile beläuft sich das Geschäft auf viele große sowie kleine Städte Norddeutschlands, und die Kapazitätsgrenze ist noch lange nicht erreicht.

   </p>
</section>

   <!-- Kurzwarenmobil -->

<section id="DasKurzwarenmobil">
    <br>
    <h3>Das Kurzwarenmobil</h3>
    <hr>
    <img src="img/333.jpg" alt="INSERT IMG Hülli WAGEN+ Sie">
    <h4>Was Ist das Kurzwarenmobil?</h4>
    <p>
     Das Kurzwarenmobil ist mein Transporter, mit dem ich täglich verschiedene Städte  Deutschlands besuche und meinen über 300 Kunden, die
    benötigten Utensilien und Stoffe direkt zu ihren Läden liefere.

    </p>
    <br>
    <br>
</section>

   <br>

  <!-- großhandel--->
<section id="Großhandel">

 <h4>Ich bringe den Großhandel zu ihnen</h4>

 <img src="img/4444.jpg" alt="Großhandel">
 <br>
 <br>

 <p>

 Da das Hauptgeschäft des Kurzwarenmobils auf die Mobilität und große Auswahl ausgelegt ist  und ich die Waren direkt vom Großhandel beziehe,
 bin ich in der Lage die beste Ware zum günstigen Preis anzubieten. wodurch sie selbstverständlich bares Geld sparen können!
 <br>
 Umfangreiches Angebot und stets die aktuellsten Waren der Kurzwarenwelt, Ob Knöpfe und
 Reißverschlüsse für individuelle Modeschöpfungen, Handarbeitsgarne oder modische
 Bänder und Kordeln für kreative Deko-Ideen: Das Kurzwarenmobil führt stehts eine Große Auswahl an hochwertigen
 Arbeitsmaterialien und das ohne Einschränkung und in voller Ausführung direkt vor ihrer Tür!
 Durch regelmäßige Besuche und kostenloser Anfahrt können sie dadurch Einsparungen in ihren Lagerhaltungs- bzw Lieferungskosten einsparen.

 </p>

</section>

  <!-- individueller service-->

<section id="service">
 <br>

 <h4>Individueller Service</h4>

 <img src="img/222.jpg" alt="Sortiment innen">
 <br>
 <br>

 <p>

 Durch die Natur meiner Arbeit haben sie nicht nur den Vorteil, dass ich ihnen alle benötigten Utensilien bis vor die Türe bringe, sondern auch das Privileg sich am gesamten Katalog des Kurzwarenmobils vor Ort inspirieren und individuell beraten zu lassen. Fehlerhafte Bestellung gehören damit der vergangenheit an!

 </p>
 <br>

</section>

    <!-- Contact -->

<section id="Kontakt">
   <h3>Kontakt</h3>
   <hr>

   <form>
   <input class="input_text" type="email" tabindex="1" Placeholder="E-mail" ><br><br>
   <input class="input_text" type="text" tabindex="2" Placeholder="Betreff" ><br><br>
      <textarea class="input_text" tabindex="3" Placeholder="Nachricht" ></textarea> <br><br>
       <input class="button" type="submit">

   </form>
</section>

    <!-- Footer -->

  <footer>
   <p>
    © 2018-2019 B.Ertürk, All rights reserved
   </p>
  </footer>

  <script src="https://code.jquery.com/jquery-1.12.4.min.js"integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous">

  </script>
  <script
  src="js/mobile-menu.js" type="text/javascript">
   </script>

   </body>
 </html></code>```

this is it! solved by removing margin on your home h1 and adding padding!
you should alway use remove padding and margin on all elements because by default they got some margin and padding values!

Body:
my navbar is set to fixed, but everytime i press on e.g. home, it doesnt scroll to the most top, the site is just a little under the maximum you can possibly scroll to the top, this makes my H1 beeing covered partly by my navbar.

I've tried different settings for my nav bar like static etc.

I've tried to change the padding of my nav bar which didnt helped either.

I've tried to achieve better results with different min heights for the sections, currently its set to 85%

home

Über mich

Das Kurzwarenmobil

Kontakt

Kurzwarenmobil

H.S. Schneiderbedarf

html, body{margin: 0; padding: 0; height: 100%; text-align: center;}
section { min-height: 85%}
a {text-decoration: none;}
li {list-style-type: none;}

header { width: 100%; height: 65px; position: fixed; top:0; left: 0;

background: #FEFCFB; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) ; z-index:
1; }

logo {

width: 140px;
float: left;
margin: 10px 0 0 -10px
}

home{

background: url(../img/landing.jpg);
background-position: center center;
background-size: cover;
background-attachment:  fixed;
}

home h1 {

margin: 62px auto 0 auto;
font-size: 110px}

home h2 {

margin: 50 auto 0 auto;
font-size: 25px;

}

home img  {

width: 32px;
margin-top: 150px;
opacity: 0.7;
}

home img:hover {

opacity: 1;
}

home {min-height: 100%}

I want my Nav bar to Navigate to the most top part of the site, which means that there is no more space to scroll to the top. right now when i click on "home" on the nav bar, half of my H1 is covered by the navbar because it´s not scrolled up enough

Body:
html, body{margin: 0; padding: 0; height: 100%; text-align: center;}
section { min-height: 85%}
a {text-decoration: none;}
li {list-style-type: none;}

h1, h2, h3,a { font-family: "Roboto Slab", sans-serif ; font-weight: 500; color: #494949;text-transform: uppercase;}
h1, h2 {color: white;
text-shadow: 0 -1px #999999, 1px 0 #999999, 0 1px #999999, -1px 0 #999999;}
h3 {font-size: 40px; padding-top: 0%;margin-bottom: 5px;}
h4, p {font-family: "Roboto Slab", serif; color:#494949;}

/* h1 padding as solution for the "jump to home" problem :h1 {padding-top: 2.5%} *******/

hr {width: 100px;height: 3px;background: #494949;border: 0;margin: 0 auto 40px auto;}
#logo,li,img,.button {transition: all 300ms; -webkit-transition: all 300ms; -moz-transition: all 300ms; -o-transition: all 300ms}

/* HEADER ********************************/
header { width: 100%; height: 65px; position: fixed; top:0; left: 0; background: #FEFCFB; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) ; z-index: 1; }

 #logo {

 width: 140px;
 float: left;
 margin: 10px 0 0 -10px
 }

#logo img{

 width: 56%;

}

#logo:hover {
 opacity: 0.5;
}

header nav {

 float:right;
 margin:6px 50px 0 0;
}

header nav ul li {
 float:left;
 margin-left: 25px;
}

header nav ul li a {
 font-size: 16px
}

header nav ul li:hover {
 padding-top: 5px;
}
/* Header

#headerino {
 min-height: 10%
}
 ********************************/

/* Home ********************************/

#home{
 background: url(../img/landing.jpg);
 background-position: center center;
 background-size: cover;
 background-attachment:  fixed;
 }

#home h1 {
 margin: 0;
  padding-top:60px;
 font-size: 110px}

#home h2 {
 margin: 0 auto 0 auto;
 font-size: 25px;

}

#home img  {
 width: 32px;
 margin-top: 150px;
 opacity: 0.7;
}
#home img:hover {
 opacity: 1;
}
#home {min-height: 100%}
/* About ********************************/

#about img {
 width: 240px;
}

#about h4{
 font-size: 15px;
}

#about p{
 width: 70%;
 margin:0 auto 0 auto;

}

#about img:hover {
 transform: scale(1.1);
}

/* Kurzwarenmobil ********************************/

#DasKurzwarenmobil img {
 width: 400px;
 border-radius: 3px;

}
#DasKurzwarenmobil {
 background-color: #D3D3D3;
 opacity: 1;
}
#DasKurzwarenmobil p{
 width: 70%;
 margin:0 auto 0 auto;
 }

#DasKurzwarenmobil img:hover {
 transform: scale(1.1);
}

/* Ich bringe den Großhandel zu ihnen ********************************/
#Großhandel img {
 width: 400px;
 border-radius: 3px;}

 #Großhandel img:hover {
 transform: scale(1.1);
}

#Großhandel p{
 width: 70%;
 margin:0 auto 0 auto;
}
/* Service ********************************/
#service img {
 width: 400px;
 border-radius: 3px;
}

#service {
 background-color: #D3D3D3;
 opacity: 1;
}
#service img:hover {
 transform: scale(1.1);}

#service p{
 width: 70%;
 margin:0 auto 0 auto;
 }

/* Contact  ********************************/

form input, textarea {
font-family: "Roboto Slab", serif;
font-size: 15px;
margin-bottom: 10px;
border-radius: 10px;
border: 2px solid;
border-color: #494949;
outline: none;
}

form input {

 width: 552px;
 height: 30px

}

form textarea {
 width: 552px;
 height: 200px;
 resize: none;
 border-color: #494949;
}

.input_text {
 color:#494949 ;
 padding-left: 10px;
}

.button {

 width: 566px;
 height: 50px;
 background-color: #f0f0f0;
 color: #494949;
}

.button:hover {

 background-color: #494949;
 color: #f0f0f0;

}

/* Footer  ********************************/

footer {

width: 100%;
height: 70px;
background-color: #3f3f3f;
}

footer p {
 font-size: 12px;
 color: #f0f0f0;
 padding-top:30px;
}

/* Media Queries ********************************/

/* Tablets ********************************/

@media screen and (max-width:1024px){

#logo {
 width: 100px;
 margin-top: 5px;
}

header nav {
 margin-top: 10px;

}
header nav ul li {
 font-size: 12px;
}

#home h1 {
 font-size: 65px;

}

#home h2 {
 font-size: 22px;
}
h3 {padding-top: 12%
}

}
/* Mobile********************************/

@media screen and (max-width:480px) {

}

 <!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>H.S. Schneiderbedarf &#124 Kurzwarenmobil</title>
  <link rel="stylesheet" type="text/css" href="css/fontawesome.min.css">
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">

  </head>

 <!-- Header -->
   <header>

    <div id="logo">
    <img src="img/111.jpg"="Kurzwarenmobil">
    </div>

    <nav>

     <ul>
      <a href="#home"><li>home</li></a>
      <a href="#about"><li>Über mich</li></a>
      <a href="#DasKurzwarenmobil"><li>Das Kurzwarenmobil</li></a>
      <a href="#Kontakt"><li>Kontakt</li></a>
     </ul>
    </nav>
   </header>

   <!-- Home -->
<section id="home">
     <h1>Kurzwarenmobil</h1>
     <h2>H.S. Schneiderbedarf</h2>
     <a href="#about">
     <img src="img/pfeil.png" alt="arrow">
     </a>
</section>

    <!-- Über mich -->

<section id="about">
    <h3>Über mich</h3>
    <hr>
    <img src="img/avatar.png" alt="Hüllis face">
    <h4>H.S Schneiderbedarf<h4>
    <p>
     Ich Bin Hülya S. und habe mittlerweile mehr als ein Jahrzent Erfahrung im Schneider- sowie Kurzwarengeschäft angesammelt.
    Meine Leidenschaft und Faszinierung der Branche gegenüber brachten mich
    nach jahrelangem arbeiten als Näherin in verschiedenen Unternehmen dazu, mich in dieser Branche selbstständig zu machen

    Nachdem die Entscheidung der Selbstständigkeit gefällt war, fing die Arbeit erst richtig an. Nach langem Konzeptionieren, Umsetzen, Verfeinern, Scheitern und wieder aufstehen war letzendlich die Idee des "Kurzwarenmobils" geboren.
    <br>

    Mittlerweile erstreckt sich mein Kundenstamm weit über die Grenzen Hannovers, den Heimatort des Kurzwarenmobils aus. Mittlerweile beläuft sich das Geschäft auf viele große sowie kleine Städte Norddeutschlands, und die Kapazitätsgrenze ist noch lange nicht erreicht.

   </p>
</section>

   <!-- Kurzwarenmobil -->

<section id="DasKurzwarenmobil">
    <br>
    <h3>Das Kurzwarenmobil</h3>
    <hr>
    <img src="img/333.jpg" alt="INSERT IMG Hülli WAGEN+ Sie">
    <h4>Was Ist das Kurzwarenmobil?</h4>
    <p>
     Das Kurzwarenmobil ist mein Transporter, mit dem ich täglich verschiedene Städte  Deutschlands besuche und meinen über 300 Kunden, die
    benötigten Utensilien und Stoffe direkt zu ihren Läden liefere.

    </p>
    <br>
    <br>
</section>

   <br>

  <!-- großhandel--->
<section id="Großhandel">

 <h4>Ich bringe den Großhandel zu ihnen</h4>

 <img src="img/4444.jpg" alt="Großhandel">
 <br>
 <br>

 <p>

 Da das Hauptgeschäft des Kurzwarenmobils auf die Mobilität und große Auswahl ausgelegt ist  und ich die Waren direkt vom Großhandel beziehe,
 bin ich in der Lage die beste Ware zum günstigen Preis anzubieten. wodurch sie selbstverständlich bares Geld sparen können!
 <br>
 Umfangreiches Angebot und stets die aktuellsten Waren der Kurzwarenwelt, Ob Knöpfe und
 Reißverschlüsse für individuelle Modeschöpfungen, Handarbeitsgarne oder modische
 Bänder und Kordeln für kreative Deko-Ideen: Das Kurzwarenmobil führt stehts eine Große Auswahl an hochwertigen
 Arbeitsmaterialien und das ohne Einschränkung und in voller Ausführung direkt vor ihrer Tür!
 Durch regelmäßige Besuche und kostenloser Anfahrt können sie dadurch Einsparungen in ihren Lagerhaltungs- bzw Lieferungskosten einsparen.

 </p>

</section>

  <!-- individueller service-->

<section id="service">
 <br>

 <h4>Individueller Service</h4>

 <img src="img/222.jpg" alt="Sortiment innen">
 <br>
 <br>

 <p>

 Durch die Natur meiner Arbeit haben sie nicht nur den Vorteil, dass ich ihnen alle benötigten Utensilien bis vor die Türe bringe, sondern auch das Privileg sich am gesamten Katalog des Kurzwarenmobils vor Ort inspirieren und individuell beraten zu lassen. Fehlerhafte Bestellung gehören damit der vergangenheit an!

 </p>
 <br>

</section>

    <!-- Contact -->

<section id="Kontakt">
   <h3>Kontakt</h3>
   <hr>

   <form>
   <input class="input_text" type="email" tabindex="1" Placeholder="E-mail" ><br><br>
   <input class="input_text" type="text" tabindex="2" Placeholder="Betreff" ><br><br>
      <textarea class="input_text" tabindex="3" Placeholder="Nachricht" ></textarea> <br><br>
       <input class="button" type="submit">

   </form>
</section>

    <!-- Footer -->

  <footer>
   <p>
    &copy; 2018-2019 B.Ertürk, All rights reserved
   </p>
  </footer>

  <script src="https://code.jquery.com/jquery-1.12.4.min.js"integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous">

  </script>
  <script
  src="js/mobile-menu.js" type="text/javascript">
   </script>

   </body>
 </html>

this is it! solved by removing margin on your home h1 and adding padding!
you should alway use remove padding and margin on all elements because by default they got some margin and padding values!


问:
How to fix "Xaml parsing failed"?
I'm using Visual Studio Enterprise 2017. When i try to run my UWP project on Mobile Emulator I'm getting "Xaml parse failed" error.
When i run it on "local machine" everything is ok. I didn't make any changes to xaml header from the beginning. Can anyone help me?

Image showing error below.
https://i.imgur.com/FL3Cr4K.jpg
https://i.imgur.com/65A2t9y.jpg

```<code><Page
    x:Class="KalkulatorBMI.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:KalkulatorBMI"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid Padding="10">
        <!--Padding - margines-->
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
            <!-- * zużywa co dostanie.-->
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0">
            <TextBlock Text="Trener persolany" Style="{ThemeResource CaptionTextBlockStyle}"/>
            <TextBlock Text="Użytkownik" Style="{ThemeResource HeaderTextBlockStyle}"/>
        </StackPanel>
        <StackPanel Grid.Row="1" >
            <ListBox Name="lbxUzytkownicy" HorizontalAlignment="Left" Width="150" Height="200" Margin="10" SelectedIndex="0"/>
            <Button Name="ButtonLoguj" Content="Loguj" Margin="10" Click="Click_Loguj"/>
            <StackPanel>
                <TextBlock Text="Nowy uzytkownik" Margin="10,0,0,5"/>
                <TextBox Name="TextboxNowy" Height="32" Width="138" Margin="10,0,0,0" HorizontalAlignment="Left"/>
                <TextBlock Name="TextboxZlaNazwa" Margin="10,5,0,0" Foreground="Red"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" >
                <Button Name="ButtonUtworz" Content="Dodaj użytkownika" Margin="10" Click="Click_Utworz"/>
                <Button Name="ButtonUsun" Content="Wyczyść listę" Margin="10" Click="Click_Usun"/>
            </StackPanel>
        </StackPanel>
        <StackPanel Grid.Row="2">
            <Button Name="ButtonZakoncz" Margin="10" Content="Zakończ"  Click="Click_Zakoncz" Foreground="Red"/>
        </StackPanel>
    </Grid>
</Page>
</code>```

答: Well, you need to check your app's target version & Min version first and make sure Mobile Emulator have this SDK version installed. if not, download if from here.</p>

Title: How to fix "Xaml parsing failed"?

Body:
I'm using Visual Studio Enterprise 2017. When i try to run my UWP project on Mobile Emulator I'm getting "Xaml parse failed" error.
When i run it on "local machine" everything is ok. I didn't make any changes to xaml header from the beginning. Can anyone help me?

Image showing error below.
https://i.imgur.com/FL3Cr4K.jpg
https://i.imgur.com/65A2t9y.jpg

<Page
    x:Class="KalkulatorBMI.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:KalkulatorBMI"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid Padding="10">

        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>

            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0">
            <TextBlock Text="Trener persolany" Style="{ThemeResource CaptionTextBlockStyle}"/>
            <TextBlock Text="Użytkownik" Style="{ThemeResource HeaderTextBlockStyle}"/>
        </StackPanel>
        <StackPanel Grid.Row="1" >
            <ListBox Name="lbxUzytkownicy" HorizontalAlignment="Left" Width="150" Height="200" Margin="10" SelectedIndex="0"/>
            <Button Name="ButtonLoguj" Content="Loguj" Margin="10" Click="Click_Loguj"/>
            <StackPanel>
                <TextBlock Text="Nowy uzytkownik" Margin="10,0,0,5"/>
                <TextBox Name="TextboxNowy" Height="32" Width="138" Margin="10,0,0,0" HorizontalAlignment="Left"/>
                <TextBlock Name="TextboxZlaNazwa" Margin="10,5,0,0" Foreground="Red"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" >
                <Button Name="ButtonUtworz" Content="Dodaj użytkownika" Margin="10" Click="Click_Utworz"/>
                <Button Name="ButtonUsun" Content="Wyczyść listę" Margin="10" Click="Click_Usun"/>
            </StackPanel>
        </StackPanel>
        <StackPanel Grid.Row="2">
            <Button Name="ButtonZakoncz" Margin="10" Content="Zakończ"  Click="Click_Zakoncz" Foreground="Red"/>
        </StackPanel>
    </Grid>
</Page>


问:
how to get the column name of the greatest value by using greatest function postgresql?
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

```<code>select greatest(col1,col2,col3,col4) from mytable;
</code>```

But I need to know the column name of the greatest value.

答:
You can use a lateral join:

```<code>select v.*
from t join lateral
     (select v.*
      from (values (col1, 'col1'), (col2, 'col2), (col3, 'col3'), (col4, 'col4)
           ) v(val, colname)
      order by col desc
      fetch first 1 row only
     ) v;
</code>```

The fact that you want to do this suggests that you have a problem with your data model.  You probably want another table, with each column value in a row.

Body:
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

select greatest(col1,col2,col3,col4) from mytable;

But I need to know the column name of the greatest value.

Body:
You can use a lateral join:

select v.*
from t join lateral
     (select v.*
      from (values (col1, 'col1'), (col2, 'col2), (col3, 'col3'), (col4, 'col4)
           ) v(val, colname)
      order by col desc
      fetch first 1 row only
     ) v;

The fact that you want to do this suggests that you have a problem with your data model.  You probably want another table, with each column value in a row.


问:
What's the best way to perform a differential between a list of directories?
I am interested in looking at a list of directories and comparing the previous list with a current list of directories and setting up a script to do so. Maybe in perl or as a shell script.

Should I use something like diff? Programatically, what would be an ideal way to do this? For example let say I output the diff to an output file, if there is no diff then exit, if there is results, I want to see it.

Let's for example I have the following directories today:

```<code>/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/a1b2c3
</code>```

Next day would look like this where a directory is either added, or renamed:

```<code>/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/ghi
/foo/bar/staging/a1b2c4
</code>```

答: also check the inotifywait command. it allows you to monitor files in RT.

Body:
I am interested in looking at a list of directories and comparing the previous list with a current list of directories and setting up a script to do so. Maybe in perl or as a shell script.

Should I use something like diff? Programatically, what would be an ideal way to do this? For example let say I output the diff to an output file, if there is no diff then exit, if there is results, I want to see it.

Let's for example I have the following directories today:

/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/a1b2c3

Next day would look like this where a directory is either added, or renamed:

/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/ghi
/foo/bar/staging/a1b2c4


问:
How to add extra hosts entries in helm charts
So i'm deploying my application stack on kubernetes sing helm charts and now i need to add some dependant server ip's and hostnames inside my pods /etc/hosts file so need help on this scenario</p>

答:
Kubernetes provides a DNS service that all pods get to use.  In turn, you can define an ExternalName service that just defines a DNS record.  Once you do that, your pods can talk to that service the same way they'd talk to any other Kubernetes service, and reach whatever server.

You could deploy a set of ExternalName services globally.  You could do it in a Helm chart too, if you wanted, something like

```<code>apiVersion: v1
kind: Service
metadata:
  name: {{ .Release.Name }}-{{ .Chart.Name }}-foo
spec:
  type: ExternalName
  externalName: {{ .Values.fooHostname }}
</code>```

The practice I've learned is that you should avoid using /etc/hosts if at all possible.

Body:
Kubernetes provides a DNS service that all pods get to use.  In turn, you can define an ExternalName service that just defines a DNS record.  Once you do that, your pods can talk to that service the same way they'd talk to any other Kubernetes service, and reach whatever server.

You could deploy a set of ExternalName services globally.  You could do it in a Helm chart too, if you wanted, something like

apiVersion: v1
kind: Service
metadata:
  name: {{ .Release.Name }}-{{ .Chart.Name }}-foo
spec:
  type: ExternalName
  externalName: {{ .Values.fooHostname }}

The practice I've learned is that you should avoid using /etc/hosts if at all possible.


问:
Receiving error when using Move-ADObject to an organizational unit
Trying to move a user to a different ou but I'm receiving an error. I tried looking online for solutions but no dice

```<code>$user1 = Read-Host "Terminated User: "

Move-ADObject -Identity $user1.distinguishedName -TargetPath "OU=DisabledAccounts,DC=meme,DC=com"
</code>```

The Error I am receiving is:

Move-ADObject : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.

答:
As Lotpings explains, you need to first get the user object from AD by means of the (string) value that was entered using the Read-Host cmdlet.

Make sure you ask for the SamAccountName of the user, because that is what you will need to find the AD user object.

```<code>Import-Module ActiveDirectory

$accountName = Read-Host "Enter the SamAccountName of the terminated user: "

# find the user object using the SamAccountName entered

# Get-ADUser takes a DistinghuishedName, a GUID, a SID or SamAccountName as Identity parameter
$user = Get-ADUser -Identity $accountName
if ($user) {
    # Move-ADObject takes a DistinghuishedName or GUID as Identity parameter
    Move-ADObject -Identity $user.DistinguishedName -TargetPath "OU=DisabledAccounts,DC=nfii,DC=com"

    # you can also pipe the object through:
    # $user | Move-ADObject -TargetPath "OU=DisabledAccounts,DC=nfii,DC=com"
}
else {
    Write-Warning "User with SamAccountName '$accountName' not found."
}
</code>```

Body:
Trying to move a user to a different ou but I'm receiving an error. I tried looking online for solutions but no dice

$user1 = Read-Host "Terminated User: "

Move-ADObject -Identity $user1.distinguishedName -TargetPath "OU=DisabledAccounts,DC=meme,DC=com"

The Error I am receiving is:

Move-ADObject : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.

Body:
As Lotpings explains, you need to first get the user object from AD by means of the (string) value that was entered using the Read-Host cmdlet.

Make sure you ask for the SamAccountName of the user, because that is what you will need to find the AD user object.

Import-Module ActiveDirectory

$accountName = Read-Host "Enter the SamAccountName of the terminated user: "

# find the user object using the SamAccountName entered

# Get-ADUser takes a DistinghuishedName, a GUID, a SID or SamAccountName as Identity parameter
$user = Get-ADUser -Identity $accountName
if ($user) {
    # Move-ADObject takes a DistinghuishedName or GUID as Identity parameter
    Move-ADObject -Identity $user.DistinguishedName -TargetPath "OU=DisabledAccounts,DC=nfii,DC=com"

    # you can also pipe the object through:
    # $user | Move-ADObject -TargetPath "OU=DisabledAccounts,DC=nfii,DC=com"
}
else {
    Write-Warning "User with SamAccountName '$accountName' not found."
}