问:
Using qemu Raspbian: installing libc6:i386 fails
this is my first post on this forum.

I am trying to get qemu running on my Raspberry Pi 3 with Raspbian stretch installed. My brothers DCP-350C scanner driver is only available precompiled on x86.
I have added i386 arch with sudo dpkg --add-architecture i386
and installed qemu-user binfmt-support. No problems there.

But every time I try to install libc6:i386 I get an install error:

```<code>pi@raspberrypi:/etc/apt $ sudo apt-get install libc6:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libc6:i386 : Depends: libgcc1:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
pi@raspberrypi:/etc/apt $ sudo apt-get install libgcc1:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 debconf : PreDepends: perl-base (>= 5.20.1-3~) but it is not going to be installed
           Recommends: apt-utils (>= 0.5.1) but it is not going to be installed
           Recommends: debconf-i18n but it is not going to be installed
 dpkg : PreDepends: libbz2-1.0 but it is not going to be installed
        PreDepends: liblzma5 (>= 5.2.2) but it is not going to be installed
        PreDepends: zlib1g (>= 1:1.1.4) but it is not going to be installed
        Depends: tar (>= 1.28-1)
 libgcc1 : Breaks: libgcc1:i386 (!= 1:6.3.0-18+rpi1) but 1:6.3.0-18 is to be installed
 libgcc1:i386 : Depends: gcc-6-base:i386 (= 6.3.0-18) but it is not going to be installed
                Breaks: libgcc1 (!= 1:6.3.0-18) but 1:6.3.0-18+rpi1 is to be installed
 libselinux1 : Depends: libpcre3 but it is not going to be installed
 libx11-6 : Depends: libxcb1 (>= 1.11.1) but it is not going to be installed
 libxext6 : PreDepends: multiarch-support
 lxlock : Depends: light-locker but it is not going to be installed or
                   xscreensaver but it is not going to be installed or
                   gnome-screensaver but it is not going to be installed or
                   i3lock but it is not going to be installed or
                   suckless-tools but it is not going to be installed or
                   slim but it is not going to be installed
 systemd-sysv : PreDepends: systemd
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.
</code>```

I don't know how to fix it. I have tried all sorts of repositories, but this seems not to be a repository issue.

I have no more clue how to fix this.

I hope anybody can help.

