答:
the problem

you have a constructor ProcessHeap(Process[] heap, int size) but try to call it here new ProcessHeap(HEAP_SIZE) with only an int - so the compiler stops and warns you that the parameters do not match up

how to fix it?

you either have to change the constructor/add a constructor, which I guess you can't, cause its for your assignment

the other option is that you pass an already created array of processes

```<code>final int HEAP_SIZE = 100;

final Process[] processHeap = new Process[HEAP_SIZE];

ProcessHeap heap = new ProcessHeap(processHeap , HEAP_SIZE);
</code>```

Title: Making a new object, cannot be applied to type (int)

Body:
the problem

you have a constructor ProcessHeap(Process[] heap, int size) but try to call it here new ProcessHeap(HEAP_SIZE) with only an int - so the compiler stops and warns you that the parameters do not match up

how to fix it?

you either have to change the constructor/add a constructor, which I guess you can't, cause its for your assignment

the other option is that you pass an already created array of processes

final int HEAP_SIZE = 100;

final Process[] processHeap = new Process[HEAP_SIZE];

ProcessHeap heap = new ProcessHeap(processHeap , HEAP_SIZE);


来源: stackexchange

问:
Passing data through Intent and receiving it
I am trying to pass data through my Intent into the next activity so I can receive it and give a timer values.

```<code>Button TimerButton = (Button)findViewById(R.id.TimerActivityButton);
TimerButton.setOnClickListener(new View.OnClickListener(){
     public void onClick(View v)
     {
          Intent timer = new Intent (BeefActivity.this,TimerActivity.class);
          timer.putExtra("beefType", 5000);
          timer.putExtra("beefThickness", 5000);
          timer.putExtra("grillTime", 15000);
          startActivity(timer);
      }
});
</code>```

I have tried different methods of receiving the values, and I keep getting a force close or compiler errors. I know this is simple so can somebody please show me how to do this. Thank you in advance!

```<code>This is force closing
</code>```

I tried passing in int length = beefType and it force closed

I tried changing the -1 to 200, it still force closed

I put back int length = 20000 where it worked originally

Just having int beefType = getIntent().getIntExtra("beefType", -1); at the top of my class makes it force close. No compiler errors. I am stuck :-( Here is how my code looks

```<code>package com.android.project1;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TimerActivity extends Activity {

    int beefType = getIntent().getIntExtra("beefType", 200);

  TextView timeDisplay;
  MyCount counter;
  int state = 0;
  int length = 20000;
  long startTime = 0;
  long currentTime = 0;
  long timeElapsed = 0;
  long timeRemaining = 0;
  long prevTimeRemaining = 0;
  Button control;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.timer);

    timeDisplay = (TextView) findViewById(R.id.timer);
    control = (Button) findViewById(R.id.control);
    counter = new MyCount(length, 100);
  }
  public String formatTime(long millis)
  {
      String output = "00:00:00";
      long seconds = millis / 1000;
      long minutes = seconds / 60;
      long hours = minutes / 60;

      seconds = seconds % 60;
      minutes = minutes % 60;
      hours = hours % 60;

      String secondsD = String.valueOf(seconds);
      String minutesD = String.valueOf(minutes);
      String hoursD = String.valueOf(hours);

      if (seconds < 10)
        secondsD = "0" + seconds;
      if (minutes < 10)
        minutesD = "0" + minutes;
      if (hours < 10)
        hoursD = "0" + hours;

      output = hoursD + " : " + minutesD + " : " + secondsD;
      return output;
    }
  public void control(View view) {
    switch (state) {
    case 0:
      startTime = System.currentTimeMillis();
      counter.start();
      control.setText(R.string.pause);
      state = 1;
      break;
    case 1:
      // Pause
      currentTime = System.currentTimeMillis();
      timeElapsed = currentTime - startTime;
      if (prevTimeRemaining == 0)
        timeRemaining = length - timeElapsed;
      else
        timeRemaining = prevTimeRemaining - timeElapsed;
      counter.cancel();
      timeDisplay.setText("Left: " + String.valueOf(formatTime(timeRemaining)));
      control.setText(R.string.resume);
      prevTimeRemaining = timeRemaining;

      // Resume
      counter = new MyCount(timeRemaining, 100);
      state = 0;
      break;
    case 2:
      prevTimeRemaining = 0;
      counter = new MyCount(length, 100);
      control.setText(R.string.start);
      timeDisplay.setText(R.string.timer);
      state = 0;
    }
  }

  public class MyCount extends CountDownTimer
  {

    public MyCount(long millisInFuture, long countDownInterval)
    {
      super(millisInFuture, countDownInterval);
    }
    public void onTick(long timeRemaining)
    {
        timeDisplay.setText("Left: " + formatTime(timeRemaining));
    }
    public void onFinish()
    {
      timeDisplay.setText("Finished!");
      state = 2;
      control.setText(R.string.restart);
    }
  }
}
</code>```

答:
You need to put this line:

```<code>int beefType = getIntent().getIntExtra("beefType", 200);
</code>```

in the onCreate method and not as a field initializer.

And next time - read the stacktrace before asking. If you are still stuck after reading it, attach it to youyr questioin as well.

Good Luck!

ContentLicense: CC BY-SA 2.5

Body:
I am trying to pass data through my Intent into the next activity so I can receive it and give a timer values.

Button TimerButton = (Button)findViewById(R.id.TimerActivityButton);
TimerButton.setOnClickListener(new View.OnClickListener(){
     public void onClick(View v)
     {
          Intent timer = new Intent (BeefActivity.this,TimerActivity.class);
          timer.putExtra("beefType", 5000);
          timer.putExtra("beefThickness", 5000);
          timer.putExtra("grillTime", 15000);
          startActivity(timer);
      }
});

I have tried different methods of receiving the values, and I keep getting a force close or compiler errors. I know this is simple so can somebody please show me how to do this. Thank you in advance!

This is force closing

I tried passing in int length = beefType and it force closed

I tried changing the -1 to 200, it still force closed

I put back int length = 20000 where it worked originally

Just having int beefType = getIntent().getIntExtra("beefType", -1); at the top of my class makes it force close. No compiler errors. I am stuck :-( Here is how my code looks

package com.android.project1;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TimerActivity extends Activity {

    int beefType = getIntent().getIntExtra("beefType", 200);

  TextView timeDisplay;
  MyCount counter;
  int state = 0;
  int length = 20000;
  long startTime = 0;
  long currentTime = 0;
  long timeElapsed = 0;
  long timeRemaining = 0;
  long prevTimeRemaining = 0;
  Button control;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.timer);

    timeDisplay = (TextView) findViewById(R.id.timer);
    control = (Button) findViewById(R.id.control);
    counter = new MyCount(length, 100);
  }
  public String formatTime(long millis)
  {
      String output = "00:00:00";
      long seconds = millis / 1000;
      long minutes = seconds / 60;
      long hours = minutes / 60;

      seconds = seconds % 60;
      minutes = minutes % 60;
      hours = hours % 60;

      String secondsD = String.valueOf(seconds);
      String minutesD = String.valueOf(minutes);
      String hoursD = String.valueOf(hours);

      if (seconds < 10)
        secondsD = "0" + seconds;
      if (minutes < 10)
        minutesD = "0" + minutes;
      if (hours < 10)
        hoursD = "0" + hours;

      output = hoursD + " : " + minutesD + " : " + secondsD;
      return output;
    }
  public void control(View view) {
    switch (state) {
    case 0:
      startTime = System.currentTimeMillis();
      counter.start();
      control.setText(R.string.pause);
      state = 1;
      break;
    case 1:
      // Pause
      currentTime = System.currentTimeMillis();
      timeElapsed = currentTime - startTime;
      if (prevTimeRemaining == 0)
        timeRemaining = length - timeElapsed;
      else
        timeRemaining = prevTimeRemaining - timeElapsed;
      counter.cancel();
      timeDisplay.setText("Left: " + String.valueOf(formatTime(timeRemaining)));
      control.setText(R.string.resume);
      prevTimeRemaining = timeRemaining;

      // Resume
      counter = new MyCount(timeRemaining, 100);
      state = 0;
      break;
    case 2:
      prevTimeRemaining = 0;
      counter = new MyCount(length, 100);
      control.setText(R.string.start);
      timeDisplay.setText(R.string.timer);
      state = 0;
    }
  }

  public class MyCount extends CountDownTimer
  {

    public MyCount(long millisInFuture, long countDownInterval)
    {
      super(millisInFuture, countDownInterval);
    }
    public void onTick(long timeRemaining)
    {
        timeDisplay.setText("Left: " + formatTime(timeRemaining));
    }
    public void onFinish()
    {
      timeDisplay.setText("Finished!");
      state = 2;
      control.setText(R.string.restart);
    }
  }
}

Body:
You need to put this line:

int beefType = getIntent().getIntExtra("beefType", 200);

in the onCreate method and not as a field initializer.

And next time - read the stacktrace before asking. If you are still stuck after reading it, attach it to youyr questioin as well.

Good Luck!


问:
In iOS 10.3 and above, can alternateIconName be set and used for an image outside of an app bundle/binary?
In iOS 10.3+, Apple has introduced the ability to change an app icon for an app, while running, from the default to any other image name that's been preloaded into the Info.plist:

https://developer.apple.com/reference/uikit/uiapplication/2806818-setalternateiconname

Is it possible to set the image name to something like generic.png, build and load the app on a device, and then have my code create a generic.png file within my app's sandboxed document area to then use as my icon?

Or do all images used as icons need to be pre-built within the app bundle itself?

答: The icons and info.plist are all part of your signed bundle, so you cannot modify them at run time.  Accordingly the icon image choices are limited to those that you ship with your app.</p>

ContentLicense: CC BY-SA 3.0


问:
Set up git to pull and push all branches
I'd like to push and pull all the branches by default, including the newly created ones.

Is there a setting that I can define for it?

Otherwise, when I add a new branch, locally and I want to pull it from the server, what is the simplest way to do it?

I created a new branch with the same name and tried to pull but it doesn't work. Asks me for all the remote config of the branch. How do I set it.

答:
If you are moving all branches to a new repo from an old one then in your local repo you need to set up tracking of each branch to existing origin branches, before pushing to the new repo, otherwise all your origin branches won’t appear in the new origin. Do this manually by tracking or checking out each branch, or use the one liner:

