问:
How to setup configuration files environments?
I have the following environments:

dev

stage

prod

Each environment will have different configuration and in akka documentation it says, that it is possible to include files.

Including files

  Sometimes it can be useful to include another
  configuration file, for example if you have one application.conf with
  all environment independent settings and then override some settings
  for specific environments.

Specifying system property with -Dconfig.resource=/dev.conf will load
  the dev.conf file, which includes the application.conf

```<code>include "application"

akka {   loglevel = "DEBUG" }
</code>```

My project environment looks as the following:

When I do unit test, I would like to use dev.conf configuration file and I have to setup somehow, that it will take the dev.conf file.

As the doc says above:

Specifying system property with -Dconfig.resource=/dev.conf

It is not clear to me, how to do it. Where do I have to pass it?

The content of my dev.conf looks as the following:

```<code>include "application"

akka {loglevel = "DEBUG"}
</code>```

The question is, how to make sure, when the unit test is started, that the dev.conf file is going use?

答:
That's a parameter for the JVM. The -D option is used to pass key-value system properties.

I see you're using IntelliJ, so I assume you're running your tests directly in there. If that's the case, you can pass parameters to the JVM selecting: Run -> Edit Configurations... -> (Select your test) -> VM parameters. Just paste -Dconfig.resource=/dev.conf in there, save and run your test.

Body:
I have the following environments:

dev

stage

prod

Each environment will have different configuration and in akka documentation it says, that it is possible to include files.

Including files

  Sometimes it can be useful to include another
  configuration file, for example if you have one application.conf with
  all environment independent settings and then override some settings
  for specific environments.

Specifying system property with -Dconfig.resource=/dev.conf will load
  the dev.conf file, which includes the application.conf

include "application"

akka {   loglevel = "DEBUG" }

My project environment looks as the following:

When I do unit test, I would like to use dev.conf configuration file and I have to setup somehow, that it will take the dev.conf file.

As the doc says above:

Specifying system property with -Dconfig.resource=/dev.conf

It is not clear to me, how to do it. Where do I have to pass it?

The content of my dev.conf looks as the following:

include "application"

akka {loglevel = "DEBUG"}

The question is, how to make sure, when the unit test is started, that the dev.conf file is going use?


来源: stackexchange

问:
Alignment Issue :- Second Post is not aligned properly
i am facing an alignment issue for which i have a solution.
But i wanted to know the reason behind this.
If u run the html markup which i have provided you can see that the second post is not inline with the first post.

I wanted second post to align with first post. I have the solution by using flex.But i need reason and not the solution

HTML :-

```<code><div class="_3yTtBPc-LMIvY20o00OVsF">
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO" style="">sunt aut facere repellat provident occaecati excepturi optio reprehenderit</div>
    <div>Nik</div>
  </div>
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO" style="
    /* min-height: 90px; */
">qui est esse</div>
    <div>Nik</div>
  </div>
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO">ea molestias quasi exercitationem repellat qui ipsa sit aut</div>
    <div>Nik</div>
  </div>
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO">eum et est occaecati</div>
    <div>Nik</div>
  </div>
</div>
</code>```

CSS :-

```<code>._3yTtBPc-LMIvY20o00OVsF {
  margin: auto;
  height: 200px;
  text-align: center;
}

._2wIS4xHyz03D-DXLdHPFxP {
  width: 90px;
  height: 130px;
  display: inline-block;
  padding: 20px 30px;
  margin: 10px 30px;
  border: 2px solid grey;
  box-shadow: 2px 5px 0 lightgrey;
}

._2NwLO4_WeKC2-xigIODSyO {
  max-height: 90px;
  /* white-space: nowrap; */
  overflow: hidden;
  text-overflow: ellipsis;
}

</code>```

expected :- second post should be in line with first post
actual :- second post is bit down that first post.

答:
By default when you use the display:inline-block; you are using a vertical-align: baseline;
You can see a similar problem at this url:

Why my inline-block divs are not aligned when only one of them has text?

You need to add explicitly vertical-align: top, in order to align the blocks relative to their tops, otherwise the alignment will be done based on the baselines of the internal divs, as you see on the image.

ContentLicense: CC BY-SA 4.0

Body:
i am facing an alignment issue for which i have a solution.
But i wanted to know the reason behind this.
If u run the html markup which i have provided you can see that the second post is not inline with the first post.

I wanted second post to align with first post. I have the solution by using flex.But i need reason and not the solution

HTML :-

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Nik

qui est esse

Nik

ea molestias quasi exercitationem repellat qui ipsa sit aut

Nik

eum et est occaecati

Nik

CSS :-

._3yTtBPc-LMIvY20o00OVsF {
  margin: auto;
  height: 200px;
  text-align: center;
}

._2wIS4xHyz03D-DXLdHPFxP {
  width: 90px;
  height: 130px;
  display: inline-block;
  padding: 20px 30px;
  margin: 10px 30px;
  border: 2px solid grey;
  box-shadow: 2px 5px 0 lightgrey;
}

._2NwLO4_WeKC2-xigIODSyO {
  max-height: 90px;
  /* white-space: nowrap; */
  overflow: hidden;
  text-overflow: ellipsis;
}

expected :- second post should be in line with first post
actual :- second post is bit down that first post.


问:
Unity 2d, multilayer background overdraw
The definition of the problem is simple yet I wasn't able to find a simple or straightforward solution.

 I have a background, made of several opaque layers:

Gradient sky (1pic, static);

Bright big mountain (1pic, moves a little);

Darker [closer] mountains (a few pics, randomly generated, moves faster);

Even darker [closer] mountains with some details (a few pics, randomly generated, moves even faster).

 I experience overdraw: every picture is drawing on top of each other. Every layer is dynamic so I can't just cut half of the sky or cut half of the mountain. However, 50% of the pictures are just one solid color + full transparency.

 Question 1: what is the best practice of preventing background overdraw? Consider the simplest example: background sky (100% screen) + moving mountain (80% screen).

 Question 2: some of the mountains are simple pictures - one opaque color, curved shape and the rest is full transparency. Should I keep using them as textures in sprites or I have to involve some practices to use it differently?

Background's look:

答: Regarding your first question,if i understood the question correctly,the simplest solution would be changing the z position of the pictures.</p>


问:
Navigate from a view model in xamarin forms
I am trying to push a view in xamrian forms from the view model but I cant appear to get it to work its really when the user has entered correct username and password it should show the home page.

You will see I have the on submit command this is just mock data at present so dont mind the design of code at this stage will change.

Usually I would use

```<code>var stocktakepage = new StockTake();
await Navigation.PushAsync(stocktakepage);
</code>```

But the model does not no about the navigation stack in the class is their another way to navigate from the view model thanks.

```<code>public  class LoginViewModel : INotifyPropertyChanged
{
    public Action DisplayInvalidLoginPrompt;
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private string email;
    public string Email
    {
        get { return email; }
        set
        {
            email = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Email"));
        }
    }
    private string password;
    public string Password
    {
        get { return password; }
        set
        {
            password = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Password"));
        }
    }
    public ICommand SubmitCommand { protected set; get; }
    public LoginViewModel()
    {
        SubmitCommand = new Command(OnSubmit);
    }
    public void OnSubmit()
    {
        if (email != "handheld1" || password != "test123")
        {
            DisplayInvalidLoginPrompt();
        }else

        {

        }
    }
}
</code>```

答:
I found the answer here

https://forums.xamarin.com/discussion/21822/call-navigation-pushasync-from-viewmodel But also on my main login page i have this. What this does is act like a delegate and allows you to push the view from the original calling page.

```<code>    public Login()
    {
         var vm = new LoginViewModel();
        this.BindingContext = vm;

Password.Completed += (object sender, EventArgs e) =>
{
     vm.SubmitCommand.Execute(null);

  };
}
</code>```

Body:
I am trying to push a view in xamrian forms from the view model but I cant appear to get it to work its really when the user has entered correct username and password it should show the home page.

You will see I have the on submit command this is just mock data at present so dont mind the design of code at this stage will change.

Usually I would use

var stocktakepage = new StockTake();
await Navigation.PushAsync(stocktakepage);

But the model does not no about the navigation stack in the class is their another way to navigate from the view model thanks.

public  class LoginViewModel : INotifyPropertyChanged
{
    public Action DisplayInvalidLoginPrompt;
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private string email;
    public string Email
    {
        get { return email; }
        set
        {
            email = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Email"));
        }
    }
    private string password;
    public string Password
    {
        get { return password; }
        set
        {
            password = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Password"));
        }
    }
    public ICommand SubmitCommand { protected set; get; }
    public LoginViewModel()
    {
        SubmitCommand = new Command(OnSubmit);
    }
    public void OnSubmit()
    {
        if (email != "handheld1" || password != "test123")
        {
            DisplayInvalidLoginPrompt();
        }else

        {

        }
    }
}

Body:
I found the answer here

https://forums.xamarin.com/discussion/21822/call-navigation-pushasync-from-viewmodel But also on my main login page i have this. What this does is act like a delegate and allows you to push the view from the original calling page.

    public Login()
    {
         var vm = new LoginViewModel();
        this.BindingContext = vm;

Password.Completed += (object sender, EventArgs e) =>
{
     vm.SubmitCommand.Execute(null);

  };
}


问:
Adding Nuget Packages From One Project To Another
I am using Visual Studio 2013. I am trying to add all nuget packages from another project into this project. I copied all the folders under packages from one project into this one how do I add to visual studio?

I tried using the Package Manager Console to update the nuget packages but I am not sure what to write?

I tried Update-Package -Reinstall -Solution Babysitter2 [Babysitter2]

What am I doing wrong?

This Is what my project setup looks like.

答:
You can install packages on the new project based on installed packages in another project.

Clique on "Tools/Nuget Package Manager/Package Manager Console" to open the "Package manager Console"

On "Package Manager Console", paste the following command replacing sourceProject and TargetProject by your project names:

```<code>Get-Package -ProjectName sourceProject   | ForEach-Object { Install-Package -Id $_.Id -Version $_.Versions -Projectname targetProject }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can install packages on the new project based on installed packages in another project.

Clique on "Tools/Nuget Package Manager/Package Manager Console" to open the "Package manager Console"

On "Package Manager Console", paste the following command replacing sourceProject and TargetProject by your project names:

Get-Package -ProjectName sourceProject   | ForEach-Object { Install-Package -Id $_.Id -Version $_.Versions -Projectname targetProject }


问:
Convert varchar(255) to numeric
I can't cast to convert data type varchar(255) to numeric

```<code>Amount
-1000
-500
-500,3827
-100,56
-1728,27781
</code>```

What I did:

```<code>CAST([Amount] as decimal(10,4) as values
</code>```

I get the error
    Error converting data type varchar to numeric.

What do I need to change?

答:
All of those values are too big for decimal(6,4).  Let's try a value that fits.

(Note: changing "," to "." for my locale)

```<code>DECLARE @MyVar varchar(255) = '-23'

SELECT CAST(@MyVar AS decimal(6,4))
</code>```

which results in:

-23.0000

Fitting your longest (1728,27781) requires decimal(9,5):

```<code>DECLARE @MyVar varchar(255) = '1728.27781'

SELECT CAST(@MyVar AS decimal(9,5))
</code>```

which results in:

1728.27781

From this you can see that the first number in the declaration represents the total number of digits, while the second number gives the decimals.  The decimal point itself is not part of the internal formatting.

Title: Convert varchar(255) to numeric

Body:
I can't cast to convert data type varchar(255) to numeric

Amount
-1000
-500
-500,3827
-100,56
-1728,27781

What I did:

CAST([Amount] as decimal(10,4) as values

I get the error
    Error converting data type varchar to numeric.

What do I need to change?

Body:
All of those values are too big for decimal(6,4).  Let's try a value that fits.

(Note: changing "," to "." for my locale)

DECLARE @MyVar varchar(255) = '-23'

SELECT CAST(@MyVar AS decimal(6,4))

which results in:

-23.0000

Fitting your longest (1728,27781) requires decimal(9,5):

DECLARE @MyVar varchar(255) = '1728.27781'

SELECT CAST(@MyVar AS decimal(9,5))

which results in:

1728.27781

From this you can see that the first number in the declaration represents the total number of digits, while the second number gives the decimals.  The decimal point itself is not part of the internal formatting.


问:
jspdf doesn't return the entire html page to pdf
enter image description hereI am trying to convert html page to PDF using JSPDF.The page is rendered in my screen with 65% resolution by default and upon converting this to PDF, it renders the PDF with a black strip on the right side of the generated PDF.
Resolving screen size to 100%, the black strip increases in thickness.

JSPDF method is applied to the entire div<> containing the page content.
Tried to fix the width of the content and page to adjust the content within the screen.

```<code>var pdf = new jsPDF('p', 'pt','a4');
    pdf.page = 1;
    var totalPages=1;

    pdf.text("Report", 220, 22);// set your margins

    var str = "Page " + pdf.page  + " of " +  totalPages;
    pdf.setFontSize(9);// optional
    pdf.text(str, 250, pdf.internal.pageSize.height - 10);
    pdf.text("Confidential", 490, pdf.internal.pageSize.height - 10);
    pdf.internal.scaleFactor = 2.10;
    pdf.addHTML($('#reportTabContent')[0], 30, 30, {
        'height': 1750,
        'width': 1058,
        background: '#fff',
        pageSplit:'true'
      },function () {
          pdf.save('Reports.pdf');
      });
</code>```

I expect the HTML page as it is in PDF form.
But the jspdf is creating pdf of the html page with a black patch in the right side of the generated pdf. Please help.enter image description here

答:
remove the height and width in that code and page split in that code and trey once
damn sure</p>

Body:
enter image description hereI am trying to convert html page to PDF using JSPDF.The page is rendered in my screen with 65% resolution by default and upon converting this to PDF, it renders the PDF with a black strip on the right side of the generated PDF.
Resolving screen size to 100%, the black strip increases in thickness.

JSPDF method is applied to the entire div<> containing the page content.
Tried to fix the width of the content and page to adjust the content within the screen.

var pdf = new jsPDF('p', 'pt','a4');
    pdf.page = 1;
    var totalPages=1;

    pdf.text("Report", 220, 22);// set your margins

    var str = "Page " + pdf.page  + " of " +  totalPages;
    pdf.setFontSize(9);// optional
    pdf.text(str, 250, pdf.internal.pageSize.height - 10);
    pdf.text("Confidential", 490, pdf.internal.pageSize.height - 10);
    pdf.internal.scaleFactor = 2.10;
    pdf.addHTML($('#reportTabContent')[0], 30, 30, {
        'height': 1750,
        'width': 1058,
        background: '#fff',
        pageSplit:'true'
      },function () {
          pdf.save('Reports.pdf');
      });

I expect the HTML page as it is in PDF form.
But the jspdf is creating pdf of the html page with a black patch in the right side of the generated pdf. Please help.enter image description here


问:
String manipulation using list comprehension
I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.

```<code>def myfunc(*args):
    return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
</code>```

How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?

答:
The problem is, you're using var-args. That's wrapping the string passed with a list, then you're iterating over that list (which only contains one string). This means your code does work to some extent; its just alternating the case of each whole word instead of each character.

Just get rid of the var-args:

```<code>def myfunc(word):
    return ''.join([word[i].upper() if i%2==0 else word[i].lower() for i in range(len(word))])

print(myfunc("hello world"))
# HeLlo WoRlD
</code>```

I'll just note, there's a few ways this could have been debugged. If you had checked the contents of args, you would have seen that it only contained a single element when one argument was passed, and two when two arguments were passed. If you had passed two arguments in, you would have also noticed that it alternated the case of each word as a whole. That would have likely given you enough hints to figure it out.

Body:
I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.

def myfunc(*args):
    return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])

How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?

Body:
The problem is, you're using var-args. That's wrapping the string passed with a list, then you're iterating over that list (which only contains one string). This means your code does work to some extent; its just alternating the case of each whole word instead of each character.

Just get rid of the var-args:

def myfunc(word):
    return ''.join([word[i].upper() if i%2==0 else word[i].lower() for i in range(len(word))])

print(myfunc("hello world"))
# HeLlo WoRlD

I'll just note, there's a few ways this could have been debugged. If you had checked the contents of args, you would have seen that it only contained a single element when one argument was passed, and two when two arguments were passed. If you had passed two arguments in, you would have also noticed that it alternated the case of each word as a whole. That would have likely given you enough hints to figure it out.


问:
Troubleshooting Bootstrap button
Submit Button is not working if I put it on a different container or row

If my code is formatted like this the submit button works

```<code><div class="container">
    <div class="row">
       <form>
          <button type="submit">Submit</button>
       </form>
    </div>
</div>
</code>```

If my code is formatted like this the submit button do not work

```<code> <div class="container">

    <div class="row">
       <form>

           {{ some other codes }}

    </div>

    <div class="row">

          <button type="submit">Submit</button>
       </form>
    </div>
</div>
</code>```

I dont get any error message.. the button is there but its not working.

答:
Your div's are not closing properly. Your form starts in a div and ends in a different div. I'm not sure what you wanted to do, but you need to make sure the form tags both begin and end inside the same div.

       <form>

           {{ some other codes }}

           <button type="submit">Submit</button>

       </form>

```

Title: Troubleshooting Bootstrap button

Body:
Submit Button is not working if I put it on a different container or row

If my code is formatted like this the submit button works

       <form>
          <button type="submit">Submit</button>
       </form>

If my code is formatted like this the submit button do not work

       <form>

           {{ some other codes }}

          <button type="submit">Submit</button>
       </form>

I dont get any error message.. the button is there but its not working.

Body:
Your div's are not closing properly. Your form starts in a div and ends in a different div. I'm not sure what you wanted to do, but you need to make sure the form tags both begin and end inside the same div.

<div class="container">

    <div class="row">
       <form>

           {{ some other codes }}

         <div class="row">
           <button type="submit">Submit</button>

         </div>
       </form>
    </div>
</div>


问:
Insert Data Between Two Dates in Database using C#
I need help. We need to insert data between two dates in the database using C# on button click

For example, we have two calendars, Calendar1 & Calendar2.

Now from Calendar1, we choose date 01/12/2018

And from Calendar2, we choose date 30/12/2018

When we click the "Submit" button, we need to insert the data into the database

01/12/2018 to 30/12/2018

Ex.

```<code>01/12/2018
02/12/2018
03/12/2018
</code>```

答:
I personally prefer a Tally Table to an rCTE for things like this; for larger data sets a Tally Table tends to be much faster:</p>

```<code>DECLARE @StartDate date = '20181201',
        @EndDate date = '20181231';

WITH N AS (
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS (
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I
    FROM N N1, N N2, N N3, N N4) --10000 rows
SELECT DATEADD(DAY, T.I, @StartDate)
FROM Tally T
WHERE DATEADD(DAY, T.I, @StartDate) <= @EndDate;
</code>```

Body:
I need help. We need to insert data between two dates in the database using C# on button click

For example, we have two calendars, Calendar1 & Calendar2.

Now from Calendar1, we choose date 01/12/2018

And from Calendar2, we choose date 30/12/2018

When we click the "Submit" button, we need to insert the data into the database

01/12/2018 to 30/12/2018

Ex.

01/12/2018
02/12/2018
03/12/2018

Body:
I personally prefer a Tally Table to an rCTE for things like this; for larger data sets a Tally Table tends to be much faster:

DECLARE @StartDate date = '20181201',
        @EndDate date = '20181231';

WITH N AS (
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS (
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I
    FROM N N1, N N2, N N3, N N4) --10000 rows
SELECT DATEADD(DAY, T.I, @StartDate)
FROM Tally T
WHERE DATEADD(DAY, T.I, @StartDate) <= @EndDate;


问:
Why is Docker installed but not Docker Compose?
I have installed docker on CentOS 7 by running following commands,

```<code>curl -sSL https://get.docker.com/ | sh
systemctl enable docker && systemctl start docker
docker run hello-world
</code>```

NOTE: helloworld runs correctly and no issues.

however when I try to run docker-compose (docker-compose.yml exists and valid) it gives me the error on CentOS only (Windows version works fine for the docker-compose file)

```<code>/usr/local/bin/docker-compose: line 1: {error:Not Found}: command not found
</code>```

答:
The above solutions didn't work for me. But I found this that worked:</p>

```<code>sudo apt-get update -y && sudo apt-get install -y python3-pip python3-dev
sudo apt-get remove docker docker-engine docker.io
curl -fsSL get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo pip3 install docker-compose
#sudo docker-compose -f docker-compose-profess.yml pull ofw
sudo usermod -a -G docker $USER
sudo reboot
</code>```

Body:
I have installed docker on CentOS 7 by running following commands,

curl -sSL https://get.docker.com/ | sh
systemctl enable docker && systemctl start docker
docker run hello-world

NOTE: helloworld runs correctly and no issues.

however when I try to run docker-compose (docker-compose.yml exists and valid) it gives me the error on CentOS only (Windows version works fine for the docker-compose file)

/usr/local/bin/docker-compose: line 1: {error:Not Found}: command not found

Body:
The above solutions didn't work for me. But I found this that worked:

sudo apt-get update -y && sudo apt-get install -y python3-pip python3-dev
sudo apt-get remove docker docker-engine docker.io
curl -fsSL get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo pip3 install docker-compose
#sudo docker-compose -f docker-compose-profess.yml pull ofw
sudo usermod -a -G docker $USER
sudo reboot


问:
Flutter text is not ellipsized in the list
I have a list of object. There is a name that can be long and according to design it should end with three dots if it can't fit

```<code>Container(
          height: 72,
          constraints: BoxConstraints(minWidth: double.infinity),
          child: Row(
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: CircleAvatar(
                  radius: 20.0,
                  backgroundImage: NetworkImage(_model._organizerLogo),
                  backgroundColor: Colors.transparent,
                ),
              ),
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(right: 8.0),
                      child: Text(
                        _model._eventName,
                        style: TextStyle(
                            fontSize: 15,
                            color: Colors.black,
                            fontWeight: FontWeight.w500),
                        textAlign: TextAlign.start,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    ...
                  ])
            ],
          ),
        )
</code>```

Wrapping Container in Flexible or Expandable didn't work.

How to make oversized text ellipsis? Thanks!

答:
Here is the working solution:

```<code>Container(
  height: 72,
  constraints: BoxConstraints(minWidth: double.infinity),
  child: Row(
    children: <Widget>[
      Container(
        margin: const EdgeInsets.only(left: 16.0, right: 16.0),
        child: CircleAvatar(
          radius: 20.0,
          backgroundImage: NetworkImage(poolImageUrl),
          backgroundColor: Colors.transparent,
        ),
      ),
      Expanded(
        child: Container(
          padding: EdgeInsets.only(right: 8.0),
          child: Text(
            "This will not overflow now, because we have put it in Expanded, you can try any long string here for test",
            style: TextStyle(fontSize: 15, color: Colors.black, fontWeight: FontWeight.w500),
            textAlign: TextAlign.start,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    ],
  ),
),
</code>```

Body:
I have a list of object. There is a name that can be long and according to design it should end with three dots if it can't fit

Container(
          height: 72,
          constraints: BoxConstraints(minWidth: double.infinity),
          child: Row(
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: CircleAvatar(
                  radius: 20.0,
                  backgroundImage: NetworkImage(_model._organizerLogo),
                  backgroundColor: Colors.transparent,
                ),
              ),
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(right: 8.0),
                      child: Text(
                        _model._eventName,
                        style: TextStyle(
                            fontSize: 15,
                            color: Colors.black,
                            fontWeight: FontWeight.w500),
                        textAlign: TextAlign.start,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    ...
                  ])
            ],
          ),
        )