答:
That kind of error ("libgcc1:i386 Breaks: libgcc1 (!= 1:6.3.0-18) but 1:6.3.0-18+rpi1 is to be installed" and "libgcc1 : Breaks: libgcc1:i386 (!= 1:6.3.0-18+rpi1) but 1:6.3.0-18 is to be installed") is because multiarch support on Debian and Debian derivatives requires that all versions of a package for each architecture that you have installed must have exactly matching versions. So you can have libgcc1:i386 1:6.3.0-18 and libgcc1:armhf 1:6.3.0-18 installed together because the versions match, but not libgcc1:i386 1:6.3.0-18 and libgcc1:armhf 1:6.3.0-18+rpi1 (because the versions don't exactly match).

The problem here is that raspbian rebuilds packages, which is why they have the +rpi1 tag on the end of their version. So what you would need is either

a repository where the raspbian versions of packages have been built for i386 -- this may well not exist

or run pure upstream Debian rather than Raspbian -- which you likely don't want to swap to at this point

or rebuild all the packages for i386 yourself -- which is likely painful and easy to get wrong if you don't know what you're doing.

If it's any consolation I would be somewhat uncertain about whether QEMU could usefully handle emulating a hardware-specific piece of code like a scanner driver (which is probably a plugin to CUPS or other system software) anyway.

A quick google of the scanner model name brought up this webpage: http://support.brother.com/g/b/downloadlist.aspx?c=us_ot&lang=en&prod=dcp350c_all&os=128 which includes a download for source code for the scanner driver and CUPS wrapper driver. If I were you I would try the approach of building that natively for arm.

Body:
this is my first post on this forum.

I am trying to get qemu running on my Raspberry Pi 3 with Raspbian stretch installed. My brothers DCP-350C scanner driver is only available precompiled on x86.
I have added i386 arch with sudo dpkg --add-architecture i386
and installed qemu-user binfmt-support. No problems there.

But every time I try to install libc6:i386 I get an install error:

pi@raspberrypi:/etc/apt $ sudo apt-get install libc6:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libc6:i386 : Depends: libgcc1:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
pi@raspberrypi:/etc/apt $ sudo apt-get install libgcc1:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 debconf : PreDepends: perl-base (>= 5.20.1-3~) but it is not going to be installed
           Recommends: apt-utils (>= 0.5.1) but it is not going to be installed
           Recommends: debconf-i18n but it is not going to be installed
 dpkg : PreDepends: libbz2-1.0 but it is not going to be installed
        PreDepends: liblzma5 (>= 5.2.2) but it is not going to be installed
        PreDepends: zlib1g (>= 1:1.1.4) but it is not going to be installed
        Depends: tar (>= 1.28-1)
 libgcc1 : Breaks: libgcc1:i386 (!= 1:6.3.0-18+rpi1) but 1:6.3.0-18 is to be installed
 libgcc1:i386 : Depends: gcc-6-base:i386 (= 6.3.0-18) but it is not going to be installed
                Breaks: libgcc1 (!= 1:6.3.0-18) but 1:6.3.0-18+rpi1 is to be installed
 libselinux1 : Depends: libpcre3 but it is not going to be installed
 libx11-6 : Depends: libxcb1 (>= 1.11.1) but it is not going to be installed
 libxext6 : PreDepends: multiarch-support
 lxlock : Depends: light-locker but it is not going to be installed or
                   xscreensaver but it is not going to be installed or
                   gnome-screensaver but it is not going to be installed or
                   i3lock but it is not going to be installed or
                   suckless-tools but it is not going to be installed or
                   slim but it is not going to be installed
 systemd-sysv : PreDepends: systemd
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

I don't know how to fix it. I have tried all sorts of repositories, but this seems not to be a repository issue.

I have no more clue how to fix this.

I hope anybody can help.


来源: stackexchange

问:
how to mpAndroidChart remove one sideBar on the BarChart
how to remove mpAndroidChart one side Bar on the BarChart

答:
I found it

Add this line

```<code>rightAxis.setDrawLabels(false);
</code>```

To hide only the labels.

For hiding the whole right axis, call:

```<code>rightAxis.setEnabled(false);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I found it

Add this line

rightAxis.setDrawLabels(false);

To hide only the labels.

For hiding the whole right axis, call:

rightAxis.setEnabled(false);


问:
How to normalise user data from varying structures in Meteor?
Users in my Meteor app can create accounts 'manually' or with the accounts-facebook package.

If they create an account manually then in the database their email is stored like this:

```<code>emails: [address: 'hi@gmail.com', verified: false]
</code>```

But if they use the Facebook login then its stored like this:

```<code>services: {
  facebook: {
    email: "james@gmail.com"
  }
}
</code>```

I have an user account page where I need to display the users email and allow them to change it. How can I deal with the varying structure?

I made this React component to display the users email. When I just had the default Meteor user profiles it worked, but now Ive added Facebook login it errors as props.user.emails doenst exist.

```<code>        <div className="form-primary__row">
          <label>Email:</label>
          {props.user.emails.map((item, i) => {
            return (
              <input defaultValue={item.address} key={i} name="email" />
            );
          })}
        </div>
</code>```

This is my method for a user to update their email. It also worked when I just had Meteors accounts but won't work with Facebook.

```<code>Meteor.methods({
  'user.updateEmail'({ email }) {
    Meteor.users.update(
      { _id: Meteor.userId() },
      {
        $set: {
          'emails.0.address': email,
          'emails.0.verified': false,
        },
      },
    );
  },
});
</code>```

答:
One approach is to use Accounts.onCreated()

The function should return the user document (either the one passed in
  or a newly-created object) with whatever modifications are desired.
  The returned document is inserted directly into the Meteor.users
  collection.

```<code>Accounts.onCreateUser(function (options, user) {
    // if the account is created using the manual approach,
    // simply return the user object that will be inserted into
    // the Users collection.
    if (!user.services.facebook) {
        return user;
    }

    // if user is created using fb's API,
    // manually set the emails array, then return the user object
    // which will be inserted into the Users collection.
    user.username = user.services.facebook.name;
    user.emails = [{address: user.services.facebook.email}];

    return user;
});
</code>```

The above ensures that the emails array always contains the email, whichever the login method the user chooses to use.

ContentLicense: CC BY-SA 4.0

Body:
Users in my Meteor app can create accounts 'manually' or with the accounts-facebook package.

If they create an account manually then in the database their email is stored like this:

emails: [address: 'hi@gmail.com', verified: false]

But if they use the Facebook login then its stored like this:

services: {
  facebook: {
    email: "james@gmail.com"
  }
}

I have an user account page where I need to display the users email and allow them to change it. How can I deal with the varying structure?

I made this React component to display the users email. When I just had the default Meteor user profiles it worked, but now Ive added Facebook login it errors as props.user.emails doenst exist.

          Email:
          {props.user.emails.map((item, i) => {
            return (
              <input defaultValue={item.address} key={i} name="email" />
            );
          })}

This is my method for a user to update their email. It also worked when I just had Meteors accounts but won't work with Facebook.

Meteor.methods({
  'user.updateEmail'({ email }) {
    Meteor.users.update(
      { _id: Meteor.userId() },
      {
        $set: {
          'emails.0.address': email,
          'emails.0.verified': false,
        },
      },
    );
  },
});

Body:
One approach is to use Accounts.onCreated()

The function should return the user document (either the one passed in
  or a newly-created object) with whatever modifications are desired.
  The returned document is inserted directly into the Meteor.users
  collection.

Accounts.onCreateUser(function (options, user) {
    // if the account is created using the manual approach,
    // simply return the user object that will be inserted into
    // the Users collection.
    if (!user.services.facebook) {
        return user;
    }

    // if user is created using fb's API,
    // manually set the emails array, then return the user object
    // which will be inserted into the Users collection.
    user.username = user.services.facebook.name;
    user.emails = [{address: user.services.facebook.email}];

    return user;
});

The above ensures that the emails array always contains the email, whichever the login method the user chooses to use.


问:
Get next and previous records sorting by non-unique field
I was not able to find an answer while reading similar questions, so I'll ask my question here, appreciate any help on this matter.

In MySQL DB have a table with articles:

```<code>id        date     is_active                title                  text
 3     2017-01-20      1     New payment system goes live       some articl
 5     2017-01-21      1     Library v.2.5 released             some articl
 6     2017-01-22      1     New skins and themes               some articl
 7     2017-01-25      0     Terms and Conditions updated       some articl
 8     2017-01-26      1     Don't forget to subscribe          some articl
10     2017-01-22      0     Support Chat beta release          some articl
11     2017-01-30      1     Maintenance window next Sunday     some articl
12     2017-01-28      1     Refer a friend and get a bonus     some articl
13     2017-01-26      1     Follow us in social networks       some articl
14     2017-01-22      1     Video sharing feature is now live  some articl
</code>```

I have 2 web pages:

a list of all active articles ordered by date (important: it is possible that several articles can have same date).
This works fine, no issue here.

single article read page, additionally I have "Next" and "Previous" links on that page
This is an issue.

I would like to show 'next' and 'prev' links as a href="article.php?id=8". So I would like to get next record ID from DB according to the query like this:

```<code>SELECT id FROM articles WHERE date > (SELECT date FROM news WHERE id = 6) and isactive = 1 ORDER BY date ASC LIMIT 1;
</code>```

However my query does not work properly when it comes to defining next article id with the same date. When user stays on the article id=3 and clicks 'next' multiple times I would expect the following order of loading articles:

```<code>id        title      date     is_active
 5     Library v.2 2017-01-21      1
 6     New skins a 2017-01-22      1
14     Video shari 2017-01-22      1
 8     Don't forge 2017-01-26      1
13     Follow us i 2017-01-26      1
12     Refer a fri 2017-01-28      1
11     Maintenance 2017-01-30      1
</code>```

But what I get is: 5, 6, 8, 12, 11. So 2 records are missing in this sequence (ids: 14 and 13) because they have same date.
I tried playing with different queries, but all results are not 100% right (in some cases it keeps returning same numbers, ex.: 5, 6, 14, 6, 14....., etc. )

Is is possible to get the 'next' IDs based on current ID and desired order via MySQL query(ies)? I am not against doing several queries or working with nested queries.

As a workaround, of course I can just retrieve an ordered array of all ids like this:

```<code>SELECT id FROM articles WHERE isactive=1 ORDER BY date
</code>```

and then define 'next' and 'previous' using this array, however I don't like this solution.
If you can point me to some similar topics or other possible ways to solve this, please do.
Thank you.

答:
```<code> SELECT id
 FROM   articles
 WHERE  date >= (SELECT date -- changed
           FROM   news
           WHERE  id = 6)
          AND isactive = 1
          AND id NOT IN(6) -- added, maybe id!=6 or id<>6
 ORDER  BY date ASC
 LIMIT  1
-- (all id date >= date) - (id=6)
</code>```

Why you do this, why not use

SELECT id FROM news ORDER BY date ASC LIMIT 6,1 -- possition, count

If SQL query caching, this is may be faster.

Body:
I was not able to find an answer while reading similar questions, so I'll ask my question here, appreciate any help on this matter.

In MySQL DB have a table with articles:

id        date     is_active                title                  text
 3     2017-01-20      1     New payment system goes live       some articl
 5     2017-01-21      1     Library v.2.5 released             some articl
 6     2017-01-22      1     New skins and themes               some articl
 7     2017-01-25      0     Terms and Conditions updated       some articl
 8     2017-01-26      1     Don't forget to subscribe          some articl
10     2017-01-22      0     Support Chat beta release          some articl
11     2017-01-30      1     Maintenance window next Sunday     some articl
12     2017-01-28      1     Refer a friend and get a bonus     some articl
13     2017-01-26      1     Follow us in social networks       some articl
14     2017-01-22      1     Video sharing feature is now live  some articl

I have 2 web pages:

a list of all active articles ordered by date (important: it is possible that several articles can have same date).
This works fine, no issue here.

single article read page, additionally I have "Next" and "Previous" links on that page
This is an issue.

I would like to show 'next' and 'prev' links as a href="article.php?id=8". So I would like to get next record ID from DB according to the query like this:

SELECT id FROM articles WHERE date > (SELECT date FROM news WHERE id = 6) and isactive = 1 ORDER BY date ASC LIMIT 1;

However my query does not work properly when it comes to defining next article id with the same date. When user stays on the article id=3 and clicks 'next' multiple times I would expect the following order of loading articles:

id        title      date     is_active
 5     Library v.2 2017-01-21      1
 6     New skins a 2017-01-22      1
14     Video shari 2017-01-22      1
 8     Don't forge 2017-01-26      1
13     Follow us i 2017-01-26      1
12     Refer a fri 2017-01-28      1
11     Maintenance 2017-01-30      1

But what I get is: 5, 6, 8, 12, 11. So 2 records are missing in this sequence (ids: 14 and 13) because they have same date.
I tried playing with different queries, but all results are not 100% right (in some cases it keeps returning same numbers, ex.: 5, 6, 14, 6, 14....., etc. )

Is is possible to get the 'next' IDs based on current ID and desired order via MySQL query(ies)? I am not against doing several queries or working with nested queries.

As a workaround, of course I can just retrieve an ordered array of all ids like this:

SELECT id FROM articles WHERE isactive=1 ORDER BY date

and then define 'next' and 'previous' using this array, however I don't like this solution.
If you can point me to some similar topics or other possible ways to solve this, please do.
Thank you.

Body:
 SELECT id
 FROM   articles
 WHERE  date >= (SELECT date -- changed
           FROM   news
           WHERE  id = 6)
          AND isactive = 1
          AND id NOT IN(6) -- added, maybe id!=6 or id<>6
 ORDER  BY date ASC
 LIMIT  1
-- (all id date >= date) - (id=6)

Why you do this, why not use

SELECT id FROM news ORDER BY date ASC LIMIT 6,1 -- possition, count

If SQL query caching, this is may be faster.


问:
Excel VBA Userform - Execute Sub when something changes on dynamic comboBox
I created a userform where is a comboBox
Depending which result user chooses, new comboBoxes will appear with new choices to choose from.
Below is the latest test I tried.

How do I make it so that when user changes the value in the new comboBox it will execute a premade function/sub

Code in Form

```<code>Dim WB As Workbook
Dim structSheet As Worksheet
Dim tbCollection As Collection

Private Sub UserForm_Activate()
    Dim ignoreList(3) As String

    ignoreList(0) = "main"
    ignoreList(1) = "configurator"
    ignoreList(2) = "create structure"
    Set WB = Excel.ActiveWorkbook

    For Each sheet In WB.Worksheets
        If Not isInTable(ignoreList, sheet.Name) Then
            supercode_box.AddItem sheet.Name
        End If
    Next
End Sub

Private Sub supercode_box_Change()
    If Not sheetExists(supercode_box.text) Then Exit Sub
    Set structSheet = WB.Worksheets(supercode_box.text)

    'Dim obj As clsControlBox

    topPos = 10
    leftPos = 54
    ID = 1

   ' For ID = 1 To 2
        Set ComboBox = createProductForm.Controls.add("Forms.ComboBox.1")
        With ComboBox
            .Name = "comboBoxName"
            .Height = 16
            .Width = 100
            .Left = leftPos
            .Top = topPos + ID * 18
            .AddItem "test"
            .Object.Style = 2
        End With

        Set tbCollection = New Collection
        tbCollection.add ComboBox

    'Next ID
End Sub
</code>```

code in class1 module

```<code>Private WithEvents MyTextBox As MSForms.controlBox

Public Property Set Control(tb As MSForms.controlBox)
    Set MyTextBox = tb
    MsgBox ("did it get here?")
End Property

Public Sub comboBoxName_Change()
    MsgBox ("start working ffs")
End Sub

Public Sub comboBoxName()
    MsgBox ("?? maybe this?")
End Sub
</code>```

答:
Judging on your code, the easiest way is to write the value you need in a separate worksheet.

Then make a check, whether it is changed and if it is changed, write the new value and fire the procedure that you want.

In short, something like this:

```<code>Sub TestMe()

    If Worksheets("Special").Cells(1, 1) = WB.Worksheets(supercode_box.Text) Then
        Call TheSpecificSub
    End If

    Worksheets("Special").Cells(1, 1) = WB.Worksheets(supercode_box.Text)

End Sub
</code>```

Body:
I created a userform where is a comboBox
Depending which result user chooses, new comboBoxes will appear with new choices to choose from.
Below is the latest test I tried.

How do I make it so that when user changes the value in the new comboBox it will execute a premade function/sub

Code in Form

Dim WB As Workbook
Dim structSheet As Worksheet
Dim tbCollection As Collection

Private Sub UserForm_Activate()
    Dim ignoreList(3) As String

    ignoreList(0) = "main"
    ignoreList(1) = "configurator"
    ignoreList(2) = "create structure"
    Set WB = Excel.ActiveWorkbook

    For Each sheet In WB.Worksheets
        If Not isInTable(ignoreList, sheet.Name) Then
            supercode_box.AddItem sheet.Name
        End If
    Next
End Sub

Private Sub supercode_box_Change()
    If Not sheetExists(supercode_box.text) Then Exit Sub
    Set structSheet = WB.Worksheets(supercode_box.text)

    'Dim obj As clsControlBox

    topPos = 10
    leftPos = 54
    ID = 1

   ' For ID = 1 To 2
        Set ComboBox = createProductForm.Controls.add("Forms.ComboBox.1")
        With ComboBox
            .Name = "comboBoxName"
            .Height = 16
            .Width = 100
            .Left = leftPos
            .Top = topPos + ID * 18
            .AddItem "test"
            .Object.Style = 2
        End With

        Set tbCollection = New Collection
        tbCollection.add ComboBox

    'Next ID
End Sub

code in class1 module

Private WithEvents MyTextBox As MSForms.controlBox

Public Property Set Control(tb As MSForms.controlBox)
    Set MyTextBox = tb
    MsgBox ("did it get here?")
End Property

Public Sub comboBoxName_Change()
    MsgBox ("start working ffs")
End Sub

Public Sub comboBoxName()
    MsgBox ("?? maybe this?")
End Sub

Body:
Judging on your code, the easiest way is to write the value you need in a separate worksheet.

Then make a check, whether it is changed and if it is changed, write the new value and fire the procedure that you want.

In short, something like this:

Sub TestMe()

    If Worksheets("Special").Cells(1, 1) = WB.Worksheets(supercode_box.Text) Then
        Call TheSpecificSub
    End If

    Worksheets("Special").Cells(1, 1) = WB.Worksheets(supercode_box.Text)

End Sub


问:
UIViews with UIPageControl
I'm a beginner when it comes to page control, and that's why I'm not sure 100% if my title agrees with what I want.  I want to make a UIPageControl that when the user swipes on the screen, the view would switch over to another view and the UIPageController at the bottom of the screen would update itself.  Also, to make my request even more confusing, I want a tab bar at the bottom of the screen that would stay put as the views change.

A great example of this is The Iconfactory's Ramp Champ:
http://img.slidetoplay.com/screenshots/ramp-champ_5.jpg

The bar at the bottom stays put while the rest of the items on the screen moves. What would be the easiest way to do this?

EDIT: I know I have to use a UISrollView, I just don't know how to go about implementing it...

答:
I believe what you're looking for is actually a UIScrollView with pagingEnabled set to YES.  You can leave the scrollview as a view above a regular UITabBar.  You'll use a UIPageControl to get the little dots. You can update it programmatically when the UIScrollView scrolls to a page by implementing an appropriate delegate method of the scroll view, maybe -scrollViewDidScroll:.

Assume you have two ivars: scrollView and pageControl. When you know how many pages your scroll view will have, you can set the contentSize of scrollView. It should be a multiple of the scrollView's bounds. For example, if the number of pages is static you can hardcode it in your -viewDidLoad...

```<code>- (void)viewDidLoad {
    // Any other code.

    scrollView.pagingEnabled = YES;
    scrollView.contentSize = CGSizeMake(scrollView.bounds.size.width * 3, scrollView.bounds.size.height); // 3 pages wide.
    scrollView.delegate = self;
}
</code>```

Then, to update your little dots...

```<code>- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat pageWidth = scrollView.bounds.size.width;
    NSInteger pageNumber = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = pageNumber;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: UIViews with UIPageControl

Body:
I believe what you're looking for is actually a UIScrollView with pagingEnabled set to YES.  You can leave the scrollview as a view above a regular UITabBar.  You'll use a UIPageControl to get the little dots. You can update it programmatically when the UIScrollView scrolls to a page by implementing an appropriate delegate method of the scroll view, maybe -scrollViewDidScroll:.

Assume you have two ivars: scrollView and pageControl. When you know how many pages your scroll view will have, you can set the contentSize of scrollView. It should be a multiple of the scrollView's bounds. For example, if the number of pages is static you can hardcode it in your -viewDidLoad...

- (void)viewDidLoad {
    // Any other code.

    scrollView.pagingEnabled = YES;
    scrollView.contentSize = CGSizeMake(scrollView.bounds.size.width * 3, scrollView.bounds.size.height); // 3 pages wide.
    scrollView.delegate = self;
}

Then, to update your little dots...

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat pageWidth = scrollView.bounds.size.width;
    NSInteger pageNumber = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = pageNumber;
}