```<code>for remote in `git branch -r | grep -v '\->' | grep -v master`; do git branch --track `echo $remote|sed 's=origin/=='` `echo $remote`; done
</code>```

This one line command is based on versions of it in other answers on this page, but is arguably better because:

it correctly sets up the branch tracking, unlike some older variants of this command on this page which only supply one parameter to --track and thus each branch ends up tracking master - not good

names the local branches without the prefix “origin/” which I personally don’t want - and is consistent with what happens when you checkout a branch normally.

skips tracking master since that is already happening

doesn’t actually checkout anything thus is fast

avoids stumbling over the -> in the output of git branch -r

Next, if you are switching origins, replace the link to the old origin and point to a new remote.  Ensure you create the new remote first, using bitbucket/github GUI, but don’t add any files to it or there will be a merge problem. E.g.

```<code>git remote set-url origin git@bitbucket.org:YOUR/SOMEREPO.git
</code>```

Now push.  Note the second command is needed to push the tags as well:

```<code>git push -u --all origin
git push --tags origin
</code>```

Body:
If you are moving all branches to a new repo from an old one then in your local repo you need to set up tracking of each branch to existing origin branches, before pushing to the new repo, otherwise all your origin branches won’t appear in the new origin. Do this manually by tracking or checking out each branch, or use the one liner:

for remote in `git branch -r | grep -v '\->' | grep -v master`; do git branch --track `echo $remote|sed 's=origin/=='` `echo $remote`; done

This one line command is based on versions of it in other answers on this page, but is arguably better because:

it correctly sets up the branch tracking, unlike some older variants of this command on this page which only supply one parameter to --track and thus each branch ends up tracking master - not good

names the local branches without the prefix “origin/” which I personally don’t want - and is consistent with what happens when you checkout a branch normally.

skips tracking master since that is already happening

doesn’t actually checkout anything thus is fast

avoids stumbling over the -> in the output of git branch -r

Next, if you are switching origins, replace the link to the old origin and point to a new remote.  Ensure you create the new remote first, using bitbucket/github GUI, but don’t add any files to it or there will be a merge problem. E.g.

git remote set-url origin git@bitbucket.org:YOUR/SOMEREPO.git

Now push.  Note the second command is needed to push the tags as well:

git push -u --all origin
git push --tags origin


问:
How do I make sure that Antlr4 gets credit for my new language
I just developed a new language using that Antlr4 libraries. I was reading the license and I noticed that if I do develop a product using Antlr, I need to give the credit to the Antlr contributors (Particularly Terrance Parr). I want to make sure that I do everything correctly and on the up and up, so I'm not sure where to put the credit, in my product.

Can someone help me?

答: Typcially you would mention 3rd party libraries in a readme file or a contributors file. Often used is also the "about" information all applications have. Yet another possibility is the documentation, but that must be accessible in public. You don't need to add a note everywhere, just one place is enough.</p>


问:
Label disappear when table is reloaded / scrolled
I have a UITableview with two UILabels like in the chat. When the visible UITableview is filled and when I add extra cells, my UILabels get disappeared.

There are may other UILabels which is visible. Only those 2 chat UILabels is hidden. Can anyone suggest me the possible solution?

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];
index = indexPath.row + 1;
indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;
cell.ChatLabel1.layer.masksToBounds = YES;
cell.ChatLabel2.layer.cornerRadius = 8;
cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;
cell.ImageviewLabel1.layer.masksToBounds = YES;
cell.ImageviewLabel2.layer.cornerRadius = 20;
cell.ImageviewLabel2.layer.masksToBounds = YES;
cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

    cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];
    cell.ChatLabel2.hidden = YES;
    cell.ImageviewLabel2.hidden = YES;

    cell.TimeLabel1.text = TimeArray[indexPath.row];
}
else
{

    cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];
    cell.ChatLabel1.hidden = YES;
    cell.ImageviewLabel1.hidden = YES;
    cell.TimeLabel2.text = TimeArray[indexPath.row];
}

