问:
Multiple foreach passes to different class lists
I'm working on a "bank application" in C# WPF where I came upon error:CS0052

Inconsistent accessibility: field type 'List' is less
  accessible than field 'Customer.CustomerAccountsList'

The idea is that the method bool DoseThisAccountExistAlready() should check all  customers one by one and see if his/her accounts have the same data as the account that is about to be created.

However CustomerAccountsList must be public or DoseThisAccountExistAlready() can't access the accounts data.

How do I fix this error?

```<code>//main window

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Uppgift2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public List<Customer> ListOfAllCustomers = new List<Customer>();

        public bool Login(string fornamn, string efternamn, string pin)
        {
            foreach (Customer c in ListOfAllCustomers)
            {
                if (c.firstname == fornamn && c.lastname == efternamn && c.pinKod == pin)
                {
                    MessageBox.Show("Login succesfull. Welcome " + c.firstname + " " + c.lastname);
                    WindowAccountOperations LoggedInUser = new WindowAccountOperations();
                    LoggedInUser.ShowDialog();
                    return true;
                }
                else
                {
                    MessageBox.Show("Det finns inte ett sånt användare. Kontrolera användarnamn och pin");
                    return false;
                }
            }
            return false;
        }

        //Customer pin could be remade into a rondom generator with an if() that forces it to be a four digit number
       /*
        *   Random randomPin = new Random();
            randomPin.Next(x, y);

            if(randomPin.ToString().Length!=4)
             {

             }
      */

        public bool CreateNewCustomer(string fornamn, string efternamn, string telefon, string customerAdress, string customerPin)
        {
            //Is there already such customer?
            foreach (Customer c in ListOfAllCustomers)
            {
                if ((c.firstname == fornamn && c.lastname == efternamn && c.adress == customerAdress))
                {
                    MessageBox.Show("Kunden med ett sånt förnamn, efternamn och adress redan finns");
                    return false;
                }

                if(c.pinKod == customerPin)
                {
                    MessageBox.Show("Kunden med ett sånt pinkod redan finns");
                    return false;
                }
                else
                {
                    ListOfAllCustomers.Add(new Customer(TBFirstNameNyKund.Text, TBSecondNameLogin.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text));
                    MessageBox.Show("Registration complete. Du kan nu logga in");

                    TBFirstNameNyKund.Clear(); TBSecondNameLogin.Clear(); TBAdressNyKund.Clear(); TBPinNyKund.Clear();//clear login textboxes
                    return true;
                }
            }
            return false;
        }

        public bool DoseThisAccountExistAlready(string kontoNummer, string kontotyp)
        {
            foreach (Customer c in ListOfAllCustomers )
            {
                foreach(Account a in c.CustomerAccountsList)
                {

                    if(a.accountType==kontotyp)//Does customer c try to create another type of account he already has?
                    {
                        return true;
                    }

                    if(a.accountNumber==kontoNummer)
                    {
                        return true;
                    }

                }
                return false;
            }

            return false;
        }

        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            Login(TBFirstNameLogin.Text, TBSecondNameLogin.Text, TBPinLogin.Text);
        }

        private void ButtonSkapaKund_Click(object sender, RoutedEventArgs e)
        {
            CreateNewCustomer(TBFirstNameNyKund.Text, TBSecondNameNyKund.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text);
        }
    }
}

//customer class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Uppgift2
{
  public class Customer
  {
    public string adress;
    public string celphone;
    public string firstname;
    public string lastname;
    public string pinKod;

    public List<Account> CustomerAccountsList = new List<Account>();//Error apears here.

    public Customer(string fname,string lname, string tel, string    customerAdress,string customerPin)
    {
        adress = customerAdress;
        celphone = tel;
        firstname = fname;
        lastname = lname;
        pinKod = customerPin;
    }

  }
}

//account base class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Uppgift2
{
     abstract class Account   //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation=base class for other classes
    {

        public double payoutAmmount;
        protected double payoutTax;
        public bool creditPosible;

        public string accountNumber;
        public string accountType;
        public double balance;
        protected double interest; //customer shouldent be able to modify interest %

        //constructor
        public Account(string kontoNummer, double KontoStartsaldo,string kontoTyp, double ranta, bool finsdetkredit,double uttagPris)
        {
            accountNumber = kontoNummer;
            balance = KontoStartsaldo;
            accountType = kontoTyp;
            creditPosible = finsdetkredit;
            payoutTax = uttagPris;
        }

        public double InsertMoney(int chosenAccount, double payout)  //int chosenAccount becouse i thought to use a combo box index
        {
            payoutAmmount = payout;

            balance = balance - payout + (payout * payoutTax);
            return balance;

        }
    }
}
</code>```

答: You can't have a public List<Account> because the Account class has no access modifier so it is defaulted by the compiler to be internal. You can't have a public property of an internal type. You need to make it public for this to work.

Body:
I'm working on a "bank application" in C# WPF where I came upon error:CS0052

Inconsistent accessibility: field type 'List' is less
  accessible than field 'Customer.CustomerAccountsList'

The idea is that the method bool DoseThisAccountExistAlready() should check all  customers one by one and see if his/her accounts have the same data as the account that is about to be created.

However CustomerAccountsList must be public or DoseThisAccountExistAlready() can't access the accounts data.

How do I fix this error?

//main window

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Uppgift2
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public List<Customer> ListOfAllCustomers = new List<Customer>();

        public bool Login(string fornamn, string efternamn, string pin)
        {
            foreach (Customer c in ListOfAllCustomers)
            {
                if (c.firstname == fornamn && c.lastname == efternamn && c.pinKod == pin)
                {
                    MessageBox.Show("Login succesfull. Welcome " + c.firstname + " " + c.lastname);
                    WindowAccountOperations LoggedInUser = new WindowAccountOperations();
                    LoggedInUser.ShowDialog();
                    return true;
                }
                else
                {
                    MessageBox.Show("Det finns inte ett sånt användare. Kontrolera användarnamn och pin");
                    return false;
                }
            }
            return false;
        }

        //Customer pin could be remade into a rondom generator with an if() that forces it to be a four digit number
       /*
        *   Random randomPin = new Random();
            randomPin.Next(x, y);

            if(randomPin.ToString().Length!=4)
             {

             }
      */

        public bool CreateNewCustomer(string fornamn, string efternamn, string telefon, string customerAdress, string customerPin)
        {
            //Is there already such customer?
            foreach (Customer c in ListOfAllCustomers)
            {
                if ((c.firstname == fornamn && c.lastname == efternamn && c.adress == customerAdress))
                {
                    MessageBox.Show("Kunden med ett sånt förnamn, efternamn och adress redan finns");
                    return false;
                }

                if(c.pinKod == customerPin)
                {
                    MessageBox.Show("Kunden med ett sånt pinkod redan finns");
                    return false;
                }
                else
                {
                    ListOfAllCustomers.Add(new Customer(TBFirstNameNyKund.Text, TBSecondNameLogin.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text));
                    MessageBox.Show("Registration complete. Du kan nu logga in");

                    TBFirstNameNyKund.Clear(); TBSecondNameLogin.Clear(); TBAdressNyKund.Clear(); TBPinNyKund.Clear();//clear login textboxes
                    return true;
                }
            }
            return false;
        }

        public bool DoseThisAccountExistAlready(string kontoNummer, string kontotyp)
        {
            foreach (Customer c in ListOfAllCustomers )
            {
                foreach(Account a in c.CustomerAccountsList)
                {

                    if(a.accountType==kontotyp)//Does customer c try to create another type of account he already has?
                    {
                        return true;
                    }

                    if(a.accountNumber==kontoNummer)
                    {
                        return true;
                    }

                }
                return false;
            }

            return false;
        }

        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            Login(TBFirstNameLogin.Text, TBSecondNameLogin.Text, TBPinLogin.Text);
        }

        private void ButtonSkapaKund_Click(object sender, RoutedEventArgs e)
        {
            CreateNewCustomer(TBFirstNameNyKund.Text, TBSecondNameNyKund.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text);
        }
    }
}

//customer class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Uppgift2
{
  public class Customer
  {
    public string adress;
    public string celphone;
    public string firstname;
    public string lastname;
    public string pinKod;

    public List<Account> CustomerAccountsList = new List<Account>();//Error apears here.

    public Customer(string fname,string lname, string tel, string    customerAdress,string customerPin)
    {
        adress = customerAdress;
        celphone = tel;
        firstname = fname;
        lastname = lname;
        pinKod = customerPin;
    }

  }
}