问:
How can I sort lines in a text file based on the third word?
What I am trying to do is sort the students' details in a text file based on their first name, id, results and grades.

Here is what my Text_File.txt looks like: (each word is separated by tab '\t')

```<code>rose     ramzi     154ss6    85    A
john     watson    123aq1    96    A+
ellen    thomas    qs2115    75    B+
</code>```

I am trying to sort the lines in my text file in ascending order based on the third word (which is the student's ID).

I was able to sort the list with the first name and also I could extract the third word and tried using sort() function but it is still not sorting by ID.

Here is my sorting_by_id code:

```<code>int main() {
    fstream input("Text_File.txt", ios::in | ios::out);
    string line;
    vector<string> lines;

    while (getline(input, line))
        lines.push_back(line);
    sort(lines.begin(), lines.end(), [](const string& a, const string& b) {
        int wordStartPositionA = 0, wordStartPositionB = 0;//The start of each word in the string

        for (int i = 0; i < 2; i++)//looking for the third word in 1st sentence
            wordStartPositionA = a.find_first_of('  ', wordStartPositionA + 1);

        for (int i = 0; i < 2; i++)//looking for the third word in 2nd sentence
            wordStartPositionB = b.find_first_of('  ', wordStartPositionB + 1);

        //Getting where our word ends:
        int wordEndPositionA = a.find_first_of('    ', wordStartPositionA + 1);
        int wordEndPositionB = b.find_first_of('    ', wordStartPositionB + 1);

        //Getting the desired word
        string resultA = a.substr(wordStartPositionA + 1, a.length() - wordEndPositionA - 1);
        string resultB = b.substr(wordStartPositionB + 1, b.length() - wordEndPositionB - 1);

        //cout << resultA << "  " << resultB << endl;

        return resultA < resultB;

    });
    for_each(lines.begin(), lines.end(), [](const string& s) {
        cout << s << endl; });

    getchar();
    return 0;
}
</code>```

My aim is to sort the students based on their ID number.

Thank you for your help :)

答:
You need some data abstraction.

First define a suitable data type:

```<code>struct Student
{
    std::string firstName;
    std::string lastName;
    std::string id;
    int result;
    std::string grade;
};
</code>```

then you define how to read one of them:

```<code>std::istream& operator>>(std::istream& is, Student& s)
{
    return is >> s.firstName >> s.lastName >> s.id >> s.result >> s.grade;
}
</code>```

then you read them:

```<code>int main()
{
    std::ifstream input("Text_File.txt");
    std::vector<Student> students;
    Student s;
    while (input >> s)
    {
        students.push_back(s);
    }
</code>```

then you can easily sort them by id:

```<code>std::sort(students.begin(),
          students.end(),
          [](const Student& s1, const Student& s2) { return s1.id < s2.id; });
</code>```

or by decreasing result:

```<code>std::sort(students.begin(),
          students.end(),
          [](const Student& s1, const Student& s2) { return s1.result > s2.result; });
</code>```

or by whatever.

Body:
What I am trying to do is sort the students' details in a text file based on their first name, id, results and grades.

Here is what my Text_File.txt looks like: (each word is separated by tab '\t')

rose     ramzi     154ss6    85    A
john     watson    123aq1    96    A+
ellen    thomas    qs2115    75    B+