return cell;
</code>```

}

答:
Labels in custom TableView cells disappearing after scrolling

My code has an if else statement where one branch can set cell.ChatLabel2.hidden = YES; but the other branch does not set cell.ChatLabel2.hidden = NO;. So, once the label is hidden it will never be un-hidden. When the cell with the hidden label is reused the label remains hidden.

Add cell.ChatLabel2.hidden = NO; (and any other 'inverse' configuration required) to your if statement.

Body:
I have a UITableview with two UILabels like in the chat. When the visible UITableview is filled and when I add extra cells, my UILabels get disappeared.

There are may other UILabels which is visible. Only those 2 chat UILabels is hidden. Can anyone suggest me the possible solution?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];
index = indexPath.row + 1;
indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;
cell.ChatLabel1.layer.masksToBounds = YES;
cell.ChatLabel2.layer.cornerRadius = 8;
cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;
cell.ImageviewLabel1.layer.masksToBounds = YES;
cell.ImageviewLabel2.layer.cornerRadius = 20;
cell.ImageviewLabel2.layer.masksToBounds = YES;
cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

    cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];
    cell.ChatLabel2.hidden = YES;
    cell.ImageviewLabel2.hidden = YES;

    cell.TimeLabel1.text = TimeArray[indexPath.row];
}
else
{

    cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];
    cell.ChatLabel1.hidden = YES;
    cell.ImageviewLabel1.hidden = YES;
    cell.TimeLabel2.text = TimeArray[indexPath.row];
}

return cell;

}


答:
The expression:

```<code>SUM(Sales) OVER (PARTITION BY empid
                 ORDER BY empid
                 ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
</code>```

calculates the sum considering the current row and the 2 rows immediately preceding it. So it actually calculates a rolling sum, which is what you really don't want.

I think you are actually looking for something like the following:

```<code>;WITH CTE_Group AS (
    SELECT EmpId, Yr, sales,
          (ROW_NUMBER() OVER (PARTITION BY empid ORDER BY yr) + 1 ) / 2 AS grp
    FROM sales
)
SELECT EmpId, Yr, sales,
       SUM(sales) OVER (PARTITION BY empid, grp
                        ORDER BY yr) AS TotalSales2
FROM CTE_Group
</code>```

The above query uses a CTE in order to calculate field grp: the value of this field is 1 for the first two records of an empid partition, 2 for the next two records, and so on.

Using grp we can calculate the running total of sales for groups of 2 as is the requirement of the OP.

Demo here

Edit:

To offset a larger group of records try using (credit goes to @Max Szczurek for pointing this out):

```<code>(ROW_NUMBER() OVER (PARTITION BY empid ORDER BY yr) - 1 ) / n AS grp
</code>```

where n is the number of records each group contains.

Title: Running count for each 2 rows

Body:
I am trying to calculate running count for each 2 rows like below,

CREATE TABLE sales
(
     EmpId INT,
     Yr INT,
     Sales DECIMAL(8,2)
)

INSERT INTO sales (EmpId, Yr, Sales)
VALUES (1, 2005, 12000), (1, 2006, 18000), (1, 2007, 25000),
       (1, 2008, 25000), (1, 2009, 25000),
       (2, 2005, 15000), (2, 2006, 6000), (2, 2007, 6000)

SELECT
    EmpId, Yr, sales,
    SUM(Sales) OVER (PARTITION BY empid ORDER BY empid ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS TotalSales2
FROM
    sales

Output:

EmpId   Yr      sales   TotalSales2
-----------------------------------
  1     2005    12000      12000
  1     2006    18000      30000
  1     2007    25000      55000
  1     2008    25000      68000
  1     2009    25000      75000
  2     2005    15000      15000
  2     2006     6000      21000
  2     2007     6000      27000

But expected output:

EmpId   Yr     Sales    TotalSales2
-----------------------------------
  1     2005    12000   12000
  1     2006    18000   30000
  1     2007    25000   25000
  1     2008    25000   50000
  1     2009    25000   25000
  2     2005    15000   15000
  2     2006     6000   21000
  2     2007     6000    6000

What am I doing wrong in this query?

Note: SQL Servre version is 2012.

Body:
The expression:

SUM(Sales) OVER (PARTITION BY empid
                 ORDER BY empid
                 ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)

calculates the sum considering the current row and the 2 rows immediately preceding it. So it actually calculates a rolling sum, which is what you really don't want.

I think you are actually looking for something like the following:

;WITH CTE_Group AS (
    SELECT EmpId, Yr, sales,
          (ROW_NUMBER() OVER (PARTITION BY empid ORDER BY yr) + 1 ) / 2 AS grp
    FROM sales
)
SELECT EmpId, Yr, sales,
       SUM(sales) OVER (PARTITION BY empid, grp
                        ORDER BY yr) AS TotalSales2
FROM CTE_Group

The above query uses a CTE in order to calculate field grp: the value of this field is 1 for the first two records of an empid partition, 2 for the next two records, and so on.

Using grp we can calculate the running total of sales for groups of 2 as is the requirement of the OP.

Demo here

Edit:

To offset a larger group of records try using (credit goes to @Max Szczurek for pointing this out):

(ROW_NUMBER() OVER (PARTITION BY empid ORDER BY yr) - 1 ) / n AS grp

where n is the number of records each group contains.


问:
XPath query to fetch value of custom attribute
I am trying to extract "yes" from the following HTML using XPath locator.

The problem is that div tag has a class, which is fine, but the span does not have a class. It only has a bunch of custom attributes.

HTML Code:

```<code><div class="bcdef">
<span lalalala="no" hahahaha="yes"> </span>

-----a lot of other stuff-------------
</div>
</code>```

How can I fetch the attribute value?

答:
You can use the following XPath to fetch the attribute value of a tag:

```<code>//div[@class='bcdef']/span/@hahahaha
</code>```

Once you locate the tag, simply use the attribute name to fetch the value.

Body:
I am trying to extract "yes" from the following HTML using XPath locator.

The problem is that div tag has a class, which is fine, but the span does not have a class. It only has a bunch of custom attributes.

HTML Code:

-----a lot of other stuff-------------

How can I fetch the attribute value?

Body:
You can use the following XPath to fetch the attribute value of a tag:

//div[@class='bcdef']/span/@hahahaha

Once you locate the tag, simply use the attribute name to fetch the value.


问:
How to extract the host name from a git repo URI?
Given a git repository URI Like

```<code>git@company-name.com:/company-name/repo.git
</code>```

or

```<code>https://company-name.com/company-name/repo.git
</code>```

How can I extract company-name.com from them? I am trying to fetch the hostname so I can pass them to a cookbook called ssk_known_hosts.

答:
You can use a Regular Expression to extract the hostname from the url (regex101.com). This expression will match any user and both protocols (http/https).

```<code>[a-zA-Z0-9_]+@(.+?):|https?:\/\/(.+?)\/
</code>```

Usage:

```<code>repo_uri = '...'
repo_host = repo_uri.scan( /[a-zA-Z0-9_]+@(.+?):|https?:\/\/(.+?)\//).last.first
</code>```

Body:
Given a git repository URI Like

git@company-name.com:/company-name/repo.git

or

https://company-name.com/company-name/repo.git

How can I extract company-name.com from them? I am trying to fetch the hostname so I can pass them to a cookbook called ssk_known_hosts.

Body:
You can use a Regular Expression to extract the hostname from the url (regex101.com). This expression will match any user and both protocols (http/https).

[a-zA-Z0-9_]+@(.+?):|https?:\/\/(.+?)\/

Usage:

repo_uri = '...'
repo_host = repo_uri.scan( /[a-zA-Z0-9_]+@(.+?):|https?:\/\/(.+?)\//).last.first


问:
How to reduce the font size according to the length of the header in php?
I've created a form which displays header in the starting of the page.if the length of the header is larger it displays two lines and it looks bad, so please tell me is there any way to reduce the font size according to the length of the header.</p>

答:
First methode : You can use media-queries :

```<code>@media screen and (max-device-width : 320px)
{
  body or yourdiv element
  {
    font:<size>px/em/cm;
  }
}
@media screen and (max-device-width : 1204px)
{
  body or yourdiv element
  {
    font:<size>px/em/cm;
  }
}
</code>```

Second methode : You can give it manually according to screen size of screen.Just have a look of different screen size and add manually the font size.

Then, You can use em or %. Also, CSS3 have some new values for sizing things relative to the current viewport size: vw, vh, and vmin. See link about that.

Body:
First methode : You can use media-queries :

@media screen and (max-device-width : 320px)
{
  body or yourdiv element
  {
    font:<size>px/em/cm;
  }
}
@media screen and (max-device-width : 1204px)
{
  body or yourdiv element
  {
    font:<size>px/em/cm;
  }
}

Second methode : You can give it manually according to screen size of screen.Just have a look of different screen size and add manually the font size.

Then, You can use em or %. Also, CSS3 have some new values for sizing things relative to the current viewport size: vw, vh, and vmin. See link about that.


问:
How to use native c++ in android code?
i have a native class for C++ . but it use in my java class or activity.also give me inform for a hoe to use library of it.

Blockquote

答:
You'll need to read up on Android NDK.

The Android NDK is a toolset that lets you implement parts of your app using native-code languages such as C and C++. For certain types of apps, this can help you reuse code libraries written in those languages.

For more info, check out this link:
https://developer.android.com/ndk/index.html

Title: How to use native c++ in android code?


问:
Converting several bytes in an array to another type in Go
I just started yesterday with Go so I apologise in advance for the silly question.

Imagine that I have a byte array such as:

```<code>func main(){
    arrayOfBytes := [10]byte{1,2,3,4,5,6,7,8,9,10}
}
</code>```

Now what if I felt like taking the first four bytes of that array and using it as an integer? Or perhaps I have a struct that looks like this:

```<code>type eightByteType struct {
    a uint32
    b uint32
}
</code>```

Can I easily take the first 8 bytes of my array and turn it into an object of type eightByteType?

I realise these are two different questions but I think they may have similar answers. I've looked through the documentation and haven't seen a good example to achieve this.

Being able to cast a block of bytes to anything is one of the things I really like about C. Hopefully I can still do it in Go.

答:
Look at encoding/binary, as well as bytes.Buffer

TL;DR version:

```<code>import (
    "encoding/binary"
    "bytes"
)

func main() {
    var s eightByteType
    binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &s)
}
</code>```

A few things to note here: we pass array[:], alternatively you could declare your array as a slice instead ([]byte{1, 2, 3, 4, 5}) and let the compiler worry about sizes, etc, and eightByteType won't work as is (IIRC) because binary.Read won't touch private fields. This would work:

```<code>type eightByteType struct {
    A, B uint32
}
</code>```

Body:
I just started yesterday with Go so I apologise in advance for the silly question.

Imagine that I have a byte array such as:

func main(){
    arrayOfBytes := [10]byte{1,2,3,4,5,6,7,8,9,10}
}

Now what if I felt like taking the first four bytes of that array and using it as an integer? Or perhaps I have a struct that looks like this:

type eightByteType struct {
    a uint32
    b uint32
}

Can I easily take the first 8 bytes of my array and turn it into an object of type eightByteType?

I realise these are two different questions but I think they may have similar answers. I've looked through the documentation and haven't seen a good example to achieve this.

Being able to cast a block of bytes to anything is one of the things I really like about C. Hopefully I can still do it in Go.

Body:
Look at encoding/binary, as well as bytes.Buffer

TL;DR version:

import (
    "encoding/binary"
    "bytes"
)

func main() {
    var s eightByteType
    binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &s)
}

A few things to note here: we pass array[:], alternatively you could declare your array as a slice instead ([]byte{1, 2, 3, 4, 5}) and let the compiler worry about sizes, etc, and eightByteType won't work as is (IIRC) because binary.Read won't touch private fields. This would work:

type eightByteType struct {
    A, B uint32
}


问:
How to send a file from one email to another email id in PHP?
I have PHP code where i code for sending attached file via email from one email id to another email id, But the name ,message ,email_id all send but not attached file sended.

```<code><?php

   $name=$_REQUEST['name'];
   $email_id=$_REQUEST['email_id'];
   $message=$_REQUEST['message'];
   $attached_file=$_REQUEST['attached_file'];
   $name= mysql_real_escape_string($name);
   $email_id = mysql_real_escape_string($email_id);
   if(isset($_REQUEST['submit']))
   {
    $sql="select * from user where BINARY name = BINARY '$name' AND
     BINARY email_id = BINARY '$email_id' and status='1'";
   $qex=mysql_query($sql);
   $numrow=mysql_num_rows($qex);
   $res=mysql_fetch_array($qex);
   if($numrow==1)
  {
    $_SESSION['name']=$res['name'];
   $_SESSION['email_id']=$res['email_id'];

        $email_to .= "nehamitta919@gmail.com";
        $email_subject="A user send Tariffs file to their Client";
        $email_from="neha@studioscue.in";

        $email_message = "User Attached File Successfully send     ".$time."\n\n";

        $email_message .= "User Name  : ".$name."\n\n";
        $email_message .= "User Email: ".$email_id."\n\n";
        $email_message .= "User Message: ".$message."\n\n";
        $email_message .= "User Send File: ".$attached_file."\n\n";

        $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);

        ?>
</code>```

html code :

```<code><form class="form-horizontal" method="post" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-4 control-label">User name</font></label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="inputEmail3" placeholder="Name" required
                                name="name" value="<?Php echo $uvw['name']; ?>">
                            </div>
                            </div>
                        </div>
                    </div><!----row-------->
                    <br>
                    <br>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-4 control-label">User Email Id<br><strong>(Send From)</strong></font></label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="inputEmail3" ng-model="email_id" placeholder="email" required
                            name="email_id" value="<?Php echo $uvw['email_id']; ?>">
                        </div>
                        </div>
                    </div>
                </div><!----row-------->
                <br>
                <br>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-4 control-label">Send To</font></label>
                    <div class="col-sm-4">
                        <select required class="form-control" id="client_id" name="client_id" ng-model="client_id">
                                          <option required="required" selected="" hidden="" value="">Select Your Client Email Id</option>
                                           <?php
                        $id= $_SESSION['id'];
                        $qex = mysql_query("select * from client where status!='4' and status!='0' and client.user_id='$id'");
                                            while ($res = mysql_fetch_array($qex)) {
                                                ?>
                                                <option value="<?php echo trim($res['group_id']); ?>">
                                                    <?php
                                                    echo trim($res['group_id']);
                                                    ?>
                                                </option>
                                            <?php }
                                            ?>

                    </select>
                </div>
                </div>
            </div>
        </div><!----row-------->
        <br />
        <br />
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="inputEmail3" class="col-sm-4 control-label">Message</font></label>
                <div class="col-sm-4">
                    <textarea class="form-control" id="inputEmail3" placeholder="Message" required style="height: 50px;"
                    name="message"></textarea>
                </div>
                </div>
            </div>
        </div><!----row-------->
        <br>
        <br>
    <div class="row"
        <div class="col-md-12">
            <div class="form-group">
                <label for="inputEmail3" class="img-rounded col-sm-4 control-label animate-css-css" >Attach File</font></label>
            <div class="col-sm-3">
                <input type="file"name="attached_file" id="attached_file" required>
            </div>
            </div>
        </div><!----row-------->
        <br>
        <br />
    <div class="form-group">
        <div class="col-sm-offset-5 col-sm-5">
            <button type="submit" class="btn btn-primary col-md-5" name="submit">Send File</button>
        </div>

    </div>
            </form>
</code>```

Please check & reply me. what am i missing.
Thanks & Regards
Ankit

答:
u must be use phpmailer
https://github.com/PHPMailer/PHPMailer</p>

```<code>$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "mail.example.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "yourname@example.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('from@example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto@example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('whoto@example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images              to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
   } else {
    echo "Message sent!";
   }
</code>```

Body:
I have PHP code where i code for sending attached file via email from one email id to another email id, But the name ,message ,email_id all send but not attached file sended.

<?php

   $name=$_REQUEST['name'];
   $email_id=$_REQUEST['email_id'];
   $message=$_REQUEST['message'];
   $attached_file=$_REQUEST['attached_file'];
   $name= mysql_real_escape_string($name);
   $email_id = mysql_real_escape_string($email_id);
   if(isset($_REQUEST['submit']))
   {
    $sql="select * from user where BINARY name = BINARY '$name' AND
     BINARY email_id = BINARY '$email_id' and status='1'";
   $qex=mysql_query($sql);
   $numrow=mysql_num_rows($qex);
   $res=mysql_fetch_array($qex);
   if($numrow==1)
  {
    $_SESSION['name']=$res['name'];
   $_SESSION['email_id']=$res['email_id'];

        $email_to .= "nehamitta919@gmail.com";
        $email_subject="A user send Tariffs file to their Client";
        $email_from="neha@studioscue.in";

        $email_message = "User Attached File Successfully send     ".$time."\n\n";

        $email_message .= "User Name  : ".$name."\n\n";
        $email_message .= "User Email: ".$email_id."\n\n";
        $email_message .= "User Message: ".$message."\n\n";
        $email_message .= "User Send File: ".$attached_file."\n\n";

        $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);

        ?>

html code :

<form class="form-horizontal" method="post" enctype="multipart/form-data">

                                User name

                                <input type="text" class="form-control" id="inputEmail3" placeholder="Name" required
                                name="name" value="<?Php echo $uvw['name']; ?>">

                            User Email Id
(Send From)

                            <input type="text" class="form-control" id="inputEmail3" ng-model="email_id" placeholder="email" required
                            name="email_id" value="<?Php echo $uvw['email_id']; ?>">

                        Send To

                        <select required class="form-control" id="client_id" name="client_id" ng-model="client_id">
                                          <option required="required" selected="" hidden="" value="">Select Your Client Email Id</option>
                                           <?php
                        $id= $_SESSION['id'];
                        $qex = mysql_query("select * from client where status!='4' and status!='0' and client.user_id='$id'");
                                            while ($res = mysql_fetch_array($qex)) {
                                                ?>
                                                <option value="<?php echo trim($res['group_id']); ?>">
                                                    <?php
                                                    echo trim($res['group_id']);
                                                    ?>
                                                </option>
                                            <?php }
                                            ?>

                    </select>

                    Message

                    <textarea class="form-control" id="inputEmail3" placeholder="Message" required style="height: 50px;"
                    name="message"></textarea>

    <div class="row"

                Attach File

                <input type="file"name="attached_file" id="attached_file" required>

            <button type="submit" class="btn btn-primary col-md-5" name="submit">Send File</button>

            </form>

Please check & reply me. what am i missing.
Thanks & Regards
Ankit

Body:
u must be use phpmailer
https://github.com/PHPMailer/PHPMailer

$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "mail.example.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "yourname@example.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('from@example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto@example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('whoto@example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images              to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
   } else {
    echo "Message sent!";
   }


问:
Using Jackson to dynamically serialize an entity as either its ID or its full representation at runtime
We're developing a RESTful API using Java EE 7 (RESTEasy / Hibernate / Jackson).

We want the API to serialize all child entities using their IDs, by default. We're doing this mostly to maintain consistency with our deserialization strategy, where we insist on receiving an ID.

However, we also want our users to be able to choose to get an expanded view of any of our child entities, either through a custom endpoint or a query parameter (undecided). For example:

```<code>// http://localhost:8080/rest/operator/1
// =====================================
{
    "operatorId": 1,
    "organization": 34,
    "endUser": 23
}

// http://localhost:8080/rest/operator/1?expand=organization
// =====================================
{
    "operatorId": 1,
    "organization": {
        "organizationId": 34,
        "organizationName": "name"
    },
    "endUser": 23
}

// http://localhost:8080/rest/operator/1?expand=enduser
// =====================================
{
    "operatorId": 1,
    "organization": 34,
    "endUser": {
        "endUserId": 23,
        "endUserName": "other name"
    }
}

// http://localhost:8080/rest/operator/1?expand=organization,enduser
// =====================================
{
    "operatorId": 1,
    "organization": {
        "organizationId": 34,
        "organizationName": "name"
    },
    "endUser": {
        "endUserId": 23,
        "endUserName": "other name"
    }
}
</code>```

Is there a way to dynamically change the behavior of Jackson to determine whether a specified AbstractEntity field is serialized in full form or as its ID? How might it be done?

Additional Info

We know of a few ways to serialize our child entities using their IDs, including:

```<code>public class Operator extends AbstractEntity {
    ...
    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="organizationId")
    @JsonIdentityReference(alwaysAsId=true)
    public getOrganization() { ... }
    ...
}
</code>```

and

```<code>public class Operator extends AbstractEntity {
    ...
    @JsonSerialize(using=AbstractEntityIdSerializer.class)
    public getOrganization() { ... }
    ...
}
</code>```

where AbstractEntityIdSerializer serializes the entity using its ID.

The problem is that we don't know of a way for the user to override that default behavior and revert to standard Jackson object serialization. Ideally they'd also be able to choose which child properties to serialize in full form.

It would be awesome to dynamically toggle the alwaysAsId argument of @JsonIdentityReference for any property at runtime, if that's possible, or make the equivalent change to ObjectMapper/ObjectWriter.

Update: Working(?) Solution
We haven't had a chance to fully test this yet, but I've been working on a solution that leverages overriding Jackson's AnnotationIntrospector class. It seems to be working as intended.

```<code>public class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {
    private final Set<String> expandFieldNames_;

    public CustomAnnotationIntrospector(Set<String> expandFieldNames) {
        expandFieldNames_ = expandFieldNames;
    }

    @Override
    public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo) {
        JsonIdentityReference ref = _findAnnotation(ann, JsonIdentityReference.class);
        if (ref != null) {

            for (String expandFieldName : expandFieldNames_) {
                String expandFieldGetterName = "get" + expandFieldName;
                String propertyName = ann.getName();

                boolean fieldNameMatches = expandFieldName.equalsIgnoreCase(propertyName);
                boolean fieldGetterNameMatches = expandFieldGetterName.equalsIgnoreCase(propertyName);

                if (fieldNameMatches || fieldGetterNameMatches) {
                    return objectIdInfo.withAlwaysAsId(false);
                }
            }

            objectIdInfo = objectIdInfo.withAlwaysAsId(ref.alwaysAsId());
        }

        return objectIdInfo;
    }
}
</code>```

At serialization time, we copy our ObjectMapper (so the AnnotationIntrospector runs again) and apply CustomAnnotationIntrospector as follows:

```<code>@Context
private HttpRequest httpRequest_;

