问:
Best algorithm to generate even strong teams
I got a list of players with a skill from 0-100 and a list of teams which have all their own members list.

Now I want to put the players to the teams so that teams mostly got the same size (+-1 difference is ok) and the sums of the skills should be as close at possible.

My current solution is a simple voting algorithm (teams vote players in circle, an take the next best player):

```<code>public class Teamgenerator {
    public void calcTeams(){
        List<Team> teams = new ArrayList<>();
        teams.add(new Team("Team 1"));
        teams.add(new Team("Team 2"));

        List<Player> players = new ArrayList<>();
        players.add(new Player("Player 1",25));
        players.add(new Player("Player 2",50));
        players.add(new Player("Player 3",50));
        players.add(new Player("Player 4",75));

        int nextTeam = 0;
        while (players.size() > 0) {
            int bestPlayer = findBestPlayerIndex(players);
            teams.get(nextTeam).players.add(players.get(bestPlayer));
            players.remove(bestPlayer);

            if (nextTeam < teams.size() - 1) nextTeam++;
            else nextTeam = 0;
        }

        for(Team t:teams){
            System.out.println(t.getName()+":");
            for(Player p:t.players)
                System.out.println(p.getName()+", Skill "+p.getSkill());
        }
    }

    private int findBestPlayerIndex(List<Player> players) {
        //In my real programm i have to pick the skill of a more complex player object from a DB,
        //depending on a specific competition,  which causes i really need this index finding
        int index = -1;
        int highestSkill=-1;
        for (int i = 0; i < players.size(); i++) {
            if (players.get(i).getSkill() > highestSkill) {
                highestSkill = players.get(i).getSkill();
                index = i;
            }
        }
        return index;
    }
}

public class Team {
    private String name;
    public ArrayList<Player> players=new ArrayList<>();

    public Team(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Player {
    private String name;
    private int skill=50; //From 0-100

    public Player(String name, int skill) {
        this.name = name;
        this.skill = skill;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSkill() {
        return skill;
    }

    public void setSkill(int skill) {
        this.skill = skill;
    }
}
</code>```

The problem is that gives not the most even teams, console output is:

Team 1:
Player 4, Skill 75;
Player 3, Skill 50

Team 2:
Player 2, Skill 50;
Player 1, Skill 25

But it would be more fair if the teams are 4+1 and player 3+2.
You got any idea of a more fair algorithm? Thanks for help!

答:
As seen on YouTube - The Fairest Sharing Sequence Ever - Standup Maths the Thue-Morse Sequence is probably your best bet for minimising first turn advantage.

Wikipedia:

In mathematics, the Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is the binary sequence (an infinite sequence of 0s and 1s) obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained thus far. The first few steps of this procedure yield the strings 0 then 01, 0110, 01101001, 0110100110010110, and so on, which are prefixes of the Thue–Morse sequence. ...

Intro Computer Science - Princeton

```<code>//Copyright © 2000–2016, Robert Sedgewick and Kevin Wayne.
public class ThueMorse {
   public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        String thue   = "0";
        String morse  = "1";

        for (int i = 1; i <= n; i++) {
            String t = thue;             // save away values
            String m = morse;
            thue  += m;
            morse += t;
        }
        System.out.println(thue);
    }
}
</code>```

Porting from a Python answer, to get a SO copyright approved version:

```<code>public static int whoseTurn(int turnCount){
    return Integer.bitCount(turnCount) % 2;
}
</code>```

Using this turn order, with a sorted list based on skill level should give fairer teams, and meet your constraint of being within +-1 member.

Verified against the online encyclopedia of integer sequences (A010060) by generating the first 105 digits.

```<code>import java.util.stream.IntStream;

public class NodeStack {

public static int whoseTurn(int turnCount){
    return Integer.bitCount(turnCount) % 2;
}

public static void main(String[] args) {
    System.out.print("OEIS: ");
    IntStream.range(0,105).map(NodeStack::whoseTurn).forEach(i->System.out.print(i+", "));
    String result = IntStream.range(0,105).map(NodeStack::whoseTurn).collect(StringBuilder::new,(sb,i)->sb.append(i), StringBuilder::append).toString();
    System.out.println();
    IntStream.range(1,105).forEach(
            (i)-> System.out.println(i+"# "+result.substring(0,i)+ " : " +diff(result.substring(0,i)))
    );
}

public static int diff(String s){
    int zero = 0;
    int one = 0;
    for (char c:s.toCharArray()){
        if (c=='0')zero++;
        if (c=='1')one++;
    }
    return zero-one;
}

}
</code>```

Body:
I got a list of players with a skill from 0-100 and a list of teams which have all their own members list.

Now I want to put the players to the teams so that teams mostly got the same size (+-1 difference is ok) and the sums of the skills should be as close at possible.

My current solution is a simple voting algorithm (teams vote players in circle, an take the next best player):

public class Teamgenerator {
    public void calcTeams(){
        List<Team> teams = new ArrayList<>();
        teams.add(new Team("Team 1"));
        teams.add(new Team("Team 2"));

        List<Player> players = new ArrayList<>();
        players.add(new Player("Player 1",25));
        players.add(new Player("Player 2",50));
        players.add(new Player("Player 3",50));
        players.add(new Player("Player 4",75));

        int nextTeam = 0;
        while (players.size() > 0) {
            int bestPlayer = findBestPlayerIndex(players);
            teams.get(nextTeam).players.add(players.get(bestPlayer));
            players.remove(bestPlayer);

            if (nextTeam < teams.size() - 1) nextTeam++;
            else nextTeam = 0;
        }

        for(Team t:teams){
            System.out.println(t.getName()+":");
            for(Player p:t.players)
                System.out.println(p.getName()+", Skill "+p.getSkill());
        }
    }

    private int findBestPlayerIndex(List<Player> players) {
        //In my real programm i have to pick the skill of a more complex player object from a DB,
        //depending on a specific competition,  which causes i really need this index finding
        int index = -1;
        int highestSkill=-1;
        for (int i = 0; i < players.size(); i++) {
            if (players.get(i).getSkill() > highestSkill) {
                highestSkill = players.get(i).getSkill();
                index = i;
            }
        }
        return index;
    }
}

public class Team {
    private String name;
    public ArrayList<Player> players=new ArrayList<>();