Wrapping Container in Flexible or Expandable didn't work.

How to make oversized text ellipsis? Thanks!

Body:
Here is the working solution:

Container(
  height: 72,
  constraints: BoxConstraints(minWidth: double.infinity),
  child: Row(
    children: <Widget>[
      Container(
        margin: const EdgeInsets.only(left: 16.0, right: 16.0),
        child: CircleAvatar(
          radius: 20.0,
          backgroundImage: NetworkImage(poolImageUrl),
          backgroundColor: Colors.transparent,
        ),
      ),
      Expanded(
        child: Container(
          padding: EdgeInsets.only(right: 8.0),
          child: Text(
            "This will not overflow now, because we have put it in Expanded, you can try any long string here for test",
            style: TextStyle(fontSize: 15, color: Colors.black, fontWeight: FontWeight.w500),
            textAlign: TextAlign.start,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    ],
  ),
),


问:
How can I redirect to different file extension via htaccess
How can I redirect all the visitors to a different file extension. Example:
Visitor trying to access: http://www.anywebsite.com/0001.jpeg but redirect to http://www.anywebsite.com/0001.pdf. There are thousands of files in one directory with such redirect. How can i redirect all files using a single code in .htaccess ??</p>

答:
This maybe a possible duplicate question but you can find it easily via search

```<code># change file extensions
RewriteEngine on
RewriteRule ^(.*).jpeg$ http://domain.tld/$1.pdf [R=301,L]
</code>```

Review this link for further explanation:
https://htaccessbook.com/add-remove-change-file-extensions-htaccess/

Body:
This maybe a possible duplicate question but you can find it easily via search

# change file extensions
RewriteEngine on
RewriteRule ^(.*).jpeg$ http://domain.tld/$1.pdf [R=301,L]

Review this link for further explanation:
https://htaccessbook.com/add-remove-change-file-extensions-htaccess/


答:
The simplest method is probably:

```<code>select CAST(REPLACE([Amount], ',', '.') as decimal(10, 4))
</code>```

Note:  Don't use values as a column alias.  It is a SQL keyword and a SQL Server reserved word.

Your problem is that you have bad values in the column.  You can avoid the error using:

```<code>select TRY_CAST(REPLACE(Amount, ',', '.') as decimal(10, 4))
</code>```

You can find the problems using:

```<code>select amount
from t
where TRY_CAST(REPLACE(Amount, ',', '.') as decimal(10, 4)) is  null and Amount is not null;
</code>```

Moral:  Never store numeric values in a string.

Title: Convert varchar(255) to numeric

Body:
The simplest method is probably:

select CAST(REPLACE([Amount], ',', '.') as decimal(10, 4))

Note:  Don't use values as a column alias.  It is a SQL keyword and a SQL Server reserved word.

Your problem is that you have bad values in the column.  You can avoid the error using:

select TRY_CAST(REPLACE(Amount, ',', '.') as decimal(10, 4))

You can find the problems using:

select amount
from t
where TRY_CAST(REPLACE(Amount, ',', '.') as decimal(10, 4)) is  null and Amount is not null;

Moral:  Never store numeric values in a string.


问:
Help with merging adjacent nodes
I apologize for not knowing xsl very well, but i have an xml document that I would like to transform and I've not been able to find an example that works for me. I would like to merge the locations into a single element. I have the following document:

```<code><?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Lake Athletic Complex</name>
    </locations>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Athletic Complex</name>
    </locations>
    <locations>
        <id>6</id>
        <name>HS Baseball Field</name>
    </locations>
</event>
</code>```

I am trying to make it like this:

```<code><?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <location_name>Lake Athletic Complex</location_name>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <location_name>Athletic Complex, HS Baseball Field</location_name>
</event>
</code>```

答:
EDIT: Sorry, I'd missed the sequence constructor.

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="node()" mode="sequence">
        <xsl:if test="position()!=1">, </xsl:if>
        <xsl:value-of select="."/>
    </xsl:template>
    <xsl:template match="locations"/>
    <xsl:template match="locations[1]">
        <location_name>
            <xsl:apply-templates select="../locations/name" mode="sequence"/>
        </location_name>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><tfs_events>
    <title>Referees Events</title>
    <event>
        <id>256</id>
        <name>SB-V,SB-JV vs McKinley HS</name>
        <time_start>2011-04-12 17:00:00</time_start>
        <time_end>2011-04-12 19:00:00</time_end>
        <status>Active</status>
        <location_name>Lake Athletic Complex</location_name>
    </event>
    <event>
        <id>257</id>
        <name>SB-V,SB-JV vs Jackson HS</name>
        <time_start>2011-04-14 17:00:00</time_start>
        <time_end>2011-04-14 19:00:00</time_end>
        <status>Active</status>
        <location_name>Athletic Complex, HS Baseball Field</location_name>
    </event>
</tfs_events>
</code>```

Note: Pull style perform the transformation only when is needed, meaning when there is some locations.

Title: Help with merging adjacent nodes

Body:
I apologize for not knowing xsl very well, but i have an xml document that I would like to transform and I've not been able to find an example that works for me. I would like to merge the locations into a single element. I have the following document:

<?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Lake Athletic Complex</name>
    </locations>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Athletic Complex</name>
    </locations>
    <locations>
        <id>6</id>
        <name>HS Baseball Field</name>
    </locations>
</event>

I am trying to make it like this:

<?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <location_name>Lake Athletic Complex</location_name>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <location_name>Athletic Complex, HS Baseball Field</location_name>
</event>

Body:
EDIT: Sorry, I'd missed the sequence constructor.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="node()" mode="sequence">
        <xsl:if test="position()!=1">, </xsl:if>
        <xsl:value-of select="."/>
    </xsl:template>
    <xsl:template match="locations"/>
    <xsl:template match="locations[1]">
        <location_name>
            <xsl:apply-templates select="../locations/name" mode="sequence"/>
        </location_name>
    </xsl:template>
</xsl:stylesheet>

Output:

<tfs_events>
    <title>Referees Events</title>
    <event>
        <id>256</id>
        <name>SB-V,SB-JV vs McKinley HS</name>
        <time_start>2011-04-12 17:00:00</time_start>
        <time_end>2011-04-12 19:00:00</time_end>
        <status>Active</status>
        <location_name>Lake Athletic Complex</location_name>
    </event>
    <event>
        <id>257</id>
        <name>SB-V,SB-JV vs Jackson HS</name>
        <time_start>2011-04-14 17:00:00</time_start>
        <time_end>2011-04-14 19:00:00</time_end>
        <status>Active</status>
        <location_name>Athletic Complex, HS Baseball Field</location_name>
    </event>
</tfs_events>

Note: Pull style perform the transformation only when is needed, meaning when there is some locations.


问:
How do I set a value as a string React-Native?
I am setting up a new token value with react native fetch method and ı take the token value which is 'AGFsdkhgdgdkFSADLfksdgk' for example.
I want to use this token with string value how ?

I am also tried get and set method but it is not necessary. For example ı have a string value which is '_token'. I want to use this _token value every class when ı using get method for reading data.

Here is my fetch method function.

```<code>_getToken () {
    const data = {
        grant_type: "",
        branchcode: "",
        password: "",
        username: "",
        dbname: "",
        dbuser: "",
        dbpassword: "",
        dbtype: ""
    }
    return (
        fetch('http:/192.168.1.29:7070/api/v2/token', {
            method: 'POST',
            body: qs.stringify(data)
        }).then(response => response.json())
            .then(responseData => {
                console.log(responseData['access_token']);
            })
            .catch(function (error) {
                console.log("HATA!!!" + error);
            })
    );
}
</code>```

答:
you can use AsyncStorage for store access token like this :

```<code>import {AsyncStorage} from 'react-native';

AsyncStorage.setItem('token',responseData['access_token']);
</code>```

and use it like this :

```<code>  AsyncStorage.getItem('token').then((value)=>{
 console.log(value) //value is stored token
})
</code>```

Body:
I am setting up a new token value with react native fetch method and ı take the token value which is 'AGFsdkhgdgdkFSADLfksdgk' for example.
I want to use this token with string value how ?

I am also tried get and set method but it is not necessary. For example ı have a string value which is '_token'. I want to use this _token value every class when ı using get method for reading data.

Here is my fetch method function.

_getToken () {
    const data = {
        grant_type: "",
        branchcode: "",
        password: "",
        username: "",
        dbname: "",
        dbuser: "",
        dbpassword: "",
        dbtype: ""
    }
    return (
        fetch('http:/192.168.1.29:7070/api/v2/token', {
            method: 'POST',
            body: qs.stringify(data)
        }).then(response => response.json())
            .then(responseData => {
                console.log(responseData['access_token']);
            })
            .catch(function (error) {
                console.log("HATA!!!" + error);
            })
    );
}

Body:
you can use AsyncStorage for store access token like this :

import {AsyncStorage} from 'react-native';

AsyncStorage.setItem('token',responseData['access_token']);

and use it like this :

  AsyncStorage.getItem('token').then((value)=>{
 console.log(value) //value is stored token
})


答:
By writing *args in your function declaration, it means that you're iterating over a number of strings and not just one string. For example:

```<code>myfunc('hello', 'goodbye')
</code>```

Your function will iterate over a hello and goodbye, with hello having an index of 0 which is even number and thus converting its characters to uppercase, whereas goodbye has an index of 1 which is odd and thus covnerting its characters to lowercase:

```<code>HELLOgoodbye
</code>```

If you wish to call your function for only one string, you have to remove the * from *args or inserting the string's characters one by one:

```<code>myfunc('h','e','l','l','o')
</code>```

So, the declaration and implementation of your function should look like this:

```<code>def myfunc(args):
    return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
</code>```

Calling myfunc('hello') will return the correct result.

Title: String manipulation using list comprehension

Body:
By writing *args in your function declaration, it means that you're iterating over a number of strings and not just one string. For example:

myfunc('hello', 'goodbye')

Your function will iterate over a hello and goodbye, with hello having an index of 0 which is even number and thus converting its characters to uppercase, whereas goodbye has an index of 1 which is odd and thus covnerting its characters to lowercase:

HELLOgoodbye

If you wish to call your function for only one string, you have to remove the * from *args or inserting the string's characters one by one:

myfunc('h','e','l','l','o')

So, the declaration and implementation of your function should look like this:

def myfunc(args):
    return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])

Calling myfunc('hello') will return the correct result.


问:
How to make the removal of lines from the file?
the key is the name of the player, the value is the record (in seconds) there is a code that needs to be improved

I have a file with the name and result of the player (they are written in a different form), on this form, these data are recorded in the dictionary and then the 5 best results are distributed by rating.

Objective: make removal from file

below are my attempts to do this:

```<code>private static Dictionary<string, int> AllNames()
{
    return File
      .ReadLines(@"C:\Users\D205\Desktop\картинки\results.txt")
      .Where(line => !string.IsNullOrWhiteSpace(line))
      .Select(item => item.Split(' '))
      .ToDictionary(items => items[0],
                    items => int.Parse(items[1]));
}

private void updateRatingLabels()
{
    var tops = AllNames()
      .OrderBy(pair => pair.Value)
      .ThenBy(pair => pair.Key, StringComparer.Ordinal)
      .Take(5)
      .ToArray();

    if (System.IO.File.ReadAllLines(@"C:\Users\D205\Desktop\картинки\results.txt").Length >5)
    {

        for (int i = 18; i <= 22; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 28; i <= 32; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}";  //Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
               // remove tops.key

        }

        for (...)
        {
            // set delete from file by key
            // remove these items from the dictionary
        }

    }
</code>```

答: You have to do a File.WriteAllLines with the data from the dictionary where you removed the items. So you simply have to overwrite the old file.</p>

Body:
the key is the name of the player, the value is the record (in seconds) there is a code that needs to be improved

I have a file with the name and result of the player (they are written in a different form), on this form, these data are recorded in the dictionary and then the 5 best results are distributed by rating.

Objective: make removal from file

below are my attempts to do this:

private static Dictionary<string, int> AllNames()
{
    return File
      .ReadLines(@"C:\Users\D205\Desktop\картинки\results.txt")
      .Where(line => !string.IsNullOrWhiteSpace(line))
      .Select(item => item.Split(' '))
      .ToDictionary(items => items[0],
                    items => int.Parse(items[1]));
}

private void updateRatingLabels()
{
    var tops = AllNames()
      .OrderBy(pair => pair.Value)
      .ThenBy(pair => pair.Key, StringComparer.Ordinal)
      .Take(5)
      .ToArray();

    if (System.IO.File.ReadAllLines(@"C:\Users\D205\Desktop\картинки\results.txt").Length >5)
    {

        for (int i = 18; i <= 22; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 28; i <= 32; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}";  //Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
               // remove tops.key

        }

        for (...)
        {
            // set delete from file by key
            // remove these items from the dictionary
        }

    }


问:
NHibernate or SQL Server 2005 Regarding Max Results
Is there a way to query Sql Server 2005 and return out of a 100 records.
Records 10 - 20. In other words only 10 rows would be returned. Not the first 10 but the second 10 - 20.

I want to do this in TSQL. This would also be acceptable with NHibernate but ultimatley NHibernate would need to convert the HQL into TSQL. I know its possible to do this from Linq but I want to know whether its possible from TSQL.

Oh btw. This is for optimization purpose. So just like you would return the Max 100 rows. You would return it for the same reason but a subset. Performance is the reason!!

Body:
Try:

http://www.sqlservercurry.com/2009/06/skip-and-take-n-number-of-records-in.html


问:
Why java.lang.IllegalStateException occurs when running Word2VecExample form Scala Spark mllib?
I am trying to read a text file in Spark-mllib examples (Word2VecExample) and create it word vectors. I run it by some text files and it gives no error but when reading one of my files, it gives this error and I am really confuse with that because I tried everything such as file format(utf-8) and ASCII characters.
this is my source code:

```<code>package org.apache.spark.examples.mllib

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
// $example on$
import org.apache.spark.mllib.feature.{Word2Vec, Word2VecModel}
// $example off$

object Word2VecExample {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("Word2VecExample")
    conf.setMaster("local[4]")
    val sc = new SparkContext(conf)

    val input = sc.textFile("C:\\Users\\...\\Desktop\\yelp_labelled.txt").map(line => line.split(" ").toSeq)

    val word2vec = new Word2Vec()

    val model = word2vec.fit(input)

    val synonyms = model.findSynonyms("1", 5)

    for((synonym, cosineSimilarity) <- synonyms) {
      println(s"$synonym $cosineSimilarity")
    }

    model.save(sc, "C:\\Users\\...\\Desktop\\Edited1Yelp")
    val sameModel = Word2VecModel.load(sc, "C:\\Users\\...\\Edited1Yelp")

    // $example off$

    sc.stop()
  }
}
</code>```

And this is the Error:

```<code>Exception in thread "main" 19/05/29 18:36:29 INFO BlockManagerInfo: Removed broadcast_4_piece0 on DESKTOP-T5EN156:64774 in memory (size: 13.0 KB, free: 2.2 GB)
java.lang.IllegalStateException: 1 not in vocabulary
    at org.apache.spark.mllib.feature.Word2VecModel.transform(Word2Vec.scala:533)
    at org.apache.spark.mllib.feature.Word2VecModel.findSynonyms(Word2Vec.scala:545)
    at org.apache.spark.examples.mllib.Word2VecExample$.main(Word2VecExample.scala:43)
    at org.apache.spark.examples.mllib.Word2VecExample.main(Word2VecExample.scala)
</code>```

And line 43 refers to val synonyms = model.findSynonyms("1", 5) but I'm sure it's true because I run the program correctly with some other files.

答:
Based on the Spark example and documentation, this error raises from findSynonyms(String, int) method. There must be a vector for String parameter in this method and if it doesn't exist a vector for this, the error

Java.lang.IllegalStateException.

appears.
So, in my example there is no vector for the input String parameter "1".

Body:
I am trying to read a text file in Spark-mllib examples (Word2VecExample) and create it word vectors. I run it by some text files and it gives no error but when reading one of my files, it gives this error and I am really confuse with that because I tried everything such as file format(utf-8) and ASCII characters.
this is my source code:

package org.apache.spark.examples.mllib

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
// $example on$
import org.apache.spark.mllib.feature.{Word2Vec, Word2VecModel}
// $example off$

object Word2VecExample {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("Word2VecExample")
    conf.setMaster("local[4]")
    val sc = new SparkContext(conf)

    val input = sc.textFile("C:\\Users\\...\\Desktop\\yelp_labelled.txt").map(line => line.split(" ").toSeq)

    val word2vec = new Word2Vec()

    val model = word2vec.fit(input)

    val synonyms = model.findSynonyms("1", 5)

    for((synonym, cosineSimilarity) <- synonyms) {
      println(s"$synonym $cosineSimilarity")
    }

    model.save(sc, "C:\\Users\\...\\Desktop\\Edited1Yelp")
    val sameModel = Word2VecModel.load(sc, "C:\\Users\\...\\Edited1Yelp")

    // $example off$

    sc.stop()
  }
}

And this is the Error:

Exception in thread "main" 19/05/29 18:36:29 INFO BlockManagerInfo: Removed broadcast_4_piece0 on DESKTOP-T5EN156:64774 in memory (size: 13.0 KB, free: 2.2 GB)
java.lang.IllegalStateException: 1 not in vocabulary
    at org.apache.spark.mllib.feature.Word2VecModel.transform(Word2Vec.scala:533)
    at org.apache.spark.mllib.feature.Word2VecModel.findSynonyms(Word2Vec.scala:545)
    at org.apache.spark.examples.mllib.Word2VecExample$.main(Word2VecExample.scala:43)
    at org.apache.spark.examples.mllib.Word2VecExample.main(Word2VecExample.scala)

And line 43 refers to val synonyms = model.findSynonyms("1", 5) but I'm sure it's true because I run the program correctly with some other files.


问:
How to scrape embedded links and tabular information
I'm trying to scrape information about the datasets available on this website.

I want to collect the URLs to the resources and at least the title of the dataset.

Using this resource as an example, I want to capture the URL embedded in "Go to resource" and the title listed in the table:

I have created a basic scraper, but it doesn't seem work:

```<code>import requests
import csv
from bs4 import BeautifulSoup

site = requests.get('https://data.nsw.gov.au/data/dataset');
data_list=[]

if site.status_code is 200:
    content = BeautifulSoup(site.content, 'html.parser')
    internals = content.select('.resource-url-analytics')
    for url in internals:
        title = internals.select=('.resource-url-analytics')[0].get_text()
        link = internals.select=('.resource-url-analytics')[0].get('href')
        new_data = {"title": title, "link": link}
        data_list.append(new_data)
    with open ('selector.csv','w') as file:
            writer = csv.DictWriter(file, fieldnames = ["dataset", "link"], delimiter = ';')
            writer.writeheader()
            for row in data_list:
                writer.writerow(row)
</code>```

I would like to write the output to a CSV with columns for the URLs and the titles.

This is an example of the desired output

Greatly appreciative for any assistance

答:
For simplicity use selenium package:

```<code>from selenium import webdriver
import os

# initialise browser
browser = webdriver.Chrome(os.getcwd() + '/chromedriver')
browser.get('https://data.nsw.gov.au/data/dataset')

# find all elements by xpath
get_elements = browser.find_elements_by_xpath('//*[@id="content"]/div/div/section/div/ul/li/div/h3/a[2]')

# collect data
data = []
for item in get_elements:
    data.append((item.text, item.get_attribute('href')))
</code>```

Output:

```<code>('Vegetation of the Guyra 1:25000 map sheet VIS_ID 240', 'https://datasets.seed.nsw.gov.au/dataset/vegetation-of-the-guyra-1-25000-map-sheet-vis_id-2401ee52')
('State Vegetation Type Map: Riverina Region Version v1.2 - VIS_ID 4469', 'https://datasets.seed.nsw.gov.au/dataset/riverina-regional-native-vegetation-map-version-v1-0-vis_id-4449')
('Temperate Highland Peat Swamps on Sandstone (THPSS) spatial distribution maps...', 'https://datasets.seed.nsw.gov.au/dataset/temperate-highland-peat-swamps-on-sandstone-thpss-vegetation-maps-vis-ids-4480-to-4485')
('Environmental Planning Instrument - Flood', 'https://www.planningportal.nsw.gov.au/opendata/dataset/epi-flood')

and so on
</code>```

Body:
I'm trying to scrape information about the datasets available on this website.

I want to collect the URLs to the resources and at least the title of the dataset.

Using this resource as an example, I want to capture the URL embedded in "Go to resource" and the title listed in the table:

I have created a basic scraper, but it doesn't seem work:

import requests
import csv
from bs4 import BeautifulSoup

site = requests.get('https://data.nsw.gov.au/data/dataset');
data_list=[]

if site.status_code is 200:
    content = BeautifulSoup(site.content, 'html.parser')
    internals = content.select('.resource-url-analytics')
    for url in internals:
        title = internals.select=('.resource-url-analytics')[0].get_text()
        link = internals.select=('.resource-url-analytics')[0].get('href')
        new_data = {"title": title, "link": link}
        data_list.append(new_data)
    with open ('selector.csv','w') as file:
            writer = csv.DictWriter(file, fieldnames = ["dataset", "link"], delimiter = ';')
            writer.writeheader()
            for row in data_list:
                writer.writerow(row)

I would like to write the output to a CSV with columns for the URLs and the titles.

This is an example of the desired output

Greatly appreciative for any assistance

Body:
For simplicity use selenium package:

from selenium import webdriver
import os

# initialise browser
browser = webdriver.Chrome(os.getcwd() + '/chromedriver')
browser.get('https://data.nsw.gov.au/data/dataset')

# find all elements by xpath
get_elements = browser.find_elements_by_xpath('//*[@id="content"]/div/div/section/div/ul/li/div/h3/a[2]')

# collect data
data = []
for item in get_elements:
    data.append((item.text, item.get_attribute('href')))

Output:

('Vegetation of the Guyra 1:25000 map sheet VIS_ID 240', 'https://datasets.seed.nsw.gov.au/dataset/vegetation-of-the-guyra-1-25000-map-sheet-vis_id-2401ee52')
('State Vegetation Type Map: Riverina Region Version v1.2 - VIS_ID 4469', 'https://datasets.seed.nsw.gov.au/dataset/riverina-regional-native-vegetation-map-version-v1-0-vis_id-4449')
('Temperate Highland Peat Swamps on Sandstone (THPSS) spatial distribution maps...', 'https://datasets.seed.nsw.gov.au/dataset/temperate-highland-peat-swamps-on-sandstone-thpss-vegetation-maps-vis-ids-4480-to-4485')
('Environmental Planning Instrument - Flood', 'https://www.planningportal.nsw.gov.au/opendata/dataset/epi-flood')

and so on


问:
how to add account name in the url and redirect or get the records based on account name
For Ex:- http://localhost:3000/account_name/dashboard
All user will have an account name based on their account name I need
attach all the URL to be attached in front of account_name and need all the records based on that account name

Basically, how the GitHub will redirect to our repository like that I need to implement.
for ex:- https://github.com/account_name/ecommerce

I have no idea what I have to search it in google

I came across redirect based on constraint but I'm not sure.

association:- User has_one association with the account.

答:
You can try like this in your session or login controller. If the user is signing in your application.

```<code>def create
    @user = User.find_by(email: params[:email]) #you can try your own sign_in method
     if @user && @user.valid_password?(params[:password])
      redirect_to get_redir_link(@user) #you can call the redirect link here
    else
      redirect_to login_path
    end
end

def get_redir_link(user)
    account_name = user.account_name #by using user find the account name for your scenarios
    return "#{account_name}/dashboard" #return the url whatever you want
end
</code>```

In my application i have done like. You can make use of it.

Body:
You can try like this in your session or login controller. If the user is signing in your application.

def create
    @user = User.find_by(email: params[:email]) #you can try your own sign_in method
     if @user && @user.valid_password?(params[:password])
      redirect_to get_redir_link(@user) #you can call the redirect link here
    else
      redirect_to login_path
    end
end

def get_redir_link(user)
    account_name = user.account_name #by using user find the account name for your scenarios
    return "#{account_name}/dashboard" #return the url whatever you want
end

In my application i have done like. You can make use of it.


问:
Best way to create a trend/graph in my application
I have currently some values in an array that I would like to display in a trend / graph ( don't know the appropriate english word)

I have been looking in Android source code to find the Gingerbread battery graph (https://android.googlesource.com/platform/packages/apps/Settings/+/gingerbread-release/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
)

That solution seem to be a little bit overcomplicated and too much for a simple and nice graph.

Can someone point me a tutorial / code sample?

答: Try AChartEngine, it's really easy to understand and set up. Comes with plenty of examples too. http://www.achartengine.org/</p>


问:
How to encode an object to json in Flutter
I am trying to convert the object "Week" to json.

https://flutter.dev/docs/development/data-and-backend/json this is the source that i used

```<code>class Week{
  DateTime _startDate;
  DateTime _endDate;
  List<Goal> _goalList;
  String _improvement;

  Week(this._startDate, this._endDate){
    this._goalList = List<Goal>();
    this._improvement = "";
  }

  Week.fromJson(Map<String, dynamic> json)
    : _startDate =  json['startDate'],
      _endDate = json['endDate'],
      _goalList = json['goalList'],
      _improvement = json['improvement'];

  Map<String, dynamic> toJson() =>
  {
    'startDate': _startDate,
    'endDate': _endDate,
    'goalList': _goalList,
    'improvement': _improvement,
  };
}
</code>```

I used this:

```<code>DateTime startDate = currentDate.subtract(new Duration(days:(weekday-1)));
DateTime endDate = currentDate.add(new Duration(days:(7-weekday)));

Week week = new Week(startDate, endDate);
var json = jsonEncode(week);
</code>```

But the problem is that I get this result:

```<code>Unhandled Exception: Converting object to an encodable object failed: Instance of 'Week'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:834:17)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:819:5)
#3      JsonEncoder.convert (dart:convert/json.dart:255:30)
#4      JsonCodec.encode (dart:convert/json.dart:166:45)
#5      jsonEncode (dart:convert/json.dart:80:10)
</code>```

答:
jsonEncode requires a Map<String, dynamic>, not a Week object. Calling your toJson() method should do the trick.

```<code>var json = jsonEncode(week.toJson());
</code>```

However, keep in mind that your toJson() method is also incorrect, as things like _goalList and the dates are still objects, not Maps or Lists. You'll need to implement toJson methods on those as well.

To answer your specific questions:

Because dart is not javascript / typescript. Dart checks types at runtime, therefore you have to explicitly tell it how to convert things - also there is no reflection in dart, so it can't figure it out by itself.

You can use a library that uses code generation to do these things automatically for you - it still wont be possible at runtime though - read more about JSON serialization.

The easiest way would be to implement the methods directly in the classes, as that's where you have access to in your root object. Keep in mind that the structure that jsonEncode needs is a Map<String, dynamic>, but the dynamic part really means List<dynamic>, Map<String, dynamic> or a primitive that is json compatible such as String or double - if you try to imagine how such a nested structure of said types looks, you'll realise that it's basically json. So when you do something like 'goalList': _goalList, you're giving it an object, which is not one of the allowed types.

Hope this clears things up a bit.

Body:
I am trying to convert the object "Week" to json.

https://flutter.dev/docs/development/data-and-backend/json this is the source that i used

class Week{
  DateTime _startDate;
  DateTime _endDate;
  List<Goal> _goalList;
  String _improvement;

  Week(this._startDate, this._endDate){
    this._goalList = List<Goal>();
    this._improvement = "";
  }

  Week.fromJson(Map<String, dynamic> json)
    : _startDate =  json['startDate'],
      _endDate = json['endDate'],
      _goalList = json['goalList'],
      _improvement = json['improvement'];

  Map<String, dynamic> toJson() =>
  {
    'startDate': _startDate,
    'endDate': _endDate,
    'goalList': _goalList,
    'improvement': _improvement,
  };
}

I used this:

DateTime startDate = currentDate.subtract(new Duration(days:(weekday-1)));
DateTime endDate = currentDate.add(new Duration(days:(7-weekday)));

Week week = new Week(startDate, endDate);
var json = jsonEncode(week);

But the problem is that I get this result:

Unhandled Exception: Converting object to an encodable object failed: Instance of 'Week'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:834:17)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:819:5)
#3      JsonEncoder.convert (dart:convert/json.dart:255:30)
#4      JsonCodec.encode (dart:convert/json.dart:166:45)
#5      jsonEncode (dart:convert/json.dart:80:10)

Body:
jsonEncode requires a Map<String, dynamic>, not a Week object. Calling your toJson() method should do the trick.

var json = jsonEncode(week.toJson());

However, keep in mind that your toJson() method is also incorrect, as things like _goalList and the dates are still objects, not Maps or Lists. You'll need to implement toJson methods on those as well.

To answer your specific questions:

Because dart is not javascript / typescript. Dart checks types at runtime, therefore you have to explicitly tell it how to convert things - also there is no reflection in dart, so it can't figure it out by itself.

You can use a library that uses code generation to do these things automatically for you - it still wont be possible at runtime though - read more about JSON serialization.

The easiest way would be to implement the methods directly in the classes, as that's where you have access to in your root object. Keep in mind that the structure that jsonEncode needs is a Map<String, dynamic>, but the dynamic part really means List<dynamic>, Map<String, dynamic> or a primitive that is json compatible such as String or double - if you try to imagine how such a nested structure of said types looks, you'll realise that it's basically json. So when you do something like 'goalList': _goalList, you're giving it an object, which is not one of the allowed types.

Hope this clears things up a bit.


问:
How to upload profile pic of a user using MULTIPART/FORM-DATA?
I'm trying to upload an image (which is selected from mobile ) using MULTIPART/FORM-DATAg and couldn't figure it out as I'm a newbie to Multipart.
The data that is to be Uploaded are the image(NOT AS BASE64CODE) and user id.</p>

答:
Try this, when you get file path on

onActivityResult

Add this code

```<code>String fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length());
String ext = fileName.substring(fileName.lastIndexOf("."));