@Override
writeTo(...) {
    // Get our application's ObjectMapper.
    ContextResolver<ObjectMapper> objectMapperResolver = provider_.getContextResolver(ObjectMapper.class,
                                                                                MediaType.WILDCARD_TYPE);
    ObjectMapper objectMapper = objectMapperResolver.getContext(Object.class);

    // Get Set of fields to be expanded (pre-parsed).
    Set<String> fieldNames = (Set<String>)httpRequest_.getAttribute("ExpandFields");

    if (!fieldNames.isEmpty()) {
        // Pass expand fields to AnnotationIntrospector.
        AnnotationIntrospector expansionAnnotationIntrospector = new CustomAnnotationIntrospector(fieldNames);

        // Replace ObjectMapper with copy of ObjectMapper and apply custom AnnotationIntrospector.
        objectMapper = objectMapper.copy();
        objectMapper.setAnnotationIntrospector(expansionAnnotationIntrospector);
    }

    ObjectWriter objectWriter = objectMapper.writer();
    objectWriter.writeValue(...);
}
</code>```

Any glaring flaws in this approach? It seems relatively straightforward and is fully dynamic.

答:
The answer is Jackson's mixin feature:

You create a simple Java class that has the exact same method signature as the anotated method of the entity. You annotate that method with the modified value. the body of the method is insignificant (it would not be called):

```<code>public class OperatorExpanded {
    ...
    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="organizationId")
    @JsonIdentityReference(alwaysAsId=false)
    public Organization getOrganization() { return null; }
    ...
}
</code>```

you tie the mixin to the entity-to-be-serialized using Jackson's module system: this can be decided at run time

```<code>ObjectMapper mapper = new ObjectMapper();
if ("organization".equals(request.getParameter("exapnd")) {
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.setMixInAnnotation(Operator.class, OperatorExpanded.class);
    mapper.registerModule(simpleModule);
}
</code>```

now, the mapper will take the annotations from the mixin, but invoke the method of the entity.

Body:
We're developing a RESTful API using Java EE 7 (RESTEasy / Hibernate / Jackson).

We want the API to serialize all child entities using their IDs, by default. We're doing this mostly to maintain consistency with our deserialization strategy, where we insist on receiving an ID.

However, we also want our users to be able to choose to get an expanded view of any of our child entities, either through a custom endpoint or a query parameter (undecided). For example:

// http://localhost:8080/rest/operator/1
// =====================================
{
    "operatorId": 1,
    "organization": 34,
    "endUser": 23
}

// http://localhost:8080/rest/operator/1?expand=organization
// =====================================
{
    "operatorId": 1,
    "organization": {
        "organizationId": 34,
        "organizationName": "name"
    },
    "endUser": 23
}

// http://localhost:8080/rest/operator/1?expand=enduser
// =====================================
{
    "operatorId": 1,
    "organization": 34,
    "endUser": {
        "endUserId": 23,
        "endUserName": "other name"
    }
}

// http://localhost:8080/rest/operator/1?expand=organization,enduser
// =====================================
{
    "operatorId": 1,
    "organization": {
        "organizationId": 34,
        "organizationName": "name"
    },
    "endUser": {
        "endUserId": 23,
        "endUserName": "other name"
    }
}

Is there a way to dynamically change the behavior of Jackson to determine whether a specified AbstractEntity field is serialized in full form or as its ID? How might it be done?

Additional Info

We know of a few ways to serialize our child entities using their IDs, including:

public class Operator extends AbstractEntity {
    ...
    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="organizationId")
    @JsonIdentityReference(alwaysAsId=true)
    public getOrganization() { ... }
    ...
}

and

public class Operator extends AbstractEntity {
    ...
    @JsonSerialize(using=AbstractEntityIdSerializer.class)
    public getOrganization() { ... }
    ...
}

where AbstractEntityIdSerializer serializes the entity using its ID.

The problem is that we don't know of a way for the user to override that default behavior and revert to standard Jackson object serialization. Ideally they'd also be able to choose which child properties to serialize in full form.

It would be awesome to dynamically toggle the alwaysAsId argument of @JsonIdentityReference for any property at runtime, if that's possible, or make the equivalent change to ObjectMapper/ObjectWriter.

Update: Working(?) Solution
We haven't had a chance to fully test this yet, but I've been working on a solution that leverages overriding Jackson's AnnotationIntrospector class. It seems to be working as intended.

public class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {
    private final Set<String> expandFieldNames_;

    public CustomAnnotationIntrospector(Set<String> expandFieldNames) {
        expandFieldNames_ = expandFieldNames;
    }

    @Override
    public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo) {
        JsonIdentityReference ref = _findAnnotation(ann, JsonIdentityReference.class);
        if (ref != null) {

            for (String expandFieldName : expandFieldNames_) {
                String expandFieldGetterName = "get" + expandFieldName;
                String propertyName = ann.getName();

                boolean fieldNameMatches = expandFieldName.equalsIgnoreCase(propertyName);
                boolean fieldGetterNameMatches = expandFieldGetterName.equalsIgnoreCase(propertyName);

                if (fieldNameMatches || fieldGetterNameMatches) {
                    return objectIdInfo.withAlwaysAsId(false);
                }
            }

            objectIdInfo = objectIdInfo.withAlwaysAsId(ref.alwaysAsId());
        }

        return objectIdInfo;
    }
}

At serialization time, we copy our ObjectMapper (so the AnnotationIntrospector runs again) and apply CustomAnnotationIntrospector as follows:

@Context
private HttpRequest httpRequest_;

@Override
writeTo(...) {
    // Get our application's ObjectMapper.
    ContextResolver<ObjectMapper> objectMapperResolver = provider_.getContextResolver(ObjectMapper.class,
                                                                                MediaType.WILDCARD_TYPE);
    ObjectMapper objectMapper = objectMapperResolver.getContext(Object.class);

    // Get Set of fields to be expanded (pre-parsed).
    Set<String> fieldNames = (Set<String>)httpRequest_.getAttribute("ExpandFields");

    if (!fieldNames.isEmpty()) {
        // Pass expand fields to AnnotationIntrospector.
        AnnotationIntrospector expansionAnnotationIntrospector = new CustomAnnotationIntrospector(fieldNames);

        // Replace ObjectMapper with copy of ObjectMapper and apply custom AnnotationIntrospector.
        objectMapper = objectMapper.copy();
        objectMapper.setAnnotationIntrospector(expansionAnnotationIntrospector);
    }

    ObjectWriter objectWriter = objectMapper.writer();
    objectWriter.writeValue(...);
}

Any glaring flaws in this approach? It seems relatively straightforward and is fully dynamic.

Body:
The answer is Jackson's mixin feature:

You create a simple Java class that has the exact same method signature as the anotated method of the entity. You annotate that method with the modified value. the body of the method is insignificant (it would not be called):

public class OperatorExpanded {
    ...
    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="organizationId")
    @JsonIdentityReference(alwaysAsId=false)
    public Organization getOrganization() { return null; }
    ...
}

you tie the mixin to the entity-to-be-serialized using Jackson's module system: this can be decided at run time

ObjectMapper mapper = new ObjectMapper();
if ("organization".equals(request.getParameter("exapnd")) {
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.setMixInAnnotation(Operator.class, OperatorExpanded.class);
    mapper.registerModule(simpleModule);
}

now, the mapper will take the annotations from the mixin, but invoke the method of the entity.


问:
Looping through Pandas dataframes by addressing those with a variable
I am trying to do a set of repetitive operations on a set of similar dataframes (in this example, converting strings of timestamps to datetime objects).
My original dataframe:

```<code>     Date_assetA  assetA    Date_assetB  assetB    Date_assetC  assetC  \
0  06/09/16 8:00  4629.0  06/09/16 5:50   208.2  06/09/16 5:50  209.05
1  06/09/16 8:10  4629.5  06/09/16 6:00   208.0  06/09/16 6:00  208.85
2  06/09/16 8:20  4630.0  06/09/16 6:10   208.1  06/09/16 6:10  208.95
3  06/09/16 8:30  4632.5  06/09/16 6:20   208.1  06/09/16 6:20  208.95
4  06/09/16 8:40  4630.5  06/09/16 6:30   208.1  06/09/16 6:30  208.95

   Date_assetD  assetD
0  06/09/16 5:50  209.70
1  06/09/16 6:00  209.50
2  06/09/16 6:10  209.60
3  06/09/16 6:50  209.55
4  06/09/16 7:10  209.65
</code>```

I build four independant DataFrames from the initial one, as i will need to align those after converting the Date_assetX columns to timestamps. I want to loop through those by adressing them using the list of assets. Here is my code, with the missing part. Any attempt as concatenating a name of df_assetX failed so far:

```<code>import pandas as pd

df = pd.read_csv('example.csv')

df_assetA = df[['Date_assetA', 'assetA']]
df_assetB = df[['Date_assetB', 'assetB']]
df_assetC = df[['Date_assetC', 'assetC']]
df_assetD = df[['Date_assetD', 'assetD']]

contract_list = ['assetA', 'assetB', 'assetC', 'assetD']
for contract in contract_list:
    date_column = 'Date_' + str(contract)
    df_contract = # That's the part where i'm stuck...
    df_contract.date_column = pd.to_datetime(df_contract.date_column, dayfirst=True)
</code>```

Is there something obvious i'm missing, or is the whole approach botched  and i should try the dictionary route instead ?

Thanks,

答:
I used a dictionary instead. Surely this code can be improved to build the dictionary using loops, but for my current needs, it'll cut it for now.</p>

```<code>import pandas as pd

df = pd.read_csv('example.csv')

df_assetA = df[['Date_assetA', 'assetA']]
df_assetB = df[['Date_assetB', 'assetB']]
df_assetC = df[['Date_assetC', 'assetC']]
df_assetD = df[['Date_assetD', 'assetD']]

dico = {'assetA':df_assetA,
        'assetB':df_assetB,
        'assetC':df_assetC,
        'assetD':df_assetD}

for contract, df_contract in dico.items():
    Date_contract = 'Date_' + contract
    df_contract[Date_contract] = pd.to_datetime(df_contract[Date_contract], dayfirst=True)
    print df_contract.head()
</code>```

Body:
I am trying to do a set of repetitive operations on a set of similar dataframes (in this example, converting strings of timestamps to datetime objects).
My original dataframe:

     Date_assetA  assetA    Date_assetB  assetB    Date_assetC  assetC  \
0  06/09/16 8:00  4629.0  06/09/16 5:50   208.2  06/09/16 5:50  209.05
1  06/09/16 8:10  4629.5  06/09/16 6:00   208.0  06/09/16 6:00  208.85
2  06/09/16 8:20  4630.0  06/09/16 6:10   208.1  06/09/16 6:10  208.95
3  06/09/16 8:30  4632.5  06/09/16 6:20   208.1  06/09/16 6:20  208.95
4  06/09/16 8:40  4630.5  06/09/16 6:30   208.1  06/09/16 6:30  208.95

   Date_assetD  assetD
0  06/09/16 5:50  209.70
1  06/09/16 6:00  209.50
2  06/09/16 6:10  209.60
3  06/09/16 6:50  209.55
4  06/09/16 7:10  209.65

I build four independant DataFrames from the initial one, as i will need to align those after converting the Date_assetX columns to timestamps. I want to loop through those by adressing them using the list of assets. Here is my code, with the missing part. Any attempt as concatenating a name of df_assetX failed so far:

import pandas as pd

df = pd.read_csv('example.csv')

df_assetA = df[['Date_assetA', 'assetA']]
df_assetB = df[['Date_assetB', 'assetB']]
df_assetC = df[['Date_assetC', 'assetC']]
df_assetD = df[['Date_assetD', 'assetD']]

contract_list = ['assetA', 'assetB', 'assetC', 'assetD']
for contract in contract_list:
    date_column = 'Date_' + str(contract)
    df_contract = # That's the part where i'm stuck...
    df_contract.date_column = pd.to_datetime(df_contract.date_column, dayfirst=True)

Is there something obvious i'm missing, or is the whole approach botched  and i should try the dictionary route instead ?

Thanks,

Body:
I used a dictionary instead. Surely this code can be improved to build the dictionary using loops, but for my current needs, it'll cut it for now.

import pandas as pd

df = pd.read_csv('example.csv')

df_assetA = df[['Date_assetA', 'assetA']]
df_assetB = df[['Date_assetB', 'assetB']]
df_assetC = df[['Date_assetC', 'assetC']]
df_assetD = df[['Date_assetD', 'assetD']]

dico = {'assetA':df_assetA,
        'assetB':df_assetB,
        'assetC':df_assetC,
        'assetD':df_assetD}

for contract, df_contract in dico.items():
    Date_contract = 'Date_' + contract
    df_contract[Date_contract] = pd.to_datetime(df_contract[Date_contract], dayfirst=True)
    print df_contract.head()


问:
how do you import mapbox-gl-draw using webpack?
I am using create-react-app and trying to install mapbox-gl-draw.

```<code>npm install @mapbox/mapbox-gl-draw
</code>```

This works with some npm warnings. I then try to pull mapbox-gl-draw into a component like this:

```<code>import React,{Component} from 'react';
import mapboxgl from 'mapbox-gl/dist/mapbox-gl.js';
import ReactMapboxGl from 'react-mapbox-gl';
import MapboxDraw from '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw'

console.log(MapboxDraw)
</code>```

I just get an empty object.

I am using create-react-app. Do I need to use a different webpack .config file.

What is the best way to import mapbox modules like this?

答:
If you're using webpack, you need to alias to use mapbox-gl dist file, here is how I have done it using webpack2:

```<code>    resolve: {
      modules: ['src', 'node_modules'],
      extensions: ['.js', '.jsx', '.json', '.css', '.svg'],
      alias: {
        // mapbox-gl related packages in webpack should use dist instead of the default src
        '@mapbox/mapbox-gl-draw': path.resolve(root, 'node_modules/@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.js'),
      },
    },
</code>```

Variable "root" was defined earlier in the file to refer to the root directory of the project, on the same level as package.json etc.

The same problem can happen in react-map-gl-alt where you need to alias 'mapbox' to 'node_modules/mapbox/dist/distfilehere.js'.

Body:
I am using create-react-app and trying to install mapbox-gl-draw.

npm install @mapbox/mapbox-gl-draw

This works with some npm warnings. I then try to pull mapbox-gl-draw into a component like this:

import React,{Component} from 'react';
import mapboxgl from 'mapbox-gl/dist/mapbox-gl.js';
import ReactMapboxGl from 'react-mapbox-gl';
import MapboxDraw from '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw'

console.log(MapboxDraw)

I just get an empty object.

I am using create-react-app. Do I need to use a different webpack .config file.

What is the best way to import mapbox modules like this?

Body:
If you're using webpack, you need to alias to use mapbox-gl dist file, here is how I have done it using webpack2:

    resolve: {
      modules: ['src', 'node_modules'],
      extensions: ['.js', '.jsx', '.json', '.css', '.svg'],
      alias: {
        // mapbox-gl related packages in webpack should use dist instead of the default src
        '@mapbox/mapbox-gl-draw': path.resolve(root, 'node_modules/@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.js'),
      },
    },

Variable "root" was defined earlier in the file to refer to the root directory of the project, on the same level as package.json etc.

The same problem can happen in react-map-gl-alt where you need to alias 'mapbox' to 'node_modules/mapbox/dist/distfilehere.js'.


问:
How to inject dispatch into functional React Component?
I need to dispatch an action when an item is clicked within my component. However, I am getting dispatch is undefined when the attendHandler is fired. How do I properly pass dispatch to a component?

This is my action. I am using thunk, so I'm actually return a dispatch.

export function attendEvent(token) {
  const config = {
    headers: { Authorization: token },
  };
  console.log(config);
  return dispatch => axios.post('api/events', config)
  .then((response) => {
    dispatch({ type: 'ATTEND EVENT SUCCESSFUL', payload: response.data });
  })
  .catch((err) => {
    dispatch({ type: 'ATTEND EVENT UNSUCCESSFUL', payload: 'Could not attend event' });
  });
}```
</div>
</div>
</p>

<p>This is my component
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    import React from 'react';
    import { connect } from 'react-redux';
    import attendEvent from '../actions/eventActions';
    import check from '../assets/hatch_complete.svg';
    import crossout from '../assets/hatch_multiply.svg';

    const Event = (props) => {
      const attendHandler = (e) => {
        e.preventDefault();
        dispatch(attendEvent({
          token: window.localStorage.getItem('token'),
        }));
      };
      return (
        <div className="event">
          <section className="eventdescription">
            <p>{props.title}</p>
            <p>{props.description}</p>
            <p>{props.date}</p>
            <p>{props.owner}</p>
            <p>{props.attendees}</p>
            <p>{props.capacity}</p>
            <p>Attend / unattend</p>
          </section>
          <section className="attend"><img onClick={attendHandler}className="eventgraphic" src={check} alt="" /></section>
          <section className="unattend"><img className="eventgraphic" src={crossout} alt="" /></section>
        </div>
      );
    };

    export default connect(state => ({
      events: state.event.events,
    }))(Event);</code>```

This is my store, in case it is needed for reference. I do not mapDispatchToProps, perhaps that is my problem.

import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

export default createStore(rootReducer, applyMiddleware(thunk, createLogger()));```

答:
You need to export your action as default and then call the dispatch on props as connect provides dispatch as props.

```<code>export default function attendEvent(token) {
  const config = {
    headers: { Authorization: token },
  };
  console.log(config);
  return dispatch => axios.post('api/events', config)
  .then((response) => {
    dispatch({ type: 'ATTEND EVENT SUCCESSFUL', payload: response.data });
  })
  .catch((err) => {
    dispatch({ type: 'ATTEND EVENT UNSUCCESSFUL', payload: 'Could not attend event' });
  });
}

const Event = (props) => {
      const attendHandler = (e) => {
        e.preventDefault();
        props.dispatch(attendEvent({
          token: window.localStorage.getItem('token'),
        }));
      };
      return (
        <div className="event">
          <section className="eventdescription">
            <p>{props.title}</p>
            <p>{props.description}</p>
            <p>{props.date}</p>
            <p>{props.owner}</p>
            <p>{props.attendees}</p>
            <p>{props.capacity}</p>
            <p>Attend / unattend</p>
          </section>
          <section className="attend"><img onClick={attendHandler}className="eventgraphic" src={check} alt="" /></section>
          <section className="unattend"><img className="eventgraphic" src={crossout} alt="" /></section>
        </div>
      );
    };

    export default connect(state => ({
      events: state.event.events,
    }))(Event);
</code>```

Body:
I need to dispatch an action when an item is clicked within my component. However, I am getting dispatch is undefined when the attendHandler is fired. How do I properly pass dispatch to a component?

This is my action. I am using thunk, so I'm actually return a dispatch.

export function attendEvent(token) {
  const config = {
    headers: { Authorization: token },
  };
  console.log(config);
  return dispatch => axios.post('api/events', config)
  .then((response) => {
    dispatch({ type: 'ATTEND EVENT SUCCESSFUL', payload: response.data });
  })
  .catch((err) => {
    dispatch({ type: 'ATTEND EVENT UNSUCCESSFUL', payload: 'Could not attend event' });
  });
}

This is my component

    import React from 'react';
    import { connect } from 'react-redux';
    import attendEvent from '../actions/eventActions';
    import check from '../assets/hatch_complete.svg';
    import crossout from '../assets/hatch_multiply.svg';

    const Event = (props) => {
      const attendHandler = (e) => {
        e.preventDefault();
        dispatch(attendEvent({
          token: window.localStorage.getItem('token'),
        }));
      };
      return (

{props.title}

{props.description}

{props.date}

{props.owner}

{props.attendees}

{props.capacity}

Attend / unattend

      );
    };

    export default connect(state => ({
      events: state.event.events,
    }))(Event);

This is my store, in case it is needed for reference. I do not mapDispatchToProps, perhaps that is my problem.

import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

export default createStore(rootReducer, applyMiddleware(thunk, createLogger()));

Body:
You need to export your action as default and then call the dispatch on props as connect provides dispatch as props.

export default function attendEvent(token) {
  const config = {
    headers: { Authorization: token },
  };
  console.log(config);
  return dispatch => axios.post('api/events', config)
  .then((response) => {
    dispatch({ type: 'ATTEND EVENT SUCCESSFUL', payload: response.data });
  })
  .catch((err) => {
    dispatch({ type: 'ATTEND EVENT UNSUCCESSFUL', payload: 'Could not attend event' });
  });
}

const Event = (props) => {
      const attendHandler = (e) => {
        e.preventDefault();
        props.dispatch(attendEvent({
          token: window.localStorage.getItem('token'),
        }));
      };
      return (
        <div className="event">
          <section className="eventdescription">
            <p>{props.title}</p>
            <p>{props.description}</p>
            <p>{props.date}</p>
            <p>{props.owner}</p>
            <p>{props.attendees}</p>
            <p>{props.capacity}</p>
            <p>Attend / unattend</p>
          </section>
          <section className="attend"><img onClick={attendHandler}className="eventgraphic" src={check} alt="" /></section>
          <section className="unattend"><img className="eventgraphic" src={crossout} alt="" /></section>
        </div>
      );
    };

    export default connect(state => ({
      events: state.event.events,
    }))(Event);


问:
What are good grep tools for Windows?
Any recommendations on grep tools for Windows? Ideally ones that could leverage 64-bit OS.

I'm aware of Cygwin, of course, and have also found PowerGREP, but I'm wondering if there are any hidden gems out there?

答:
GrepWin is free and open source (GPL)

I've been using grepWin which was written by one of the TortoiseSVN guys. It does the job on Windows...

OwnerDisplayName: Portman

Title: What are good grep tools for Windows?

LastEditorDisplayName: Portman

ContentLicense: CC BY-SA 4.0


问:
Second CSS class not applying to div
I'm attempting to break my html into separate php files and have an error I can't seem to crack. Here is the first file, index.php

.topheader {
  background-color: #404040;
  color: white;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: white;
  padding: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="./css/main.css">
</head>

<div class="topheader">
  <h1>KivaGIS</h1>
</div>

<div class="footer">
  <h1>Footer</h1>
</div></code>```

As of right now, only .topheader is applying to the html. I understand that both classes are identical, I plan to expand on each once I confirm they are applying individually. Can someone please take a look and advise why .footer wouldn't be applying to the sheet?

Here is a sample of the output on my machine

答:
Check this code once and in your code check once href of your stylesheet.</p>

```<code><!DOCTYPE html>
<html>
<head>
 <style>
.topheader {background-color: #404040;color: white;padding:16px;}
.footer {background-color: #404040;color: white;padding:16px;}
</style>
</head>
<body>
<div class="topheader">
  <h1>KivaGIS</h1>
</div>

<div class="footer">
  <h1>Footer</h1>
</div>
</body>
</code>```

Title: Second CSS class not applying to div

Body:
I'm attempting to break my html into separate php files and have an error I can't seem to crack. Here is the first file, index.php

.topheader {
  background-color: #404040;
  color: white;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: white;
  padding: 16px;
}

  <link rel="stylesheet" href="./css/main.css">

KivaGIS

Footer

As of right now, only .topheader is applying to the html. I understand that both classes are identical, I plan to expand on each once I confirm they are applying individually. Can someone please take a look and advise why .footer wouldn't be applying to the sheet?

Here is a sample of the output on my machine

Body:
Check this code once and in your code check once href of your stylesheet.

<!DOCTYPE html>
<html>
<head>
 <style>
.topheader {background-color: #404040;color: white;padding:16px;}
.footer {background-color: #404040;color: white;padding:16px;}
</style>
</head>
<body>
<div class="topheader">
  <h1>KivaGIS</h1>
</div>

<div class="footer">
  <h1>Footer</h1>
</div>
</body>


问:
Terminal, Editor, Project
I want to write a piece of code, a loop.

So I start:

```<code>for_i. i.10 do.
</code>```

Press "Enter" in order to write a new line, get an error:

```<code>|spelling error
|   for_i. i.10 do.
|   ^
</code>```

So I go to the Editor (one with green code area, Terminal has yellow color).

Write these code, press "run".

But Editor runs code in the Terminal as well. And yes, I get the same error.

I start new project in Editor. Write the code. Press "run project". And??? Nothing. No errors, no results, no anything.

I know that I can wrap this code into function, like

```<code>f =: 3 : 0
   for_i. i.10 do.
   ....
)
</code>```

And it will work.

But why doesn't it work in straightforward way?

Why doesn't it work even in editor?

How to make a code in projects run? And where should I see results?

答:
J's control structures only work in an explicit definition (which is what bob was getting at).

If you want to use them on a single line, you'll need a complete enclosing explicit definition on that line. And if you want results from that line you will also need to provide that definition with an argument to work on.

For example:

verb def 'for_i. i.10 do. echo i end.' 0

Title: Terminal, Editor, Project

Body:
I want to write a piece of code, a loop.

So I start:

for_i. i.10 do.

Press "Enter" in order to write a new line, get an error:

|spelling error
|   for_i. i.10 do.
|   ^

So I go to the Editor (one with green code area, Terminal has yellow color).

Write these code, press "run".

But Editor runs code in the Terminal as well. And yes, I get the same error.

I start new project in Editor. Write the code. Press "run project". And??? Nothing. No errors, no results, no anything.

I know that I can wrap this code into function, like

f =: 3 : 0
   for_i. i.10 do.
   ....
)

And it will work.

But why doesn't it work in straightforward way?

Why doesn't it work even in editor?

How to make a code in projects run? And where should I see results?


问:
how to execute multiple insert statements from HANA at once
I am having a file file.txt which consists of millions of insert commands like below:

```<code>    "INSERT INTO T (id, serial)  VALUES (0, ARRAY (1) );"
    "INSERT INTO T (id, serial)  VALUES (1, ARRAY (1, 2) );"
    "INSERT INTO T (id, serial)  VALUES (2, ARRAY (1, 2, 3, 4, 5) );"
    "INSERT INTO T (id, serial)  VALUES (3, ARRAY (1, 2) ); "
    "INSERT INTO T (id, serial)  VALUES (4, ARRAY (1, 2, 3) );"
.....
.....
.....
</code>```

I want to execute them in HANA using hdbsql or Studio. But how to execute them from the file? Any help is appreciated.

答:
Ideally, the commands shouldn't be enclosed in quotation marks.

Then you can either just run the file as-is in HANA studio (only a good idea if your file is not actually MILLIONS of files, since HANA studio parses the SQL commands first and likely will stall, when there are too many), or you run it via hdbsql with the -I option:

hdbsql -U <your secure store logon key here> -I insert.sql

Thinking about it, the latter method would be the one I would likely go for.

Body:
I am having a file file.txt which consists of millions of insert commands like below:

    "INSERT INTO T (id, serial)  VALUES (0, ARRAY (1) );"
    "INSERT INTO T (id, serial)  VALUES (1, ARRAY (1, 2) );"
    "INSERT INTO T (id, serial)  VALUES (2, ARRAY (1, 2, 3, 4, 5) );"
    "INSERT INTO T (id, serial)  VALUES (3, ARRAY (1, 2) ); "
    "INSERT INTO T (id, serial)  VALUES (4, ARRAY (1, 2, 3) );"
.....
.....
.....

I want to execute them in HANA using hdbsql or Studio. But how to execute them from the file? Any help is appreciated.


问:
Align image in center without getting space
I want to align the logo at the center in the navigation bar of the page.

This is my code:

```<code><div class="nav">
    <ul>
        <li id="center">
           <a href="home.php"><img src="images/w_logo.gif"></a>
        </li>
    </ul>
</div>
</code>```

I have found this solution online:

```<code>#center img{
    display: block;
    margin: auto;
}
</code>```

But the problem is that by using display:block property I am getting space around the image which is increasing the height of my navigation bar and I am not being able to remove that space.

Help would be appreciated.

答:
Try something like the below. This method sets the img to display: inline-block, making it an inline element and allowing it to align center when declaring text-align: center on the parent element.

/*#center img {
  display: block;
  margin: auto;
}*/

#center {
    text-align: center;
}

ul {
    list-style: none;
    margin: auto;
    padding: 0px;
}

.nav {
    background: #ddd;
    border-bottom: 1px solid #bebebe;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul>
    <li id="center">
      <img src="https://placeholdit.imgix.net/~text?txtsize=38&txt=300%C3%97100&w=300&h=100">
    </li>
  </ul>
</div></code>```

The extra space is probably coming from a rogue browser/vendor style somewhere, suspect elements to look at are the ul and li which typically come with default padding & margin rules.

Inspect these elements through your browser developer tool/IDE and have a look at the "box model", or "layout", or "computed styles" depending on the browser you're using.

Body:
I want to align the logo at the center in the navigation bar of the page.

This is my code:

I have found this solution online:

#center img{
    display: block;
    margin: auto;
}

But the problem is that by using display:block property I am getting space around the image which is increasing the height of my navigation bar and I am not being able to remove that space.

Help would be appreciated.

Body:
Try something like the below. This method sets the img to display: inline-block, making it an inline element and allowing it to align center when declaring text-align: center on the parent element.

/*#center img {
  display: block;
  margin: auto;
}*/

#center {
    text-align: center;
}