//account base class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Uppgift2
{
     abstract class Account   //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation=base class for other classes
    {

        public double payoutAmmount;
        protected double payoutTax;
        public bool creditPosible;

        public string accountNumber;
        public string accountType;
        public double balance;
        protected double interest; //customer shouldent be able to modify interest %

        //constructor
        public Account(string kontoNummer, double KontoStartsaldo,string kontoTyp, double ranta, bool finsdetkredit,double uttagPris)
        {
            accountNumber = kontoNummer;
            balance = KontoStartsaldo;
            accountType = kontoTyp;
            creditPosible = finsdetkredit;
            payoutTax = uttagPris;
        }

        public double InsertMoney(int chosenAccount, double payout)  //int chosenAccount becouse i thought to use a combo box index
        {
            payoutAmmount = payout;

            balance = balance - payout + (payout * payoutTax);
            return balance;

        }
    }
}


来源: stackexchange

问:
Any way to provide Eclipse auto error-discovery feature in Vim/Emacs?
I know that Vim/Emacs offers some enticing mouse-free capabilities for typing out programs. I have tried both and I love these facilities. But when coding Java, especially when using the libraries extensively, the auto-complete and error-highlighting features of Eclipse are too useful to be set aside.
                                                                                Is there a way to combine the best of both worlds? </p>

答:
Vim JDE (script) does this for vi, Eclim tries to make vi do everything Eclipse does in that sense, but also requires you to run Eclipse in headless mode while you're using vi.

For Emacs, you can try JDEE.

Good luck!

ContentLicense: CC BY-SA 2.5


问:
Iterate through xml file and store content inside Textfield c#
I have an Xml file where I want to loop through each module node which increments by 1. Here is a sample of my xml file:

```<code><PersonDetails>
  <PersonTitle>Teacher</PersonTitle>
  <Keystage3>
    <Subject>
      <subjectName>maths</subjectName>
      <subjectId>qq1</subjectId>
      <subjectvalue>20</subjectvalue>
      <subjectscore />
    </Subject>
    <Subject>
      <subjectName>science</subjectName>
      <subjectId>sla1s</subjectId>
      <subjectvalue>25</subjectvalue>
      <subjectscore />
    </Subject>
  </Keystage3>
</PersonDetails>
</code>```

I want to loop through the xml file and get all data of Subject for both
<Subject> node and store each value inside a variable.

I have a piece of code which gets the value from a specific node and outputs
it on a textfield.

here is the code I have so far:

```<code>public partial class Form1 : Form
{
    private string subName, subId, subvalue;

    public XmlDocument Doc;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        XmlTextReader reader = new XmlTextReader("data.xml");
        XmlNodeType type;

        while (reader.Read()) {

            type = reader.NodeType;

            if(type == XmlNodeType.Element)
            {

                    if (reader.Name == "subjectName")
                    {
                        reader.Read();
                        textBox1.Text = reader.Value;
                    }
                    if (reader.Name == "subjectId")
                    {
                        reader.Read();
                        textBox2.Text = reader.Value;
                    }
                    if (reader.Name == "subjectvalue")
                    {
                        reader.Read();
                        textBox3.Text = reader.Value;
                   }

            }
        }
        reader.Close();

    }
</code>```

How can I make it so that the output recieved is something like:

```<code>{maths,qq1,20}
{science,sla1s,25}
</code>```

答:
Using some LINQ-Magic you can do the folowing:

```<code>XElement root = XElement.Load("data.xml");
        var subjects = from subject in root.Descendants()
                          where subject.Name.LocalName.Contains("Subject")
                          select new
                          {
                              SubjectName = subject.Element("subjectName").Value,
                              SubjectId = subject.Element("subjectId").Value,
                              SubjectValue = subject.Element("subjectvalue").Value
                          };

foreach (var subject in subjects)
{
    Console.WriteLine(subject);

    //you can use subject like this:
    string subjectName = subject.SubjectName;
    string subjectId = subject.SubjectId;
    string subjectValue = subject.SubjectValue;
}
</code>```

This will print:

```<code>{ SubjectName = maths, SubjectId = qq1, SubjectValue = 20 }
{ SubjectName = science, SubjectId = sla1s, SubjectValue = 25 }
</code>```

Includes:

```<code>using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an Xml file where I want to loop through each module node which increments by 1. Here is a sample of my xml file:

<PersonDetails>
  <PersonTitle>Teacher</PersonTitle>
  <Keystage3>
    <Subject>
      <subjectName>maths</subjectName>
      <subjectId>qq1</subjectId>
      <subjectvalue>20</subjectvalue>
      <subjectscore />
    </Subject>
    <Subject>
      <subjectName>science</subjectName>
      <subjectId>sla1s</subjectId>
      <subjectvalue>25</subjectvalue>
      <subjectscore />
    </Subject>
  </Keystage3>
</PersonDetails>

I want to loop through the xml file and get all data of Subject for both
<Subject> node and store each value inside a variable.

I have a piece of code which gets the value from a specific node and outputs
it on a textfield.

here is the code I have so far:

public partial class Form1 : Form
{
    private string subName, subId, subvalue;

    public XmlDocument Doc;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        XmlTextReader reader = new XmlTextReader("data.xml");
        XmlNodeType type;

        while (reader.Read()) {

            type = reader.NodeType;

            if(type == XmlNodeType.Element)
            {

                    if (reader.Name == "subjectName")
                    {
                        reader.Read();
                        textBox1.Text = reader.Value;
                    }
                    if (reader.Name == "subjectId")
                    {
                        reader.Read();
                        textBox2.Text = reader.Value;
                    }
                    if (reader.Name == "subjectvalue")
                    {
                        reader.Read();
                        textBox3.Text = reader.Value;
                   }

            }
        }
        reader.Close();

    }

How can I make it so that the output recieved is something like:

{maths,qq1,20}
{science,sla1s,25}

Body:
Using some LINQ-Magic you can do the folowing:

XElement root = XElement.Load("data.xml");
        var subjects = from subject in root.Descendants()
                          where subject.Name.LocalName.Contains("Subject")
                          select new
                          {
                              SubjectName = subject.Element("subjectName").Value,
                              SubjectId = subject.Element("subjectId").Value,
                              SubjectValue = subject.Element("subjectvalue").Value
                          };

foreach (var subject in subjects)
{
    Console.WriteLine(subject);

    //you can use subject like this:
    string subjectName = subject.SubjectName;
    string subjectId = subject.SubjectId;
    string subjectValue = subject.SubjectValue;
}

This will print:

{ SubjectName = maths, SubjectId = qq1, SubjectValue = 20 }
{ SubjectName = science, SubjectId = sla1s, SubjectValue = 25 }

Includes:

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;


问:
Angular JS 1 : multiple-date-picker time change
I am new to AngularJS and trying to implement multi date time picker functionlity with one check box .

I am using multiple-date-picker

multiple-date-picker

and here I am trying to change the time of the date I have picked and want the two values(date with changes time and the check box value) in one new array

right now when I am trying to iterate the array I am getting and pushing the array value to the new array but nothing is working

below is the code

```<code>    <div class="col-sm-9">
        <div class="input-group">
            <multiple-date-picker ng-model="myArrayOfDates"></multiple-date-picker>
        </div>
    </div>
    <div class="form-group booking-groups" ng-repeat="m in myArrayOfDates">
        <div class="col-sm-3 text-right">

            <label>{{m| cmdate:'EEEE, d MMM yy' }}   Time</label>

        </div>
        <div class="col-sm-5">
            <div class="input-time" width="50%">
                <div uib-timepicker ng-model="myArrayofTimes" ng-init="LoadTimes(m)" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian" required></div>
            </div>
        </div>
        <div class="col-sm-4">
            <div >
                <div class="input-time" width="50%">
                <label>Allow Multiround Booking</label>
                <div><input type="checkbox" ng-model="checkboxModel"></div>
            </div>
        </div>
    </div>
</code>```

JavaScript:

```<code>        $scope.myArrayOfDates = [];

        $scope.myArrayofTimes = [];

        $scope.checkboxModel = [{}];

        $scope.myFinalArray=[];

        $scope.LoadTimes = function (datentime) {

            alert(datentime);

            for (var i = 0; i < $scope.myArrayOfDates.length; i++) {

                alert($scope.myArrayOfDates.length);
                alert($scope.myArrayofTimes.length);
                $scope.myArrayofTimes[i] = $scope.myArrayofDates[i];
                $scope.myArrayofTimes[i] = datentime;
            }

        }
</code>```

Please advice.

答:
I'm not exactly sure what you want, but please see below findings.

Just check this for loop.

```<code>for (var i = 0; i < $scope.myArrayOfDates.length; i++) {

                alert($scope.myArrayOfDates.length);
                alert($scope.myArrayofTimes.length);
                $scope.myArrayofTimes[i] = $scope.myArrayofDates[i];
                $scope.myArrayofTimes[i] = datentime;  //Something is wrong with this
            }