I am trying to sort the lines in my text file in ascending order based on the third word (which is the student's ID).

I was able to sort the list with the first name and also I could extract the third word and tried using sort() function but it is still not sorting by ID.

Here is my sorting_by_id code:

int main() {
    fstream input("Text_File.txt", ios::in | ios::out);
    string line;
    vector<string> lines;

    while (getline(input, line))
        lines.push_back(line);
    sort(lines.begin(), lines.end(), [](const string& a, const string& b) {
        int wordStartPositionA = 0, wordStartPositionB = 0;//The start of each word in the string

        for (int i = 0; i < 2; i++)//looking for the third word in 1st sentence
            wordStartPositionA = a.find_first_of('  ', wordStartPositionA + 1);

        for (int i = 0; i < 2; i++)//looking for the third word in 2nd sentence
            wordStartPositionB = b.find_first_of('  ', wordStartPositionB + 1);

        //Getting where our word ends:
        int wordEndPositionA = a.find_first_of('    ', wordStartPositionA + 1);
        int wordEndPositionB = b.find_first_of('    ', wordStartPositionB + 1);

        //Getting the desired word
        string resultA = a.substr(wordStartPositionA + 1, a.length() - wordEndPositionA - 1);
        string resultB = b.substr(wordStartPositionB + 1, b.length() - wordEndPositionB - 1);

        //cout << resultA << "  " << resultB << endl;

        return resultA < resultB;

    });
    for_each(lines.begin(), lines.end(), [](const string& s) {
        cout << s << endl; });

    getchar();
    return 0;
}

My aim is to sort the students based on their ID number.

Thank you for your help :)

Body:
You need some data abstraction.

First define a suitable data type:

struct Student
{
    std::string firstName;
    std::string lastName;
    std::string id;
    int result;
    std::string grade;
};

then you define how to read one of them:

std::istream& operator>>(std::istream& is, Student& s)
{
    return is >> s.firstName >> s.lastName >> s.id >> s.result >> s.grade;
}

then you read them:

int main()
{
    std::ifstream input("Text_File.txt");
    std::vector<Student> students;
    Student s;
    while (input >> s)
    {
        students.push_back(s);
    }

then you can easily sort them by id:

std::sort(students.begin(),
          students.end(),
          [](const Student& s1, const Student& s2) { return s1.id < s2.id; });

or by decreasing result:

std::sort(students.begin(),
          students.end(),
          [](const Student& s1, const Student& s2) { return s1.result > s2.result; });

or by whatever.


问:
Saving a two-d list to a file in python 2.7 changes the list?
I would like to save my list to a file after adding a new name to it. The main issue is that if I save using:

```<code>money =  [['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
finaldata = ""
for row in money:
    data  = " ".join(map(str,row))
    finaldata = str(finaldata) + str(data) + "\n"

f1 = open('bank.txt', 'w')
print >> f1, finaldata
f1.close()

with open("bank.txt") as textFile:
    money = [line.split() for line in textFile]
</code>```

It creates an extra position in the list. Before the list is saved it looks exactly as it should, therefore I know the issue is something to do with the code that saves the list to the file.

The result should save the list like this:

```<code>[['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
</code>```

But instead prints it like this:

```<code>[['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0'], []]
</code>```

I have tried another method (Without the "\n") and this also saves it wrong. Like with the attempt before the name is added to the list correctly but saving using the code:

```<code>money =  [['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
finaldata = ""
for row in money:
    data  = " ".join(map(str,row))
    finaldata = str(finaldata) + str(data)

f1 = open('bank.txt', 'w')
print >> f1, finaldata
f1.close()

with open("bank.txt") as textFile:
    money = [line.split() for line in textFile]
</code>```

Makes the list look like this:

```<code>[['Amber', '87000000000Theo', '15Duncan', '0Russell', '0Lauren', '0Sandra', '0']]
</code>```

Can anyone help me understand where I am going wrong? I have been working on  this one piece of code for several hours now.

答:
The trick is to avoid the extra \n at the end of your array.

```<code>money =  [['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
finaldata = []
for row in money:
    data  = " ".join(map(str,row))
    finaldata.append(str(data))

f1 = open('bank.txt', 'w')
print >> f1, "\n".join(finaldata)
f1.close()
</code>```

Observe that I make use of join to chain the finaldata array into a single string with \n.

Body:
I would like to save my list to a file after adding a new name to it. The main issue is that if I save using:

money =  [['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
finaldata = ""
for row in money:
    data  = " ".join(map(str,row))
    finaldata = str(finaldata) + str(data) + "\n"

f1 = open('bank.txt', 'w')
print >> f1, finaldata
f1.close()

with open("bank.txt") as textFile:
    money = [line.split() for line in textFile]

It creates an extra position in the list. Before the list is saved it looks exactly as it should, therefore I know the issue is something to do with the code that saves the list to the file.

The result should save the list like this:

[['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]

But instead prints it like this:

[['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0'], []]

I have tried another method (Without the "\n") and this also saves it wrong. Like with the attempt before the name is added to the list correctly but saving using the code:

money =  [['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
finaldata = ""
for row in money:
    data  = " ".join(map(str,row))
    finaldata = str(finaldata) + str(data)

f1 = open('bank.txt', 'w')
print >> f1, finaldata
f1.close()

with open("bank.txt") as textFile:
    money = [line.split() for line in textFile]

Makes the list look like this:

[['Amber', '87000000000Theo', '15Duncan', '0Russell', '0Lauren', '0Sandra', '0']]

Can anyone help me understand where I am going wrong? I have been working on  this one piece of code for several hours now.

Body:
The trick is to avoid the extra \n at the end of your array.

money =  [['Amber', '87000000000'], ['Theo', '15'], ['Duncan', '0'], ['Russell', '0'], ['Lauren', '0'], ['Sandra', '0']]
finaldata = []
for row in money:
    data  = " ".join(map(str,row))
    finaldata.append(str(data))

f1 = open('bank.txt', 'w')
print >> f1, "\n".join(finaldata)
f1.close()

Observe that I make use of join to chain the finaldata array into a single string with \n.


问:
How to purge unused source/class files from Directory tree
We have about 280 Java source code spread over 10 packages, and a bunch of txt and image files for a software project. Quite a few of them are not being used currently. They do not break the system, since we can just do a "javac //*.java" and "jar cmf metafile " to build up the executable jar which works. The question:

How do we find the class files never accessed, or image/txt files never used as resources in the jar?

答:
It has been answered in How to find unused/dead code in java projects.

For the images, I would write a small program, pseudocode would look like:

```<code>//list image names
//for each image name
    //find ocurrences in other files
</code>```

Body:
It has been answered in How to find unused/dead code in java projects.

For the images, I would write a small program, pseudocode would look like:

//list image names
//for each image name
    //find ocurrences in other files


问:
find nearest items from lat, lng in postgresql
My table contains lat and lng columns:

lng | double precision | not null

lat | double precision | not null

I want to retrieve only the results from a location (lat, lng).

How do I do ?

答:
A much better way is, you can take help of postgis to create a separate geometry/geography column for geo-spatial queries.

CREATE EXTENSION postgis;

ALTER TABLE your_table ADD COLUMN geom geometry(Point, 4326);

UPDATE your_table SET geom=st_SetSrid(st_MakePoint(lng, lat), 4326);

Once your table is updated you can do a simple nearest neighbor query like bellow.

SELECT name FROM your_table ORDER BY geom <-> ST_GeomFromText ('POINT(-49.2653819 -25.4244287 )', 4326);

Which will return nearest records to given points.


问:
How to Customize bootstrap carousel using fade in effect
This is my html code for carousal

```<code>  <section id="showcase">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item carousel-image-1 active">
      <div class="container">
        <div class="carousel-caption d-none d-sm-block text-right mb-5">
          <h1 class="display-3">Heading One</h1>
          <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.</p>
          <a href="#" class="btn btn-danger btn-lg">Sign Up Now</a>
        </div>
      </div>
    </div>

    <div class="carousel-item carousel-image-2">
      <div class="container">
        <div class="carousel-caption d-none d-sm-block mb-5">
          <h1 class="display-3">Heading Two</h1>
          <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.</p>
          <a href="#" class="btn btn-primary btn-lg">Learn More</a>
        </div>
      </div>
    </div>

    <div class="carousel-item carousel-image-3">
      <div class="container">
        <div class="carousel-caption d-none d-sm-block text-right mb-5">
          <h1 class="display-3">Heading Three</h1>
          <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.</p>
          <a href="#" class="btn btn-success btn-lg">Learn More</a>
        </div>
      </div>
    </div>
  </div>

  <a href="#myCarousel" data-slide="prev" class="carousel-control-prev">
    <span class="carousel-control-prev-icon"></span>
  </a>
  <a href="#myCarousel" data-slide="next" class="carousel-control-next">
    <span class="carousel-control-next-icon"></span>
  </a>
</div>
</code>```

I want to style fade in effect for this slide. can anyone help me to make my css code.
i found some css code for carousel like this.

but it's not working properly.

```<code>     .carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
  transition-property: opacity;
 }
  .carousel-fade .carousel-inner .item,
 .carousel-fade .carousel-inner .active.left,
 .carousel-fade .carousel-inner .active.right {
   opacity: 0;
 }
 .carousel-fade .carousel-inner .active,
  .carousel-fade .carousel-inner .next.left,
 .carousel-fade .carousel-inner .prev.right {
  opacity: 1;
 }
 .carousel-fade .carousel-inner .next,
  .carousel-fade .carousel-inner .prev,
 .carousel-fade .carousel-inner .active.left,
  .carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
 }
 .carousel-fade .carousel-control {
  z-index: 2;
 }
  html,
  body,
 .carousel,
 .carousel-inner,
 .carousel-inner .item
{
  height: 100%;
  }
 .item:nth-child(1) {
    background: url("../img/img2.jpeg");
   background-size: cover;
  }
  }
 .item:nth-child(2) {
    background: url("../img/img2.jpeg");
    background-size: cover;
 }
 }
 .item:nth-child(3) {
   background: url("../img/img2.jpeg");
   background-size: cover;
  }
 }
</code>```

i want to edit this css code for my bootstrap carousal.

if anyone know another method for fade in effect please help me.

答:
Try this one. Hope it is helpful to you</p>

```<code>.carousel .item {
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
-ms-transition: opacity 0.5s ease-in-out;
-o-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
opacity:0;
}

.carousel .active.item {
opacity:1;
}

.carousel.carousel-fade .active.left,
.carousel.carousel-fade .active.right {
left: 0;
z-index: 2;
opacity: 0;
filter: alpha(opacity=0);
}

.carousel.carousel-fade .next,
.carousel.carousel-fade .prev {
left: 0;
z-index: 1;
}

.carousel.carousel-fade .carousel-control {
z-index: 3;
}
</code>```

Body:
This is my html code for carousal

Heading One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.

          Sign Up Now

Heading Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.

          Learn More

Heading Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.

          Learn More

I want to style fade in effect for this slide. can anyone help me to make my css code.
i found some css code for carousel like this.

but it's not working properly.

     .carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
  transition-property: opacity;
 }
  .carousel-fade .carousel-inner .item,
 .carousel-fade .carousel-inner .active.left,
 .carousel-fade .carousel-inner .active.right {
   opacity: 0;
 }
 .carousel-fade .carousel-inner .active,
  .carousel-fade .carousel-inner .next.left,
 .carousel-fade .carousel-inner .prev.right {
  opacity: 1;
 }
 .carousel-fade .carousel-inner .next,
  .carousel-fade .carousel-inner .prev,
 .carousel-fade .carousel-inner .active.left,
  .carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
 }
 .carousel-fade .carousel-control {
  z-index: 2;
 }
  html,
  body,
 .carousel,
 .carousel-inner,
 .carousel-inner .item
{
  height: 100%;
  }
 .item:nth-child(1) {
    background: url("../img/img2.jpeg");
   background-size: cover;
  }
  }
 .item:nth-child(2) {
    background: url("../img/img2.jpeg");
    background-size: cover;
 }
 }
 .item:nth-child(3) {
   background: url("../img/img2.jpeg");
   background-size: cover;
  }
 }

i want to edit this css code for my bootstrap carousal.

if anyone know another method for fade in effect please help me.

Body:
Try this one. Hope it is helpful to you

.carousel .item {
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
-ms-transition: opacity 0.5s ease-in-out;
-o-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
opacity:0;
}

.carousel .active.item {
opacity:1;
}

.carousel.carousel-fade .active.left,
.carousel.carousel-fade .active.right {
left: 0;
z-index: 2;
opacity: 0;
filter: alpha(opacity=0);
}

.carousel.carousel-fade .next,
.carousel.carousel-fade .prev {
left: 0;
z-index: 1;
}

.carousel.carousel-fade .carousel-control {
z-index: 3;
}


问:
What is a circular shift with extend used for?
I remember in an assembly class, we learned the m68k processor, and there were 3 kinds of shifts you could do. Linear shift, circular shift, and circular shift with extend.

The last one, circular shift with extend, basically rotates all bits left or right but it puts the outermost one into an extend bit before it would be moved to the beginning again (if you ever shifted by 1 again).

I drew a little pic:

Basically, a 33rd bit is used in the circular shifting, but doesn't show up in the 32-bit word of course. The 33rd bit is the X flag of the processor, which stands for extend. You could just as easily use any status flag, such as the carry flag, but I guess the motorola guys wanted to preserve that flag so it doesn't get overwritten, in case you need the carry flag for its normal duties in the middle of some algorithm that also needs rotate with extend.

Anyway, what is the purpose of rotate with extend? What is it used for? What is it needed for? It seems so strange. Why in the world do you need a 33rd bit?

I've read this and this, two related questions, but they didn't talk about the circular shift with extend.

I'm aware of some uses for normal shifts. Basically to divide by two, or test divisibility, and permutate the bits for randomness. Stuff like that. But I cannot think of why you would need some extended bit inserted into the rotate but doesn't come out in the result.

EDIT: I'm interested in any use of it, modern or old, and doesn't matter if it's on the m68k or not. The m68k is just the first placed I encountered it (and I never even used it there).

答:
ROXL is pretty useful for non-destructively testing bits and can save quite some instructions compared to BTST.x instruction (which is only avalable in 8 and 32 bit sizes). Once you do that, rotating by more than one place also can make things like skipping bits possible.</p>

```<code>  ROXL.W #4,D0      ; shift bit 12 into carry and X
  BCC.S isNotSet    ; branch if bit is not set
  BSR isSet         ; do whatever you want
isNotSet:
  ROXL.W #11,D0     ; rotate around to reset to previous value
</code>```

Body:
ROXL is pretty useful for non-destructively testing bits and can save quite some instructions compared to BTST.x instruction (which is only avalable in 8 and 32 bit sizes). Once you do that, rotating by more than one place also can make things like skipping bits possible.

  ROXL.W #4,D0      ; shift bit 12 into carry and X
  BCC.S isNotSet    ; branch if bit is not set
  BSR isSet         ; do whatever you want
isNotSet:
  ROXL.W #11,D0     ; rotate around to reset to previous value


问:
Nullablity of DB generated attributes
I'm working in a Kotlin based project and It force me to deal with any attribute that possibly can hold null. It's nice to find out somewhere nulls are possible while they are not welcome; but I see so much of ?.s and .!!s for attributes that DB generates, e.g. IDs. Maybe I'm abusing that operators?

Is there any convention to mark attribute as not nullable but still have DB generated values here? If I lookup an object It's safe to assume DB generated values are not null anymore. Can VM be made known to this? Maybe by framework or some annotations that language provide?

答:
If your id is generated by the database it is nullable since the JVM/compiler/IDE has no way to know if your entity is already persisted or not.

What you could do though is implement additional methods that are guaranteed to return non-null values by throwing an exception otherwise.

Title: Nullablity of DB generated attributes


问:
Insert Path of a file with \\ in mysql using java
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

```<code>filename.replaceall("\","\\");
</code>```

But this didn't work out.

答: The slash should not be an issue.  Make sure your path has the slash before you insert into the database.   Also make sure you are using a PreparedStatement to insert the data.</p>

Body:
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

filename.replaceall("\","\\");

But this didn't work out.


答:
try this.</p>

```<code>LineChart chart = findViewById(R.id.chart);
chart.getAxisRight().setEnabled(false);
</code>```

Title: how to mpAndroidChart remove one sideBar on the BarChart

Body: how to remove mpAndroidChart one side Bar on the BarChart

Body:
try this.

LineChart chart = findViewById(R.id.chart);
chart.getAxisRight().setEnabled(false);


问:
Showing error while installing laravel
have got this error while installing Laravel

```<code>PHP Warning:  require(/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16
PHP Fatal error:  require(): Failed opening required '/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php') in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16
</code>```

I have tried this source solve this

```<code>composer create-project laravel/laravel laraout "5.2.*" --no-scripts
</code>```

But it is not working for me.

答:
Don't use "" try this

```<code>composer create-project laravel/laravel laraout 5.2.*
</code>```

just copy past the above command

Title: Showing error while installing laravel

Body:
have got this error while installing Laravel

PHP Warning:  require(/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16
PHP Fatal error:  require(): Failed opening required '/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php') in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16

I have tried this source solve this

composer create-project laravel/laravel laraout "5.2.*" --no-scripts

But it is not working for me.

Body:
Don't use "" try this

composer create-project laravel/laravel laraout 5.2.*

just copy past the above command


问:
cannot create maven project
I want to create maven project but failed. I use proxy in my network. I can reach "https://repo.maven.apache.org/maven2" in browser. the error show:

Could not resolve archetype
  org.apache.maven.archetypes:maven-archetype-webapp:1.0 from any of the
  configured repositories. Could not resolve artifact
  org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 Could not
  transfer artifact
  org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 from/to
  central (https://repo.maven.apache.org/maven2): Connect timed out
  Could not transfer artifact
  org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 from/to
  central (https://repo.maven.apache.org/maven2): Connect timed out

I already create setting.xml and put to .m2 folder. the setting.xml contains:

```<code><proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>idnproxy.myproxy.asia</host>
      <port>8080</port>
      <username>c76266</username>
      <password>Password09</password>
      <nonProxyHosts>localhost|128.*.*.*|10.*.*.*|*.intranet.asia|*.group.local</nonProxyHosts>
    </proxy>
  </proxies>
</code>```

this setting proxy, port, username and password same with setting in my browser and I can running internet. I assume that configuration is true. how to fix this problem? thanks.

答:
It should be settings.xml , not setting.xml

Or if you do want to use this setting.xml , from command line, point maven to this xml file

```<code>mvn -s Full_PATH_TO_setting.xml install
</code>```

Title: cannot create maven project

Body:
I want to create maven project but failed. I use proxy in my network. I can reach "https://repo.maven.apache.org/maven2" in browser. the error show:

Could not resolve archetype
  org.apache.maven.archetypes:maven-archetype-webapp:1.0 from any of the
  configured repositories. Could not resolve artifact
  org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 Could not
  transfer artifact
  org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 from/to
  central (https://repo.maven.apache.org/maven2): Connect timed out
  Could not transfer artifact
  org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 from/to
  central (https://repo.maven.apache.org/maven2): Connect timed out

I already create setting.xml and put to .m2 folder. the setting.xml contains:

<proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>idnproxy.myproxy.asia</host>
      <port>8080</port>
      <username>c76266</username>
      <password>Password09</password>
      <nonProxyHosts>localhost|128.*.*.*|10.*.*.*|*.intranet.asia|*.group.local</nonProxyHosts>
    </proxy>
  </proxies>

this setting proxy, port, username and password same with setting in my browser and I can running internet. I assume that configuration is true. how to fix this problem? thanks.

Body:
It should be settings.xml , not setting.xml

Or if you do want to use this setting.xml , from command line, point maven to this xml file

mvn -s Full_PATH_TO_setting.xml install


问:
reset the Select2 dropdowns on Ajax Form Submit
im using jquery select2 library

```<code>http://ivaynberg.github.io/select2/
</code>```

Problem i am facing, i have multiple dropdowns in my form and if i submit the form through Ajax all feilds do get reset/empty except the select2 dropdowns..

i use this for the reset

```<code>$("#block-validate")[0].reset();
</code>```

and it works perfectly fine and reset/empty all the fields in the form except the select2

i know there is a way to clear the the feild of select2 using this

```<code>$("#e8").select2("val", "");
</code>```

But it will only reset the value for the intended select2. i mean we can do like this

```<code>$("#e8, #e9, #e10, #e11").select2("val", "");
</code>```

what i am trying to say is there any way to reset/empty all the form fields including the select2 dropdowns without specifically calling there ID's.

or even just a code to reset or empty all the dropdowns for select2 without specifically calling there ID's, just all the Select2 dropdowns go reset on page.

答:
This works for me. Select2 4.0.3</p>

```<code>$('.select2').val('').trigger("change");
</code>```

Body:
im using jquery select2 library

http://ivaynberg.github.io/select2/

Problem i am facing, i have multiple dropdowns in my form and if i submit the form through Ajax all feilds do get reset/empty except the select2 dropdowns..

i use this for the reset

$("#block-validate")[0].reset();

and it works perfectly fine and reset/empty all the fields in the form except the select2

i know there is a way to clear the the feild of select2 using this

$("#e8").select2("val", "");

But it will only reset the value for the intended select2. i mean we can do like this

$("#e8, #e9, #e10, #e11").select2("val", "");

what i am trying to say is there any way to reset/empty all the form fields including the select2 dropdowns without specifically calling there ID's.

or even just a code to reset or empty all the dropdowns for select2 without specifically calling there ID's, just all the Select2 dropdowns go reset on page.

Body:
This works for me. Select2 4.0.3

$('.select2').val('').trigger("change");


问:
Merge maps and make values as array
```<code>public class MapCheck {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("John", "Taxi Driver");
        data.put("Mark", "Professional Killer");
        Map<String, String> data1 = new HashMap<String, String>();
        data1.put("John", "Driver");
        data1.put("Mark", "Murderer");
        Map<String, String> data3 = new HashMap<String, String>();
        data3.putAll(data);
        data3.putAll(data1);
        System.out.println(data3);
    }
}
</code>```

I have few maps which contains same key, their values are different. I want to merge them. But when I merge them with the usual putAll() it gives me only the value of the key which was inserted latest.

Output from above code is  {John=Driver, Mark=Murderer}

Is there a method which will get me all the values associated with the key and give me as a array like

```<code>{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}
</code>```

答:
the data structure Multimap may be the best choice. The implementation in guava is highly recommended.

https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap

Title: Merge maps and make values as array

Body:
public class MapCheck {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("John", "Taxi Driver");
        data.put("Mark", "Professional Killer");
        Map<String, String> data1 = new HashMap<String, String>();
        data1.put("John", "Driver");
        data1.put("Mark", "Murderer");
        Map<String, String> data3 = new HashMap<String, String>();
        data3.putAll(data);
        data3.putAll(data1);
        System.out.println(data3);
    }
}

I have few maps which contains same key, their values are different. I want to merge them. But when I merge them with the usual putAll() it gives me only the value of the key which was inserted latest.

Output from above code is  {John=Driver, Mark=Murderer}

Is there a method which will get me all the values associated with the key and give me as a array like

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}


问:
Weird characters from the BSFN B76B0220
I'm trying to recover Strings from a .txt file with the bsfn B76B0220.FetchNextLineFromFlatFile

When the text is recovered the String should looks like this:

170015560220171030070567000400000

Instead of that the String recovered is this one:

㜱〰㔱㘵㈰〲㜱〱〳㜰㔰㜶〰㐰〰〰രㄊ〷㄰㔵〶㈳㄰ㄷ㌰〰〷㘵〷〰〱〸〰਍㜱〰㔱㘵㔰〲㜱〱〳㜰㔰㜶〰㜰㘵〰രㄊ〷㄰㔵〶㈶㄰ㄷ㌰〰〷㘵〷〰㠰〴〰਍㜱〰㔱㘵㜰〲㜱〱〳㜰㔰㜶〰〰㜰〵愰††††††††††††††††††††††††††††††††ഠਠ

Here is my code:

```<code>VA rpt_VA_PATH = "C:\Users\User\Desktop\Fichero.txt"
Fetch Next Line From Flat File
       VA rpt_VA_PATH -> BF szFlatFileName
       VA rpt_VA_GENLNG <> BF idFilePtr
       "1500" -> BF mnRecordLength
       VA rpt_VA_ERROR_CODE <- BF cErrorCode
       VA rpt_VA_ACTUAL_LINE <- BF szFlatFileRecord
</code>```

I think that the problem is related with the file codification(UTF8, ansi, etc..)

Thanks for the help.

答:
Depending your JDEdwards release it will expected to read and write in UNICODE encoding.

On this cases you could use the application P93081 to set the text encoding that your APPL/UBE will use.

Title: Weird characters from the BSFN B76B0220

Body:
I'm trying to recover Strings from a .txt file with the bsfn B76B0220.FetchNextLineFromFlatFile

When the text is recovered the String should looks like this:

170015560220171030070567000400000

Instead of that the String recovered is this one:

㜱〰㔱㘵㈰〲㜱〱〳㜰㔰㜶〰㐰〰〰രㄊ〷㄰㔵〶㈳㄰ㄷ㌰〰〷㘵〷〰〱〸〰਍㜱〰㔱㘵㔰〲㜱〱〳㜰㔰㜶〰㜰㘵〰രㄊ〷㄰㔵〶㈶㄰ㄷ㌰〰〷㘵〷〰㠰〴〰਍㜱〰㔱㘵㜰〲㜱〱〳㜰㔰㜶〰〰㜰〵愰††††††††††††††††††††††††††††††††ഠਠ

Here is my code:

VA rpt_VA_PATH = "C:\Users\User\Desktop\Fichero.txt"
Fetch Next Line From Flat File
       VA rpt_VA_PATH -> BF szFlatFileName
       VA rpt_VA_GENLNG <> BF idFilePtr
       "1500" -> BF mnRecordLength
       VA rpt_VA_ERROR_CODE <- BF cErrorCode
       VA rpt_VA_ACTUAL_LINE <- BF szFlatFileRecord

I think that the problem is related with the file codification(UTF8, ansi, etc..)

Thanks for the help.


问:
Android Studio 3.0 not able to import google play service even it is added in build.gradle file
I am trying to fetch device current location but when i am trying to imported Location Service it. But it show can not resolve symbol LocationService

```<code>import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
</code>```

Build.gradle file

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support:design:26.0.0-beta1'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

I have tried with google play services previous version (11.4.2) as well

答:
Importing below dependencies might help you.

```<code>compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.android.gms:play-services-places:10.0.1'
</code>```

Please check once. (Make sure you use latest dependencies).
Below link might help you to do the same.
http://gradleplease.appspot.com/

Body:
I am trying to fetch device current location but when i am trying to imported Location Service it. But it show can not resolve symbol LocationService

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

Build.gradle file

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support:design:26.0.0-beta1'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

I have tried with google play services previous version (11.4.2) as well

Body:
Importing below dependencies might help you.

compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.android.gms:play-services-places:10.0.1'

Please check once. (Make sure you use latest dependencies).
Below link might help you to do the same.
http://gradleplease.appspot.com/


问:
Verify if a service is marked for deletion
Sometimes when I uninstall the setup (made with WIX) the service remain marked for deletion, and the user must restart the machine to install again.
How could I verify that the service is marked for deletion and tell to the user to restart the computer before making other installation?</p>

答:
In my case the service was marked for deletion after uninstalling it, because I didn't dispose an object properly (rabbitmq-connection in my case).

This is not a direct answer on the question but may help to solve the root-issue of it.


问:
Javascript error in jssh in Firefox 4.0b1
Using this Javascript through jssh compiled and built for the new Firefox 4.0 beta 1 returns an odd message. Here is the code (sorry if it's a little messy).

In summary the code checks all frames of a Firefox window which is a test page of our unit tests for a  element that has an onclick which contains the phrase Goodbye Wonderful, instead of getting a failed response back we are receiving this odd nserror at the end which we cannot explain.

```<code>var firefoxWindow = getWindows()[0];
var browser = firefoxWindow.getBrowser();
var doc = browser.contentDocument;

var elem = null;
var elems = doc.getElementsByTagName('td');

for(a=0;a < elems.length;a++){ if( ((elems[a] !== null && elems[a].hasAttributes() === true && elems[a].getAttribute('onclick') !== null && elems[a].getAttribute('onclick').toString().match(/doNothing/gim) !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim).length >= 0) || (elems[a] !== null && elems[a].onclick !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim) !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim).length >= 0))) { elem = elems[a]; } }

var found = false;
var window = null;

for(var i=0; i < firefoxWindow.frames.length; i++){if(firefoxWindow.frames[i].toString().toLowerCase().indexOf('object window') > -1){window = firefoxWindow.frames[i]; break;}}

function recursiveSearch(frames){ for(var i=0; i<frames.length; i++){var elems = frames[i].document.getElementsByTagName('td'); for(a=0;a < elems.length;a++){ if( ((elems[a] !== null && elems[a].hasAttributes() === true && elems[a].getAttribute('onclick') !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim) !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim).length >= 0) || (elems[a] !== null && elems[a].onclick !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim) !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim).length >= 0))) { elem = elems[a]; } } if(elem){found = true; return;} else{ if(frames[i].frames.length>0){recursiveSearch(frames[i].frames);}}}}if(!elem && window.frames.length > 0){ recursiveSearch(window.frames); }var origColor = '';if(elem !== null){origColor = elem.style.backgroundColor;if(origColor === null){origColor = '';} elem.style.backgroundColor = 'yellow';}
</code>```

Here is the return message from jssh :

Received: uncaught exception: [Exception... "Component is not available"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: interactive :: <TOP_LEVEL> :: line 1"  data: no]

答: JSSh is no longer supported in Firefox 4 and is a mess to handle, switching to mozrepl since it's written mostly in javascript and adding my own javascript commands directly to the extension seems to be a better way of accomplishing certain things.</p>

Body:
Using this Javascript through jssh compiled and built for the new Firefox 4.0 beta 1 returns an odd message. Here is the code (sorry if it's a little messy).

In summary the code checks all frames of a Firefox window which is a test page of our unit tests for a  element that has an onclick which contains the phrase Goodbye Wonderful, instead of getting a failed response back we are receiving this odd nserror at the end which we cannot explain.

var firefoxWindow = getWindows()[0];
var browser = firefoxWindow.getBrowser();
var doc = browser.contentDocument;

var elem = null;
var elems = doc.getElementsByTagName('td');

for(a=0;a < elems.length;a++){ if( ((elems[a] !== null && elems[a].hasAttributes() === true && elems[a].getAttribute('onclick') !== null && elems[a].getAttribute('onclick').toString().match(/doNothing/gim) !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim).length >= 0) || (elems[a] !== null && elems[a].onclick !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim) !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim).length >= 0))) { elem = elems[a]; } }

var found = false;
var window = null;

for(var i=0; i < firefoxWindow.frames.length; i++){if(firefoxWindow.frames[i].toString().toLowerCase().indexOf('object window') > -1){window = firefoxWindow.frames[i]; break;}}

function recursiveSearch(frames){ for(var i=0; i<frames.length; i++){var elems = frames[i].document.getElementsByTagName('td'); for(a=0;a < elems.length;a++){ if( ((elems[a] !== null && elems[a].hasAttributes() === true && elems[a].getAttribute('onclick') !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim) !== null && elems[a].getAttribute('onclick').toString().match(/Goodbye Wonderful/gim).length >= 0) || (elems[a] !== null && elems[a].onclick !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim) !== null && elems[a].onclick.toString().match(/Goodbye Wonderful/gim).length >= 0))) { elem = elems[a]; } } if(elem){found = true; return;} else{ if(frames[i].frames.length>0){recursiveSearch(frames[i].frames);}}}}if(!elem && window.frames.length > 0){ recursiveSearch(window.frames); }var origColor = '';if(elem !== null){origColor = elem.style.backgroundColor;if(origColor === null){origColor = '';} elem.style.backgroundColor = 'yellow';}

Here is the return message from jssh :

Received: uncaught exception: [Exception... "Component is not available"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: interactive :: <TOP_LEVEL> :: line 1"  data: no]


问:
is bigquery's farm_fingerprint not randomly distributed?
When I take the hash of an ordered set (ie numerical userids), the resulting distribution of their MD5 hashes is approximately uniformly distributed: ie. If I divide the hashes into n quantiles, low-numbered userids (10001)are equally likely to be found in a quantile of hashes as high-numbered userids (99999).  On the other hand, if I do this with farm_fingerprint, the resulting buckets of hashes don't seem to be uniformly distributed: low-numbered buckets have more low-numbered userids.  The documentation doesn't immediately mention the distribution properties of the hashes and I can't find it in the additional references.

I realize that a better way to uniformly distribute userids is by assigning a random number to each userid, as mentioned here; my questions is specifically regarding the distribution properties of the FARM_FINGERPRINT hash mentioned.

Below is an example query illustrating the relative skew in the quantiles:

```<code>    SELECT
      avg(n_low) as avg_n_low,
      avg(n_med) as avg_n_med,
      avg(n_high) as avg_n_high
    FROM (
      SELECT bucket_id,
        SUM(CASE WHEN label = 'low' THEN 1 ELSE 0 END) as n_low,
        SUM(CASE WHEN label = 'med' THEN 1 ELSE 0 END) as n_med,
        SUM(CASE WHEN label = 'high' THEN 1 ELSE 0 END) as n_high
      FROM (
        SELECT
          x,
          label,
          ntile(1000) OVER (ORDER by h) as bucket_id
        FROM (
          SELECT x,
          CASE
            WHEN x BETWEEN 00001 and 20000 THEN 'low'
            WHEN x BETWEEN 20001 and 40000 THEN 'med'
            WHEN x BETWEEN 40001 and 60000 THEN 'high'
          END as label,
          --FARM_FINGERPRINT(CAST(x AS STRING)) h
          MD5(CAST(x AS STRING)) h
          FROM UNNEST((SELECT GENERATE_ARRAY(1,60000,10) xs)) AS x
        )
      )
      GROUP BY 1
    )
    WHERE
      bucket_id < 100
      --bucket_id > 900
</code>```

I bucket 2000 'low', 'med', and 'high' users into 100 buckets.  One can see that using the FARM_FINGERPRINT yields a higher variance in the bucket averages than MD5, ie. FARM_FINGERPRINT seems to have a higher avg_n_low for buckets < 100 than MD5 and higher avg_n_high for buckets > 900.  ie. assignment to buckets via the hash is not as uniformly distributed as MD5.

I realize this is somewhat subjective at this point, please let me know if I'm missing something or can provide more details.

答:
Can you help us reproduce the issue?

I see a very regular distribution - at least when doing the AVG(ABS()) of the fingerprint results:

```<code>SELECT CEIL(x/10000000000), AVG(ABS(h)), COUNT(*)
FROM (
  SELECT x, FARM_FINGERPRINT(CAST(x AS STRING)) h
  FROM UNNEST((SELECT GENERATE_ARRAY(1,100000000000,100000) xs)) AS x
)
GROUP BY 1
ORDER BY 2
</code>```

Same with the range of the ids the question has:

```<code>SELECT CEIL(x/10000), AVG(ABS(h)), COUNT(*)
FROM (
  SELECT x, FARM_FINGERPRINT(CAST(x AS STRING)) h
  FROM UNNEST((SELECT GENERATE_ARRAY(10001,100000) xs)) AS x
)
GROUP BY 1
ORDER BY 2
</code>```

Body:
When I take the hash of an ordered set (ie numerical userids), the resulting distribution of their MD5 hashes is approximately uniformly distributed: ie. If I divide the hashes into n quantiles, low-numbered userids (10001)are equally likely to be found in a quantile of hashes as high-numbered userids (99999).  On the other hand, if I do this with farm_fingerprint, the resulting buckets of hashes don't seem to be uniformly distributed: low-numbered buckets have more low-numbered userids.  The documentation doesn't immediately mention the distribution properties of the hashes and I can't find it in the additional references.

I realize that a better way to uniformly distribute userids is by assigning a random number to each userid, as mentioned here; my questions is specifically regarding the distribution properties of the FARM_FINGERPRINT hash mentioned.

Below is an example query illustrating the relative skew in the quantiles:

    SELECT
      avg(n_low) as avg_n_low,
      avg(n_med) as avg_n_med,
      avg(n_high) as avg_n_high
    FROM (
      SELECT bucket_id,
        SUM(CASE WHEN label = 'low' THEN 1 ELSE 0 END) as n_low,
        SUM(CASE WHEN label = 'med' THEN 1 ELSE 0 END) as n_med,
        SUM(CASE WHEN label = 'high' THEN 1 ELSE 0 END) as n_high
      FROM (
        SELECT
          x,
          label,
          ntile(1000) OVER (ORDER by h) as bucket_id
        FROM (
          SELECT x,
          CASE
            WHEN x BETWEEN 00001 and 20000 THEN 'low'
            WHEN x BETWEEN 20001 and 40000 THEN 'med'
            WHEN x BETWEEN 40001 and 60000 THEN 'high'
          END as label,
          --FARM_FINGERPRINT(CAST(x AS STRING)) h
          MD5(CAST(x AS STRING)) h
          FROM UNNEST((SELECT GENERATE_ARRAY(1,60000,10) xs)) AS x
        )
      )
      GROUP BY 1
    )
    WHERE
      bucket_id < 100
      --bucket_id > 900

I bucket 2000 'low', 'med', and 'high' users into 100 buckets.  One can see that using the FARM_FINGERPRINT yields a higher variance in the bucket averages than MD5, ie. FARM_FINGERPRINT seems to have a higher avg_n_low for buckets < 100 than MD5 and higher avg_n_high for buckets > 900.  ie. assignment to buckets via the hash is not as uniformly distributed as MD5.

I realize this is somewhat subjective at this point, please let me know if I'm missing something or can provide more details.

Body:
Can you help us reproduce the issue?

I see a very regular distribution - at least when doing the AVG(ABS()) of the fingerprint results:

SELECT CEIL(x/10000000000), AVG(ABS(h)), COUNT(*)
FROM (
  SELECT x, FARM_FINGERPRINT(CAST(x AS STRING)) h
  FROM UNNEST((SELECT GENERATE_ARRAY(1,100000000000,100000) xs)) AS x
)
GROUP BY 1
ORDER BY 2

Same with the range of the ids the question has:

SELECT CEIL(x/10000), AVG(ABS(h)), COUNT(*)
FROM (
  SELECT x, FARM_FINGERPRINT(CAST(x AS STRING)) h
  FROM UNNEST((SELECT GENERATE_ARRAY(10001,100000) xs)) AS x
)
GROUP BY 1
ORDER BY 2


问:
Convert JSON data from API to array and display it separately in Laravel and Guzzle HTTP Client?
I am using API's for fetching data which are in JSON format, I want to convert them into Array and display each 'name'=>'value' pairs separately in Laravel and I am using Guzzle Http Client for fetching API data,

Code for fetching data:

```<code>$pnrNumber = 4238007735;

    $client = new Client();

    $res = $client->request('GET', 'https://api.railwayapi.com/v2/pnr-status/pnr/'.$pnrNumber.'/apikey/<API-KEY>/');

    $body =  $res->getBody();

    echo $body;
</code>```

Thank you!

答:
Use json_decode function:

$array = json_decode($body, true);

Notice that the second parameter is set to true, so that the output is an array not a stdClass.

Body:
I am using API's for fetching data which are in JSON format, I want to convert them into Array and display each 'name'=>'value' pairs separately in Laravel and I am using Guzzle Http Client for fetching API data,

Code for fetching data:

$pnrNumber = 4238007735;

    $client = new Client();

    $res = $client->request('GET', 'https://api.railwayapi.com/v2/pnr-status/pnr/'.$pnrNumber.'/apikey/<API-KEY>/');

    $body =  $res->getBody();

    echo $body;

Thank you!


问:
upload image file through ajax and php
I am not familiar with this problem I am facing.. I would like to upload image file through ajax & php

so far I have done these:
HTML:

```<code><input type="file" name="file" id="file" class="inputfile">
<label for="file">Choose a file</label>
</code>```

ajax:

```<code>jQuery(document).ready(function($) {
var data = {

                business_name: $('#business_name').val(),
                business_country: $('#business-country').val(),
                business_region: $('#business-region').val(),
                business_phone: $('#business_phone').val(),
                //business_image: $('#image-data').val(),
                business_image: $('#file').val(),
                token: $('#token').val()
            }
$.ajax({
                type: "POST",
                data: data,
                url: "index.php?route=account/profile/savetoken=" + data.token,
            success: function(data) {
                $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your profile has been successfully saved!</div>");
                }
            });
});
</code>```

I could get the path name of the image and store it to database.. But I could not upload the image on e specific folder..

I am using MVC model like openCart.. Actually I got the structure of OC, and building a dashboard from it..

Is there any way of using the tools already OC have like:

```<code>$this->load->model('tool/image');
</code>```

otherwise, how could I upload images?
serialize the form or something?

please be specific as possible so I could understand!

thanks in advance!

答:
ok I solved my issue/error about my own question. I understood a lot actually about how openCart upload images, how ajax and xhr works and so on. Anyway, the code I have used is this:

Inside file profile.tpl:

```<code>$('#upload-image').on('click',function(e){
    var formData = new FormData($('#submitProfile')[0]);
    formData.append('route','account/profile');
    $.ajax({
        url: 'index.php?route=tool/upload/logo',
        type: 'post',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function() {
          $("#containerAlertMessages").html("<div class='alert alert-info'><strong>Sending...</strong></div>");
                    $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        complete: function() {
            $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your logo has been uploaded successfully! Do not forget to save the abovr information by clicking the Save button at the bottom right corner!</div>");
            $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        success: function() {
            //nothing yet
        },
        error: function(xhr, ajaxOptions, thrownError) {
          alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    });
</code>```

Inside file upload.php:

```<code>public function logo() {
        $this->load->language('tool/upload');

        if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
            $filename = html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8');

            $route = $this->request->post['route'];
            if($route == "account/profile") {
                $file = "image/" . $filename;
                move_uploaded_file($this->request->files['file']['tmp_name'], DIR_LOGOS . $file);
            }
        }
    }
</code>```

DIR_LOGOS has been defined inside config.php file, so I could reffer to this variable again in another file if I want it to.

Furthermore, I am sending the route variable, in order to know from where the image upload is coming.
So, if the uploading is coming from 'account/profile' I am saving the image to '/image' folder
if its coming from 'accoun/register' I am saving to '/image/register' or whatever folder I want to (existing one or not), and so on

I hope that helps someone, with same issues!

Title: upload image file through ajax and php

Body:
I am not familiar with this problem I am facing.. I would like to upload image file through ajax & php

so far I have done these:
HTML:

<input type="file" name="file" id="file" class="inputfile">
Choose a file

ajax:

jQuery(document).ready(function($) {
var data = {

                business_name: $('#business_name').val(),
                business_country: $('#business-country').val(),
                business_region: $('#business-region').val(),
                business_phone: $('#business_phone').val(),
                //business_image: $('#image-data').val(),
                business_image: $('#file').val(),
                token: $('#token').val()
            }
$.ajax({
                type: "POST",
                data: data,
                url: "index.php?route=account/profile/savetoken=" + data.token,
            success: function(data) {
                $("#containerAlertMessages").html("
Success! Your profile has been successfully saved!
");
                }
            });
});

I could get the path name of the image and store it to database.. But I could not upload the image on e specific folder..

I am using MVC model like openCart.. Actually I got the structure of OC, and building a dashboard from it..

Is there any way of using the tools already OC have like:

$this->load->model('tool/image');

otherwise, how could I upload images?
serialize the form or something?

please be specific as possible so I could understand!

thanks in advance!

Body:
ok I solved my issue/error about my own question. I understood a lot actually about how openCart upload images, how ajax and xhr works and so on. Anyway, the code I have used is this:

Inside file profile.tpl:

$('#upload-image').on('click',function(e){
    var formData = new FormData($('#submitProfile')[0]);
    formData.append('route','account/profile');
    $.ajax({
        url: 'index.php?route=tool/upload/logo',
        type: 'post',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function() {
          $("#containerAlertMessages").html("<div class='alert alert-info'><strong>Sending...</strong></div>");
                    $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        complete: function() {
            $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your logo has been uploaded successfully! Do not forget to save the abovr information by clicking the Save button at the bottom right corner!</div>");
            $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        success: function() {
            //nothing yet
        },
        error: function(xhr, ajaxOptions, thrownError) {
          alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    });

Inside file upload.php:

public function logo() {
        $this->load->language('tool/upload');

        if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
            $filename = html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8');

            $route = $this->request->post['route'];
            if($route == "account/profile") {
                $file = "image/" . $filename;
                move_uploaded_file($this->request->files['file']['tmp_name'], DIR_LOGOS . $file);
            }
        }
    }

DIR_LOGOS has been defined inside config.php file, so I could reffer to this variable again in another file if I want it to.

Furthermore, I am sending the route variable, in order to know from where the image upload is coming.
So, if the uploading is coming from 'account/profile' I am saving the image to '/image' folder
if its coming from 'accoun/register' I am saving to '/image/register' or whatever folder I want to (existing one or not), and so on

I hope that helps someone, with same issues!