    public Team(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Player {
    private String name;
    private int skill=50; //From 0-100

    public Player(String name, int skill) {
        this.name = name;
        this.skill = skill;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSkill() {
        return skill;
    }

    public void setSkill(int skill) {
        this.skill = skill;
    }
}

The problem is that gives not the most even teams, console output is:

Team 1:
Player 4, Skill 75;
Player 3, Skill 50

Team 2:
Player 2, Skill 50;
Player 1, Skill 25

But it would be more fair if the teams are 4+1 and player 3+2.
You got any idea of a more fair algorithm? Thanks for help!

Body:
As seen on YouTube - The Fairest Sharing Sequence Ever - Standup Maths the Thue-Morse Sequence is probably your best bet for minimising first turn advantage.

Wikipedia:

In mathematics, the Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is the binary sequence (an infinite sequence of 0s and 1s) obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained thus far. The first few steps of this procedure yield the strings 0 then 01, 0110, 01101001, 0110100110010110, and so on, which are prefixes of the Thue–Morse sequence. ...

Intro Computer Science - Princeton

//Copyright © 2000–2016, Robert Sedgewick and Kevin Wayne.
public class ThueMorse {
   public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        String thue   = "0";
        String morse  = "1";

        for (int i = 1; i <= n; i++) {
            String t = thue;             // save away values
            String m = morse;
            thue  += m;
            morse += t;
        }
        System.out.println(thue);
    }
}

Porting from a Python answer, to get a SO copyright approved version:

public static int whoseTurn(int turnCount){
    return Integer.bitCount(turnCount) % 2;
}

Using this turn order, with a sorted list based on skill level should give fairer teams, and meet your constraint of being within +-1 member.

Verified against the online encyclopedia of integer sequences (A010060) by generating the first 105 digits.

import java.util.stream.IntStream;

public class NodeStack {

public static int whoseTurn(int turnCount){
    return Integer.bitCount(turnCount) % 2;
}

public static void main(String[] args) {
    System.out.print("OEIS: ");
    IntStream.range(0,105).map(NodeStack::whoseTurn).forEach(i->System.out.print(i+", "));
    String result = IntStream.range(0,105).map(NodeStack::whoseTurn).collect(StringBuilder::new,(sb,i)->sb.append(i), StringBuilder::append).toString();
    System.out.println();
    IntStream.range(1,105).forEach(
            (i)-> System.out.println(i+"# "+result.substring(0,i)+ " : " +diff(result.substring(0,i)))
    );
}

public static int diff(String s){
    int zero = 0;
    int one = 0;
    for (char c:s.toCharArray()){
        if (c=='0')zero++;
        if (c=='1')one++;
    }
    return zero-one;
}

}


来源: stackexchange

问:
No connection string named 'MyEntities' could be found in the application config file
I am using entity framework and ASP.NET MVC 4 to build an application

My solution is split into two projects;

A class library that includes my data model (.edmx) file and a few custom interfaces

The 'container' MVC project that references the class library above

My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:

No connection string named 'MyEntities' could be found in the
  application config file.

I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.

Does anyone have any suggestions?

答: I have faced the same issue. I was missed to put connection string to startup project as I am performing data access operation from other layer. also if you don't have app.config in your startup project then add app.config file and then add a connection string to that config file.</p>

ContentLicense: CC BY-SA 3.0


问:
Selenium: Automate Vertical Scrolling in Java
I need to automate scrolling down using the scroll bar. This is what the scroll bar looks like.
This is the html code of the scroll bar:

```<code><div class="z-biglistbox-wscroll-vertical">
    <div class="z-biglistbox-wscroll-drag" style="top: 132.253px;">
        <div class="z-biglistbox-wscroll-home" title="Home"></div>
        <div class="z-biglistbox-wscroll-up" title="Previous"></div>
        <div class="z-biglistbox-wscroll-down" title="Next"></div>
        <div class="z-biglistbox-wscroll-end" title="End"></div>
    </div>
</div>
</code>```

I think of maybe clicking the "Next" button of the scroll bar but my code's not working. I did something like the following:

```<code>((JavascriptExecutor)driver).executeScript("arguments[0].click();", scroll_down);
</code>```

.

```<code>WebElement scroll_down = driver.findElement(By.cssSelector(".z-biglistbox-wscroll-down"));
scroll_down.click();
</code>```

Neither of the two worked. Can anyone give me an idea how to do it?

UPDATE:
This problem was already solved. Refer to alecxe's answer in this link for the solution that worked for me.

答:
You can use javascriptexecutor directly for scrolling. Below code might give you some idea.

Case 1: To scroll upto a certain element so that the expected element will be visible

```<code>JavascriptExecutor je = (JavascriptExecutor) driver;

//Identify the WebElement which will appear after scrolling down
WebElement element = driver.findElement(By.xpath(".//*[@id='mCSB_3_container']/p[3]"));

// now execute query which actually will scroll until that element is not appeared on page.
je.executeScript("arguments[0].scrollIntoView(true);",element);
</code>```

Case 2: To scroll upto a certain element

```<code>((JavascriptExecutor)driver).executeScript("scroll(0,400)");
</code>```

Hope this helps you. Thanks.

Body:
I need to automate scrolling down using the scroll bar. This is what the scroll bar looks like.
This is the html code of the scroll bar:

I think of maybe clicking the "Next" button of the scroll bar but my code's not working. I did something like the following:

((JavascriptExecutor)driver).executeScript("arguments[0].click();", scroll_down);

.

WebElement scroll_down = driver.findElement(By.cssSelector(".z-biglistbox-wscroll-down"));
scroll_down.click();

Neither of the two worked. Can anyone give me an idea how to do it?

UPDATE:
This problem was already solved. Refer to alecxe's answer in this link for the solution that worked for me.

Body:
You can use javascriptexecutor directly for scrolling. Below code might give you some idea.

Case 1: To scroll upto a certain element so that the expected element will be visible

JavascriptExecutor je = (JavascriptExecutor) driver;

//Identify the WebElement which will appear after scrolling down
WebElement element = driver.findElement(By.xpath(".//*[@id='mCSB_3_container']/p[3]"));

// now execute query which actually will scroll until that element is not appeared on page.
je.executeScript("arguments[0].scrollIntoView(true);",element);

Case 2: To scroll upto a certain element

((JavascriptExecutor)driver).executeScript("scroll(0,400)");

Hope this helps you. Thanks.


问:
Google Analytics non-interaction implementations (ni=1 vs nonInteraction:true)
I have a question regarding two seemingly different ways to implement sending an event in google analytics as a non-interaction hit type.

(1) Protocol docs:
 https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ni

In query param:

```<code>&ni=1

/collect?v=1&t=event&ni=1
</code>```

(2) Analytics dev guide:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events

```<code>ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {
  nonInteraction: true
});
</code>```

which I inferred allows me to do this:

```<code>ga('send', {
  hitType: 'event'
  eventCategory: 'myCategory',
  eventAction: 'myAction',
  eventLabel: 'myLabel',
  nonIteraction: true
});
</code>```

However, when I look at the network traffic in the chrome browser dev console I do not see the "ni=1" url parameter. Here is a list of the parameters that are present (values excluded):

v:
_v:
a:
t:
_s:
cd:
dl:
dp:
ul:
de:
dt:
sd:
sr:
vp:
je:
ec:
ea:
an:
av:
aid:
aiid:
_u:
jid:
gjid:
cid:
tid:
_gid:
z:

What is the difference betweeen these two implementations, and are the end results the same?

答:
The answer to my original question:
Yes - the end result of both implementations is the same. Both should include the "ni=1" url parameter.

If you do not see this in the dev console network traffic or in your server logs there is a mistake. In my case, my mistake is evident in my original post - notice the typo:

nonIteraction: true

should've been:

nonInteraction: true

Body:
I have a question regarding two seemingly different ways to implement sending an event in google analytics as a non-interaction hit type.

(1) Protocol docs:
 https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ni

In query param:

&ni=1

/collect?v=1&t=event&ni=1

(2) Analytics dev guide:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events

ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {
  nonInteraction: true
});

which I inferred allows me to do this:

ga('send', {
  hitType: 'event'
  eventCategory: 'myCategory',
  eventAction: 'myAction',
  eventLabel: 'myLabel',
  nonIteraction: true
});

However, when I look at the network traffic in the chrome browser dev console I do not see the "ni=1" url parameter. Here is a list of the parameters that are present (values excluded):

v:
_v:
a:
t:
_s:
cd:
dl:
dp:
ul:
de:
dt:
sd:
sr:
vp:
je:
ec:
ea:
an:
av:
aid:
aiid:
_u:
jid:
gjid:
cid:
tid:
_gid:
z:

What is the difference betweeen these two implementations, and are the end results the same?


问:
Rstudio server not running on Google Cloud Compute Engine
Why does "rstudio-server start" not work??

At this point, I could not find any helpful answer even on stackoverflow.
I cross-checked that the below steps 1-5 are sufficient for installing Rstudio Server on Ubuntu from the following blog-posts:
https://www.r-bloggers.com/installing-rstudio-server-on-ubuntu-server/
http://www.joeroe.eu/blog/2015/08/rstudio-server-on-a-google-compute-engine-instance/
https://gist.github.com/rweald/4321052

Here's what I did:

1. Create Google Cloud VM

Google Cloud Compute Engine > Create VM Instance (on Ubuntu 16.04 LTS)

2. Installing R

```<code>sudo nano /etc/sources.list
</code>```

enter:

```<code>deb http://cran.rstudio.com/bin/linux/ubuntu xenial/
</code>```

get public key for ubuntu:

```<code>sudo apt-key adv —keyserver keys.gnupg.net —recv-key 381BA480
sudo apt-get update
sudo apt-get install r-base libapparmor1
sudo apt-get install r-base
</code>```

3. Installing Rstudio Server

```<code>sudo apt-get install gdebi-core
wget https://download2.rstudio.org/rstudio-server-1.0.143-amd64.deb
sudo gdebi rstudio-server-1.0.143-amd64.deb
</code>```

4. Open port 8787 in Google Cloud firewall

```<code>gcloud compute firewall-rules create allow-rstudio --allow tcp:8787
</code>```

Remark: I did verify that the port 8787 is open:
gcloud compute firewall-rules list
NAME                    NETWORK  SRC_RANGES    RULES                         SRC_TAGS  TARGET_TAGS
allow-rstudio           default  0.0.0.0/0     tcp:8787                                allow-rstudio

5. Verify Rstudio Server

No response: http://:8787 >> browser is hanging

No response: sudo rstudio-server verify-installation >> command executes, no message

No response: sudo rstudio-server restart >> no running process to restart ("rsession: no process found")

No response: sudo rstudio-server start >> command executes, no message

Thanks for any thoughtful help why RStudio Server is not running.

答:
You created a firewall rule, but you didn't apply it to any VM, so the port is still not open on that VM, and thus, you cannot reach your server.

When you create a firewall rule, add a tag to it as per the docs:

```<code>gcloud compute firewall-rules create allow-rstudio-server \
    --allow tcp:8787 \
    --target-tags rstudio-server
</code>```

Then, add the rstudio-server tag to the VM(s):

```<code>gcloud compute instances add-tags [INSTANCE_NAME] --tags rstudio-server
</code>```

Then try accessing the UI on your server again.

That said, you should really consider using an encrypted SSH tunnel to connect to your GCE VM securely instead, to avoid eavesdropping on your data while it is in transit from your computer to your GCE VM and back, or risk MITM attack which can intercept your password and take over your server, since you're using plain-text HTTP to access your server.

Body:
Why does "rstudio-server start" not work??

At this point, I could not find any helpful answer even on stackoverflow.
I cross-checked that the below steps 1-5 are sufficient for installing Rstudio Server on Ubuntu from the following blog-posts:
https://www.r-bloggers.com/installing-rstudio-server-on-ubuntu-server/
http://www.joeroe.eu/blog/2015/08/rstudio-server-on-a-google-compute-engine-instance/
https://gist.github.com/rweald/4321052

Here's what I did:

1. Create Google Cloud VM

Google Cloud Compute Engine > Create VM Instance (on Ubuntu 16.04 LTS)

2. Installing R

sudo nano /etc/sources.list

enter:

deb http://cran.rstudio.com/bin/linux/ubuntu xenial/

get public key for ubuntu:

sudo apt-key adv —keyserver keys.gnupg.net —recv-key 381BA480
sudo apt-get update
sudo apt-get install r-base libapparmor1
sudo apt-get install r-base

3. Installing Rstudio Server

sudo apt-get install gdebi-core
wget https://download2.rstudio.org/rstudio-server-1.0.143-amd64.deb
sudo gdebi rstudio-server-1.0.143-amd64.deb

4. Open port 8787 in Google Cloud firewall

gcloud compute firewall-rules create allow-rstudio --allow tcp:8787

Remark: I did verify that the port 8787 is open:
gcloud compute firewall-rules list
NAME                    NETWORK  SRC_RANGES    RULES                         SRC_TAGS  TARGET_TAGS
allow-rstudio           default  0.0.0.0/0     tcp:8787                                allow-rstudio

5. Verify Rstudio Server

No response: http://:8787 >> browser is hanging

No response: sudo rstudio-server verify-installation >> command executes, no message

No response: sudo rstudio-server restart >> no running process to restart ("rsession: no process found")

No response: sudo rstudio-server start >> command executes, no message

Thanks for any thoughtful help why RStudio Server is not running.

Body:
You created a firewall rule, but you didn't apply it to any VM, so the port is still not open on that VM, and thus, you cannot reach your server.

When you create a firewall rule, add a tag to it as per the docs:

gcloud compute firewall-rules create allow-rstudio-server \
    --allow tcp:8787 \
    --target-tags rstudio-server

Then, add the rstudio-server tag to the VM(s):

gcloud compute instances add-tags [INSTANCE_NAME] --tags rstudio-server

Then try accessing the UI on your server again.

That said, you should really consider using an encrypted SSH tunnel to connect to your GCE VM securely instead, to avoid eavesdropping on your data while it is in transit from your computer to your GCE VM and back, or risk MITM attack which can intercept your password and take over your server, since you're using plain-text HTTP to access your server.

ContentLicense: CC BY-SA 4.0


问:
how do i change an image if i click on a button in Swift?
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button. </p>

```<code>let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}
</code>```

答:
```<code>button.setImage(UIImage(named: circleArray[0]),forState:Normal)
</code>```

You can set various images for various state of the button(e.g Normal,highlighted,selected)

Is this something you are looking for? Please elaborate more if you are looking for something else.

Body:
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button.

let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}