</code>```

You are first assigning value to $scope.myArrayofTimes[i]. And on the next step again overriding this value with datentime.

Body:
I am new to AngularJS and trying to implement multi date time picker functionlity with one check box .

I am using multiple-date-picker

multiple-date-picker

and here I am trying to change the time of the date I have picked and want the two values(date with changes time and the check box value) in one new array

right now when I am trying to iterate the array I am getting and pushing the array value to the new array but nothing is working

below is the code

            <multiple-date-picker ng-model="myArrayOfDates"></multiple-date-picker>

            {{m| cmdate:'EEEE, d MMM yy' }}   Time

                Allow Multiround Booking

<input type="checkbox" ng-model="checkboxModel">

JavaScript:

        $scope.myArrayOfDates = [];

        $scope.myArrayofTimes = [];

        $scope.checkboxModel = [{}];

        $scope.myFinalArray=[];

        $scope.LoadTimes = function (datentime) {

            alert(datentime);

            for (var i = 0; i < $scope.myArrayOfDates.length; i++) {

                alert($scope.myArrayOfDates.length);
                alert($scope.myArrayofTimes.length);
                $scope.myArrayofTimes[i] = $scope.myArrayofDates[i];
                $scope.myArrayofTimes[i] = datentime;
            }

        }

Please advice.

Body:
I'm not exactly sure what you want, but please see below findings.

Just check this for loop.

for (var i = 0; i < $scope.myArrayOfDates.length; i++) {

                alert($scope.myArrayOfDates.length);
                alert($scope.myArrayofTimes.length);
                $scope.myArrayofTimes[i] = $scope.myArrayofDates[i];
                $scope.myArrayofTimes[i] = datentime;  //Something is wrong with this
            }

You are first assigning value to $scope.myArrayofTimes[i]. And on the next step again overriding this value with datentime.


问:
Cannot find Method inside Stream.generate().forEach()

System.out.println(GraphController.GRAPHPOOL.peek().getEdge());
    Stream.generate(() -> {
     try {
       return GraphController.GRAPHPOOL.take();
     } catch (InterruptedException ie) {
       return "Interrupted!";
     }
    })
    .forEach(g   -> {System.out.println(g.getEdge());}
    });
```

I am able to print the object Edge returned by getEdge out of Stream.generate().forEach(), however, within forEach I can access only object g.

When trying to access g.getEdge() I get an error as follows:

error: cannot find symbol

System.out.println(g.getEdge());

symbol:   method getEdge()

location: variable g of type Object

How can I access g.getEdge()?

答:
due to the call GraphController.GRAPHPOOL.take(); returning a different type to the statement return "Interrupted!", the elements returned by the generate intermediate method will all be of type Object and there is no such method called getEdge() within the Object class. To overcome the problem you can do something like:

```<code>.forEach(g -> {
       if(g instanceof TheType){
           System.out.println(((TheType)g).getEdge());
       }
       else{
           // "interrupted"
       }
   });
</code>```

Also, note that the method generate(Supplier<T> s) returns an infinite sequential stream, usually in cases like this you'll want to utilize limit to truncate the stream.

Body:
System.out.println(GraphController.GRAPHPOOL.peek().getEdge());
    Stream.generate(() -> {
     try {
       return GraphController.GRAPHPOOL.take();
     } catch (InterruptedException ie) {
       return "Interrupted!";
     }
    })
    .forEach(g   -> {System.out.println(g.getEdge());}
    });

I am able to print the object Edge returned by getEdge out of Stream.generate().forEach(), however, within forEach I can access only object g.

When trying to access g.getEdge() I get an error as follows:

error: cannot find symbol

System.out.println(g.getEdge());

symbol:   method getEdge()

location: variable g of type Object

How can I access g.getEdge()?

Body:
due to the call GraphController.GRAPHPOOL.take(); returning a different type to the statement return "Interrupted!", the elements returned by the generate intermediate method will all be of type Object and there is no such method called getEdge() within the Object class. To overcome the problem you can do something like:

.forEach(g -> {
       if(g instanceof TheType){
           System.out.println(((TheType)g).getEdge());
       }
       else{
           // "interrupted"
       }
   });

Also, note that the method generate(Supplier<T> s) returns an infinite sequential stream, usually in cases like this you'll want to utilize limit to truncate the stream.


答:
You want cumulative sums (well, the difference between them):

```<code>select a, b, sum(a - b) over (order by num, artid)
from mytbl;
</code>```

Note:  SQL tables represent unordered sets.  You need a column to specify the ordering to define previous. If you really only have two columns, then I might assume the ordering is based on a, and the query would be:

```<code>select a, b, sum(a - b) over (order by a)
from mytbl;
</code>```

Title: SQL Server sum field from previous calculation

Body:
In SQL Server, I have table with 4 column

 artid    num     A           B
   46     1     417636000     0
   47     1     15024000      0
  102     1     3418105650    0
  226     1     1160601286    0
  60     668    260000        0
  69     668    5500000       0

I want in result set create new column for some calculation

This column should have value like this:

artid       num         a                      b                      newColumnValue
----------- ----------- ---------------------- ---------------------- ----------------------
46          1           417636000              0                      a-b+previous newColumnValue

I write this query, but I can't get previous newColumnValue:

select *, (a- b+ lag(a- b, 1, a- b) over (order by num,artid)) as newColumnValue
 FROM MainTbl
  ORDER BY  num,artid

i get this result

artid       num         a                      b                      newColumnValue
----------- ----------- ---------------------- ---------------------- ----------------------
46          1           417636000              0                      417636000
47          1           15024000               0                      432660000
102         1           3418105650             0                      3433129650
226         1           1160601286             0                      4578706936
60          668         260000                 0                      1160861286
69          668         5500000                0                      5760000

i want get this result

artid       num         a                      b                      newColumnValue
----------- ----------- ---------------------- ---------------------- ----------------------
46          1           417636000              0                      417636000
47          1           15024000               0                      432660000
102         1           3418105650             0                      3850765650
226         1           1160601286             0                      5011366936
60          668         260000                 0                      5011626936
69          668         5500000                0                      5017126936

Body:
You want cumulative sums (well, the difference between them):

select a, b, sum(a - b) over (order by num, artid)
from mytbl;

Note:  SQL tables represent unordered sets.  You need a column to specify the ordering to define previous. If you really only have two columns, then I might assume the ordering is based on a, and the query would be:

select a, b, sum(a - b) over (order by a)
from mytbl;


问:
let variable conflict on closure compiler
I have 2 javascript files and each has a variable 'let logger' in file scope. And file2 imports file1.

 file1.js

let logger;

 file2.js

mod = require("./file1.js);
 let logger;

Javascript parsers(nodejs) create file scope for let variables(instead of global scope). But JSC_REDECLARED_VARIABLE_ERROR is thrown in closure compiler.

Is there any way to suppress this error?

答:
JS parsers do not create file scope for variables of any type. NodeJS files are modules which have a unique scope. If your file is processed as a module, it will be given a unique scope.

For commonJS modules, using the --process_common_js_modules flag of the compiler will recognize and bundle CommonJS modules.

However the Closure Compiler is primarily designed to target browsers. It's not currently designed to properly bundle code that targets NodeJS - though some users utilize the type checking functionality only for Node.


问:
Slim framework Message: Callable Homecontroller does not exist

Project Structure

public/index.php

```<code><?php

require __DIR__ . '/../vendor/autoload.php';

ini_set('display_errors', 'On');

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $url  = parse_url($_SERVER['REQUEST_URI']);
    $file = __DIR__ . $url['path'];
    if (is_file($file)) {
        return false;
    }
}

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';

$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();
</code>```

Here we have the composer.json

```<code>{

"autoload":{
    "psr-4": {
        "App\\": "src"
    }
},

"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "slim/php-view": "^2.0",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.3"
},
"require-dev": {
    "phpunit/phpunit": ">=4.8 < 6.0"
},

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"config": {
    "process-timeout" : 0
},
}
</code>```

Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more

```<code><?php

namespace \App\Controllers;

class Homecontroller
{
    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        echo "locura";
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}
</code>```

Actual configuration
In my routes.php I have put this:

```<code>$app->get('/new', \Homecontroller::class . ':home');
</code>```

Before configuration

In the above code, I tried to create the controller into the container, and then use

```<code>$app->get('/new', '\HomeController:home');
</code>```

And in the dependencies.php I put this code:

```<code>$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
</code>```

};

but I didn't obtain any result with any configuration

I would like to load the HomeController from router

This is the error that I have when I put api.powertv/new

```<code> Type: RuntimeException
 Message: Callable Homecontroller does not exist
File:       /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90
</code>```