if ((ext.equalsIgnoreCase(".jpg"))
    || (ext.equalsIgnoreCase(".jpeg"))
    || (ext.equalsIgnoreCase(".png"))) {
    // Call method to upload your image
} else {
    // Show alert to select Image with above extension
}
</code>```

Hope this will help you.

Body:
Try this, when you get file path on

onActivityResult

Add this code

String fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length());
String ext = fileName.substring(fileName.lastIndexOf("."));

if ((ext.equalsIgnoreCase(".jpg"))
    || (ext.equalsIgnoreCase(".jpeg"))
    || (ext.equalsIgnoreCase(".png"))) {
    // Call method to upload your image
} else {
    // Show alert to select Image with above extension
}

Hope this will help you.


问:
Cannot find module '@angular/core/src/metadata/lifecycle_hooks' - primeng/table/table.d.ts
I have got issue of importing primeNG table to my angular project. so i have import the table module to app.module.ts, i have got error.

ERROR in ./node_modules/primeng/components/dropdown/dropdown.js
Module not found: Error: Can't resolve '@angular/cdk/scrolling' in 'D:\test angular\primengs\node_modules\primeng\components\dropdown'
i ｢wdm｣: Failed to compile.

```<code>ERROR in node_modules/primeng/components/table/table.d.ts(5,27): error TS2307: Cannot find module '@angular/core/src/metadata/lifecycle_hooks'.
</code>```

答:
I have found the solution for it. what i have done is Navigate to "/node_modules/primeng/components/table/table.d.ts". and line no 5 have this

```<code>import { OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';
</code>```

i have changed to this.

```<code>import {OnDestroy } from '@angular/core';
</code>```

Body:
I have got issue of importing primeNG table to my angular project. so i have import the table module to app.module.ts, i have got error.

ERROR in ./node_modules/primeng/components/dropdown/dropdown.js
Module not found: Error: Can't resolve '@angular/cdk/scrolling' in 'D:\test angular\primengs\node_modules\primeng\components\dropdown'
i ｢wdm｣: Failed to compile.

ERROR in node_modules/primeng/components/table/table.d.ts(5,27): error TS2307: Cannot find module '@angular/core/src/metadata/lifecycle_hooks'.

Body:
I have found the solution for it. what i have done is Navigate to "/node_modules/primeng/components/table/table.d.ts". and line no 5 have this

import { OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';

i have changed to this.

import {OnDestroy } from '@angular/core';


问:
Archive MySQL data using PHP every week
I have a MySQL DB that receives a lot of data from a source once every week on a certain day of the week at a given time (about 1.2million rows) and stores it in, lets call it, the "live" table.

I want to copy all the data from "live" table into an archive and truncate the live table to make space for the next "current data" that will come in the following week.

Can anyone suggest an efficient way of doing this. I am really trying to avoid  -- insert into archive_table select * from live --. I would like the ability to run this archiver using PHP so I cant use Maatkit. Any suggestions?

EDIT: Also, the archived data needs to be readily accessible. Since every insert is timestamped, if I want to look for the data from last month, I can just search for it in the archives

答:
Write a script to run as a cron job to:

Dump the archive data from the "live" table (this is probably more efficient using mysqldump from a shell script)

Truncate the live table

Modify the INSERT statements in the dump file so that the table name references the archive table instead of the live table

Append the archive data to the archive table (again, could just import from dump file via shell script, e.g. mysql dbname < dumpfile.sql)

Title: Archive MySQL data using PHP every week


问:
How to read line by line from mapped file in java using MappedByteBuffer
I want to read a large file in a very fast way. I am using MappedByteBuffer like this:

```<code>String line = "";

try (RandomAccessFile file2 = new RandomAccessFile(new File(filename), "r"))
        {

            FileChannel fileChannel = file2.getChannel();

            MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());

            for (int i = 0; i < buffer.limit(); i++)
            {
               char a = (char) buffer.get();
               if (a == '\n'){
                   System.out.println(line);
                   line = "";
             }else{
                 line += Character.toString(c);

            }
        }
</code>```

This is not working correctly. It is changing the content of the file and printing the changed content. Is there a better way to read a line of a file with MappedByteBuffer?

Eventually I would like to split the line and extract certain content (since its csv) so this is just a minimal example that reproduces the problem.

答:
I made some tests using a 21 GB file filled with random strings, each line had a length of 20-40 characters.
It seems like the builtin BufferedReader is still the fastest method.

```<code>File f = new File("sfs");
try(Stream<String> lines = Files.lines(f.toPath(), StandardCharsets.UTF_8)){
    lines.forEach(line -> System.out.println(line));
} catch (IOException e) {}
</code>```

Reading the lines to a stream ensures you read the lines as you need them instead of reading the entire file at once.

To improve speed even further you can increase the buffer size of the BufferedReader by a moderate factor. In my tests it starter to outperform the normal buffer size at about 10 millions lines.

```<code> CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
 int size = 8192 * 16;
 try (BufferedReader br = new BufferedReader(new InputStreamReader(newInputStream(f.toPath()), decoder), size)) {
        br.lines().limit(LINES_TO_READ).forEach(s -> {
     });
 } catch (IOException e) {
     e.printStackTrace();
 }
</code>```

The code I used for testing:

```<code>private static long LINES_TO_READ = 10_000_000;

private static void java8Stream(File f) {

    long startTime = System.nanoTime();

    try (Stream<String> lines = Files.lines(f.toPath(), StandardCharsets.UTF_8).limit(LINES_TO_READ)) {
        lines.forEach(line -> {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    long endTime = System.nanoTime();
    System.out.println("no buffer took " + (endTime - startTime) + " nanoseconds");
}

private static void streamWithLargeBuffer(File f) {
    long startTime = System.nanoTime();

    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
    int size = 8192 * 16;
    try (BufferedReader br = new BufferedReader(new InputStreamReader(newInputStream(f.toPath()), decoder), size)) {
        br.lines().limit(LINES_TO_READ).forEach(s -> {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    long endTime = System.nanoTime();
    System.out.println("using large buffer took " + (endTime - startTime) + " nanoseconds");
}

private static void memoryMappedFile(File f) {
    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();

    long linesReadCount = 0;
    String line = "";
    long startTime = System.nanoTime();

    try (RandomAccessFile file2 = new RandomAccessFile(f, "r")) {

        FileChannel fileChannel = file2.getChannel();
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, Integer.MAX_VALUE - 10_000_000);
        CharBuffer decodedBuffer = decoder.decode(buffer);

        for (int i = 0; i < decodedBuffer.limit(); i++) {
            char a = decodedBuffer.get();
            if (a == '\n') {
                line = "";
            } else {
                line += Character.toString(a);

            }
            if (linesReadCount++ >= LINES_TO_READ){
                break;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    long endTime = System.nanoTime();

    System.out.println("using memory mapped files took " + (endTime - startTime) + " nanoseconds");

}
</code>```

Btw I noticed that FileChannel.map throws an exception if the mapped file is larger than Integer.MAX_VALUE which makes the method impractical for reading very large files.

Body:
I want to read a large file in a very fast way. I am using MappedByteBuffer like this:

String line = "";

try (RandomAccessFile file2 = new RandomAccessFile(new File(filename), "r"))
        {

            FileChannel fileChannel = file2.getChannel();

            MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());

            for (int i = 0; i < buffer.limit(); i++)
            {
               char a = (char) buffer.get();
               if (a == '\n'){
                   System.out.println(line);
                   line = "";
             }else{
                 line += Character.toString(c);

            }
        }

This is not working correctly. It is changing the content of the file and printing the changed content. Is there a better way to read a line of a file with MappedByteBuffer?

Eventually I would like to split the line and extract certain content (since its csv) so this is just a minimal example that reproduces the problem.

Body:
I made some tests using a 21 GB file filled with random strings, each line had a length of 20-40 characters.
It seems like the builtin BufferedReader is still the fastest method.

File f = new File("sfs");
try(Stream<String> lines = Files.lines(f.toPath(), StandardCharsets.UTF_8)){
    lines.forEach(line -> System.out.println(line));
} catch (IOException e) {}

Reading the lines to a stream ensures you read the lines as you need them instead of reading the entire file at once.

To improve speed even further you can increase the buffer size of the BufferedReader by a moderate factor. In my tests it starter to outperform the normal buffer size at about 10 millions lines.

 CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
 int size = 8192 * 16;
 try (BufferedReader br = new BufferedReader(new InputStreamReader(newInputStream(f.toPath()), decoder), size)) {
        br.lines().limit(LINES_TO_READ).forEach(s -> {
     });
 } catch (IOException e) {
     e.printStackTrace();
 }

The code I used for testing:

private static long LINES_TO_READ = 10_000_000;

private static void java8Stream(File f) {

    long startTime = System.nanoTime();

    try (Stream<String> lines = Files.lines(f.toPath(), StandardCharsets.UTF_8).limit(LINES_TO_READ)) {
        lines.forEach(line -> {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    long endTime = System.nanoTime();
    System.out.println("no buffer took " + (endTime - startTime) + " nanoseconds");
}

private static void streamWithLargeBuffer(File f) {
    long startTime = System.nanoTime();

    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
    int size = 8192 * 16;
    try (BufferedReader br = new BufferedReader(new InputStreamReader(newInputStream(f.toPath()), decoder), size)) {
        br.lines().limit(LINES_TO_READ).forEach(s -> {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    long endTime = System.nanoTime();
    System.out.println("using large buffer took " + (endTime - startTime) + " nanoseconds");
}

private static void memoryMappedFile(File f) {
    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();

    long linesReadCount = 0;
    String line = "";
    long startTime = System.nanoTime();

    try (RandomAccessFile file2 = new RandomAccessFile(f, "r")) {

        FileChannel fileChannel = file2.getChannel();
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, Integer.MAX_VALUE - 10_000_000);
        CharBuffer decodedBuffer = decoder.decode(buffer);

        for (int i = 0; i < decodedBuffer.limit(); i++) {
            char a = decodedBuffer.get();
            if (a == '\n') {
                line = "";
            } else {
                line += Character.toString(a);

            }
            if (linesReadCount++ >= LINES_TO_READ){
                break;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    long endTime = System.nanoTime();

    System.out.println("using memory mapped files took " + (endTime - startTime) + " nanoseconds");

}

Btw I noticed that FileChannel.map throws an exception if the mapped file is larger than Integer.MAX_VALUE which makes the method impractical for reading very large files.


问:
Unable to install override class from module in PrestaShop 1.7.5.2
On start:

Server: Apache2

DB: MySQL 5.7

PrestaShop 1.7.5.2 (fresh install)

PHP 7.2

I create custom module where i try to override class: Customer (located in root dir of prestashop in folder classes/Customer.php)
So i created folder in my module ovveride/classes/ and put my code:

```<code>    <?php
use PrestaShop\PrestaShop\Adapter\ServiceLocator;
use PrestaShop\PrestaShop\Adapter\CoreException;

/***
 * Class CustomerCore
 */
class CustomerCore extends ObjectModel
{
    public function customHook()
    {
        $isSuccess = $this->isLogged($withGuest = false);

        if ($isSuccess == true) {
            Hook::exec('actionCustomerLoginAfter', array('customer' => $this));
        }
    }
}
</code>```

And that looks folder strucute:

When i install module, evrything looks good BUT

The file (Customer.php) did not copy to override/classes/

When i try enable module i see error: Cannot enable module adminnotify. Unable to install override: Class CustomerOverride5cf26a545fb27 does not exist

I try with:

clear cache (didnt work)

manual remove cache (didnt work)

I check filenames, folder structure (looks good)

Thx all for help :)

答:
Ok problem solved :)
In this case i creat ovveride when i try to redefine class CustomerCore with orginal extends. In ovveride we must create new class and extends to core class (in this case CustomerCore). So in this case new Customer class looks like</p>

```<code><?php
    class Customer extends CustomerCore {
     //your own code
}
</code>```

Body:
On start:

Server: Apache2

DB: MySQL 5.7

PrestaShop 1.7.5.2 (fresh install)

PHP 7.2

I create custom module where i try to override class: Customer (located in root dir of prestashop in folder classes/Customer.php)
So i created folder in my module ovveride/classes/ and put my code:

    <?php
use PrestaShop\PrestaShop\Adapter\ServiceLocator;
use PrestaShop\PrestaShop\Adapter\CoreException;

/***
 * Class CustomerCore
 */
class CustomerCore extends ObjectModel
{
    public function customHook()
    {
        $isSuccess = $this->isLogged($withGuest = false);

        if ($isSuccess == true) {
            Hook::exec('actionCustomerLoginAfter', array('customer' => $this));
        }
    }
}

And that looks folder strucute:

When i install module, evrything looks good BUT

The file (Customer.php) did not copy to override/classes/

When i try enable module i see error: Cannot enable module adminnotify. Unable to install override: Class CustomerOverride5cf26a545fb27 does not exist

I try with:

clear cache (didnt work)

manual remove cache (didnt work)

I check filenames, folder structure (looks good)

Thx all for help :)

Body:
Ok problem solved :)
In this case i creat ovveride when i try to redefine class CustomerCore with orginal extends. In ovveride we must create new class and extends to core class (in this case CustomerCore). So in this case new Customer class looks like

<?php
    class Customer extends CustomerCore {
     //your own code
}


问:
Hint text color for SearchView
How to set Hint text color in SearchView?

```<code><SearchView
                android:id="@+id/search_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:iconifiedByDefault="false"
                android:transitionGroup="true" />
</code>```

I tried :

```<code><item name="android:textColorHint">@android:color/grey</item>
</code>```

And :

```<code><string name="search_hint">Search for a contact<font fgcolor="#ffbbbbbb"></font></string>
</code>```

But none of them applied hint text color.

答:
You can set the hint text color by setting a theme to your SearchView.

```<code>    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:iconifiedByDefault="false"
        android:theme="@style/SearchViewStyle"
        android:transitionGroup="true" />
</code>```

And in your styles.xml create the style.

```<code>    <style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
        <item name="android:textColorHint">@android:color/grey</item>
    </style>
</code>```

Title: Hint text color for SearchView

Body:
How to set Hint text color in SearchView?

<SearchView
                android:id="@+id/search_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:iconifiedByDefault="false"
                android:transitionGroup="true" />

I tried :

<item name="android:textColorHint">@android:color/grey</item>

And :

<string name="search_hint">Search for a contact</string>

But none of them applied hint text color.

Body:
You can set the hint text color by setting a theme to your SearchView.

    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:iconifiedByDefault="false"
        android:theme="@style/SearchViewStyle"
        android:transitionGroup="true" />

And in your styles.xml create the style.

    <style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
        <item name="android:textColorHint">@android:color/grey</item>
    </style>


问:
How to export from BigQuery to Datastore?
I have tables in BigQuery which I want to export and import in Datastore.
How to achieve that?</p>

答:
Table from BigQuery can be exported and imported to your datastore.

Download the jar file from https://github.com/yu-iskw/bigquery-to-datastore/releases

Then run the command

```<code>java -cp bigquery-to-datastore-bundled-0.5.1.jar com.github.yuiskw.beam.BigQuery2Datastore --project=yourprojectId --runner=DataflowRunner  --inputBigQueryDataset=datastore  --inputBigQueryTable=metainfo_internal_2 --outputDatastoreNamespace=default --outputDatastoreKind=meta_internal  --keyColumn=key --indexedColumns=column1,column2 --tempLocation=gs://gsheetbackup_live/temp  --gcpTempLocation=gs://gsheetlogfile_live/temp
</code>```

--tempLocation and --gcpTempLocation are valid cloud storage bucket urls.

--keyColumn=key - the key here is the unique field on your big query table

Body:
Table from BigQuery can be exported and imported to your datastore.

Download the jar file from https://github.com/yu-iskw/bigquery-to-datastore/releases

Then run the command

java -cp bigquery-to-datastore-bundled-0.5.1.jar com.github.yuiskw.beam.BigQuery2Datastore --project=yourprojectId --runner=DataflowRunner  --inputBigQueryDataset=datastore  --inputBigQueryTable=metainfo_internal_2 --outputDatastoreNamespace=default --outputDatastoreKind=meta_internal  --keyColumn=key --indexedColumns=column1,column2 --tempLocation=gs://gsheetbackup_live/temp  --gcpTempLocation=gs://gsheetlogfile_live/temp

--tempLocation and --gcpTempLocation are valid cloud storage bucket urls.

--keyColumn=key - the key here is the unique field on your big query table


问:
How to retain cursor position when using :%!filtercmd in vim?
When I issue a vim command that starts with :%!, such as :%!sort to sort all lines in the buffer, the cursor moves to the first line. How do I preserve the cursor position?

Ultimately, I want to use this command in an autocmd, such as:

```<code>augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :%!sort
augroup END
</code>```

Will the same method work in both places?

答:
I would rather use the Preserve function. Beyond solving your problem in this particular task you can use it for much more.

```<code>" preserve function
if !exists('*Preserve')
    function! Preserve(command)
        try
            let l:win_view = winsaveview()
             "silent! keepjumps keeppatterns execute a:command
            silent! execute 'keeppatterns keepjumps ' . a:command
        finally
            call winrestview(l:win_view)
        endtry
    endfunction
endif

augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :call Preserve("%!sort")
augroup END
</code>```

You can also use the "Preserve Function" to perform other useful tasks like:

```<code>command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"')
</code>```

```<code>DelBlankLines')
    fun! DelBlankLines() range
        if !&binary && &filetype != 'diff'
            call Preserve(':%s/\s\+$//e')
            call Preserve(':%s/^\n\{2,}/\r/ge')
        endif
    endfun
endif
command! -nargs=0 DelBlank :call DelBlankLines()
nnoremap <Leader>d :call DelBlankLines()<cr>

" remove trailing spaces
if !exists('*StripTrailingWhitespace')
    function! StripTrailingWhitespace()
        if !&binary && &filetype != 'diff'
            call Preserve(":%s,\\s\\+$,,e")
        endif
    endfunction
endif
command! Cls call StripTrailingWhitespace()
cnoreabbrev cls Cls
cnoreabbrev StripTrailingSpace Cls

</code>```

Body:
When I issue a vim command that starts with :%!, such as :%!sort to sort all lines in the buffer, the cursor moves to the first line. How do I preserve the cursor position?

Ultimately, I want to use this command in an autocmd, such as:

augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :%!sort
augroup END

Will the same method work in both places?

Body:
I would rather use the Preserve function. Beyond solving your problem in this particular task you can use it for much more.

" preserve function
if !exists('*Preserve')
    function! Preserve(command)
        try
            let l:win_view = winsaveview()
             "silent! keepjumps keeppatterns execute a:command
            silent! execute 'keeppatterns keepjumps ' . a:command
        finally
            call winrestview(l:win_view)
        endtry
    endfunction
endif

augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :call Preserve("%!sort")
augroup END

You can also use the "Preserve Function" to perform other useful tasks like:

command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"')

DelBlankLines')
    fun! DelBlankLines() range
        if !&binary && &filetype != 'diff'
            call Preserve(':%s/\s\+$//e')
            call Preserve(':%s/^\n\{2,}/\r/ge')
        endif
    endfun
endif
command! -nargs=0 DelBlank :call DelBlankLines()
nnoremap <Leader>d :call DelBlankLines()<cr>

" remove trailing spaces
if !exists('*StripTrailingWhitespace')
    function! StripTrailingWhitespace()
        if !&binary && &filetype != 'diff'
            call Preserve(":%s,\\s\\+$,,e")
        endif
    endfunction
endif
command! Cls call StripTrailingWhitespace()
cnoreabbrev cls Cls
cnoreabbrev StripTrailingSpace Cls


问:
Xcode Error When Added AdMob Plugin To Ionic Project
I have an Ionic 3 Project and its running normally on Ionic DevApp And Xcode. But When i added AdMob Plugin , its running normally Ionic DevApp but its not running on Xcode. I tried Simulator and Real Device but i have some mistake both of them.

There is my error codes;

```<code>Terminating app due to uncaught exception
'GADInvalidInitializationException', reason:
'The Google Mobile Ads SDK was initialized incorrectly.
Google AdMob publishers should follow instructions here:

https://googlemobileadssdk.page.link/admob-ios-update-plist
to include the AppMeasurement framework,
set the -ObjC linker flag, and set
GADApplicationIdentifier with a valid App ID.

Google Ad Manager publishers should follow
instructions here:
https://googlemobileadssdk.page.link/ad-manager-ios-update-plist
</code>```

答: There is a new procedure, you need to add GADIsAdManagerApp key for info.plist file with boolean YES value

Body:
I have an Ionic 3 Project and its running normally on Ionic DevApp And Xcode. But When i added AdMob Plugin , its running normally Ionic DevApp but its not running on Xcode. I tried Simulator and Real Device but i have some mistake both of them.

There is my error codes;

Terminating app due to uncaught exception
'GADInvalidInitializationException', reason:
'The Google Mobile Ads SDK was initialized incorrectly.
Google AdMob publishers should follow instructions here:

https://googlemobileadssdk.page.link/admob-ios-update-plist
to include the AppMeasurement framework,
set the -ObjC linker flag, and set
GADApplicationIdentifier with a valid App ID.

Google Ad Manager publishers should follow
instructions here:
https://googlemobileadssdk.page.link/ad-manager-ios-update-plist


问:
How can I cast to Int an object from userInfo notification?
I am trying to parse gcm.notification.createdAt key, but its value is not being casted as Int.
Strangely it is not working even though the value type is clearly Int as you can see.
Any idea what am I doing wrong here?

```<code>userInfo is [AnyHashable("gcm.notification.chatUID"): -LgHYXKFNmP-mQo7s9nB,
             AnyHashable("gcm.notification.type"): chat,
             AnyHashable("gcm.notification.createdAt"): 1559389303,
             AnyHashable("google.c.a.e"): 1,
             AnyHashable("gcm.message_id"): 0:1559389316529351%e413fc3ee413fc3e,
             AnyHashable("aps"): {
    alert =     {
        body = "You have a new message";
        title = "New Message from Lehz Raus";
    };
    badge = 1;
    sound = default;
}]

let userInfo =  response.notification.request.content.userInfo

guard let createdAt = userInfo["gcm.notification.createdAt"] as? Int else {
            print("gcm.notification.createdAt is not showing")
            return
           }

 //this works as expected
    guard let chatUUUUID = userInfo["gcm.notification.chatUID"] as? String else {
        print("no chatUUUUID printed")
        return
    }
</code>```

答:
I suspect your value is not really an Int.

You can investigate the underlying type by printing:

```<code>print(type(of: userInfo["gcm.notification.createdAt"]!))
</code>```

From the comments, you said it returned: __NSCFString so the server is giving you a String.  You can convert that to an Int with an additional line in your guard statement:

```<code>guard let createdAt = userInfo["gcm.notification.createdAt"] as? String,
      let createdAtInt = Int(createdAt) else {
    print("gcm.notification.createdAt is not showing")
    return
}
</code>```

Body:
I am trying to parse gcm.notification.createdAt key, but its value is not being casted as Int.
Strangely it is not working even though the value type is clearly Int as you can see.
Any idea what am I doing wrong here?

userInfo is [AnyHashable("gcm.notification.chatUID"): -LgHYXKFNmP-mQo7s9nB,
             AnyHashable("gcm.notification.type"): chat,
             AnyHashable("gcm.notification.createdAt"): 1559389303,
             AnyHashable("google.c.a.e"): 1,
             AnyHashable("gcm.message_id"): 0:1559389316529351%e413fc3ee413fc3e,
             AnyHashable("aps"): {
    alert =     {
        body = "You have a new message";
        title = "New Message from Lehz Raus";
    };
    badge = 1;
    sound = default;
}]

let userInfo =  response.notification.request.content.userInfo

guard let createdAt = userInfo["gcm.notification.createdAt"] as? Int else {
            print("gcm.notification.createdAt is not showing")
            return
           }

 //this works as expected
    guard let chatUUUUID = userInfo["gcm.notification.chatUID"] as? String else {
        print("no chatUUUUID printed")
        return
    }

Body:
I suspect your value is not really an Int.

You can investigate the underlying type by printing:

print(type(of: userInfo["gcm.notification.createdAt"]!))

From the comments, you said it returned: __NSCFString so the server is giving you a String.  You can convert that to an Int with an additional line in your guard statement:

guard let createdAt = userInfo["gcm.notification.createdAt"] as? String,
      let createdAtInt = Int(createdAt) else {
    print("gcm.notification.createdAt is not showing")
    return
}


问:
Python Jupyter notebook, call a bash function declared in a different cell
I know that different cells in a Python Jupiter notebook are executed in different subshells. However, I would want to declare a bash function in one shell and the call it from other multiple cells:

In [1]:

%%bash
function my_func {
    #...
}
```

<p>In [2]:</p>

```%%bash
my_func
```

<p>In [3]:</p>

```%%bash
my_func
```

Is there some way to do it? I don't want to put the function in ~/.bashrc for example because I want it to be a part of the notebook.

答:
You could use the inline alias magic to reference my_func. Here is a quick example of doing multiple commands in a single alias and passing a parameter if needed.

Another way would be to use the python subprocess module. You would define the subprocess and call it as needed.

Body:
I know that different cells in a Python Jupiter notebook are executed in different subshells. However, I would want to declare a bash function in one shell and the call it from other multiple cells:

In [1]:

%%bash
function my_func {
    #...
}

In [2]:

%%bash
my_func

In [3]:

%%bash
my_func

Is there some way to do it? I don't want to put the function in ~/.bashrc for example because I want it to be a part of the notebook.