Body:
button.setImage(UIImage(named: circleArray[0]),forState:Normal)

You can set various images for various state of the button(e.g Normal,highlighted,selected)

Is this something you are looking for? Please elaborate more if you are looking for something else.


问:
Regex question about parsing method signature
I'm trying to parse a method signature that is in this format:

```<code>'function_name(foo=<str>, bar=<array>)'
</code>```

From this, I want the name of the method, and each argument and it's type. Obviously I don't want the <, > characters, etc. The number of parameters will be variable.

My question is: How is it possible to get all the parameters when using this regex? I'm using Python, but I'm just looking for a general idea. Do I need named groups and, if so, how can I use them to capture multiple parameters, each with it's type, all in one regex?

答:
You can't match a variable number of groups with Python regular expressions (see this). Instead you can use a combination of regex and split().

```<code>>>> name, args = re.match(r'(\w+)\((.*)\)', 'function_name(foo=<str>, bar=<array>, baz=<int>)').groups()
>>> args = [re.match(r'(\w+)=<(\w+)>', arg).groups() for arg in args.split(', ')]
>>> name, args
('function_name', [('foo', 'str'), ('bar', 'array'), ('baz', 'int')])
</code>```

This will match a variable number (including 0) arguments. I have chosen not to allow additional whitespace, although you should allow for it by adding \s+ between identifiers if your format isn't very strict.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to parse a method signature that is in this format:

'function_name(foo=<str>, bar=<array>)'

From this, I want the name of the method, and each argument and it's type. Obviously I don't want the <, > characters, etc. The number of parameters will be variable.

My question is: How is it possible to get all the parameters when using this regex? I'm using Python, but I'm just looking for a general idea. Do I need named groups and, if so, how can I use them to capture multiple parameters, each with it's type, all in one regex?

Body:
You can't match a variable number of groups with Python regular expressions (see this). Instead you can use a combination of regex and split().

>>> name, args = re.match(r'(\w+)\((.*)\)', 'function_name(foo=<str>, bar=<array>, baz=<int>)').groups()
>>> args = [re.match(r'(\w+)=<(\w+)>', arg).groups() for arg in args.split(', ')]
>>> name, args
('function_name', [('foo', 'str'), ('bar', 'array'), ('baz', 'int')])

This will match a variable number (including 0) arguments. I have chosen not to allow additional whitespace, although you should allow for it by adding \s+ between identifiers if your format isn't very strict.


问:
Try Open a PDF , i get the Error "Cannot find image data or EI" with lib ItextSharp 7
I am trying to extract the text from the pdf (attachment link) with the code (lib itext7) below:

```<code>       public static PageDescribe GetTextFromPage(PdfDocument fullDoc, int pageNum)
    {
        if (pageNum < 1)
            return null;
        else
        {
            PdfPage page = fullDoc.GetPage(pageNum);
            if (page == null)
                return null;
            else
            {

                LocatedTextStrategy lStrat = new LocatedTextStrategy();
                string s = PdfTextExtractor.GetTextFromPage(page, lStrat,);

                DateTime _startPoint = DateTime.Now;
                lStrat.Points.Defragmentation();

                PageDescribe _res = new PageDescribe(pageNum, lStrat.Points);
                return _res;
            }
        }
    }
}
</code>```

but i get the error Cannot find image data or EI :

See Image Error

If I Manually remove the initial logo of the pdf this error does not occur. But I can not change the source system that provides this files.

Sample of pdf here

Anyone have any suggestions?

答:
I downloaded your PDF file, and tried with the following code, it works for me (I tried for page 1):

```<code>public string GetTextFromPage(string path, int pagenum)
{
    PdfReader reader = new PdfReader(path);
    string text = PdfTextExtractor.GetTextFromPage(reader, pagenum, new LocationTextExtractionStrategy());
    reader.Close();
    return text;
}
</code>```

You can modify the method above to return your PageDescribe class.

Body:
I am trying to extract the text from the pdf (attachment link) with the code (lib itext7) below:

       public static PageDescribe GetTextFromPage(PdfDocument fullDoc, int pageNum)
    {
        if (pageNum < 1)
            return null;
        else
        {
            PdfPage page = fullDoc.GetPage(pageNum);
            if (page == null)
                return null;
            else
            {

                LocatedTextStrategy lStrat = new LocatedTextStrategy();
                string s = PdfTextExtractor.GetTextFromPage(page, lStrat,);

                DateTime _startPoint = DateTime.Now;
                lStrat.Points.Defragmentation();

                PageDescribe _res = new PageDescribe(pageNum, lStrat.Points);
                return _res;
            }
        }
    }
}

but i get the error Cannot find image data or EI :

See Image Error

If I Manually remove the initial logo of the pdf this error does not occur. But I can not change the source system that provides this files.

Sample of pdf here

Anyone have any suggestions?

Body:
I downloaded your PDF file, and tried with the following code, it works for me (I tried for page 1):

public string GetTextFromPage(string path, int pagenum)
{
    PdfReader reader = new PdfReader(path);
    string text = PdfTextExtractor.GetTextFromPage(reader, pagenum, new LocationTextExtractionStrategy());
    reader.Close();
    return text;
}

You can modify the method above to return your PageDescribe class.


问:
Http DELETE endpoint losing body data when called on Openshift
I added a v1/health_check endpoint to my service running on Openshift.  The endpoint accepts all http verbs and returns what was in the request.

For example, running:
curl -X DELETE -G 'http://localhost:8080/v1/health_check' -F "user_id=1" -F "build_category_id=14" -F "notification_type=slack"
against the service when it is running locally returns:

```<code>{
  "endpoint": "/v1/health_check",
  "form_data": {
    "build_category_id": "14",
    "notification_type": "slack",
    "user_id": "1"
  },
  "http_method": "DELETE",
  "request_data": {}
}
</code>```

When I use the same curl request against the service when it is running on Openshift, I get:

```<code>{
  "endpoint": "/v1/health_check",
  "form_data": {},
  "http_method": "DELETE",
  "request_data": {}
}
</code>```

Does anyone have any ideas why the body of the DELETE methods are getting lost in Openshift?

Other notes:

It's a flask service using gevent.wsgi WSGIServer

I also acknowledge after some research that this isn't the most RESTful approach, especially after reading Is an entity body allowed for an HTTP DELETE request?

When I rsh onto the Openshift pod and curl the service, the endpoint works as expected, meaning the entity body goes through.

答:
Don't use both -X DELETE and  -G options. The -G options says to use HTTP GET. The -X DELETE says to use DELETE for the HTTP method.

My tests from MacOS X suggests that using both confuses curl, causing it to not actually send the request content.

```<code>$ curl -v --request DELETE -G --data xxx http://.../
*   Trying 52.87.56.37...
* Connected to ... (52.87.56.37) port 80 (#0)
> DELETE /?xxx HTTP/1.1
> Host: ...
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
...
</code>```

Body:
I added a v1/health_check endpoint to my service running on Openshift.  The endpoint accepts all http verbs and returns what was in the request.

For example, running:
curl -X DELETE -G 'http://localhost:8080/v1/health_check' -F "user_id=1" -F "build_category_id=14" -F "notification_type=slack"
against the service when it is running locally returns:

{
  "endpoint": "/v1/health_check",
  "form_data": {
    "build_category_id": "14",
    "notification_type": "slack",
    "user_id": "1"
  },
  "http_method": "DELETE",
  "request_data": {}
}

When I use the same curl request against the service when it is running on Openshift, I get:

{
  "endpoint": "/v1/health_check",
  "form_data": {},
  "http_method": "DELETE",
  "request_data": {}
}

Does anyone have any ideas why the body of the DELETE methods are getting lost in Openshift?

Other notes:

It's a flask service using gevent.wsgi WSGIServer

I also acknowledge after some research that this isn't the most RESTful approach, especially after reading Is an entity body allowed for an HTTP DELETE request?

When I rsh onto the Openshift pod and curl the service, the endpoint works as expected, meaning the entity body goes through.

Body:
Don't use both -X DELETE and  -G options. The -G options says to use HTTP GET. The -X DELETE says to use DELETE for the HTTP method.

My tests from MacOS X suggests that using both confuses curl, causing it to not actually send the request content.