i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.

答:
with the answer of Pheara I obtain another error, is the next:

```<code>Type: Error
Message: Undefined constant 'App\controllers'
File:/Users/alfonso/Sites/powertv_api/src/Controllers/HomeController.php
Line: 5
</code>```

the trace of the error is the next:

```<code> /Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(444):   include()
#1  /Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(322):   Composer\Autoload\includeFile('/Users/alfonso/...')
#2 [internal function]: Composer\Autoload\ClassLoader- >loadClass('App\\Controllers...')
#3 [internal function]: spl_autoload_call('App\\Controllers...')
#4 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(89): class_exists('App\\Controllers...')
#5 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(67): Slim\CallableResolver->resolveCallable('App\\Controllers...')
#6 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolverAwareTrait.php(45): Slim\CallableResolver->resolve('App\\Controllers...')
#7 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(330): Slim\Routable->resolveCallable('App\\Controllers...')
#8 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(313): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(495): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#11 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#12 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(388): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#13 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(296): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#14 /Users/alfonso/Sites/powertv_api/public/index.php(39): Slim\App->run()
#15 {main}
</code>```

For solve this error you have to put the namespace in the 3 line:

```<code><?php

namespace [yournamespace]

//rest of your controller
</code>```

Body:
Project Structure

public/index.php

<?php

require __DIR__ . '/../vendor/autoload.php';

ini_set('display_errors', 'On');

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $url  = parse_url($_SERVER['REQUEST_URI']);
    $file = __DIR__ . $url['path'];
    if (is_file($file)) {
        return false;
    }
}

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';

$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();

Here we have the composer.json

{

"autoload":{
    "psr-4": {
        "App\\": "src"
    }
},

"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "slim/php-view": "^2.0",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.3"
},
"require-dev": {
    "phpunit/phpunit": ">=4.8 < 6.0"
},

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"config": {
    "process-timeout" : 0
},
}

Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more

<?php

namespace \App\Controllers;

class Homecontroller
{
    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        echo "locura";
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}

Actual configuration
In my routes.php I have put this:

$app->get('/new', \Homecontroller::class . ':home');

Before configuration

In the above code, I tried to create the controller into the container, and then use

$app->get('/new', '\HomeController:home');

And in the dependencies.php I put this code:

$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);

};

but I didn't obtain any result with any configuration

I would like to load the HomeController from router

This is the error that I have when I put api.powertv/new

 Type: RuntimeException
 Message: Callable Homecontroller does not exist
File:       /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90

i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.

Body:
with the answer of Pheara I obtain another error, is the next:

Type: Error
Message: Undefined constant 'App\controllers'
File:/Users/alfonso/Sites/powertv_api/src/Controllers/HomeController.php
Line: 5

the trace of the error is the next:

 /Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(444):   include()
#1  /Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(322):   Composer\Autoload\includeFile('/Users/alfonso/...')
#2 [internal function]: Composer\Autoload\ClassLoader- >loadClass('App\\Controllers...')
#3 [internal function]: spl_autoload_call('App\\Controllers...')
#4 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(89): class_exists('App\\Controllers...')
#5 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(67): Slim\CallableResolver->resolveCallable('App\\Controllers...')
#6 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolverAwareTrait.php(45): Slim\CallableResolver->resolve('App\\Controllers...')
#7 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(330): Slim\Routable->resolveCallable('App\\Controllers...')
#8 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(313): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(495): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#11 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#12 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(388): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#13 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(296): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#14 /Users/alfonso/Sites/powertv_api/public/index.php(39): Slim\App->run()
#15 {main}

For solve this error you have to put the namespace in the 3 line:

<?php

namespace [yournamespace]

//rest of your controller


问:
How do I detect a click outside an element?
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.

Is something like this possible with jQuery?

```<code>$("#menuscontainer").clickOutsideThisElement(function() {
    // Hide the menus
});
</code>```

答:
If you just want to display a window when you click on a button and undisp this window when you click outside (or on the button again), this below works good:

```<code>document.body.onclick = function() { undisp_menu(); };
var menu_on = 0;

function menu_trigger(event) {

    if (menu_on == 0)
    {
        // Otherwise you will call the undisp on body when
        // click on the button
        event.stopPropagation();

        disp_menu();
    }
    else {
        undisp_menu();
    }
}

function disp_menu() {

    menu_on = 1;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu on";
}

function undisp_menu() {

    menu_on = 0;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu";
}
</code>```

Don't forget this for the button:

```
<p>And the CSS:</p>
<pre class="lang-css prettyprint-override"><code>.menu {
    display: none;
}

.on {
    display: inline-block;
}
</code>```

OwnerDisplayName: Sergio del Amo

Body:
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.

Is something like this possible with jQuery?

$("#menuscontainer").clickOutsideThisElement(function() {
    // Hide the menus
});

Body:
If you just want to display a window when you click on a button and undisp this window when you click outside (or on the button again), this below works good:

document.body.onclick = function() { undisp_menu(); };
var menu_on = 0;

function menu_trigger(event) {

    if (menu_on == 0)
    {
        // Otherwise you will call the undisp on body when
        // click on the button
        event.stopPropagation();

        disp_menu();
    }
    else {
        undisp_menu();
    }
}

function disp_menu() {

    menu_on = 1;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu on";
}

function undisp_menu() {

    menu_on = 0;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu";
}

Don't forget this for the button:

<div class="button" onclick="menu_trigger(event)">

<div class="menu">

And the CSS:

.menu {
    display: none;
}

.on {
    display: inline-block;
}

ContentLicense: CC BY-SA 4.0


问:
Retrieve exchange rate from website with Excel
I want to write a date in Excel and get the rate on this date .

I search solutions but not found something that can help me.

I am using Excel 2016.

My code:

```<code>Function CryptoQuote(enteredDate As String)
    If IsDate(enteredDate) Then
        enteredDate = Format(Date, "yyyy-mm-dd")
        Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
        MsgBox strURL
        Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
        http.Open "GET", strURL, False
        http.Send
        Dim strCSV As String
        Found = InStr(http.responseText, "/graph/?from=USD&to=ILS") 'find this in the HTML
        If Found <> 0 Then
            Length = Len(http.responseText) - Found 'check the length of the HTML
            strCSV = Right(http.responseText, Length) 'Trim the begining of the String until we get to our value
            strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
            strCSV = Replace(strCSV, "graph/?from=USD&to=ILS'>", "") 'replace the original search string with nothing so we are left with numbers only
        Else
        CryptoQuote = "Could not find the data!"
        End If
    Else
        MsgBox "Please enter a correct date as yyyy-mm-dd"
    End If
    CryptoQuote = Val(strCSV)
    MsgBox strCSV
End Function
</code>```

答:
Is this what you want?</p>

```<code>Sub gethtmltable()
    Dim objWeb As QueryTable
    Dim sWebTable As String
     'You have to count down the tables on the URL listed in your query
     'This example shows how to retrieve the 2nd table from the web page.
    sWebTable = 2
     'Sets the url to run the query and the destination in the excel file
     'You can change both to suit your needs

    LValue = Format(Date, "yyyy-mm-dd")
    Set objWeb = ActiveSheet.QueryTables.Add( _
    Connection:="URL;http://www.x-rates.com/historical/?from=USD&amount=1&date=" & LValue, _
    Destination:=Range("A1"))

    With objWeb

        .WebSelectionType = xlSpecifiedTables
        .WebTables = sWebTable
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
    Set objWeb = Nothing
End Sub
</code>```

Body:
I want to write a date in Excel and get the rate on this date .

I search solutions but not found something that can help me.

I am using Excel 2016.

My code:

Function CryptoQuote(enteredDate As String)
    If IsDate(enteredDate) Then
        enteredDate = Format(Date, "yyyy-mm-dd")
        Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
        MsgBox strURL
        Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
        http.Open "GET", strURL, False
        http.Send
        Dim strCSV As String
        Found = InStr(http.responseText, "/graph/?from=USD&to=ILS") 'find this in the HTML
        If Found <> 0 Then
            Length = Len(http.responseText) - Found 'check the length of the HTML
            strCSV = Right(http.responseText, Length) 'Trim the begining of the String until we get to our value
            strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
            strCSV = Replace(strCSV, "graph/?from=USD&to=ILS'>", "") 'replace the original search string with nothing so we are left with numbers only
        Else
        CryptoQuote = "Could not find the data!"
        End If
    Else
        MsgBox "Please enter a correct date as yyyy-mm-dd"
    End If
    CryptoQuote = Val(strCSV)
    MsgBox strCSV
End Function

Body:
Is this what you want?