ul {
    list-style: none;
    margin: auto;
    padding: 0px;
}

.nav {
    background: #ddd;
    border-bottom: 1px solid #bebebe;
}

<div class="nav">
  <ul>
    <li id="center">
      <a href="#"><img src="https://placeholdit.imgix.net/~text?txtsize=38&txt=300%C3%97100&w=300&h=100"></a>
    </li>
  </ul>
</div>

The extra space is probably coming from a rogue browser/vendor style somewhere, suspect elements to look at are the ul and li which typically come with default padding & margin rules.

Inspect these elements through your browser developer tool/IDE and have a look at the "box model", or "layout", or "computed styles" depending on the browser you're using.


问:
BufferedOutputStream not throwing I/O exception
While working on BufferedOutputStream found it does not throw an IOException when we wrote on it after closing the stream.

To verify my result, i checked FileOutputStream found it is throwing IOException once we try to write on it after closing it.

```<code>public class Test {
    public static void main(String[] args) {
        try {
            // Created a byte[] barry1 barry2
            byte[] barry1 = { '1', '3' };
            byte[] barray2 = { '2', '4' };
            OutputStream os = new BufferedOutputStream(
                  new FileOutputStream("abc.txt", false));
            // Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // this suceeds - bug

            os = new FileOutputStream("abc.txt", true);
             //Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // crashes here, correct.
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Could some one help me on this, Why this behavior is different ?

答: After checking the JDK code found that ensureOpen() method that throws an IOException with a detail message of "Stream closed"is missing in BufferedOutputStream. From my understanding this must be there.

Body:
While working on BufferedOutputStream found it does not throw an IOException when we wrote on it after closing the stream.

To verify my result, i checked FileOutputStream found it is throwing IOException once we try to write on it after closing it.

public class Test {
    public static void main(String[] args) {
        try {
            // Created a byte[] barry1 barry2
            byte[] barry1 = { '1', '3' };
            byte[] barray2 = { '2', '4' };
            OutputStream os = new BufferedOutputStream(
                  new FileOutputStream("abc.txt", false));
            // Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // this suceeds - bug

            os = new FileOutputStream("abc.txt", true);
             //Writing to stream
            os.write(barry1);
            os.close();
            os.write(barray2); // crashes here, correct.
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Could some one help me on this, Why this behavior is different ?


问:
How many watchers we can have at max in a single page in an angular applicaiton without affecting the performance?
How many watchers or scope variable can be kept in a page without affecting its performance of the page loading. Whether there is any limit for the scopes which used in terms of number or memory size?</p>

答: There is realy not an answer to this question. The biggest part that affects performance is what you do when the watchers are triggered. If you have logic calculations which loops through large arrays etc then a single watch may demand more then 1000+ simple watchers all together.


问:
How to get list of times between two time in android?
Hi I want to get list of times between two time.

Example 10 PM to 6 AM

Currently i am getting 6 AM to 10 PM but it's not working for 10 PM to 6 AM

Code :

```<code>List<java.sql.Time> intervals = new ArrayList<>();
Calendar calStart = Calendar.getInstance();
calStart.set(calStart.HOUR_OF_DAY, 22);
calStart.set(calStart.MINUTE, 00);
calStart.set(calStart.AM_PM, Calendar.PM);