$ curl -v --request DELETE -G --data xxx http://.../
*   Trying 52.87.56.37...
* Connected to ... (52.87.56.37) port 80 (#0)
> DELETE /?xxx HTTP/1.1
> Host: ...
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
...


问:
How to convert Json type with array to .net object?
I have JSON string:
// the coverage value is an array.

```<code>  string jsonData = @"{
""plans"":
[
{
""plan_code"":""UL500"",
    ""plan_name"":""Unlimited 500M"",
    ""days"":1,
    ""limit"":500,
    ""coverage"":
[
{
""country"":""SE"",
},
{
""country"":""BZ""
}
]
},
{
""plan_code"":""UL1GB"",
    ""plan_name"":""Unlimited 1GB"",
    ""days"":1,
    ""limit"":1024,
    ""coverage"":
[
{
""country"":""SG"",
},
{
""country"":""JP""
}
]
}
]
}
";
</code>```

and i'm parse by JsonConvert.DeserializeObject as sample code below:

```<code> try
    {
        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("", content);
        var result = await response.Content.ReadAsStringAsync();
        var tempRecords = JsonConvert.DeserializeObject<List<plan>>(result);
    }
</code>```

and then i'm get an error message:
    "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[DAL.plan]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'plans', line 1, position 9."

please show me a right way for this issue.

答:
Hello，I have just looked at your question, I found that you provided the json string, not the standard format json string. Here I am giving me a good json string, you can try it out。</p>

```<code>{
    "plans": [`enter code here`
        {
            "plan_code": "UL500",
            "plan_name": "Unlimited500M",
            "days": 1,
            "limit": 500,
            "coverage": [
                {
                    "country": "SE"
                },
                {
                    "country": "BZ"
                }
            ]
        },
        {
            "plan_code": "UL1GB",
            "plan_name": "Unlimited1GB",
            "days": 1,
            "limit": 1024,
            "coverage": [
                {
                    "country": "SG"
                },
                {
                    "country": "JP"
                }
            ]
        }
    ]
}
</code>```

Body:
I have JSON string:
// the coverage value is an array.

  string jsonData = @"{
""plans"":
[
{
""plan_code"":""UL500"",
    ""plan_name"":""Unlimited 500M"",
    ""days"":1,
    ""limit"":500,
    ""coverage"":
[
{
""country"":""SE"",
},
{
""country"":""BZ""
}
]
},
{
""plan_code"":""UL1GB"",
    ""plan_name"":""Unlimited 1GB"",
    ""days"":1,
    ""limit"":1024,
    ""coverage"":
[
{
""country"":""SG"",
},
{
""country"":""JP""
}
]
}
]
}
";

and i'm parse by JsonConvert.DeserializeObject as sample code below:

 try
    {
        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("", content);
        var result = await response.Content.ReadAsStringAsync();
        var tempRecords = JsonConvert.DeserializeObject<List<plan>>(result);
    }

and then i'm get an error message:
    "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[DAL.plan]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'plans', line 1, position 9."

please show me a right way for this issue.

Body:
Hello，I have just looked at your question, I found that you provided the json string, not the standard format json string. Here I am giving me a good json string, you can try it out。

{
    "plans": [`enter code here`
        {
            "plan_code": "UL500",
            "plan_name": "Unlimited500M",
            "days": 1,
            "limit": 500,
            "coverage": [
                {
                    "country": "SE"
                },
                {
                    "country": "BZ"
                }
            ]
        },
        {
            "plan_code": "UL1GB",
            "plan_name": "Unlimited1GB",
            "days": 1,
            "limit": 1024,
            "coverage": [
                {
                    "country": "SG"
                },
                {
                    "country": "JP"
                }
            ]
        }
    ]
}


问:
Google As Service Provider, Identify by SAML IdP. SSO
I want my portal that allows me to use service like Google Apps and Office 365.

In this case, Google and Microsoft are service provider. My portal will be IdP as I am doing the authentication. Is this correct?

I wonder how can I build my own IdP. Because if I want to achieve Single Sign On, the user can login my portal with username and pw stored in my database.

However, the password of users from my portal and Google can be totally different.

For example, user in my database = id:Peter, pw:peter123, email:abc@google.com

user in Google's Database = email: abc@gmail.com, pw: peter456

How can I map those accounts to achieve Single Sign On, allowing user to login only ONCE on my portal.

And then he can access Google Service by just clicking the buttons linking to Gmail, Google Drive...etc without logging in Google accounts?

I would appreciate if anyone could tell me more about SAML IdP and solutions.

I am building it in PHP.

答:
I moved a little bit forward,

I think some of my thoughts are wrong.
My portal won't be the IdP.

But I will have to build a IdP server myself for communicating with my portal and Google and Microsoft

The following link will guide you throughout the basic setup of Shibboleth IdP server.
https://wiki.shibboleth.net/confluence/display/IDP30/Installation

I will update if I can configure successfully. Cheers.


问:
How to prevent unauthorized spidering
I want to prevent automated html scraping from one of our sites while not affecting legitimate spidering (googlebot, etc.). Is there something that already exists to accomplish this? Am I even using the correct terminology?

EDIT: I'm mainly looking to prevent people that would be doing this maliciously. I.e. they aren't going to abide by robots.txt

EDIT2: What about preventing use by "rate of use" ... i.e. captcha to continue browsing if automation is detected and the traffic isn't from a legitimate (google, yahoo, msn, etc.) IP.

答:
You should do what good firewalls do when they detect malicious use - let them keep going but don't give them anything else. If you start throwing 403 or 404 they'll know something is wrong. If you return random data they'll go about their business.

For detecting malicious use though, try adding a trap link on search results page (or the page they are using as your site map) and hide it with CSS. Need to check if they are claiming to be a valid bot and let them through though. You can store their IP for future use and a quick ARIN WHOIS search.

OwnerDisplayName: Kyle West

Title: How to prevent unauthorized spidering

LastEditorDisplayName: Kyle West

OwnerDisplayName: David Thomas Garcia


问:
AJAX, response headers are not sent by PHP script!
I'm banging my head for some hours now. I have a select option that it updates a database using AJAX (at least it's trying to!). What happens is while running the PHP script directly with params required the database gets updated but not when running indirectly through AJAX, instead I get 3 times the alert("There was a problem in the returned data:\n"); and then it gets updated. JavaScript is on  and not in an external file. Here it goes:

JavaScript:

```<code>function updateHub(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
       if (xmlhttp.readyState==4 && xmlhttp.status==200){
           document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
       }else{
           alert("There was a problem in the returned data:\n");
       }
    }
    var prefHub = document.getElementById("prefHub");
    var hubID = prefHub.options[prefHub.selectedIndex].value;
    xmlhttp.open("GET","updateHub.php?hubID="+hubID,true);
    xmlhttp.send();
}
</code>```

updateHub.php:

```<code>session_start();
include '../../../common/config.php';
$hubID = '';
if(isset($_POST['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_POST['hubID'])));
}elseif(isset($_GET['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_GET['hubID'])));
}
mysql_query("UPDATE prefs set hubID='$hubID' where userID = '".$_SESSION['userID']."'") or die(mysql_error());
if(mysql_affected_rows()){
    echo "Updated";
}else{
    echo 'Error';
}
return $hubID;
</code>```

and the HTML:

```<code><form action="" method="post" onsubmit="updateHub();">
    <select name="prefHub" id="prefHub">
        <option value="43">opt1</option>
        <option value="64">opt2</option>
        <option value="30">opt2</option>
     </select>
     <input type="submit" name="update" value="Update Hub"/>
</form>
<div id="hubinfo"></div>
</code>```

答:
instead I get 3 times the alert("There
  was a problem in the returned
  data:\n");

```<code>if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
}
else{
alert("There was a problem in the returned data:\n");
}
</code>```

This means that you will always see the alert. Since for any other xmlhttp.readyState values the else {} block will be executed.

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)

```<code>The object has been constructed.
</code>```

OPENED (numeric value 1)

```<code>The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
</code>```

HEADERS_RECEIVED (numeric value 2)

```<code>All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
</code>```

LOADING (numeric value 3)

```<code>The response entity body is being received.
</code>```

DONE (numeric value 4)

Body:
I'm banging my head for some hours now. I have a select option that it updates a database using AJAX (at least it's trying to!). What happens is while running the PHP script directly with params required the database gets updated but not when running indirectly through AJAX, instead I get 3 times the alert("There was a problem in the returned data:\n"); and then it gets updated. JavaScript is on  and not in an external file. Here it goes:

JavaScript:

function updateHub(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
       if (xmlhttp.readyState==4 && xmlhttp.status==200){
           document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
       }else{
           alert("There was a problem in the returned data:\n");
       }
    }
    var prefHub = document.getElementById("prefHub");
    var hubID = prefHub.options[prefHub.selectedIndex].value;
    xmlhttp.open("GET","updateHub.php?hubID="+hubID,true);
    xmlhttp.send();
}

updateHub.php:

session_start();
include '../../../common/config.php';
$hubID = '';
if(isset($_POST['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_POST['hubID'])));
}elseif(isset($_GET['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_GET['hubID'])));
}
mysql_query("UPDATE prefs set hubID='$hubID' where userID = '".$_SESSION['userID']."'") or die(mysql_error());
if(mysql_affected_rows()){
    echo "Updated";
}else{
    echo 'Error';
}
return $hubID;

and the HTML:

<form action="" method="post" onsubmit="updateHub();">
    <select name="prefHub" id="prefHub">
        <option value="43">opt1</option>
        <option value="64">opt2</option>
        <option value="30">opt2</option>
     </select>
     <input type="submit" name="update" value="Update Hub"/>
</form>

Body:
instead I get 3 times the alert("There
  was a problem in the returned
  data:\n");

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
}
else{
alert("There was a problem in the returned data:\n");
}

This means that you will always see the alert. Since for any other xmlhttp.readyState values the else {} block will be executed.

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)


问:
Firebase INNER JOIN and GROUP BY month query
I am having some difficulties in designing the database structure in Firebase. I am new to it so I am not so familiar with it yet.

The transaction table will record the date together with the overall amount from all sub categories. As for each sub-categories table, it will only record the relevant data according to its type.

What I tried to do is, is there anyway to count the total amount of certain sub-category for each user group by month? In MySQL, I can simply INNER JOIN, WHERE clause and GROUP BY date, but I not sure with this design structure, is it possible to do so? Or I should modify the structure?

The output should be like for instance I am choosing food transaction:

```<code>Month: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
Amount : 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0
</code>```

答:
Trying to model a SQL table structure in a NoSQL database like Firebase is a recipe for pain. Stop thinking about SQL concepts like inner joins and group by clauses.

Instead embrace the nature of the platform you are using. For example: do you need to usually show the list of transactions for an account? If so, why not model that in your JSON tree:

```<code>accountTransactions
  accountId1
    transaction1: {
      type: "entertainment"
      ...
    }
    transaction2: {
      type: "food"
      ...
    }
  accountId2
    transaction3: {
      type: "food"
      ...
    }
    transaction4: {
      type: "food"
      ...
    }
</code>```

Now if you want the list of transactions for account 1, instead of needing a query, you can directly them from /accountTransactions/accountId1.

If you also want other lists of transactions, you may need to duplicate some of the data in your tree. For example, if you want to show a list of all food transactions, you could add this to the database:

```<code>transactionPathsByType
  food
    transaction2: "/accountTransactions/accountId1/transaction2"
    transaction3: "/accountTransactions/accountId2/transaction3"
    transaction4: "/accountTransactions/accountId2/transaction4"
</code>```

There are many ways to model this last relationship. For example, you could also keep the list of transactions as a single flat list:

```<code>accountTransactions
    transaction1: {
      account: "accountId1"
      type: "entertainment"
      ...
    }
    transaction2: {
      account: "accountId2"
      type: "food"
      ...
    }
    transaction3: {
      account: "accountId2"
      type: "food"
      ...
    }
    transaction4: {
      account: "accountId2"
      type: "food"
      ...
    }
</code>```

Which would simplify the mapping from transaction type to transactions to:

```<code>transactionIdsByType
  food
    transaction2: true
    transaction3: true
    transaction4: true
</code>```

We're just using true as a dummy value here, since all the information needed to look up each transaction is already present in the key.

If you with the straight list of transactions also want a quick way to look up the transaction IDs for an account, you could add an index that maps the account ID to the corresponding transaction IDs:

```<code>transactionIDsByAccount
  accountId1
    transaction1: true
    transaction2: true
  accountId2
    transaction3: true
    transaction4: true
</code>```

There are as many possible models as there are app ideas out there. More probably. For a good introduction article, I recommend reading NoSQL data modeling. Definitely also watch Firebase for SQL developers on youtube.

Body:
I am having some difficulties in designing the database structure in Firebase. I am new to it so I am not so familiar with it yet.

The transaction table will record the date together with the overall amount from all sub categories. As for each sub-categories table, it will only record the relevant data according to its type.

What I tried to do is, is there anyway to count the total amount of certain sub-category for each user group by month? In MySQL, I can simply INNER JOIN, WHERE clause and GROUP BY date, but I not sure with this design structure, is it possible to do so? Or I should modify the structure?

The output should be like for instance I am choosing food transaction:

Month: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
Amount : 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0

Body:
Trying to model a SQL table structure in a NoSQL database like Firebase is a recipe for pain. Stop thinking about SQL concepts like inner joins and group by clauses.

Instead embrace the nature of the platform you are using. For example: do you need to usually show the list of transactions for an account? If so, why not model that in your JSON tree:

accountTransactions
  accountId1
    transaction1: {
      type: "entertainment"
      ...
    }
    transaction2: {
      type: "food"
      ...
    }
  accountId2
    transaction3: {
      type: "food"
      ...
    }
    transaction4: {
      type: "food"
      ...
    }

Now if you want the list of transactions for account 1, instead of needing a query, you can directly them from /accountTransactions/accountId1.

If you also want other lists of transactions, you may need to duplicate some of the data in your tree. For example, if you want to show a list of all food transactions, you could add this to the database:

transactionPathsByType
  food
    transaction2: "/accountTransactions/accountId1/transaction2"
    transaction3: "/accountTransactions/accountId2/transaction3"
    transaction4: "/accountTransactions/accountId2/transaction4"

There are many ways to model this last relationship. For example, you could also keep the list of transactions as a single flat list:

accountTransactions
    transaction1: {
      account: "accountId1"
      type: "entertainment"
      ...
    }
    transaction2: {
      account: "accountId2"
      type: "food"
      ...
    }
    transaction3: {
      account: "accountId2"
      type: "food"
      ...
    }
    transaction4: {
      account: "accountId2"
      type: "food"
      ...
    }

Which would simplify the mapping from transaction type to transactions to:

transactionIdsByType
  food
    transaction2: true
    transaction3: true
    transaction4: true

We're just using true as a dummy value here, since all the information needed to look up each transaction is already present in the key.

If you with the straight list of transactions also want a quick way to look up the transaction IDs for an account, you could add an index that maps the account ID to the corresponding transaction IDs:

transactionIDsByAccount
  accountId1
    transaction1: true
    transaction2: true
  accountId2
    transaction3: true
    transaction4: true

There are as many possible models as there are app ideas out there. More probably. For a good introduction article, I recommend reading NoSQL data modeling. Definitely also watch Firebase for SQL developers on youtube.


问:
is this regular grammar- S -> 0S0/00?
Let L denotes the language generated by the grammar S -> 0S0/00. Which of the following is true?
(A) L = 0+
(B) L is regular but not 0+
(C) L is context free but not regular
(D) L is not context free

HI can anyone explain me how the language represented by the grammar S -> 0S0/00 is regular? I know very well the grammar is context free but not sure how can that be regular?

答:
We don't need the machinery of regular grammars to answer your question. Just note the possible derivations all look like this:

```<code>S -> (0 S 0) -> 0 (0 S 0) 0 -> 0 0 (0 S 0) 0 0 -> ... -> 0...0 (0 0) 0...0
                                                         \_ _/       \_ _/
                                                           k           k
</code>```

Here I've added parens ( ) to show the result of the previous expansion of S. These aren't part of the derived string. I.e. we substitute S with 0 S 0 k >= 0 times followed by a single substitution with 00.

From this is should be easy to see L is the set of strings of 0's of length 2k + 2 for some integer k >= 0. A shorthand notation for this is

L = { 02m | m >= 1 }

In words: The set of all even length strings of zeros excluding the empty string.

To prove L is regular, all we need is a regular expression for L.  This is easy: (00)+.  Or if you prefer, 00(00)*.

You might be confused because a small change to the grammar makes its language context free but not regular:

S -> 0S1/01

This is the more complex language { 0m 1m | m >= 1 }. It's straightforward to show this isn't a regular language using the Pumping Lemma.

Title: is this regular grammar- S -> 0S0/00?

Body:
We don't need the machinery of regular grammars to answer your question. Just note the possible derivations all look like this:

S -> (0 S 0) -> 0 (0 S 0) 0 -> 0 0 (0 S 0) 0 0 -> ... -> 0...0 (0 0) 0...0
                                                         \_ _/       \_ _/
                                                           k           k

Here I've added parens ( ) to show the result of the previous expansion of S. These aren't part of the derived string. I.e. we substitute S with 0 S 0 k >= 0 times followed by a single substitution with 00.

From this is should be easy to see L is the set of strings of 0's of length 2k + 2 for some integer k >= 0. A shorthand notation for this is

L = { 02m | m >= 1 }

In words: The set of all even length strings of zeros excluding the empty string.

To prove L is regular, all we need is a regular expression for L.  This is easy: (00)+.  Or if you prefer, 00(00)*.

You might be confused because a small change to the grammar makes its language context free but not regular:

S -> 0S1/01

This is the more complex language { 0m 1m | m >= 1 }. It's straightforward to show this isn't a regular language using the Pumping Lemma.


问:
got an error when uploading 14000 rows of csv file
i have an csv file that has 14000 rows,
im trying to import it on phpmyadmin, I've edited the ff:

```<code>post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

In my.ini (MySQL File)

Under mysqld add: max_allowed_packet = 500M
</code>```

but still when i import it i got an error:
:

what should i do?

答: You need to increase the size of max_allowed_packet to some larger value.</p>

Body:
i have an csv file that has 14000 rows,
im trying to import it on phpmyadmin, I've edited the ff:

post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

In my.ini (MySQL File)

Under mysqld add: max_allowed_packet = 500M

but still when i import it i got an error:
:

what should i do?


问:
Initialize variables inside a switch statement
```<code>#include <stdio.h>
int main(void) {
    int a = 1;
    switch(a) {
        int i = 2;
        case 1: printf("%d",i);
                break;
        default: printf("Hello\n");
    }
}
</code>```

The following code sample is giving 36 as the output. How is this possible? I understand that the compiler will transfer the control to case 1 directly, without evaluating i. But, why am I getting the output as 36?

PS: I am using GCC.

答:
In C++ this code is ill-formed because you cannot jump into the scope of a variable.

In C the code is undefined behaviour: int i; inside the switch block exists, however by jumping to case 1: you bypassed the part where the value 2 would have been assigned to i.  So in fact you are attempting to print an uninitialized variable.

Body:
#include <stdio.h>
int main(void) {
    int a = 1;
    switch(a) {
        int i = 2;
        case 1: printf("%d",i);
                break;
        default: printf("Hello\n");
    }
}

The following code sample is giving 36 as the output. How is this possible? I understand that the compiler will transfer the control to case 1 directly, without evaluating i. But, why am I getting the output as 36?

PS: I am using GCC.


答: The entity corresponding to the JSON format does not match. Your format is an object, and the object has an array of attributes, not List</p>

Title: How to convert Json type with array to .net object?


问:
Back button issue in login module
Let say I have 2 forms in my app. let say loginForm and mainForm. In loginForm allows the user to enter his/her username and password then goes to mainForm. From mainForm is I click the back button it will go back to loginForm and now my issue is from loginForm if I will click back button it goes again to mainForm without logging in.

What is the best to make this correct?

loginForm

```<code>EditText edtU = (EditText) findViewById (R.id.txtU);
EditText edtP = (EditText) findViewById (R.id.txtP);
Button btnLogin = (Button) findViewById (R.id.btLog);
btnLogin.setOnclickListener(new OnclickListener).......{
    if(u.matches("ryan") && p.matches("biugos"){
      Intent i = new Intent(getApplicationContext(),mainForm.class);
      startActivity(i);
    }
}
</code>```

答:
First, without correct info, you should not let mainForm start;
Second, you should finish self after start other activity if you don't want user to use it again.</p>

Title: Back button issue in login module

Body:
Let say I have 2 forms in my app. let say loginForm and mainForm. In loginForm allows the user to enter his/her username and password then goes to mainForm. From mainForm is I click the back button it will go back to loginForm and now my issue is from loginForm if I will click back button it goes again to mainForm without logging in.

What is the best to make this correct?

loginForm

EditText edtU = (EditText) findViewById (R.id.txtU);
EditText edtP = (EditText) findViewById (R.id.txtP);
Button btnLogin = (Button) findViewById (R.id.btLog);
btnLogin.setOnclickListener(new OnclickListener).......{
    if(u.matches("ryan") && p.matches("biugos"){
      Intent i = new Intent(getApplicationContext(),mainForm.class);
      startActivity(i);
    }
}


问:
cameraKit-android output video
Does anyone use the CameraKit-Android by gogopop? My problem is that I set the listener of video but the outputfile is null. Anyone know how to solve it?

this is my code:

```<code>        cameraView.getCamera().setVideoQuality(CameraKit.Constants.VIDEO_QUALITY_720P);
        cameraView.getCamera().startRecordingVideo();
        cameraView.getCamera().setCameraListener(new CameraListener() {
            @Override
            public void onVideoTaken(final File video) {
                super.onVideoTaken(video);
            /*    new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final byte[] videoBytes = FileUtils.File2byte(video.getAbsolutePath());
                        if (!isExit) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    saveFile(videoBytes);
                                }
                            }).start();
                        }
                        isExit = false;
                    }
                }).start();*/
            }
        });
</code>```

I've used to make a new file to save the mp4, but when I'm recording a video longer than one minute, the app is OOM. Anyone can help me? Thanks.

答:
i slove it. this is not cameraKit-android issuse. it is the Android 's problem,it have two point:

the file is exit, but you don't notification the system. so you should :

```<code>      cameraView.getCamera().setCameraListener(new CameraListener() {
        @Override
        public void onVideoTaken(final File video) {
            super.onVideoTaken(video);
            //notify system refresh
            Uri localUri = Uri.fromFile(video);
            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
            sendBroadcast(localIntent);
</code>```

try this guys idea, i use it save susscess:

```<code>String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/milai/";

File appDir = new File(path);

if (!appDir.exists()) {
    appDir.mkdir();
}
mVideoFile = new File(mPreview.getView().getContext().getExternalFilesDir(null), getPicTime()+".mp4");
String myFile = path+getPicTime()+".mp4";
mMediaRecorder.setOutputFile(myFile);
</code>```

it look the same , but i don't know why success. if eveybody have other problem, can ask me . i will try to help you.

Title: cameraKit-android output video

Body:
Does anyone use the CameraKit-Android by gogopop? My problem is that I set the listener of video but the outputfile is null. Anyone know how to solve it?

this is my code:

        cameraView.getCamera().setVideoQuality(CameraKit.Constants.VIDEO_QUALITY_720P);
        cameraView.getCamera().startRecordingVideo();
        cameraView.getCamera().setCameraListener(new CameraListener() {
            @Override
            public void onVideoTaken(final File video) {
                super.onVideoTaken(video);
            /*    new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final byte[] videoBytes = FileUtils.File2byte(video.getAbsolutePath());
                        if (!isExit) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    saveFile(videoBytes);
                                }
                            }).start();
                        }
                        isExit = false;
                    }
                }).start();*/
            }
        });

I've used to make a new file to save the mp4, but when I'm recording a video longer than one minute, the app is OOM. Anyone can help me? Thanks.

Body:
i slove it. this is not cameraKit-android issuse. it is the Android 's problem,it have two point:

the file is exit, but you don't notification the system. so you should :

      cameraView.getCamera().setCameraListener(new CameraListener() {
        @Override
        public void onVideoTaken(final File video) {
            super.onVideoTaken(video);
            //notify system refresh
            Uri localUri = Uri.fromFile(video);
            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
            sendBroadcast(localIntent);

try this guys idea, i use it save susscess:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/milai/";

File appDir = new File(path);

if (!appDir.exists()) {
    appDir.mkdir();
}
mVideoFile = new File(mPreview.getView().getContext().getExternalFilesDir(null), getPicTime()+".mp4");
String myFile = path+getPicTime()+".mp4";
mMediaRecorder.setOutputFile(myFile);

it look the same , but i don't know why success. if eveybody have other problem, can ask me . i will try to help you.


问:
How to move one word left in the vi editor
I use the shortcut w to move the cursor one word right. Is there a shortcut to move a word left?

答:
Use b to move back one word.

Use w to move forward one word.

And here is a cheat sheet that might be useful for you:

Source: Graphical vi-vim Cheat Sheet and Tutorial


问:
Make a HMTL  hyperlink not appear as a hyperlink
I'm making a website (for schoolwork) using a combination of php, html and css. I'm currently working on the initial design stages of my site and as I'm inexperienced at html / css, I am going slowly through tutorials trying to learn.

Including the hyperlink my banner looks like:

Not including the hyperlink my banner looks like:

I want to have the functionality of the link, but the visual design effect of without the link.

The necessary code is:

```<code><html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <center>
    <div id = "indexBackgroundOne"><h2 style="font-family:verdana"> Q U E S T S ®</h2></div>
    </center>
</html>
</code>```

Thanks!

答:
try this in your style.css file

```<code>#indexBackgroundOne h2 a{
    text-decoration: none;
    color:black;
}
</code>```

Here is a sample code :

        <link rel="stylesheet" type="text/css" href="style.css">

 Q U E S T S ®

```

Title: Make a HMTL <a href> hyperlink not appear as a hyperlink

Body:
I'm making a website (for schoolwork) using a combination of php, html and css. I'm currently working on the initial design stages of my site and as I'm inexperienced at html / css, I am going slowly through tutorials trying to learn.

Including the hyperlink my banner looks like:

Not including the hyperlink my banner looks like:

I want to have the functionality of the link, but the visual design effect of without the link.

The necessary code is:

        <link rel="stylesheet" type="text/css" href="style.css">

 Q U E S T S ®

Thanks!

Body:
try this in your style.css file

#indexBackgroundOne h2 a{
    text-decoration: none;
    color:black;
}

Here is a sample code :

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <style>
    #indexBackgroundOne h2 a{
        text-decoration: none;
        color:black;
    }
    </style>
    <center>
    <div id = "indexBackgroundOne"><h2 style="font-family:verdana"> Q U E S T S &reg;</h2></div>
    </center>
</html>


问:
Lumen - modifying the route through middleware
So I have an api-version middleware that I use in laravel 5 that I am trying to use in lumen. However it uses getAction() and setAction() in the middleware which isn't available to lumen ("yet"). If I do $request->route()[1] I can get the current route but updating that with the new route does no good. I have thought about cloning the request and modifying it but I can't tell what part of the request object I would need to "update".

Here are my routes:

```<code>$app->group(['middleware' => ['api-version']], function() use ($app) {
    $app->get('users', '{api-namespace}\UsersController@index');
    $app->get('vips/{per_page?}', '{api-namespace}\VipsController@index');
    $app->get('vip/{id}/profile', '{api-namespace}\VipsController@showProfile');
    $app->get('vip/{id}', '{api-namespace}\VipsController@show');
});
</code>```

Can anyone tell me how i can update the request with my simple route update?

答:
Found this in my search for a solution. Here's what I came up with using middleware in Lumen 5.4.

First, I created an ExtractApiVersionMiddleware that extracts the version from the Accept header. I used the accept header because not all headers passed are trusted and it is becoming "Best Practice": to pass API versions in this manner:

```<code><?php

namespace App\Http\Middleware;

use Closure;

class ExtractApiVersionMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure $next
 *
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $app = app();
    $version = "0";
    foreach (explode(';', $request->header('accept')) as $frag) {
        if (stristr($frag, "version=")) {
            $version = str_replace("version=", "", $frag);
            break;
        }
    }

    if ($version != 0) {
        $app->group(['namespace' => "App\Http\Controllers\V{$version}\Reductions"],
            function () use ($app, $version) {
            require base_path() . "/routes/web/v{$version}.php";
        });
    } else {
        $app->group(['namespace' => 'App\Http\Controllers\V0'], function () use ($app, $version) {
            require base_path() . "/routes/web/v0.php";
        });
    }

    return $next($request);
}
}
</code>```

Second, I namespaced my code according to versions (the legacy codebase hasn't died yet).

Third, I pass the version that the call uses in the Accept header
Accept: application/json;version=1

Fourth, I have separate route files for each supported version. So, instead of having a web.php for all my routes, I created a web folder under routes and I placed my version files in there v0.php & v1.php

So, when I make a request, the Middleware extracts the API version and based on the version number enables the appropriate route group. This keeps the versions clean and separate but still enables me to get 'creative' with my Models.

Hope this helps. I had to apply this solution because I wasn't sure about using Dingo API in pre-release form

Body:
So I have an api-version middleware that I use in laravel 5 that I am trying to use in lumen. However it uses getAction() and setAction() in the middleware which isn't available to lumen ("yet"). If I do $request->route()[1] I can get the current route but updating that with the new route does no good. I have thought about cloning the request and modifying it but I can't tell what part of the request object I would need to "update".

Here are my routes:

$app->group(['middleware' => ['api-version']], function() use ($app) {
    $app->get('users', '{api-namespace}\UsersController@index');
    $app->get('vips/{per_page?}', '{api-namespace}\VipsController@index');
    $app->get('vip/{id}/profile', '{api-namespace}\VipsController@showProfile');
    $app->get('vip/{id}', '{api-namespace}\VipsController@show');
});

Can anyone tell me how i can update the request with my simple route update?

Body:
Found this in my search for a solution. Here's what I came up with using middleware in Lumen 5.4.

First, I created an ExtractApiVersionMiddleware that extracts the version from the Accept header. I used the accept header because not all headers passed are trusted and it is becoming "Best Practice": to pass API versions in this manner:

<?php

namespace App\Http\Middleware;

use Closure;

class ExtractApiVersionMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure $next
 *
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $app = app();
    $version = "0";
    foreach (explode(';', $request->header('accept')) as $frag) {
        if (stristr($frag, "version=")) {
            $version = str_replace("version=", "", $frag);
            break;
        }
    }

    if ($version != 0) {
        $app->group(['namespace' => "App\Http\Controllers\V{$version}\Reductions"],
            function () use ($app, $version) {
            require base_path() . "/routes/web/v{$version}.php";
        });
    } else {
        $app->group(['namespace' => 'App\Http\Controllers\V0'], function () use ($app, $version) {
            require base_path() . "/routes/web/v0.php";
        });
    }

    return $next($request);
}
}

Second, I namespaced my code according to versions (the legacy codebase hasn't died yet).

Third, I pass the version that the call uses in the Accept header
Accept: application/json;version=1

Fourth, I have separate route files for each supported version. So, instead of having a web.php for all my routes, I created a web folder under routes and I placed my version files in there v0.php & v1.php

So, when I make a request, the Middleware extracts the API version and based on the version number enables the appropriate route group. This keeps the versions clean and separate but still enables me to get 'creative' with my Models.

Hope this helps. I had to apply this solution because I wasn't sure about using Dingo API in pre-release form


问:
Upload image to folder using ajax/jquery
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:

undefined index archivo

This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)

```<code>function Registrar() {
      var cat = $('#cat').val();
      var nom = $('#name').val();
      var desc = $('#description').val();
      var image = $('#archivo').val();
     //Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')

      $.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
        success: function (data) {
          console.log(data);
        }
      });
    }
</code>```

PHP file:

```<code><?php

    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_POST['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img;
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>
</code>```

And the important parts of my HTML:

```<code><form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />
</code>```

EDIT: showimagepreview

```<code>function showimagepreview(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
</code>```

How can I solve this?

答:
Send your form data like this:

```<code>var formData = new FormData($("form")[0]);

$.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: formData,
        success: function (data) {
          console.log(data);
        }
      });
</code>```

And you have to get the file with $_FILES, you can not get it in $_POST in php code.

Body:
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:

undefined index archivo

This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)

function Registrar() {
      var cat = $('#cat').val();
      var nom = $('#name').val();
      var desc = $('#description').val();
      var image = $('#archivo').val();
     //Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')

      $.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
        success: function (data) {
          console.log(data);
        }
      });
    }

PHP file:

<?php

    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_POST['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img;
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>

And the important parts of my HTML:

<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />

EDIT: showimagepreview

function showimagepreview(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

How can I solve this?

Body:
Send your form data like this:

var formData = new FormData($("form")[0]);

$.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: formData,
        success: function (data) {
          console.log(data);
        }
      });

And you have to get the file with $_FILES, you can not get it in $_POST in php code.


问:
SQL SERVER - FETCH NEXT ROWS returns duplicate results
I had a very weird issue in my website, and finally I succeeded to pinpoint the exact cause.

In my 'Entities' table I have several columns, such as "Id", "Title", "Date", "Indexing" and some more.

"Indexing" column indexed with full-text index.

Consider the following SQL query:

```<code>SELECT Id
FROM [dbo].[Entities] AS DocTable
INNER JOIN CONTAINSTABLE(Entities, Indexing, 'otherCriteria OR criteia') AS KEY_TBL
ON DocTable.Id = KEY_TBL.[KEY]
ORDER BY KEY_TBL.RANK DESC
</code>```

This query works as expected and I getting around 600 results.

Now I adding pagination:

```<code>SELECT Id
FROM [dbo].[Entities] AS DocTable
INNER JOIN CONTAINSTABLE(Entities, Indexing, 'otherCriteria OR criteia') AS KEY_TBL
ON DocTable.Id = KEY_TBL.[KEY]
ORDER BY KEY_TBL.RANK DESC
OFFSET 50 ROWS FETCH NEXT 10 ROWS ONLY
</code>```

No matter if I using OFFSET 30 or 40 or 50 -> I always getting exactly the same results!

Now the really weird part: if inside SELECT I asking to select 'Title' also (e.g. SELECT Id, Title) --> I getting correct results.

Any ideas?

答:
OK, I think I got it

In Sql Server 2014 ORDER BY clause with OFFSET FETCH NEXT returns weird results

Says:

The ORDER BY clause contains a column or combination of columns that
  are guaranteed to be unique.

Obviously, "RANK" is not unique. When I changed my query to:

```<code>SELECT Id
FROM [dbo].[Entities] AS DocTable
INNER JOIN CONTAINSTABLE(Entities, Indexing, 'otherCriteria OR criteia') AS KEY_TBL
ON DocTable.Id = KEY_TBL.[KEY]
ORDER BY KEY_TBL.RANK DESC, Id
OFFSET 50 ROWS FETCH NEXT 10 ROWS ONLY
</code>```

I received correct results

Body:
I had a very weird issue in my website, and finally I succeeded to pinpoint the exact cause.

In my 'Entities' table I have several columns, such as "Id", "Title", "Date", "Indexing" and some more.

"Indexing" column indexed with full-text index.

Consider the following SQL query:

SELECT Id
FROM [dbo].[Entities] AS DocTable
INNER JOIN CONTAINSTABLE(Entities, Indexing, 'otherCriteria OR criteia') AS KEY_TBL
ON DocTable.Id = KEY_TBL.[KEY]
ORDER BY KEY_TBL.RANK DESC

This query works as expected and I getting around 600 results.

Now I adding pagination:

SELECT Id
FROM [dbo].[Entities] AS DocTable
INNER JOIN CONTAINSTABLE(Entities, Indexing, 'otherCriteria OR criteia') AS KEY_TBL
ON DocTable.Id = KEY_TBL.[KEY]
ORDER BY KEY_TBL.RANK DESC
OFFSET 50 ROWS FETCH NEXT 10 ROWS ONLY

No matter if I using OFFSET 30 or 40 or 50 -> I always getting exactly the same results!

Now the really weird part: if inside SELECT I asking to select 'Title' also (e.g. SELECT Id, Title) --> I getting correct results.

Any ideas?

Body:
OK, I think I got it

In Sql Server 2014 ORDER BY clause with OFFSET FETCH NEXT returns weird results

Says:

The ORDER BY clause contains a column or combination of columns that
  are guaranteed to be unique.

Obviously, "RANK" is not unique. When I changed my query to:

SELECT Id
FROM [dbo].[Entities] AS DocTable
INNER JOIN CONTAINSTABLE(Entities, Indexing, 'otherCriteria OR criteia') AS KEY_TBL
ON DocTable.Id = KEY_TBL.[KEY]
ORDER BY KEY_TBL.RANK DESC, Id
OFFSET 50 ROWS FETCH NEXT 10 ROWS ONLY

I received correct results


问:
Why are my html buttons moving in I.E? They don't move in Chrome or FF
We are using AJAX to send data to our database. I've added some feedback for the user including a spinner (animated .gif) that spins during the request, and Pass/Fail text that is displayed to the user when the request is complete.

HTML:

```<code><center>
    <table style="width:350px;">
        <tr>
            <td style="width:100px; min-width:100px;" align="right">
                <span id="spinner-and-text-displayed-here"></span>
            </td>
            <td style="width:150px">
                <input type="button" value="Submit" onclick="submit();"/>
                <input type="button" value="Cancel" onclick="cancel();"/>
            </td>
            <td style="width:100px"></td>
        </tr>
    </table>
</center>
</code>```

When the user clicks the submit button the spinner spins until the ajax callback is returned. At this point, the buttons do NOT shift. Once I receive the callback I display the text "Successful!" (displayed in the span using jQuery $(el).html("Successful!");), which causes the buttons to shift right. That message fades out (also using jquery), and once the button fades completely, the buttons shift back to their original position.

If I hardcode "Successful!" inside the span, the buttons are shifted, so I know it has something to do with the text (remember it doesn't shift when the spinner is displayed [which uses the img tag]).

It doesn't matter how wide i set the first td width.

Is there a way I can keep these buttons from shifting in IE?

答:
Try adding border-collapse:collapse; to the style definition of the table and reduce the size of the middle cell.

```<code><center>
    <table style="width:350px;border-collapse:collapse;">
        <tr>
            <td style="width:100px; min-width:100px;" align="right">
                <span id="spinner-and-text-displayed-here"></span>
            </td>
            <td style="width:145px">
                <input type="button" value="Submit" onclick="submit();"/>
                <input type="button" value="Cancel" onclick="cancel();"/>
            </td>
            <td style="width:100px"></td>
        </tr>
    </table>
</center>
</code>```

Body:
We are using AJAX to send data to our database. I've added some feedback for the user including a spinner (animated .gif) that spins during the request, and Pass/Fail text that is displayed to the user when the request is complete.

HTML:

                <input type="button" value="Submit" onclick="submit();"/>
                <input type="button" value="Cancel" onclick="cancel();"/>

When the user clicks the submit button the spinner spins until the ajax callback is returned. At this point, the buttons do NOT shift. Once I receive the callback I display the text "Successful!" (displayed in the span using jQuery $(el).html("Successful!");), which causes the buttons to shift right. That message fades out (also using jquery), and once the button fades completely, the buttons shift back to their original position.

If I hardcode "Successful!" inside the span, the buttons are shifted, so I know it has something to do with the text (remember it doesn't shift when the spinner is displayed [which uses the img tag]).

It doesn't matter how wide i set the first td width.

Is there a way I can keep these buttons from shifting in IE?

Body:
Try adding border-collapse:collapse; to the style definition of the table and reduce the size of the middle cell.

<center>
    <table style="width:350px;border-collapse:collapse;">
        <tr>
            <td style="width:100px; min-width:100px;" align="right">
                <span id="spinner-and-text-displayed-here"></span>
            </td>
            <td style="width:145px">
                <input type="button" value="Submit" onclick="submit();"/>
                <input type="button" value="Cancel" onclick="cancel();"/>
            </td>
            <td style="width:100px"></td>
        </tr>
    </table>
</center>


问:
Creating new records in dataframe based on character
I have fields in a pandas dataframe like the sample data below.  The values in one of the fields are fractions with the form something/count(something).  I would like to split the values like the example output below, and create new records.  Basically the numerator and the denominator.  Some of the values even have multiple /, like count(something)/count(thing)/count(dog).  So I'd want to split that value in to 3 records.  Any tips on how to do this would be greatly appreciated.</p>

```<code>Sample Data:

SampleDf=pd.DataFrame([['tom','sum(stuff)/count(things)'],['bob','count(things)/count(stuff)']],columns=['ReportField','OtherField'])

Example Output:

OutputDf=pd.DataFrame([['tom1','sum(stuff)'],['tom2','count(things)'],['bob1','count(things)'],['bob2','count(stuff)']],columns=['ReportField','OtherField'])
</code>```

答:
One possible way might be as following:

```<code># split and stack
new_df = pd.DataFrame(SampleDf.OtherField.str.split('/').tolist(), index=SampleDf.ReportField).stack().reset_index()
print(new_df)
</code>```

Output:

```<code>    ReportField  level_1          0
0         tom        0     sum(stuff)
1         tom        1  count(things)
2         bob        0  count(things)
3         bob        1   count(stuff)
</code>```

Now, combine ReportField with level_1:

```<code># combine strings for tom1, tom2 ,.....
new_df['ReportField'] = new_df.ReportField.str.cat((new_df.level_1+1).astype(str))

# remove level column
del new_df['level_1']
# rename columns
new_df.columns = ['ReportField', 'OtherField']
print (new_df)
</code>```

Output:

```<code>    ReportField     OtherField
0        tom1       sum(stuff)
1        tom2    count(things)
2        bob1    count(things)
3        bob2     count(stuff)
</code>```

Body:
I have fields in a pandas dataframe like the sample data below.  The values in one of the fields are fractions with the form something/count(something).  I would like to split the values like the example output below, and create new records.  Basically the numerator and the denominator.  Some of the values even have multiple /, like count(something)/count(thing)/count(dog).  So I'd want to split that value in to 3 records.  Any tips on how to do this would be greatly appreciated.

Sample Data:

SampleDf=pd.DataFrame([['tom','sum(stuff)/count(things)'],['bob','count(things)/count(stuff)']],columns=['ReportField','OtherField'])

Example Output:

OutputDf=pd.DataFrame([['tom1','sum(stuff)'],['tom2','count(things)'],['bob1','count(things)'],['bob2','count(stuff)']],columns=['ReportField','OtherField'])

Body:
One possible way might be as following:

# split and stack
new_df = pd.DataFrame(SampleDf.OtherField.str.split('/').tolist(), index=SampleDf.ReportField).stack().reset_index()
print(new_df)

Output:

    ReportField  level_1          0
0         tom        0     sum(stuff)
1         tom        1  count(things)
2         bob        0  count(things)
3         bob        1   count(stuff)

Now, combine ReportField with level_1:

# combine strings for tom1, tom2 ,.....
new_df['ReportField'] = new_df.ReportField.str.cat((new_df.level_1+1).astype(str))

# remove level column
del new_df['level_1']
# rename columns
new_df.columns = ['ReportField', 'OtherField']
print (new_df)

Output:

    ReportField     OtherField
0        tom1       sum(stuff)
1        tom2    count(things)
2        bob1    count(things)
3        bob2     count(stuff)


问:
Serialize derived type as base type over AppDomain
I've got a plugin system where the plugin itself can have several runtime instances. These instances are defined with a configuration object that gets carried is made available to the plugin itself through various APIs.

The configuration contains specific parts that the parent application understands but it is expected for the plugin to specify its own parts through subclassing.

```<code>[Serializable]
public class PluginConfiguration {
    public string Name { get; set; }
}

public class MyPluginConfiguration : PluginConfiguration {
    public string AccessToken { get; set; }
}
</code>```

This is partly technical reason as it allows the main application to just serialize the whole object as JSON/XML/etc. into database to persist both the common configuration and the plugin specific configuration.

Each plugin is hosted within its own AppDomain. However I'm getting into trouble when I'm trying to read the plugin configuration from the primary app domain and the plugin (MarshalByRefObject returns its MyPluginConfiguration object instance.

Is there a way to do some Serialization magic in the base class to ensure that the object instances are serialized as PluginConfiguration instances? The problem in serializing the MyPluginConfiguration instances are:

The custom configuration type might not be [Serializable]

Even if they were [Serializable], they don't have their Assembly loaded in the primary app domain anyway.

Ideally I'd like the implementation to be restricted to the PluginConfiguration base class. The old [Serializable] semantics and AppDomains are not the most common concept in .Net and I would like to hide some of these aspects from the plugin developers if they don't need to deal with them.

答:
Using binary serialization, per your [Serializable]

Note: XML has IXmlSerializable
and Javascript is also different. I believe JSON.net serializes ISerializable objects as implemented below

```<code>[Serializable]
public class PluginConfiguration : System.Runtime.Serialization.ISerializable
{
    public string Name { get; set; }
    public PluginConfiguration()
    {

    }
    protected PluginConfiguration(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
            throw new System.ArgumentNullException("info");
        Name = (string)info.GetValue("Name", typeof(string));

    }
    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
    }

}

[Serializable]
public class MyPluginConfiguration : PluginConfiguration
{
    public string AccessToken { get; set; }
    public MyPluginConfiguration()
    {

    }
    protected MyPluginConfiguration(SerializationInfo info, StreamingContext context) :base(info, context)
    {

    }

}

private class PluginBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        return typeof(PluginConfiguration);
    }
}
</code>```

Usage:

```<code>var c = new PluginConfiguration() { Name = "Name" };
var p = new MyPluginConfiguration() { Name = "Name", AccessToken = "MyToken" };