Sub gethtmltable()
    Dim objWeb As QueryTable
    Dim sWebTable As String
     'You have to count down the tables on the URL listed in your query
     'This example shows how to retrieve the 2nd table from the web page.
    sWebTable = 2
     'Sets the url to run the query and the destination in the excel file
     'You can change both to suit your needs

    LValue = Format(Date, "yyyy-mm-dd")
    Set objWeb = ActiveSheet.QueryTables.Add( _
    Connection:="URL;http://www.x-rates.com/historical/?from=USD&amount=1&date=" & LValue, _
    Destination:=Range("A1"))

    With objWeb

        .WebSelectionType = xlSpecifiedTables
        .WebTables = sWebTable
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
    Set objWeb = Nothing
End Sub


问:
Cypher: Neighbours of which all neighbours satisfy an inequality
Let's say you have a database that satisfies the following scheme:

```<code>(person {name:string, budget:int})
(person)-[:FRIEND]-(person)
</code>```

How would one query the following in Cypher?

"Give all friends of Alice of whom holds that ALL their friends have a budget that is greater than 100."

答:
You can use the following query in Cypher for this:</p>

```<code>MATCH (alice {name:"Alice"})
MATCH (alice)-[:FRIEND]-(f)
MATCH (f)-[:FRIEND]-(person)
WITH f, collect(person) as friends
WHERE ALL(x in friends WHERE x.budget > 100 )
RETURN f, friends
</code>```

Body:
Let's say you have a database that satisfies the following scheme:

(person {name:string, budget:int})
(person)-[:FRIEND]-(person)

How would one query the following in Cypher?

"Give all friends of Alice of whom holds that ALL their friends have a budget that is greater than 100."

Body:
You can use the following query in Cypher for this:

MATCH (alice {name:"Alice"})
MATCH (alice)-[:FRIEND]-(f)
MATCH (f)-[:FRIEND]-(person)
WITH f, collect(person) as friends
WHERE ALL(x in friends WHERE x.budget > 100 )
RETURN f, friends


问:
Difference between Debug and Release folders
Could you advise me what is the difference between Debug and Release folders?
Thanks
Furqan</p>

答:
Just to be clear, the name of the folders in your question are virtually unlimited (not simply limited to debug and release). Right click on your solution and select Configuration Manager and you can add as many configurations as you would like. The name of the configuration is the name of the folder.

As Joshua wrote, usually, people use their debug config to include things like the .pdb file (which includes debugging symbols needed to get line numbers from errors, etc.). Release is normally cleaner. However, you can easily setup folders for x86 vs. x64 vs. any cpu.

If you have a solution with 10 different projects (not uncommon if you work on something of decent size) you might want to build certain projects together and others together. In this case, you should create additional configurations to support this so you can build a group simply by changing your active configuration.

In the end, the folders you mentioned contain whatever you specify in the configuration manager that they should contain.


问:
Docker image from loca dev machine on dev windows to linux machine
I have created a simple spring-boot app and created an image of it using docker build Dockerfile.
I want to upload this image to a Linux machine and spin up the container there, Where I could find the image of this app to push it to Linux machine?
I am using Docker toolbox to run docker commands on Windows 10 Home edition.
Thanks in advance.

答:
In order to push a docker image you need a registry. Public images can be pushed through hub.docker.com. Private containers can be pushed through private registries. There are lots of registries like: nexus 3 & gitlab.

so in a nutshell you need to do:

install a docker registry on a machine which both your dev machine and prod machine can access

Configure the registry endpoints for access

login to the private registry through docker

Tag your image for the registry

push the image

go to the server

pull the image from the private registry

run it on the server

OR

without a registry

build the image again on the linux machine

run it from the linux machine from the local build

good luck


问:
Android Studio to 3.0 - Unable to merge dex[DexArchiveMergerException]
I have project and I added another project as module and I have big problem with this error message:

Error:Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge
    dex

I tried many solutions in stackoverflow and google but i don't found an answer.

For example:

I try added to defaultConfig multiDexEnabled true.

I try to clean and rebuild.

I try to Invalidate catch/Restart and then rebuild.

My project gradle:

```<code> // Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {

        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.0.1'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            google()
            jcenter()
        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }
</code>```

My app gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "adms.foxitpdf"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation files('libs/FoxitRDK.jar')
    compile project(path: ':uiextensions_src')
}
</code>```

And my module gradle:

```<code>buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
         classpath 'com.android.tools.build:gradle:2.2.3'
    }
}

apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions{
        abortOnError false
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    implementation files('src/libs/FoxitRDK.jar')
}

task clearAar(type: Delete){
    delete '../FoxitRDKUIExtensions.aar'
}

task makeAar(type: Exec){
    dependsOn(clearAar,build)
    def fromFile = 'build/outputs/aar/'
    def intoFile = '../'
    if(org.gradle.internal.os.OperatingSystem.current().windows) {
        commandLine "cmd",
                '-/C', 'copy', file("$fromFile/uiextensions_src-release.aar").absolutePath, file("$intoFile/FoxitRDKUIExtensions.aar")
    }else {
        commandLine "cp",
                file("$fromFile/uiextensions_src-release.aar").absolutePath, file("$intoFile/FoxitRDKUIExtensions.aar")
    }
}
makeAar {}.dependsOn(clearAar,build)

task makeJavaDoc(type: Javadoc) {
    List<String> mSourcePath = new ArrayList<String>();
    mSourcePath.add("../../fsdk/app/src/main/java/com/foxit/sdk/");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/UIExtensionsManager.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/Module.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/pdfreader/impl/PDFReader.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/menu/IMenuView.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/menu/MoreMenuConfig.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/menu/MoreMenuModule.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/toolbar/IBaseItem.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/toolbar/IBarsHandler.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/propertybar/IMultiLineBar.java");

    source = mSourcePath;
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    Properties properties = new Properties()
    InputStream inputStream = project.rootProject.file('local.properties').newDataInputStream() ;
    properties.load( inputStream )
    //读取文件
    def sdkDir = properties.getProperty('sdk.dir')
    ext.androidJar = sdkDir + "/extras/android/support/annotations/android-support-annotations.jar"
    classpath += project.files(ext.androidJar)

    destinationDir = file("../../docs/api_reference_android")
    failOnError false
}

makeJavaDoc {
    options {
        encoding "UTF-8"
        charSet 'UTF-8'
        author true
        version true
        memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PUBLIC
        locale = "en"
        title = "Document of RDK for Android"

        // fsdk overview
        Map<String,List<String>> map = new HashMap<>();
        List<String> fsdkOverViews= new ArrayList<>();
        fsdkOverViews.add("com.foxit.sdk");
        fsdkOverViews.add("com.foxit.sdk.*");
        map.put("Fsdk Packages",fsdkOverViews);

        // UIExtensions overview
        List<String> uiExtendOverViews = new ArrayList<>();
        uiExtendOverViews.add("com.foxit.uiextensions");
        uiExtendOverViews.add("com.foxit.uiextensions.*");
        map.put("UIExtenstions Packages",uiExtendOverViews);

        groups = map;
    }
}
</code>```

I use with Android Studio to 3.0

Someone have idea why?

答:
I guess you need to include this below one to your gradle as well as add dependencies and include in manifest also. If you have enabled only in gradle and does not include in manifest and dependencies then give it a shot.

```<code>multiDexEnabled true
</code>```

add to your dependencies

```<code>dependencies {
  compile 'com.android.support:multidex:1.0.1'
}
</code>```

gradle file

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "adms.foxitpdf"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 9
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
</code>```