java.sql.Time startTime = new java.sql.Time(calStart.getTime().getTime());
Calendar calEnd = Calendar.getInstance();
calEnd.set(calEnd.HOUR_OF_DAY, 6);
calEnd.set(calEnd.MINUTE, 00);
calEnd.set(calEnd.AM_PM, Calendar.AM);

java.sql.Time endTime = new java.sql.Time(calEnd.getTime().getTime());
intervals.add(startTime);
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);

while (cal.getTime().after(endTime)) {
     cal.add(Calendar.MINUTE, 15);
     intervals.add(new java.sql.Time(cal.getTimeInMillis()));
}

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
for (java.sql.Time time : intervals) {
    System.out.println(sdf.format(time));
}
</code>```

Please give any suggestion

答:
When going from 10PM to 6AM, make sure you add a day as well. Or else you will have 10PM 29th of March until 6AM 29th of March while you want 6AM 30th of March.</p>

```<code> calendar.add(Calendar.DATE, 1);
</code>```

Body:
Hi I want to get list of times between two time.

Example 10 PM to 6 AM

Currently i am getting 6 AM to 10 PM but it's not working for 10 PM to 6 AM

Code :

List<java.sql.Time> intervals = new ArrayList<>();
Calendar calStart = Calendar.getInstance();
calStart.set(calStart.HOUR_OF_DAY, 22);
calStart.set(calStart.MINUTE, 00);
calStart.set(calStart.AM_PM, Calendar.PM);

java.sql.Time startTime = new java.sql.Time(calStart.getTime().getTime());
Calendar calEnd = Calendar.getInstance();
calEnd.set(calEnd.HOUR_OF_DAY, 6);
calEnd.set(calEnd.MINUTE, 00);
calEnd.set(calEnd.AM_PM, Calendar.AM);

java.sql.Time endTime = new java.sql.Time(calEnd.getTime().getTime());
intervals.add(startTime);
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);

while (cal.getTime().after(endTime)) {
     cal.add(Calendar.MINUTE, 15);
     intervals.add(new java.sql.Time(cal.getTimeInMillis()));
}

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
for (java.sql.Time time : intervals) {
    System.out.println(sdf.format(time));
}

Please give any suggestion

Body:
When going from 10PM to 6AM, make sure you add a day as well. Or else you will have 10PM 29th of March until 6AM 29th of March while you want 6AM 30th of March.

 calendar.add(Calendar.DATE, 1);


问:
Imagebutton.setImageURI(uri) doesn't work
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

```<code>private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