BinaryFormatter fmt = new BinaryFormatter();

MemoryStream cms = new MemoryStream();
fmt.Serialize(cms, c);

cms.Position = 0;
PluginConfiguration revc = fmt.Deserialize(cms) as PluginConfiguration;

MemoryStream pms = new MemoryStream();
fmt.Serialize(pms, p);
pms.Position = 0;
MyPluginConfiguration prev = fmt.Deserialize(pms) as MyPluginConfiguration;

//given a stream containing the serialization of MyPluginConfiguration
// serailize it as a the known PluginConfiguration Type

pms.Position = 0;
fmt.Binder = new PluginBinder();
PluginConfiguration PluginFromCustomStream = fmt.Deserialize(pms) as PluginConfiguration;
</code>```

Body:
I've got a plugin system where the plugin itself can have several runtime instances. These instances are defined with a configuration object that gets carried is made available to the plugin itself through various APIs.

The configuration contains specific parts that the parent application understands but it is expected for the plugin to specify its own parts through subclassing.

[Serializable]
public class PluginConfiguration {
    public string Name { get; set; }
}

public class MyPluginConfiguration : PluginConfiguration {
    public string AccessToken { get; set; }
}

This is partly technical reason as it allows the main application to just serialize the whole object as JSON/XML/etc. into database to persist both the common configuration and the plugin specific configuration.

Each plugin is hosted within its own AppDomain. However I'm getting into trouble when I'm trying to read the plugin configuration from the primary app domain and the plugin (MarshalByRefObject returns its MyPluginConfiguration object instance.

Is there a way to do some Serialization magic in the base class to ensure that the object instances are serialized as PluginConfiguration instances? The problem in serializing the MyPluginConfiguration instances are:

The custom configuration type might not be [Serializable]

Even if they were [Serializable], they don't have their Assembly loaded in the primary app domain anyway.

Ideally I'd like the implementation to be restricted to the PluginConfiguration base class. The old [Serializable] semantics and AppDomains are not the most common concept in .Net and I would like to hide some of these aspects from the plugin developers if they don't need to deal with them.

Body:
Using binary serialization, per your [Serializable]

Note: XML has IXmlSerializable
and Javascript is also different. I believe JSON.net serializes ISerializable objects as implemented below

[Serializable]
public class PluginConfiguration : System.Runtime.Serialization.ISerializable
{
    public string Name { get; set; }
    public PluginConfiguration()
    {

    }
    protected PluginConfiguration(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
            throw new System.ArgumentNullException("info");
        Name = (string)info.GetValue("Name", typeof(string));

    }
    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
    }

}

[Serializable]
public class MyPluginConfiguration : PluginConfiguration
{
    public string AccessToken { get; set; }
    public MyPluginConfiguration()
    {

    }
    protected MyPluginConfiguration(SerializationInfo info, StreamingContext context) :base(info, context)
    {

    }

}

private class PluginBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        return typeof(PluginConfiguration);
    }
}

Usage:

var c = new PluginConfiguration() { Name = "Name" };
var p = new MyPluginConfiguration() { Name = "Name", AccessToken = "MyToken" };

BinaryFormatter fmt = new BinaryFormatter();

MemoryStream cms = new MemoryStream();
fmt.Serialize(cms, c);

cms.Position = 0;
PluginConfiguration revc = fmt.Deserialize(cms) as PluginConfiguration;

MemoryStream pms = new MemoryStream();
fmt.Serialize(pms, p);
pms.Position = 0;
MyPluginConfiguration prev = fmt.Deserialize(pms) as MyPluginConfiguration;

//given a stream containing the serialization of MyPluginConfiguration
// serailize it as a the known PluginConfiguration Type

pms.Position = 0;
fmt.Binder = new PluginBinder();
PluginConfiguration PluginFromCustomStream = fmt.Deserialize(pms) as PluginConfiguration;


答:
change this

```<code>  $img = $_POST['archivo'];
</code>```

to

```<code>$_FILES['archivo'];
</code>```

Files object cannot be recieved in $_POST

Title: Upload image to folder using ajax/jquery

Body:
change this

  $img = $_POST['archivo'];

to

$_FILES['archivo'];

Files object cannot be recieved in $_POST


问:
Is it possible to create "Empty Solution" with Visual Web Developer 2010 Express?
s it possible to create an "Empty Solution" with Visual Web Developer 2010 Express? It looks to me like that was possible to do so with VWD 2008 SP1 Express.

Anything to configure to get an empty solution? Or something similar, so that I can get more than one solution for a new application? I've VS2008 professional and I'd like to switch to VWD 2010 Express before I'm able to get VS2010 Professional edition.

Thanks for helping

答:
First, identify a folder location in which you will build solutions.

Then in VWD 2010 Express, create a New Project from the File menu. Select the Windows templates under your preferred language (ie C#) and highlight Class Library. Name your Class (ie, "Domain") and below that you have options to set your base directory for the solution folder, 'Create new solution', and provide a 'Solution name' with the 'Create directory for solution'.

You can then use the File -> Add... menu option to add resources to the your solution.