Depending on how you override Application add this to your manifest.

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>
</code>```

or we can just do like this and again include in manifest with name tag.

```<code>public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}
</code>```

Read full story here

Body:
I have project and I added another project as module and I have big problem with this error message:

Error:Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge
    dex

I tried many solutions in stackoverflow and google but i don't found an answer.

For example:

I try added to defaultConfig multiDexEnabled true.

I try to clean and rebuild.

I try to Invalidate catch/Restart and then rebuild.

My project gradle:

 // Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {

        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.0.1'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            google()
            jcenter()
        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }

My app gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "adms.foxitpdf"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation files('libs/FoxitRDK.jar')
    compile project(path: ':uiextensions_src')
}

And my module gradle:

buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
         classpath 'com.android.tools.build:gradle:2.2.3'
    }
}

apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions{
        abortOnError false
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    implementation files('src/libs/FoxitRDK.jar')
}

task clearAar(type: Delete){
    delete '../FoxitRDKUIExtensions.aar'
}

task makeAar(type: Exec){
    dependsOn(clearAar,build)
    def fromFile = 'build/outputs/aar/'
    def intoFile = '../'
    if(org.gradle.internal.os.OperatingSystem.current().windows) {
        commandLine "cmd",
                '-/C', 'copy', file("$fromFile/uiextensions_src-release.aar").absolutePath, file("$intoFile/FoxitRDKUIExtensions.aar")
    }else {
        commandLine "cp",
                file("$fromFile/uiextensions_src-release.aar").absolutePath, file("$intoFile/FoxitRDKUIExtensions.aar")
    }
}
makeAar {}.dependsOn(clearAar,build)

task makeJavaDoc(type: Javadoc) {
    List<String> mSourcePath = new ArrayList<String>();
    mSourcePath.add("../../fsdk/app/src/main/java/com/foxit/sdk/");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/UIExtensionsManager.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/Module.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/pdfreader/impl/PDFReader.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/menu/IMenuView.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/menu/MoreMenuConfig.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/menu/MoreMenuModule.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/toolbar/IBaseItem.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/toolbar/IBarsHandler.java");
    mSourcePath.add("src/main/java/com/foxit/uiextensions/controls/propertybar/IMultiLineBar.java");

    source = mSourcePath;
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    Properties properties = new Properties()
    InputStream inputStream = project.rootProject.file('local.properties').newDataInputStream() ;
    properties.load( inputStream )
    //读取文件
    def sdkDir = properties.getProperty('sdk.dir')
    ext.androidJar = sdkDir + "/extras/android/support/annotations/android-support-annotations.jar"
    classpath += project.files(ext.androidJar)

    destinationDir = file("../../docs/api_reference_android")
    failOnError false
}

makeJavaDoc {
    options {
        encoding "UTF-8"
        charSet 'UTF-8'
        author true
        version true
        memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PUBLIC
        locale = "en"
        title = "Document of RDK for Android"

        // fsdk overview
        Map<String,List<String>> map = new HashMap<>();
        List<String> fsdkOverViews= new ArrayList<>();
        fsdkOverViews.add("com.foxit.sdk");
        fsdkOverViews.add("com.foxit.sdk.*");
        map.put("Fsdk Packages",fsdkOverViews);

        // UIExtensions overview
        List<String> uiExtendOverViews = new ArrayList<>();
        uiExtendOverViews.add("com.foxit.uiextensions");
        uiExtendOverViews.add("com.foxit.uiextensions.*");
        map.put("UIExtenstions Packages",uiExtendOverViews);

        groups = map;
    }
}

I use with Android Studio to 3.0

Someone have idea why?

Body:
I guess you need to include this below one to your gradle as well as add dependencies and include in manifest also. If you have enabled only in gradle and does not include in manifest and dependencies then give it a shot.

multiDexEnabled true

add to your dependencies

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

gradle file

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "adms.foxitpdf"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 9
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Depending on how you override Application add this to your manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>

or we can just do like this and again include in manifest with name tag.

public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

Read full story here


问:
PHP posting error
I keep getting a Cannot POST /app/newpost/newpost.php error when i try to post a HTML form and retrieve the data from another HTML page

HTML for the form is:

    Create a new forum post

<form action="newpost.php" method="POST" style="text-align:center">

Title: <input type="text" name="title" style="font-size:24px; font-family:verdana;">

Description: <input type="text" name="desc" style="font-size:24px; font-family:verdana;">

<input type="submit" action="window.location.href='/app/forum/forum.component.html'" style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: left; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">
</form>```
</div>
</div>
</p>

<p>PHP file is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
if (isset($_POST["submit"]))
{$title = $_POST['title'];
$desc = $_POST['desc']
}
?></code>```

im still very new to PHP someone pls help!
And how to retrieve the posted data on another html page?

答: I think having action="newpost.php" as an attribute in the form tag and action="window.location.href='/app/forum/forum.component.html'" as an attribute in the input type="submit" tag is a contradiction. You might want to try to erase one of them.

Title: PHP posting error

Body:
I keep getting a Cannot POST /app/newpost/newpost.php error when i try to post a HTML form and retrieve the data from another HTML page

HTML for the form is:

    Create a new forum post

<form action="newpost.php" method="POST" style="text-align:center">

Title: <input type="text" name="title" style="font-size:24px; font-family:verdana;">

Description: <input type="text" name="desc" style="font-size:24px; font-family:verdana;">

<input type="submit" action="window.location.href='/app/forum/forum.component.html'" style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: left; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">
</form>

PHP file is

<?php
if (isset($_POST["submit"]))
{$title = $_POST['title'];
$desc = $_POST['desc']
}
?>

im still very new to PHP someone pls help!
And how to retrieve the posted data on another html page?


问:
Calculate first day and last day of week of current month
I want to calculate first date and last date of a week for the current month given current datetime.

For example, 01 December 2017 is first day and 02 December 2017 is last day of week for that week for the month of December. In the same week of year, 26 November 2017 is first day of week and
30 November 2017 is last day of week for previous month.

So if today is 01 December 2017, I should get 01-02 from current datetime , instead of 26-02 range.

PS: I am trying to do this thing in a query of Sqlite. I want to group some values on a weekly basis. The days of the week should belong to current month. Hence this requirement. Till now this is my query.

```<code>SELECT SUM(amount) as Y,
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '-'||strftime('%w', datetime(createdOn/1000, 'unixepoch'))||' day' )
||'-'||
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '+'||(6-strftime('%w', datetime(createdOn/1000, 'unixepoch')))||' day' )                 AS X
FROM my_table
GROUP BY strftime('%d', datetime(createdOn/1000, 'unixepoch'), '-'||strftime('%w', datetime(createdOn/1000, 'unixepoch'))||' day' )
||'-'||
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '+'||(6-strftime('%w', datetime(createdOn/1000, 'unixepoch')))||' day' )
</code>```

How to achieve that; given current datetime.

答:
Common table expressions are useful to hold intermediate results:</p>

```<code>WITH t1 AS (
  SELECT amount, date(createdOn / 1000, 'unixepoch', 'localtime') AS date
  FROM my_table
),
t2 AS (
  SELECT *,
         date(date, 'weekday 6') AS end_of_week,
         date(date, 'weekday 6', '-6 days') AS start_of_week
  FROM t1
),
t3 AS (
  SELECT *,
         strftime('%m', date         ) AS month,
         strftime('%m', start_of_week) AS sowk_month,
         strftime('%m', end_of_week  ) AS eowk_month,
         date(date, 'start of month') AS start_of_month,
         date(date, '+1 month', 'start of month', '-1 day') AS end_of_month
  FROM t2
),
t4 AS (
  SELECT *,
         CASE WHEN sowk_month = month THEN start_of_week
                                      ELSE start_of_month
         END AS week_in_month_start,
         CASE WHEN eowk_month = month THEN end_of_week
                                      ELSE end_of_month
         END AS week_in_month_end
  FROM t3
),
t5 AS (
  SELECT amount,
         week_in_month_start || '-' || week_in_month_end AS week_in_month
  FROM t4
)
SELECT SUM(amount) AS Y,
       week_in_month
FROM t5
GROUP BY week_in_month;
</code>```

Body:
I want to calculate first date and last date of a week for the current month given current datetime.

For example, 01 December 2017 is first day and 02 December 2017 is last day of week for that week for the month of December. In the same week of year, 26 November 2017 is first day of week and
30 November 2017 is last day of week for previous month.

So if today is 01 December 2017, I should get 01-02 from current datetime , instead of 26-02 range.

PS: I am trying to do this thing in a query of Sqlite. I want to group some values on a weekly basis. The days of the week should belong to current month. Hence this requirement. Till now this is my query.

SELECT SUM(amount) as Y,
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '-'||strftime('%w', datetime(createdOn/1000, 'unixepoch'))||' day' )
||'-'||
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '+'||(6-strftime('%w', datetime(createdOn/1000, 'unixepoch')))||' day' )                 AS X
FROM my_table
GROUP BY strftime('%d', datetime(createdOn/1000, 'unixepoch'), '-'||strftime('%w', datetime(createdOn/1000, 'unixepoch'))||' day' )
||'-'||
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '+'||(6-strftime('%w', datetime(createdOn/1000, 'unixepoch')))||' day' )

How to achieve that; given current datetime.

Body:
Common table expressions are useful to hold intermediate results:

WITH t1 AS (
  SELECT amount, date(createdOn / 1000, 'unixepoch', 'localtime') AS date
  FROM my_table
),
t2 AS (
  SELECT *,
         date(date, 'weekday 6') AS end_of_week,
         date(date, 'weekday 6', '-6 days') AS start_of_week
  FROM t1
),
t3 AS (
  SELECT *,
         strftime('%m', date         ) AS month,
         strftime('%m', start_of_week) AS sowk_month,
         strftime('%m', end_of_week  ) AS eowk_month,
         date(date, 'start of month') AS start_of_month,
         date(date, '+1 month', 'start of month', '-1 day') AS end_of_month
  FROM t2
),
t4 AS (
  SELECT *,
         CASE WHEN sowk_month = month THEN start_of_week
                                      ELSE start_of_month
         END AS week_in_month_start,
         CASE WHEN eowk_month = month THEN end_of_week
                                      ELSE end_of_month
         END AS week_in_month_end
  FROM t3
),
t5 AS (
  SELECT amount,
         week_in_month_start || '-' || week_in_month_end AS week_in_month
  FROM t4
)
SELECT SUM(amount) AS Y,
       week_in_month
FROM t5
GROUP BY week_in_month;


问:
Intrinsic content size of button with text only
I have a uibutton, i want to set text dynamically at run time with padding top: 10, bottom 10 and left: 10 and right: 10, once i set text button title cliped. Any one can provide solution.</p>

答:
You must be attentive to fontSize of the button. Setting text programmatically doesn't automatically fits the text. Following code will help you.

```<code>//Swift
let btnLabel = yourButton.titleLabel
btnLabel.adjustsFontSizeToFitWidth = true