答:
Try this

```<code>Uri imgUri=Uri.parse("android.resource://my.package.name/"+R.drawable.image);
mImageSelect.setImageURI(null);
mImageSelect.setImageURI(imgUri);
</code>```

This is a workaround for refreshing an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

Body:
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}

Body:
Try this

Uri imgUri=Uri.parse("android.resource://my.package.name/"+R.drawable.image);
mImageSelect.setImageURI(null);
mImageSelect.setImageURI(imgUri);

This is a workaround for refreshing an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.


问:
How to convert a PDF into JPG with command line in Linux?
What are fast and reliable ways for converting a PDF into a (single) JPEG using the command line on Linux?</p>

答:
You can try ImageMagick's convert utility.

On Ubuntu, you can install it with this command:

```<code>$ sudo apt-get install imagemagick
</code>```

Use convert like this:

```<code>$ convert input.pdf output.jpg
# For good quality use these parameters
$ convert -density 300 -quality 100 in.pdf out.jpg
</code>```

Body:
You can try ImageMagick's convert utility.

On Ubuntu, you can install it with this command:

$ sudo apt-get install imagemagick

Use convert like this:

$ convert input.pdf output.jpg
# For good quality use these parameters
$ convert -density 300 -quality 100 in.pdf out.jpg


问:
What are the differences between > and space?
What are the differences between these two styles :