//Objective C
UILabel *btnLabel = yourButton.titleLabel;
btnLabel.adjustsFontSizeToFitWidth = true
</code>```

Happy Coding <3

Body:
You must be attentive to fontSize of the button. Setting text programmatically doesn't automatically fits the text. Following code will help you.

//Swift
let btnLabel = yourButton.titleLabel
btnLabel.adjustsFontSizeToFitWidth = true

//Objective C
UILabel *btnLabel = yourButton.titleLabel;
btnLabel.adjustsFontSizeToFitWidth = true

Happy Coding <3


问:
Laravel implementing belongsTo one product for one or some category
in my database i have product_category and products that one product maybe belongs to one or some category in product_category table, now my question is: when user on submitting product with one or some category how can i save that on database to have for example one category have one or some product?

in view i have multiple select as:

```<code>{{ Form::select('categories[]', $productCategories, null, array('class' => 'multiselect-success multiselect_selected','multiple'=>'multiple')) }}
</code>```

products model:

```<code>class Products extends Model
{
    protected $table = 'products';
    protected $guarded = ['id'];
    protected $casts = [
        'images' => 'array'
    ];

    public function productCategories()
    {
        return $this->belongsTo(ProductCategories::class);
    }
}
</code>```

productCategories model:

```<code>class ProductCategories extends Model
{
    protected $table = 'product_categories';
    protected $guarded =['id'];
    protected $casts=[
        'images'=>'array'
    ];

    public function products()
    {
        return $this->hasMany(Products::class);
    }
}
</code>```

and store function into controller:

```<code>public function store(RequestProducts $request)
{
    try {
        $data = Products::create([
            'name' => $request->name,
            'amount' => $request->amount,
            'product_code' => $request->product_code,
            'weight' => $request->weight
            /* MY PROBLEM IS HERE */
            'category_id' => $request->categories
        ]);
    } catch (Exception $ex) {
        ...
    }

    return redirect(route('manageProductCategories.index'));
}
</code>```

in html view categories is an array and how can i implementing that?

UPDATE

after update code with createMany i get this error:

```<code>General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`name`, `lang`, `amount`, `product_code`, `weight`, `images`, `updated_at`, `created_at`) values (eqweqwe, fa, 45,000, asd, asdasd, '', 2017-12-09 04:45:44, 2017-12-09 04:45:44))
</code>```

migration files:

```<code>public function up()
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('category_name');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('amount');
        $table->string('product_code');
        $table->string('weight');
        $table->string('lang', 2);
        $table->text('images');
        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
        $table->timestamps();
    });
}
</code>```

答:
From your question and comments, I understand the following.

Many products may have the category "category_1" and "product_1" may belongs to many categories.

To implement this you have to use "Many To Many" relationship.
I have updated your code, this might help you.

Migrations:

```<code>public function up()
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('category_name');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('amount');
        $table->string('product_code');
        $table->string('weight');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}
    public function up()
{
    Schema::create('products_product_category', function (Blueprint $table) {
        $table->integer('product_id');
        $table->integer('product_category_id');
    });
}
</code>```

Models

products model:

```<code>class Products extends Model
{
    protected $table = 'products';
    protected $guarded = ['id'];
    protected $casts = [
        'images' => 'array'
    ];

    public function productCategories()
    {
        return $this->belongsToMany(ProductCategories::class,'products_product_category');
    }
}
</code>```

productCategories model:

```<code>class ProductCategories extends Model
{
    protected $table = 'product_categories';
    protected $guarded =['id'];
    protected $casts=[
        'images'=>'array'
    ];

    public function products()
    {
        return $this->belongsToMany(Products::class, 'products_product_category');
    }
}
</code>```

Controller

```<code>public function store(RequestProducts $request)
{
    try {
        $data = Products::create([
            'name' => $request->name,
            'amount' => $request->amount,
            'product_code' => $request->product_code,
            'weight' => $request->weight
        ]);
        $data->productCategories()->sync($request->categories);
    } catch (Exception $ex) {
        ...
    }

    return redirect(route('manageProductCategories.index'));
}
</code>```

Hope it will helps..

Body:
in my database i have product_category and products that one product maybe belongs to one or some category in product_category table, now my question is: when user on submitting product with one or some category how can i save that on database to have for example one category have one or some product?

in view i have multiple select as:

{{ Form::select('categories[]', $productCategories, null, array('class' => 'multiselect-success multiselect_selected','multiple'=>'multiple')) }}

products model:

class Products extends Model
{
    protected $table = 'products';
    protected $guarded = ['id'];
    protected $casts = [
        'images' => 'array'
    ];

    public function productCategories()
    {
        return $this->belongsTo(ProductCategories::class);
    }
}

productCategories model:

class ProductCategories extends Model
{
    protected $table = 'product_categories';
    protected $guarded =['id'];
    protected $casts=[
        'images'=>'array'
    ];

    public function products()
    {
        return $this->hasMany(Products::class);
    }
}

and store function into controller:

public function store(RequestProducts $request)
{
    try {
        $data = Products::create([
            'name' => $request->name,
            'amount' => $request->amount,
            'product_code' => $request->product_code,
            'weight' => $request->weight
            /* MY PROBLEM IS HERE */
            'category_id' => $request->categories
        ]);
    } catch (Exception $ex) {
        ...
    }

    return redirect(route('manageProductCategories.index'));
}

in html view categories is an array and how can i implementing that?

UPDATE

after update code with createMany i get this error:

General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`name`, `lang`, `amount`, `product_code`, `weight`, `images`, `updated_at`, `created_at`) values (eqweqwe, fa, 45,000, asd, asdasd, '', 2017-12-09 04:45:44, 2017-12-09 04:45:44))

migration files:

public function up()
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('category_name');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('amount');
        $table->string('product_code');
        $table->string('weight');
        $table->string('lang', 2);
        $table->text('images');
        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
        $table->timestamps();
    });
}

Body:
From your question and comments, I understand the following.

Many products may have the category "category_1" and "product_1" may belongs to many categories.

To implement this you have to use "Many To Many" relationship.
I have updated your code, this might help you.

Migrations:

public function up()
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('category_name');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('amount');
        $table->string('product_code');
        $table->string('weight');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}
    public function up()
{
    Schema::create('products_product_category', function (Blueprint $table) {
        $table->integer('product_id');
        $table->integer('product_category_id');
    });
}

Models

products model:

class Products extends Model
{
    protected $table = 'products';
    protected $guarded = ['id'];
    protected $casts = [
        'images' => 'array'
    ];

    public function productCategories()
    {
        return $this->belongsToMany(ProductCategories::class,'products_product_category');
    }
}

productCategories model:

class ProductCategories extends Model
{
    protected $table = 'product_categories';
    protected $guarded =['id'];
    protected $casts=[
        'images'=>'array'
    ];

    public function products()
    {
        return $this->belongsToMany(Products::class, 'products_product_category');
    }
}

Controller

public function store(RequestProducts $request)
{
    try {
        $data = Products::create([
            'name' => $request->name,
            'amount' => $request->amount,
            'product_code' => $request->product_code,
            'weight' => $request->weight
        ]);
        $data->productCategories()->sync($request->categories);
    } catch (Exception $ex) {
        ...
    }

    return redirect(route('manageProductCategories.index'));
}

Hope it will helps..


问:
Google Analytics Real-Time not showing results
The following script is not generating activity when cross-checked in Google Analytics : Real-Time section : Content section --

```<code><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-475021xx-x', 'auto');
  ga('send', 'pageview');