```<code>element1 > element2 {
   ...
}
</code>```

and

```<code>element1 element2 {
   ...
}
</code>```

答:
element1 element2 selects all elements inside element1

Example

        As you can see that this paragraph with class `element2` is inside div with class `element1` and so it's catched by css written above.

```
</div>
</div>
</p>

<p>Whereas</p>

<p><code>element1 > element2</code> selects every <code>element2</code> where the parent is a <code>element1</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>
.element1 > .element2{
    color: #2196F3;
    background-color: #FFEB3B;
}
</style>

<div class="element1">
    <p class="element2">
        This paragraph is catched by css above because this paragraph with class `element2` is immediate child of div with class `element1`.
    </p>
</div>

<!--no effect-->
<div class="element1">
   <div class="middleelement">
      <p class="element2">
          This paragraph is <strong>NOT</strong> catched by css written above because it's not immediate child of div with class `element1` because class `middleelement` comes in between. To refer to this paragraph, you have to write css as `.element1 > .middleelement > .element2`
      </p>
   </div>
</div></code>```

Body:
What are the differences between these two styles :

element1 > element2 {
   ...
}

and

element1 element2 {
   ...
}

Body:
element1 element2 selects all elements inside element1

Example

<style>
.element1 .element2{
    color: #2196F3;
    background-color: #FFEB3B;
}
</style>

<div class="element1">
    <p class="element2">
        As you can see that this paragraph with class `element2` is inside div with class `element1` and so it's catched by css written above.
    </p>
</div>

Whereas

element1 > element2 selects every element2 where the parent is a element1

<style>
.element1 > .element2{
    color: #2196F3;
    background-color: #FFEB3B;
}
</style>

<div class="element1">
    <p class="element2">
        This paragraph is catched by css above because this paragraph with class `element2` is immediate child of div with class `element1`.
    </p>
</div>

<!--no effect-->
<div class="element1">
   <div class="middleelement">
      <p class="element2">
          This paragraph is <strong>NOT</strong> catched by css written above because it's not immediate child of div with class `element1` because class `middleelement` comes in between. To refer to this paragraph, you have to write css as `.element1 &gt; .middleelement &gt; .element2`
      </p>
   </div>
</div>


问:
Is pandas' split/stack combo efficiently implemented?
I have a collection of documents that I want to break up into words. This is an example collection:

```<code>In [1]:
import pandas as pd
docs = pd.DataFrame({'docno' : ['doc1', 'doc2'], 'doc' : ['to be or not to be', 'that is the question']})
docs

Out[1]:
   doc                   docno
0  to be or not to be    doc1
1  that is the question  doc2
</code>```

I couldn't find a direct way to "unroll" each row above into a series of rows as below, but have seen that this is done with tolist() and then stack():

```<code>In [2]:
terms = pd.DataFrame(docs.doc.str.split().tolist(), index=docs.docno).stack()
terms = terms.reset_index()[[0, 'docno']]
terms.columns = ['term', 'docno']
terms

Out[2]:
   term      docno
0  to        doc1
1  be        doc1
2  or        doc1
3  not       doc1
4  to        doc1
5  be        doc1
6  that      doc2
7  is        doc2
8  the       doc2
9  question  doc2
</code>```

I suspect that is not optimised so that the stacking is done in conjunction, but rather that an intermediary table of N dimensions (where N is the size of the vocabulary) is written for the split(), before it is being stacked. The documents can be extremely large and so is the vocabulary over the whole document collection. So this seems rather inefficient.
I'm currently doing this transformation for ~5GB collection, which is at the moment using about 2.5TB of RAM (thus far); this seems to confirm my suspicion that the split/stack operations are actually done in series.

My question is: is there a better way to do this?

答:
I think you can use numpy solution - first split column docs, then str.len for get length of lists which are repeated by numpy.repeat with flattening lists:

```<code>from  itertools import chain

docs.doc = docs.doc.str.split()
df1 = pd.DataFrame({
        "docno": np.repeat(docs.docno.values, docs.doc.str.len()),
        "term": list(chain.from_iterable(docs.doc))})[['term','docno']]

print (df1)
       term docno
0        to  doc1
1        be  doc1
2        or  doc1
3       not  doc1
4        to  doc1
5        be  doc1
6      that  doc2
7        is  doc2
8       the  doc2
9  question  doc2
</code>```

Body:
I have a collection of documents that I want to break up into words. This is an example collection:

In [1]:
import pandas as pd
docs = pd.DataFrame({'docno' : ['doc1', 'doc2'], 'doc' : ['to be or not to be', 'that is the question']})
docs

Out[1]:
   doc                   docno
0  to be or not to be    doc1
1  that is the question  doc2

I couldn't find a direct way to "unroll" each row above into a series of rows as below, but have seen that this is done with tolist() and then stack():

In [2]:
terms = pd.DataFrame(docs.doc.str.split().tolist(), index=docs.docno).stack()
terms = terms.reset_index()[[0, 'docno']]
terms.columns = ['term', 'docno']
terms

Out[2]:
   term      docno
0  to        doc1
1  be        doc1
2  or        doc1
3  not       doc1
4  to        doc1
5  be        doc1
6  that      doc2
7  is        doc2
8  the       doc2
9  question  doc2

I suspect that is not optimised so that the stacking is done in conjunction, but rather that an intermediary table of N dimensions (where N is the size of the vocabulary) is written for the split(), before it is being stacked. The documents can be extremely large and so is the vocabulary over the whole document collection. So this seems rather inefficient.
I'm currently doing this transformation for ~5GB collection, which is at the moment using about 2.5TB of RAM (thus far); this seems to confirm my suspicion that the split/stack operations are actually done in series.

My question is: is there a better way to do this?

Body:
I think you can use numpy solution - first split column docs, then str.len for get length of lists which are repeated by numpy.repeat with flattening lists:

from  itertools import chain

docs.doc = docs.doc.str.split()
df1 = pd.DataFrame({
        "docno": np.repeat(docs.docno.values, docs.doc.str.len()),
        "term": list(chain.from_iterable(docs.doc))})[['term','docno']]

print (df1)
       term docno
0        to  doc1
1        be  doc1
2        or  doc1
3       not  doc1
4        to  doc1
5        be  doc1
6      that  doc2
7        is  doc2
8       the  doc2
9  question  doc2


问:
Regex for managing escaped characters for items like string literals
I would like to be able to match a string literal with the option of escaped quotations.
For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:

```<code>import re
regexc = re.compile(r"\'(.*?)(?<!\\)\'")
match = regexc.search(r""" Example: 'Foo \' Bar'  End. """)
print match.groups()
# I want ("Foo \' Bar") to be printed above
</code>```

After looking at this, there is a simple problem that the escape character being used, "\", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:

```<code># ...
re.compile(r"\'(.*?)(?<!\\(\\\\)*)\'")
# ...
</code>```

Any regex gurus able to tackle this problem? Thanks.

答:
Using cletus' expression with Python's re.findall():

```<code>re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'", s)
</code>```

A test finding several matches in a string:

```<code>>>> re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'",
 r"\''foo bar gazonk' foo 'bar' gazonk 'foo \'bar\' gazonk' 'gazonk bar foo\'")
['foo bar gazonk', 'bar', "foo \\'bar\\' gazonk"]
>>>
</code>```

Using cletus' TESTS array of strings:

```<code>["%s => %s" % (s, re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'", s)) for s in TESTS]
</code>```

Works like a charm. (Test it yourself or take my word for it.)

OwnerDisplayName: Evan Fosmark

Body:
I would like to be able to match a string literal with the option of escaped quotations.
For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:

import re
regexc = re.compile(r"\'(.*?)(?<!\\)\'")
match = regexc.search(r""" Example: 'Foo \' Bar'  End. """)
print match.groups()
# I want ("Foo \' Bar") to be printed above

After looking at this, there is a simple problem that the escape character being used, "\", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:

# ...
re.compile(r"\'(.*?)(?<!\\(\\\\)*)\'")
# ...

Any regex gurus able to tackle this problem? Thanks.

Body:
Using cletus' expression with Python's re.findall():

re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'", s)

A test finding several matches in a string:

>>> re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'",
 r"\''foo bar gazonk' foo 'bar' gazonk 'foo \'bar\' gazonk' 'gazonk bar foo\'")
['foo bar gazonk', 'bar', "foo \\'bar\\' gazonk"]
>>>

Using cletus' TESTS array of strings:

["%s => %s" % (s, re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'", s)) for s in TESTS]

Works like a charm. (Test it yourself or take my word for it.)

OwnerDisplayName: PEZ