</script>
</code>```

where xx-x masks the real account code.

The script is placed just before

We have upgraded our account to Universal Analytics. Google tells us that this is the script to use; directly copied and pasted here (with the masked account code).

On the Google Analytics page, the test page is loaded as an ACTIVE PAGE. I click links on the test page to trigger ga.

Is there an error in this script? For example, I see on other Stackoverflow posts that 'auto' is replaced with the real domain. But I don't see Google instructions to make that substitution.

Am I doing something else wrong?

答:
Here is what my issue was. I'm using google analytics with wordpress. I tried configuring google analytics for my website using plugin called Google Analytics Dashboard for WP (GADWP). This plugin generated a google analytics snippet that looks similarly to the one described in the question:

```<code><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-475021xx-x', 'auto');
  ga('send', 'pageview');
</script>
</code>```

However, in Google Analytics console, the suggested snippet looked like this:

```<code><!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-110984887-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-475021xx-x');
</script>
</code>```

It looks like this gtag.js is a new format for the google analytics snippet. So I disabled that wordpress plugin and I manually added the script suggested by Google Analytics to the page.

Body:
The following script is not generating activity when cross-checked in Google Analytics : Real-Time section : Content section --

where xx-x masks the real account code.

The script is placed just before

We have upgraded our account to Universal Analytics. Google tells us that this is the script to use; directly copied and pasted here (with the masked account code).

On the Google Analytics page, the test page is loaded as an ACTIVE PAGE. I click links on the test page to trigger ga.

Is there an error in this script? For example, I see on other Stackoverflow posts that 'auto' is replaced with the real domain. But I don't see Google instructions to make that substitution.

Am I doing something else wrong?

Body:
Here is what my issue was. I'm using google analytics with wordpress. I tried configuring google analytics for my website using plugin called Google Analytics Dashboard for WP (GADWP). This plugin generated a google analytics snippet that looks similarly to the one described in the question:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-475021xx-x', 'auto');
  ga('send', 'pageview');
</script>

However, in Google Analytics console, the suggested snippet looked like this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-110984887-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-475021xx-x');
</script>

It looks like this gtag.js is a new format for the google analytics snippet. So I disabled that wordpress plugin and I manually added the script suggested by Google Analytics to the page.


问:
SQL Change data of a column where data is the same
I have created this table:

```<code>     DROP TABLE IF EXISTS Proces1 CASCADE;
        CREATE TABLE Proces1 AS
        (
        SELECT id_importat AS id_aux, driver_city AS city_aux,
        driver_state AS state_aux, gender AS g_aux, race AS r_aux
            FROM ImportaViolations
            WHERE id_importat IN (
                SELECT id_importat
                FROM ImportaViolations
                GROUP BY id_importat
                HAVING (COUNT(*) > 1))
            GROUP BY id_importat, driver_city, driver_state, gender, race
        );
</code>```

And using this table I have created this one:

```<code>DROP TABLE IF EXISTS Proces2 CASCADE;
CREATE TABLE Proces2 AS
(
    SELECT id_aux AS id_aux2, city_aux AS city_aux2, state_aux AS state_aux2,
    g_aux AS g_aux2, r_aux AS r_aux2, rn
        FROM (
              SELECT id_aux, city_aux, state_aux,
              g_aux, r_aux, row_number() OVER(PARTITION BY id_aux ORDER BY 1) AS rn
              FROM Proces1
             ) d
        WHERE rn > 1
    );
</code>```

So, now I want to change data from the Original table called "ImportaViolations", and I want to update the column "id_serial" from this table to the "rn" column of table "Proces2", but only where information is exactly the same.

I have done the next query but it doesn't work.

```<code>UPDATE ImportaViolations
SET id_serial = p2.rn
FROM ImportaViolations iv, Proces2 p2
WHERE (iv.id_importat, iv.driver_city, iv.driver_state, iv.gender, iv.race) IN (
    SELECT id_aux2, city_aux2, state_aux2, g_aux2, r_aux2
    FROM Proces2
);
</code>```

And yes, the column "id_serial" exists on the table ImportaViolations as an empty column (full of null values). Also I have to say that there is no Primary Key on the ImportaViolations table so I don't mind if we set id_serial repeated values on different rows.

Thanks for your help!

答:
In Postgres's SQL,you don't have to repeat the name of the target table (and you could probably do the same work without intermediate temp tables):

```<code>UPDATE ImportaViolations  iv
SET id_serial = p2.rn
FROM Proces2 p2
WHERE iv.id_importat = p2.id_aux2
        AND iv.driver_city = p2.city_aux2
        AND iv.driver_state = p2.state_aux2
        AND iv.gender = p2.g_aux2
        AND iv.race = p2.r_aux2
        ;
</code>```

Body:
I have created this table:

     DROP TABLE IF EXISTS Proces1 CASCADE;
        CREATE TABLE Proces1 AS
        (
        SELECT id_importat AS id_aux, driver_city AS city_aux,
        driver_state AS state_aux, gender AS g_aux, race AS r_aux
            FROM ImportaViolations
            WHERE id_importat IN (
                SELECT id_importat
                FROM ImportaViolations
                GROUP BY id_importat
                HAVING (COUNT(*) > 1))
            GROUP BY id_importat, driver_city, driver_state, gender, race
        );

And using this table I have created this one:

DROP TABLE IF EXISTS Proces2 CASCADE;
CREATE TABLE Proces2 AS
(
    SELECT id_aux AS id_aux2, city_aux AS city_aux2, state_aux AS state_aux2,
    g_aux AS g_aux2, r_aux AS r_aux2, rn
        FROM (
              SELECT id_aux, city_aux, state_aux,
              g_aux, r_aux, row_number() OVER(PARTITION BY id_aux ORDER BY 1) AS rn
              FROM Proces1
             ) d
        WHERE rn > 1
    );

So, now I want to change data from the Original table called "ImportaViolations", and I want to update the column "id_serial" from this table to the "rn" column of table "Proces2", but only where information is exactly the same.

I have done the next query but it doesn't work.

UPDATE ImportaViolations
SET id_serial = p2.rn
FROM ImportaViolations iv, Proces2 p2
WHERE (iv.id_importat, iv.driver_city, iv.driver_state, iv.gender, iv.race) IN (
    SELECT id_aux2, city_aux2, state_aux2, g_aux2, r_aux2
    FROM Proces2
);

And yes, the column "id_serial" exists on the table ImportaViolations as an empty column (full of null values). Also I have to say that there is no Primary Key on the ImportaViolations table so I don't mind if we set id_serial repeated values on different rows.

Thanks for your help!

Body:
In Postgres's SQL,you don't have to repeat the name of the target table (and you could probably do the same work without intermediate temp tables):

UPDATE ImportaViolations  iv
SET id_serial = p2.rn
FROM Proces2 p2
WHERE iv.id_importat = p2.id_aux2
        AND iv.driver_city = p2.city_aux2
        AND iv.driver_state = p2.state_aux2
        AND iv.gender = p2.g_aux2
        AND iv.race = p2.r_aux2
        ;


问:
Add MariaDB Constraint CHECK for JSON column using sequelize
I'm using MariaDB v10.2.11, and since v10.2.7 you can have JSON columns with a constraint that validates the JSON value of a row.

I want to add a that constraint through a Sequelize migration, but I don't know how to.

MariaDB JSON Documentation:

https://mariadb.com/resources/blog/json-mariadb-102

https://mariadb.com/kb/en/library/json-data-type/

答:
I'm sharing the solution I came in this issue (https://github.com/sequelize/sequelize/issues/8767) (it's mine).

module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface
      .createTable('tableName', {
        // id, other columns
        column1: Sequelize.JSON,
        // more columns
      })
      .then(() =>
        queryInterface.addConstraint('tableName', ['column1'], {
          type: 'check',
          where: {
            column1: Sequelize.literal('JSON_VALID(column1)'),
          },
          name: 'check_column1_has_valid_json',
        }),
      ),
  down: (queryInterface) => queryInterface.dropTable('tableName'),
};
```

Since createTable and addConstraint returns a promise, it's possible to chain multiple operations in one migration :)

Body:
I'm sharing the solution I came in this issue (https://github.com/sequelize/sequelize/issues/8767) (it's mine).

module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface
      .createTable('tableName', {
        // id, other columns
        column1: Sequelize.JSON,
        // more columns
      })
      .then(() =>
        queryInterface.addConstraint('tableName', ['column1'], {
          type: 'check',
          where: {
            column1: Sequelize.literal('JSON_VALID(column1)'),
          },
          name: 'check_column1_has_valid_json',
        }),
      ),
  down: (queryInterface) => queryInterface.dropTable('tableName'),
};

Since createTable and addConstraint returns a promise, it's possible to chain multiple operations in one migration :)