问:
How do i improve my code to load images from remote server more effiecintly without UI lag?
The adapter provides data for a listview. But when you scroll up and down, it shows old images and takes a couple of seconds to finish loading the images. This is true when you open the view for the first time.</p>

```<code>public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask(imageurl);
        task.execute(imagelink);

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView img;

        ImageAsyncTask(ImageView img) {
            this.img = img;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {
            this.img.setImageBitmap(data);

        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

}
</code>```

答: I will recomend to use Glide for this task and dont invent bicycle. You can just call GlideApp.with(this).load("http://url.com").into(imageView); and Glide will do all work for you.

Body:
The adapter provides data for a listview. But when you scroll up and down, it shows old images and takes a couple of seconds to finish loading the images. This is true when you open the view for the first time.

public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask(imageurl);
        task.execute(imagelink);

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView img;

        ImageAsyncTask(ImageView img) {
            this.img = img;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {
            this.img.setImageBitmap(data);

        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

}


来源: stackexchange

问:
Parse SQL variables with session array in PHP
trying to parse multiple sql variables from one file to another using session arrays but i cant. Whats the part iam missing here?

Thanks in advance.

file1.php

```<code>session_start();
while($row=mysql_fetch_array($result,MYSQL_BOTH)) {
    echo "<tr>";
    $id=$row['id'];
    $array[] = $id;
}
$_SESSION['id'] = $array;
</code>```

file2.php

```<code>session_start();
foreach( $array as $id ) {
    echo $id;
}
</code>```

答:
That's because $array isn't your shared variable. $_SESSION['id'] is what you need to be reading from.

Example (taken from: https://web.archive.org/web/20080707052007/http://www.phpriot.com/articles/intro-php-sessions/7):

Page1.php

```<code><?php
// begin the session
session_start();

// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');

// put the array in a session variable
$_SESSION['animals']=$my_array;

// a little message to say we have done it
echo 'Putting array into a session variable';
?>
</code>```

Page2.php

```<code><?php
// begin the session
session_start();

// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
    {
    // and print out the values
    echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
    }
?>
</code>```

As mentioned in the comments, the echo on page2.php is OTT. A simpler method would be:
echo "Value of {$_SESSION[$key]} is $value
" ; (credit: RiggsFolly)

ContentLicense: CC BY-SA 3.0

Body:
trying to parse multiple sql variables from one file to another using session arrays but i cant. Whats the part iam missing here?

Thanks in advance.

file1.php

session_start();
while($row=mysql_fetch_array($result,MYSQL_BOTH)) {
    echo "
";
    $id=$row['id'];
    $array[] = $id;
}
$_SESSION['id'] = $array;

file2.php

session_start();
foreach( $array as $id ) {
    echo $id;
}

Body:
That's because $array isn't your shared variable. $_SESSION['id'] is what you need to be reading from.

Example (taken from: https://web.archive.org/web/20080707052007/http://www.phpriot.com/articles/intro-php-sessions/7):

Page1.php

<?php
// begin the session
session_start();

// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');

// put the array in a session variable
$_SESSION['animals']=$my_array;

// a little message to say we have done it
echo 'Putting array into a session variable';
?>

Page2.php

<?php
// begin the session
session_start();

// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
    {
    // and print out the values
    echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
    }
?>

As mentioned in the comments, the echo on page2.php is OTT. A simpler method would be:
echo "Value of {$_SESSION[$key]} is $value<br />" ; (credit: RiggsFolly)


问:
how to spread out buttons, they are currently stacked?
I have a bunch of buttons on my page, my html is like:

```<code><div>
  <input ..>
  <input ...>
</dvi>
</code>```

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

答:
Did you say you applied inline to the div? That sets the div to display inline, but I think what you want is for the inputs to display inline. try:

```<code>div input {
display: inline;
}
</code>```

Better?

ContentLicense: CC BY-SA 2.5

Body:
I have a bunch of buttons on my page, my html is like:

  <input ..>
  <input ...>
</dvi>

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

Body:
Did you say you applied inline to the div? That sets the div to display inline, but I think what you want is for the inputs to display inline. try:

div input {
display: inline;
}

Better?


问:
Multiple PHP versions released on same day
I have just noticed the banner across the top of php.net, stating that PHP 7.0.20 has been released. I thought it a bit strange since I'm using PHP 7.1.5. Following the link has left me very confused.

PHP 7.0.20: Released 08 Jun 2017

PHP 7.1.5: Released 11 May 2017

PHP 7.0.19: Released 11 May 2017

Is there any significance to 7.1.5 version number and it being released on the same day as 7.0.19 and being released before the lesser version of 7.0.20?

I can understand them skipping the whole 6.x.x, but the current 7.x.x version seem to be just mishmashed.

答:
In the development of PHP, the middle number is a significant version change where new features or breaking changes can occur. Due to this, the previous version is still maintained with bug fixes and security updates.

Consider you had a production server running PHP 7.0.19. When there is a bug fix or security release (7.0.20), you may only want those updates, you don't necessarily want a major version update up to 7.1 on your production server that could cause errors due to breaking changes or removed features.


问:
Recursive way to find number of items in a object of array
What is the recursive way to get the number of titi in the following object :

```<code>{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}
</code>```

Expected result is the total. In this example : 7.

答:
Use JSON.stringify:

```<code>function countTiti(obj) {
  let count = 0;
  JSON.stringify(obj, (k, v) => { if (k === 'titi') count++; return v; });
  return count;
}
</code>```

Body:
What is the recursive way to get the number of titi in the following object :

{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

Expected result is the total. In this example : 7.

Body:
Use JSON.stringify:

function countTiti(obj) {
  let count = 0;
  JSON.stringify(obj, (k, v) => { if (k === 'titi') count++; return v; });
  return count;
}


问:
PHP json decode data using foreach
I have this following link and i want to print every item with id using foreach from json decoded string. Do you know how can i get these items using foreach?
sample JSON data</p>

答:
Load data via cURL:

```<code>$data = json_decode($your_json_data, 1);
foreach($data as $item)
{
    var_dump($item);
    //...
}
</code>```

Title: PHP json decode data using foreach

Body:
Load data via cURL:

$data = json_decode($your_json_data, 1);
foreach($data as $item)
{
    var_dump($item);
    //...
}


问:
Many-to-Many & One-to-Many (EF) - Code First
Creating a code-first database, for a school-type system.

The bit I'm struggling with is the courses, and users section.

User

Can take many courses

Can teach multiple courses

Course

Can have many users

Can have only 1 teacher

Below are the 2 models for my courses, and users

```<code>public class User
{
  public virtual ICollection<Course> CoursesRunning { get; set; }

  public virtual ICollection<Course> CoursesTaking { get; set; }

  [DataType(DataType.Date)]
  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
  [Required]
  public DateTime DoB { get; set; }

  [Required]
  public string EmailAddress { get; set; }

  [Required]
  public string FirstName { get; set; }

  [Required]
  public string LastName { get; set; }

  [Required]
  public string Password { get; set; }

  [Key]
  public int UserId { get; set; }

  public User()
  {
    CoursesRunning = new HashSet<Course>();
    CoursesTaking = new HashSet<Course>();
  }
}

public class Course
{
  [Key]
  public int CourseId { get; set; }

  /// <summary>
  /// The name of the course
  /// </summary>
  public string Name { get; set; }

  /// <summary>
  /// The owner of the course
  /// </summary>
  public virtual User User { get; set; }

  /// <summary>
  /// The users on the course
  /// </summary>
  public virtual ICollection<User> Users { get; set; }

  public Course()
  {
    Users = new HashSet<User>();
  }
}
</code>```

As you can see I've got my 2 collections in my User class, and then my single and many in the Course class.

I think I have to set a foreign key attribute on my virtual properties, but I'm really unsure.

Tried searching for the last few hours, but can't see anything that fits this need.

Thank you

答:
All you need is to map the corresponding navigation properties that define each relationship.

If you prefer data annotations, you could use InverseProperty attribute like

```<code>public class User
{
    [InverseProperty(nameof(Course.User))]
    public virtual ICollection<Course> CoursesRunning { get; set; }

    [InverseProperty(nameof(Course.Users))]
    public virtual ICollection<Course> CoursesTaking { get; set; }
}
</code>```

or

```<code>public class Course
{
    [InverseProperty(nameof(User.CoursesRunning))]
    public virtual User User { get; set; }

    [InverseProperty(nameof(User.CoursesTaking))]
    public virtual ICollection<User> Users { get; set; }
}
</code>```

etc.

Or you can use fluent configuration instead (my preferred):

```<code>modelBuilder.Entity<User>()
    .HasMany(e => e.CoursesRunning)
    .WithRequired(e => e.User)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<User>()
    .HasMany(e => e.CoursesTaking)
    .WithMany(e => e.Users);
</code>```

Note: in the above samples, you might need to exchange the Running and Taking mappings if what I did is not what you meant.

Update: I almost always forget that having more than one relationship between the two entities is causing the famous multiple cascade paths error. So you need to turn the cascade delete off, and it can be done only with fluent API, hence data annotations is not an option.

Body:
Creating a code-first database, for a school-type system.

The bit I'm struggling with is the courses, and users section.

User

Can take many courses

Can teach multiple courses

Course

Can have many users

Can have only 1 teacher

Below are the 2 models for my courses, and users

public class User
{
  public virtual ICollection<Course> CoursesRunning { get; set; }

  public virtual ICollection<Course> CoursesTaking { get; set; }

  [DataType(DataType.Date)]
  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
  [Required]
  public DateTime DoB { get; set; }

  [Required]
  public string EmailAddress { get; set; }

  [Required]
  public string FirstName { get; set; }

  [Required]
  public string LastName { get; set; }

  [Required]
  public string Password { get; set; }

  [Key]
  public int UserId { get; set; }

  public User()
  {
    CoursesRunning = new HashSet<Course>();
    CoursesTaking = new HashSet<Course>();
  }
}

public class Course
{
  [Key]
  public int CourseId { get; set; }

  ///
  /// The name of the course
  ///
  public string Name { get; set; }

  ///
  /// The owner of the course
  ///
  public virtual User User { get; set; }

  ///
  /// The users on the course
  ///
  public virtual ICollection<User> Users { get; set; }

  public Course()
  {
    Users = new HashSet<User>();
  }
}

As you can see I've got my 2 collections in my User class, and then my single and many in the Course class.

I think I have to set a foreign key attribute on my virtual properties, but I'm really unsure.

Tried searching for the last few hours, but can't see anything that fits this need.

Thank you

Body:
All you need is to map the corresponding navigation properties that define each relationship.

If you prefer data annotations, you could use InverseProperty attribute like

public class User
{
    [InverseProperty(nameof(Course.User))]
    public virtual ICollection<Course> CoursesRunning { get; set; }

    [InverseProperty(nameof(Course.Users))]
    public virtual ICollection<Course> CoursesTaking { get; set; }
}

or

public class Course
{
    [InverseProperty(nameof(User.CoursesRunning))]
    public virtual User User { get; set; }

    [InverseProperty(nameof(User.CoursesTaking))]
    public virtual ICollection<User> Users { get; set; }
}

etc.

Or you can use fluent configuration instead (my preferred):

modelBuilder.Entity<User>()
    .HasMany(e => e.CoursesRunning)
    .WithRequired(e => e.User)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<User>()
    .HasMany(e => e.CoursesTaking)
    .WithMany(e => e.Users);

Note: in the above samples, you might need to exchange the Running and Taking mappings if what I did is not what you meant.

Update: I almost always forget that having more than one relationship between the two entities is causing the famous multiple cascade paths error. So you need to turn the cascade delete off, and it can be done only with fluent API, hence data annotations is not an option.


问:
Testing a PHP script on a local computer
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

```<code><form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted: <br/>
    Name:<input type="text" name="name" /> <br/><br/>
    Company: <input type="text" name="company"/> <br/><br/>
    Phone: <input type="text" name="phone" /> <br/><br/>
    Email: <input type="text" name="email" /> <br/><br/>

    <input type="submit" name="Submit" value="Submit" />
</form>
</code>```

The following is the code for the php script:

```<code><table>
<tr><th>Field Name</th><th>Value(s)</th></tr>

<?php
if (empty($_POST)) {
print "<p>No data was submitted.</p>";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "<tr><td><code>$key</code></td><td>";
    foreach ($_POST['extras'] as $value) {
            print "<i>$value</i><br />";
            }
            print "</td></tr>";
    } else {
    print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
    }
} else {

print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
}
 }
}
?>
</table>
</body>
</html>
</code>```

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

答: Check out xampp. It installs Apache, Mysql, Perl, and PHP on your machine so you can test your entire site locally. It's a one shot installer and comes with a nifty control panel to enable/disable each service as needed.</p>

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

Body:
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

<form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted:

    Name:<input type="text" name="name" />

    Company: <input type="text" name="company"/>

    Phone: <input type="text" name="phone" />

    Email: <input type="text" name="email" />

    <input type="submit" name="Submit" value="Submit" />
</form>

The following is the code for the php script:

Field Name	Value(s)

<?php
if (empty($_POST)) {
print "
No data was submitted.
";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "
$key	";
    foreach ($_POST['extras'] as $value) {
            print "$value
";
            }
            print "
";
    } else {
    print "
$key	$value
\n";
    }
} else {

print "
$key	$value
\n";
}
 }
}
?>

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

OwnerDisplayName: ryeguy


问:
Definition of Type in .NET
This question gives me curiosity... When you want to define a type you must say GetType(Type) ex.: GetType(string), but ain't String a type itself?

Why do you need to use GetType in those situations? And, if the reason is because it is expecting a Type 'Type'... why isn't the conversion implicit... I mean, all the data is there...

答:
What you're doing is getting a reference to the meta-data of the type ... it might be a little more obvious if you look at the C# version of the API, which is typeof(string) ... which returns a Type object with information about the string type.

You would generally do this when using reflection or other meta-programming techniques

Title: Definition of Type in .NET


问:
update RHS on a constraint in scip using python
Are there any good solutions for updating the rhs of a constraint? Preferably I would like to do something like:</p>

```<code>    import pyscipopt as scp
    Mod=scp.Model()
    x=Mod.addVar(ub=3,name="x")
    y=Mod.addVar(ub=4,name="y")
    c=Mod.addCons(x+y<=2,"C1")
    Mod.setObjective(0.5*x+0.3*y, "maximize")
    Mod.optimize()
    print(Mod.getObjVal())
    c.updateRHS(4) # This function does not exist..
    Mod.optimize()
    print(Mod.getObjVal())
</code>```

答:
This is fixed in the latest version of PySCIPOpt (see https://github.com/SCIP-Interfaces/PySCIPOpt/pull/70)

The methods are called chgLhs() and chgRhs(). Keep in mind that they are only going to work for linear and quadratic constraints for now.

Body:
Are there any good solutions for updating the rhs of a constraint? Preferably I would like to do something like:

    import pyscipopt as scp
    Mod=scp.Model()
    x=Mod.addVar(ub=3,name="x")
    y=Mod.addVar(ub=4,name="y")
    c=Mod.addCons(x+y<=2,"C1")
    Mod.setObjective(0.5*x+0.3*y, "maximize")
    Mod.optimize()
    print(Mod.getObjVal())
    c.updateRHS(4) # This function does not exist..
    Mod.optimize()
    print(Mod.getObjVal())


问:
How can I put labels on geom_bar() in ggplot2 (without a manual y_position)
I, here is my problem.

I'd like to make a geom_bar with ggplot2, with label on the bars.

Here is a reproducible exemple and the plot which is generated:

```<code>prop = c(rep("A",2),rep("B",2),rep("C",2))
n = c(rep(29,2),rep(63,2),rep(25,2))
var = c(rep(c("sortant","entrant"),3))
value = c(10,19,43,20,10,15)
mydata = data.frame(cbind(prop,n,var,value))

> mydata
prop  n     var value
   A 29 sortant    10
   A 29 entrant    19
   B 63 sortant    43
   B 63 entrant    20
   C 25 sortant    10
   C 25 entrant    15

mydata$n = as.integer(as.character(mydata$n))
mydata$value = as.integer(as.character(mydata$value))

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value))
</code>```

I would like to produce this plot, without creating "y_pos" manually (like the exemple following) because I'have to make this plot every week with different data.

```<code>mydata2 = mydata
mydata2$y_pos = c(7,20,20,50,7,17)

>mydata2
prop  n     var value y_pos
   A 29 sortant    10     7
   A 29 entrant    19    20
   B 63 sortant    43    20
   B 63 entrant    20    50
   C 25 sortant    10     7
   C 25 entrant    15    17

ggplot(data = mydata2)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value, y = y_pos))
</code>```

With this code, I have the plot that I want, but I don't want to make some variables manually :

If it is possible, how can I make this plot :

with good values

in the right order

in the right place ?

Thanks in advance, any help or exemple is appreciable !

NB: (I don't want use position_dodge(), I want to keep this format)

答:
You can use the position argument inside geom_text with position_stack():

```<code>library(ggplot2)

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+
    geom_col()+
    scale_fill_brewer(palette = 'Paired')+
    geom_text(aes(label = value), position = position_stack(vjust = .5))
</code>```

Body:
I, here is my problem.

I'd like to make a geom_bar with ggplot2, with label on the bars.

Here is a reproducible exemple and the plot which is generated:

prop = c(rep("A",2),rep("B",2),rep("C",2))
n = c(rep(29,2),rep(63,2),rep(25,2))
var = c(rep(c("sortant","entrant"),3))
value = c(10,19,43,20,10,15)
mydata = data.frame(cbind(prop,n,var,value))

> mydata
prop  n     var value
   A 29 sortant    10
   A 29 entrant    19
   B 63 sortant    43
   B 63 entrant    20
   C 25 sortant    10
   C 25 entrant    15

mydata$n = as.integer(as.character(mydata$n))
mydata$value = as.integer(as.character(mydata$value))

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value))

I would like to produce this plot, without creating "y_pos" manually (like the exemple following) because I'have to make this plot every week with different data.

mydata2 = mydata
mydata2$y_pos = c(7,20,20,50,7,17)

>mydata2
prop  n     var value y_pos
   A 29 sortant    10     7
   A 29 entrant    19    20
   B 63 sortant    43    20
   B 63 entrant    20    50
   C 25 sortant    10     7
   C 25 entrant    15    17

ggplot(data = mydata2)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value, y = y_pos))

With this code, I have the plot that I want, but I don't want to make some variables manually :

If it is possible, how can I make this plot :

with good values

in the right order

in the right place ?

Thanks in advance, any help or exemple is appreciable !

NB: (I don't want use position_dodge(), I want to keep this format)

Body:
You can use the position argument inside geom_text with position_stack():

library(ggplot2)

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+
    geom_col()+
    scale_fill_brewer(palette = 'Paired')+
    geom_text(aes(label = value), position = position_stack(vjust = .5))


问:
Is stat's st_blksize measured in bits or bytes?
I'm trying to find the block size on my machine using these lines:

```<code>struct stat fi;
stat("/tmp", &fi);
BLOCK_SIZE = fi.st_blksize;
</code>```

Does BLOCK_SIZE represent the amount of bytes or the amount of bits in a single block?

The documentation says:

"    blksize_t st_blksize; /* blocksize for file system I/O */ "

答: Block sizes are usually given in bytes and in the case of stat it is. Giving it in bits would not make much sense.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to find the block size on my machine using these lines:

struct stat fi;
stat("/tmp", &fi);
BLOCK_SIZE = fi.st_blksize;

Does BLOCK_SIZE represent the amount of bytes or the amount of bits in a single block?

The documentation says:

"    blksize_t st_blksize; /* blocksize for file system I/O */ "


问:
Parameters in ActionResult
In migrating a Vanilla MVC project to a Vanilla Umbraco project, i am facing a couple of issues. One of them is with the query parameters, and transferring them to my Index.

Old ActionResult from working MVC project:

```<code>public ActionResult Index(int value1, int value2, bool value3 = false)
{...}
</code>```

New ActionResult, working in a Vanilla Umbraco project

```<code>public override ActionResult Index(RenderModel model)
{...}
</code>```

But i need the parameters (coming from querystring) from the original project.
I tried simply adding them:

```<code>public override ActionResult Index(RenderModel model, int value1, int value2, bool value3 = false)
{...}
</code>```

But when i do the latter, i get the error 'Controller.Index(RenderModel, int, int, bool): no suitable method found to override'

What am i missing?

答:
That error means not all parameters got loaded as they should. Just make them all accept null as value, and check on what you get during the call.</p>

```<code>public override ActionResult Index(RenderModel model, int? value1, int? value2, bool value3 = false)
{...}
</code>```

Title: Parameters in ActionResult

Body:
In migrating a Vanilla MVC project to a Vanilla Umbraco project, i am facing a couple of issues. One of them is with the query parameters, and transferring them to my Index.

Old ActionResult from working MVC project:

public ActionResult Index(int value1, int value2, bool value3 = false)
{...}

New ActionResult, working in a Vanilla Umbraco project

public override ActionResult Index(RenderModel model)
{...}

But i need the parameters (coming from querystring) from the original project.
I tried simply adding them:

public override ActionResult Index(RenderModel model, int value1, int value2, bool value3 = false)
{...}

But when i do the latter, i get the error 'Controller.Index(RenderModel, int, int, bool): no suitable method found to override'

What am i missing?

Body:
That error means not all parameters got loaded as they should. Just make them all accept null as value, and check on what you get during the call.

public override ActionResult Index(RenderModel model, int? value1, int? value2, bool value3 = false)
{...}


问:
Is it better practice to style an element based on its state with a data attribute or class?
I'm wondering what the best practice here is for styling an element based on its state.

I have some content that can take a while to load, whilst it's loading I want to show a loading spinner.

Is it better to apply a class of 'loading' to the element until it's loaded, then remove this class with JS. Using the 'loading' class to render the spinner.

Or is it better practice to disassociate the loading state from a class and use a data attribute, i.e. [data-status = "loading"]. Then applying my styles to the data attribute rather than the class.

Cheers.

答:
Generally, class is the go-to for visual changes.

According to W3C...

data

Custom data attributes are intended to store custom data private to
  the page or application, for which there are no more appropriate
  attributes or elements. These attributes are not intended for use by
  software that is independent of the site that uses the attributes.

class

The class attribute has several roles in HTML: As a style sheet
  selector (when an author wishes to assign style information to a set
  of elements). For general purpose processing by user agents.

OwnerDisplayName: anon


问:
webkit transforms: how to roate on Z axis, but not around center?
Any idea how to get the webkit transform rotation to rotate around a point different that the center of the element (e.g. around the top right corner)?</p>

答:
Can you translate the object first, then rotate it?

i.e. if the center of the object is at the origin and the top-right corner is at 3,5 then translate the object -3,-5 such that the top-right corner is now at the origin. Then rotate the object as normal.


问:
C# MVC Query String Encoding and Decoding
I want to encode and decode the url parameters.

calling function in javascript

```<code>var url = '/Demo/Demo?id=58';
$(location).attr('href', url)
</code>```

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

```<code>public ActionResult Demo(int id)
{
   return view();
}
</code>```

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method

答:
If what you are looking to do is to hide the 58 from the rendered content (client-side), then you need to implement an encryption/decryption scheme on the backend and pass that value from/to the client side as needed.

When you provide data to the client, your server side code will encrypt the 58 into some string in order to conceal the real value and pass that to the client.

When the client issues a request to you, it should use that encrypted string that you provided before and your server should decrypt it into something it can use.

You don't need JavaScript to encrypt and C# to decrypt the values. The JavaScript portion should be working off of the encrypted id at all times since it's scripting that is executing after the fact at the client side. How the value is consumed on the server side is an internal aspect of which the client-side JavaScript does not need to know about.

Body:
I want to encode and decode the url parameters.

calling function in javascript

var url = '/Demo/Demo?id=58';
$(location).attr('href', url)

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

public ActionResult Demo(int id)
{
   return view();
}

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method


答:
If you read this POSIX <sys/stat.h> reference you will find

The unit for the st_blocks member of the stat structure is not defined within POSIX.1-2008. In some implementations it is 512 bytes. It may differ on a file system basis. There is no correlation between values of the st_blocks and st_blksize, and the f_bsize (from <sys/statvfs.h> structure members.

So while there's no standardized unit for st_blksize it's unlikely that it's in bits. To get the actual unit you have to research the current operating system, and possibly even the filesystem used.

The Linux stat manual page doesn't mention the unit explicitly, but in the example it says the unit is in bytes.

Title: Is stat's st_blksize measured in bits or bytes?


问:
readFully not defined with Java Nashorn Javascript Engine
I am trying to run a javascript script with the new Java 8 Nashorn javascript engine but it fails with the following error:

```<code><eval>:1 ReferenceError: "readFully" is not defined
</code>```

The script uses the readFully function that should be defined in the global scope nashorn is run with the scripting mode enabled (wich is default when running through a ScriptEngine as seen here http://mail.openjdk.java.net/pipermail/nashorn-dev/2013-December/002562.html).

Here is a sample to reproduce the error:

```<code>import java.io.FileNotFoundException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Test {

    public static void main(String[] argv) throws FileNotFoundException, ScriptException {
        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");

        scriptEngine.eval("print('Hey!');print(print);print(readFully);");

    }
}
</code>```

This sample prints Hey ! and then the source code of the print function (another nashorn built-in function) and finally it should print the source code of the readFully method. But I have this Exception instead:

```<code>Exception in thread "main" javax.script.ScriptException: ReferenceError: "readFully" is not defined in <eval> at line number 1
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:586)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:570)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:525)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:521)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:192)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at com.github.bringking.maven.requirejs.Test.main(Test.java:14)
Caused by: <eval>:1 ReferenceError: "readFully" is not defined
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:58)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:320)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:292)
    at jdk.nashorn.api.scripting.NashornScriptEngine.__noSuchProperty__(NashornScriptEngine.java:272)
    at jdk.nashorn.internal.scripts.Script$engine.L:35(nashorn:engine/resources/engine.js:37)
    at jdk.nashorn.internal.scripts.Script$\^eval\_.runScript(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:535)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:209)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:568)
    ... 5 more
</code>```

When the sample script is run with the nashorn command line with the -scripting parameter (with the jjs tool of the jdk), all is fine. Here is the result of the same script:

```<code>Hey!
function print() { [native code] }
function readFully() { [native code] }
</code>```

I could rewrite a readFully method and bind it with the script context, but I prefer to understand why it does not work and use already built-in functions.

Regards

答:
readFully is enabled only in scripting mode. Nashorn docs

try this:

```<code>>>jjs -scripting
jjs> readFully("your_file")
</code>```

Body:
I am trying to run a javascript script with the new Java 8 Nashorn javascript engine but it fails with the following error:

<eval>:1 ReferenceError: "readFully" is not defined

The script uses the readFully function that should be defined in the global scope nashorn is run with the scripting mode enabled (wich is default when running through a ScriptEngine as seen here http://mail.openjdk.java.net/pipermail/nashorn-dev/2013-December/002562.html).

Here is a sample to reproduce the error:

import java.io.FileNotFoundException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Test {

    public static void main(String[] argv) throws FileNotFoundException, ScriptException {
        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");

        scriptEngine.eval("print('Hey!');print(print);print(readFully);");

    }
}

This sample prints Hey ! and then the source code of the print function (another nashorn built-in function) and finally it should print the source code of the readFully method. But I have this Exception instead:

Exception in thread "main" javax.script.ScriptException: ReferenceError: "readFully" is not defined in <eval> at line number 1
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:586)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:570)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:525)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:521)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:192)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at com.github.bringking.maven.requirejs.Test.main(Test.java:14)
Caused by: <eval>:1 ReferenceError: "readFully" is not defined
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:58)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:320)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:292)
    at jdk.nashorn.api.scripting.NashornScriptEngine.__noSuchProperty__(NashornScriptEngine.java:272)
    at jdk.nashorn.internal.scripts.Script$engine.L:35(nashorn:engine/resources/engine.js:37)
    at jdk.nashorn.internal.scripts.Script$\^eval\_.runScript(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:535)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:209)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:568)
    ... 5 more

When the sample script is run with the nashorn command line with the -scripting parameter (with the jjs tool of the jdk), all is fine. Here is the result of the same script:

Hey!
function print() { [native code] }
function readFully() { [native code] }

I could rewrite a readFully method and bind it with the script context, but I prefer to understand why it does not work and use already built-in functions.

Regards

Body:
readFully is enabled only in scripting mode. Nashorn docs

try this:

>>jjs -scripting
jjs> readFully("your_file")


问:
using python variable outside with statement
In a Python script, I encountered a variable that was defined inside a with statement, but that was used outside the statement, like file in the following example:

```<code>with open(fname, 'r') as file:
    pass
print(file.mode)
</code>```

Intuitively I would say that file should not exist outside the with statement and that this only works by accident. I could not find a conclusive statement in the Python documentation on whether this should work or not though. Is this type of statement safe for use (also for future python versions), or should it be avoided? A pointer to this information in the Python docs would be very helpful as well.

答:
Variable scope only applies at the function, module, and class levels.  If you are in the same function/module/class, all variables defined will be available within that function/module/class, regardless of whether it was defined within a with, for, if, etc. block.

For example, this:

```<code>for x in range(1):
    y = 1
print(y)
</code>```

is just as valid (although pointless) as your example using the with statement.

However, you must be careful since the variable defined within your code block might not actually be defined if the block is never entered, as in this case:

```<code>try:
    with open('filedoesnotexist', 'r') as file:
        pass
except:
    pass # just to emphasize point

print(file.mode)

Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    file.mode
NameError: name 'file' is not defined
</code>```

Good description of LEGB rule of thumb for variable scope

Body:
In a Python script, I encountered a variable that was defined inside a with statement, but that was used outside the statement, like file in the following example:

with open(fname, 'r') as file:
    pass
print(file.mode)

Intuitively I would say that file should not exist outside the with statement and that this only works by accident. I could not find a conclusive statement in the Python documentation on whether this should work or not though. Is this type of statement safe for use (also for future python versions), or should it be avoided? A pointer to this information in the Python docs would be very helpful as well.

Body:
Variable scope only applies at the function, module, and class levels.  If you are in the same function/module/class, all variables defined will be available within that function/module/class, regardless of whether it was defined within a with, for, if, etc. block.

For example, this:

for x in range(1):
    y = 1
print(y)

is just as valid (although pointless) as your example using the with statement.

However, you must be careful since the variable defined within your code block might not actually be defined if the block is never entered, as in this case:

try:
    with open('filedoesnotexist', 'r') as file:
        pass
except:
    pass # just to emphasize point

print(file.mode)

Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    file.mode
NameError: name 'file' is not defined

Good description of LEGB rule of thumb for variable scope


问:
Overload resolution for multiply inherited operator()
First, consider this C++ code:

```<code>#include <stdio.h>

struct foo_int {
    void print(int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void print(const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::print;
    //using foo_str::print;
};

int main() {
    foo f;
    f.print(123);
    f.print("abc");
}
</code>```

As expected according to the Standard, this fails to compile, because print is considered separately in each base class for the purpose of overload resolution, and thus the calls are ambiguous. This is the case on Clang (4.0), gcc (6.3) and MSVC (17.0) - see godbolt results here.

Now consider the following snippet, the sole difference of which is that we use operator() instead of print:

```<code>#include <stdio.h>

struct foo_int {
    void operator() (int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void operator() (const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
};

int main() {
    foo f;
    f(123);
    f("abc");
}
</code>```

I would expect the results to be identical to the previous case, but it is not the case - while gcc still complains, Clang and MSVC can compile this fine!

Question #1: who is correct in this case? I expect it to be gcc, but the fact that two other unrelated compilers give a consistently different result here makes me wonder whether I'm missing something in the Standard, and things are different for operators when they're not invoked using function syntax.

Also note that if you only uncomment one of the using declarations, but not the other, then all three compilers will fail to compile, because they will only consider the function brought in by using during overload resolution, and thus one of the calls will fail due to type mismatch. Remember this; we'll get back to it later.

Now consider the following code:

```<code>#include <stdio.h>

auto print_int = [](int x) {
    printf("int %d\n", x);
};
typedef decltype(print_int) foo_int;

auto print_str = [](const char* x) {
    printf("str %s\n", x);
};
typedef decltype(print_str) foo_str;

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
};

int main() {
    foo f;
    f(123);
    f("foo");
}
</code>```

Again, same as before, except now we don't define operator() explicitly, but instead get it from a lambda type. Again, you'd expect the results to be consistent with the previous snippet; and this is true for the case where both using declarations are commented out, or if both are uncommented. But if you only comment out one but not the other, things are suddenly different again: now only MSVC complains as I would expect it to, while Clang and gcc both think it's fine - and use both inherited members for overload resolution, despite only one being brought in by using!

Question #2: who is correct in this case? Again, I'd expect it to be MSVC, but then why do both Clang and gcc disagree? And, more importantly, why this is different from the previous snippet? I would expect the lambda type to behave exactly the same as a manually defined type with overloaded operator()...

答:
Your analysis of the first code is incorrect. There is no overload resolution.

The name lookup process occurs wholly before overload resolution.  Name lookup determines which scope an id-expression is resolved to.

If a unique scope is found via the name look-up rules, then overload resolution begins: all instances of that name within that scope form the overload set.

But in your code, name lookup fails. The name is not declared in foo, so base classes are searched. If the name is found in more than one immediate base class then the program is ill-formed and the error message describes it as an ambiguous name.

The name lookup rules do not have special cases for overloaded operators. You should find that the code:

```<code>f.operator()(123);
</code>```

fails for the same reason as f.print failed.  However, there is another issue in your second code.  f(123) is NOT defined as always meaning f.operator()(123);.  In fact the definition in C++14 is in [over.call]:

operator() shall be a non-static member function with an arbitrary number of parameters. It can have default arguments. It implements the function call syntax

postfix-expression ( expression-list opt )

where the postfix-expression evaluates to a class object and the possibly empty expression-list matches the parameter list of an operator() member function of the class. Thus, a call x(arg1,...) is interpreted as x.operator()(arg1, ...) for a class object x of type T if T::operator()(T1, T2, T3) exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3.3).

This actually seems an imprecise specification to me so I can understand different compilers coming out with different results.  What is T1,T2,T3? Does it mean the types of the arguments? (I suspect not). What are T1,T2,T3 when multiple operator() function exist, only taking one argument?

And what is meant by "if T::operator() exists" anyway?  It could perhaps mean any of the following:

operator() is declared in T.

Unqualified lookup of operator() in the scope of T succeeds and performing overload resolution on that lookup set with the given arguments succeeds.

Qualified lookup of T::operator() in the calling context succeeds and performing overload resolution on that lookup set with the given arguments succeeds.

Something else?

To proceed from here (for me anyway) I would like to understand why the standard didn't simply say that f(123) means f.operator()(123);, the former being ill-formed if and only if the latter is ill-formed.  The motivation behind the actual wording might reveal the intent and therefore which compiler's behaviour matches the intent.

Body:
First, consider this C++ code:

#include <stdio.h>

struct foo_int {
    void print(int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void print(const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::print;
    //using foo_str::print;
};

int main() {
    foo f;
    f.print(123);
    f.print("abc");
}

As expected according to the Standard, this fails to compile, because print is considered separately in each base class for the purpose of overload resolution, and thus the calls are ambiguous. This is the case on Clang (4.0), gcc (6.3) and MSVC (17.0) - see godbolt results here.

Now consider the following snippet, the sole difference of which is that we use operator() instead of print:

#include <stdio.h>

struct foo_int {
    void operator() (int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void operator() (const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
};

int main() {
    foo f;
    f(123);
    f("abc");
}

I would expect the results to be identical to the previous case, but it is not the case - while gcc still complains, Clang and MSVC can compile this fine!

Question #1: who is correct in this case? I expect it to be gcc, but the fact that two other unrelated compilers give a consistently different result here makes me wonder whether I'm missing something in the Standard, and things are different for operators when they're not invoked using function syntax.

Also note that if you only uncomment one of the using declarations, but not the other, then all three compilers will fail to compile, because they will only consider the function brought in by using during overload resolution, and thus one of the calls will fail due to type mismatch. Remember this; we'll get back to it later.

Now consider the following code:

#include <stdio.h>

auto print_int = [](int x) {
    printf("int %d\n", x);
};
typedef decltype(print_int) foo_int;

auto print_str = [](const char* x) {
    printf("str %s\n", x);
};
typedef decltype(print_str) foo_str;

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
};

int main() {
    foo f;
    f(123);
    f("foo");
}

Again, same as before, except now we don't define operator() explicitly, but instead get it from a lambda type. Again, you'd expect the results to be consistent with the previous snippet; and this is true for the case where both using declarations are commented out, or if both are uncommented. But if you only comment out one but not the other, things are suddenly different again: now only MSVC complains as I would expect it to, while Clang and gcc both think it's fine - and use both inherited members for overload resolution, despite only one being brought in by using!

Question #2: who is correct in this case? Again, I'd expect it to be MSVC, but then why do both Clang and gcc disagree? And, more importantly, why this is different from the previous snippet? I would expect the lambda type to behave exactly the same as a manually defined type with overloaded operator()...

Body:
Your analysis of the first code is incorrect. There is no overload resolution.

The name lookup process occurs wholly before overload resolution.  Name lookup determines which scope an id-expression is resolved to.

If a unique scope is found via the name look-up rules, then overload resolution begins: all instances of that name within that scope form the overload set.

But in your code, name lookup fails. The name is not declared in foo, so base classes are searched. If the name is found in more than one immediate base class then the program is ill-formed and the error message describes it as an ambiguous name.

The name lookup rules do not have special cases for overloaded operators. You should find that the code:

f.operator()(123);

fails for the same reason as f.print failed.  However, there is another issue in your second code.  f(123) is NOT defined as always meaning f.operator()(123);.  In fact the definition in C++14 is in [over.call]:

operator() shall be a non-static member function with an arbitrary number of parameters. It can have default arguments. It implements the function call syntax

postfix-expression ( expression-list opt )

where the postfix-expression evaluates to a class object and the possibly empty expression-list matches the parameter list of an operator() member function of the class. Thus, a call x(arg1,...) is interpreted as x.operator()(arg1, ...) for a class object x of type T if T::operator()(T1, T2, T3) exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3.3).

This actually seems an imprecise specification to me so I can understand different compilers coming out with different results.  What is T1,T2,T3? Does it mean the types of the arguments? (I suspect not). What are T1,T2,T3 when multiple operator() function exist, only taking one argument?

And what is meant by "if T::operator() exists" anyway?  It could perhaps mean any of the following:

operator() is declared in T.

Unqualified lookup of operator() in the scope of T succeeds and performing overload resolution on that lookup set with the given arguments succeeds.

Qualified lookup of T::operator() in the calling context succeeds and performing overload resolution on that lookup set with the given arguments succeeds.

Something else?

To proceed from here (for me anyway) I would like to understand why the standard didn't simply say that f(123) means f.operator()(123);, the former being ill-formed if and only if the latter is ill-formed.  The motivation behind the actual wording might reveal the intent and therefore which compiler's behaviour matches the intent.


问:
POST Request, no Getting response on retrofit 2
I'm using retrofit 2 whit OkHttpClient into my Android app. It's a POST request.

Request must be Synchronous.

```<code>This is the code:
ResultObject<Integer, List<OrderResult>> resultcall =
                restclient.getApiService().createUpdateOrders(companyId,
                orderList).execute().body();
</code>```

It usually works fine but sometimes I don't get ok http response.

This is the normal response log:

```<code>06-08 11:35:56.609 24584 25168 D OkHttp  : --> POST http://93.90.20.171:8080/tpv/rest/order/create?companyId=1 http/1.1
06-08 11:35:56.609 24584 25168 D OkHttp  : Content-Type: application/json; charset=UTF-8
06-08 11:35:56.609 24584 25168 D OkHttp  : Content-Length: 644
06-08 11:35:56.609 24584 25168 D OkHttp  : Connection:
06-08 11:35:56.609 24584 25168 D OkHttp  : --> END POST
06-08 11:36:03.139 24584 25168 D OkHttp  : <-- 200 OK http://93.90.20.171:8080/tpv/rest/order/create?companyId=1 (6530ms)
06-08 11:36:03.139 24584 25168 D OkHttp  : Server: Apache-Coyote/1.1
06-08 11:36:03.139 24584 25168 D OkHttp  : Content-Type: application/json;charset=UTF-8
06-08 11:36:03.139 24584 25168 D OkHttp  : Date: Thu, 08 Jun 2017 09:36:05 GMT
06-08 11:36:03.139 24584 25168 D OkHttp  : Transfer-Encoding: chunked
06-08 11:36:03.139 24584 25168 D OkHttp  : <-- END HTTP
</code>```

And this is the error log. As you can see there is no "<-- 200 OK" line and I don'd get any error log.

```<code>06-08 11:36:03.219 24584 25168 D OkHttp  : --> POST http://93.90.20.171:8080/tpv/rest/order/create?companyId=1 http/1.1
06-08 11:36:03.219 24584 25168 D OkHttp  : Content-Type: application/json; charset=UTF-8
06-08 11:36:03.219 24584 25168 D OkHttp  : Content-Length: 604
06-08 11:36:03.219 24584 25168 D OkHttp  : Connection:
06-08 11:36:03.219 24584 25168 D OkHttp  : --> END POST
06-08 11:36:10.089 24584 24584 V ActivityThread: updateVisibility : ActivityRecord{6082a59 token=android.os.BinderProxy@463ef68 {com.six.and.cbo/com.six.and.cbo.OrdercomunnicationTabWidget}} show : true
06-08 11:36:16.343 24584 24584 D ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
06-08 11:37:11.634 24584 24584 I ORDERLISTVIEW: --> OnResume
</code>```

Please, any suggestion??

答:
you can do this instead of executing the call

```<code> call.enqueue(new Callback<List<OrderResult>>() {
            @Override
            public void onResponse(Call<List<OrderResult>> call, Response<List<OrderResult>> response) {
          // do something
            }

            @Override
            public void onFailure(Call<List<OrderResult>> call, Throwable t) {
                Log.e("call failed", t.toString());
                Toast.makeText(getApplicationContext(), "call faild ", Toast.LENGTH_LONG).show();
            }
        });
</code>```

just correct the response and send type i didnt focused on it

Body:
I'm using retrofit 2 whit OkHttpClient into my Android app. It's a POST request.

Request must be Synchronous.

This is the code:
ResultObject<Integer, List<OrderResult>> resultcall =
                restclient.getApiService().createUpdateOrders(companyId,
                orderList).execute().body();

It usually works fine but sometimes I don't get ok http response.

This is the normal response log:

06-08 11:35:56.609 24584 25168 D OkHttp  : --> POST http://93.90.20.171:8080/tpv/rest/order/create?companyId=1 http/1.1
06-08 11:35:56.609 24584 25168 D OkHttp  : Content-Type: application/json; charset=UTF-8
06-08 11:35:56.609 24584 25168 D OkHttp  : Content-Length: 644
06-08 11:35:56.609 24584 25168 D OkHttp  : Connection:
06-08 11:35:56.609 24584 25168 D OkHttp  : --> END POST
06-08 11:36:03.139 24584 25168 D OkHttp  : <-- 200 OK http://93.90.20.171:8080/tpv/rest/order/create?companyId=1 (6530ms)
06-08 11:36:03.139 24584 25168 D OkHttp  : Server: Apache-Coyote/1.1
06-08 11:36:03.139 24584 25168 D OkHttp  : Content-Type: application/json;charset=UTF-8
06-08 11:36:03.139 24584 25168 D OkHttp  : Date: Thu, 08 Jun 2017 09:36:05 GMT
06-08 11:36:03.139 24584 25168 D OkHttp  : Transfer-Encoding: chunked
06-08 11:36:03.139 24584 25168 D OkHttp  : <-- END HTTP

And this is the error log. As you can see there is no "<-- 200 OK" line and I don'd get any error log.

06-08 11:36:03.219 24584 25168 D OkHttp  : --> POST http://93.90.20.171:8080/tpv/rest/order/create?companyId=1 http/1.1
06-08 11:36:03.219 24584 25168 D OkHttp  : Content-Type: application/json; charset=UTF-8
06-08 11:36:03.219 24584 25168 D OkHttp  : Content-Length: 604
06-08 11:36:03.219 24584 25168 D OkHttp  : Connection:
06-08 11:36:03.219 24584 25168 D OkHttp  : --> END POST
06-08 11:36:10.089 24584 24584 V ActivityThread: updateVisibility : ActivityRecord{6082a59 token=android.os.BinderProxy@463ef68 {com.six.and.cbo/com.six.and.cbo.OrdercomunnicationTabWidget}} show : true
06-08 11:36:16.343 24584 24584 D ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
06-08 11:37:11.634 24584 24584 I ORDERLISTVIEW: --> OnResume

Please, any suggestion??

Body:
you can do this instead of executing the call

 call.enqueue(new Callback<List<OrderResult>>() {
            @Override
            public void onResponse(Call<List<OrderResult>> call, Response<List<OrderResult>> response) {
          // do something
            }

            @Override
            public void onFailure(Call<List<OrderResult>> call, Throwable t) {
                Log.e("call failed", t.toString());
                Toast.makeText(getApplicationContext(), "call faild ", Toast.LENGTH_LONG).show();
            }
        });

just correct the response and send type i didnt focused on it


问:
SBCL statistical profiler warns of undefined function
SBCL 1.3.9 produces the following error when I attempt to run the statistical profiler. Is start-profiling not exported?

```<code>* (in-package :cl-user)
* (require :sb-sprof)
* (sb-sprof:with-profiling (:report :flat) (bnb::solve))
; in: SB-SPROF:WITH-PROFILING (:REPORT :FLAT)
;     (SB-SPROF:START-PROFILING :MAX-DEPTH 4611686018427387903 :THREADS
;      (LIST SB-THREAD:*CURRENT-THREAD*))
;
; caught STYLE-WARNING:
;   undefined function: SB-SPROF:START-PROFILING
;
; compilation unit finished
;   Undefined function:
;     SB-SPROF:START-PROFILING
;   caught 1 STYLE-WARNING condition

debugger invoked on a UNDEFINED-FUNCTION in thread
#<THREAD "main thread" RUNNING {100292C913}>:
  The function SB-SPROF:START-PROFILING is undefined.

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [ABORT] Exit debugger, returning to top level.
</code>```

答:
It seems a problem with your distribution. please update to the last SBCL wich is

The most recent version is SBCL 1.3.18, released May 30, 2017

But if you take a look at the sources in github

```<code>git log -S start-profiling --source --all

commit 63f714af62d0ccdb9d4a793ab0245b036c3d8531 refs/tags/sbcl_1_0
Author: Juho Snellman <jsnell@iki.fi>
Date:   Fri Nov 17 02:15:47 2006 +0000

    0.9.18.58:
            Further SB-SPROF improvements.

            * Allocation profiling on gencgc. When the profiler is running in
              allocation profiling mode, the gc will signal profiler ticks
              when new allocation regions are opened.
            * Add :LOOP keyword argument to WITH-PROFILING, to allow specifying
              whether the body should be evaluated repeatedly until the maximum
              sample count is reached.
            * Improve merging of code-components with multiple debug-funs,
              better handling of multiple functions with the same name
            * More documentation
            * Also update the stepper documentation

commit 554397512eea9d6e30067c5edc2def42006a5327 refs/tags/sbcl_0_8_12
Author: Christophe Rhodes <csr21@cam.ac.uk>
Date:   Mon Jun 21 11:33:35 2004 +0000

    0.8.11.20:
            Add SB-SPROF contrib
</code>```

That funcion was added a lot time ago, so please try the latest code and follow the manual

also if you inspect the code it has this mark

```<code>#-win32
</code>```

So if you are using windows 32 bits this should not work

Body:
SBCL 1.3.9 produces the following error when I attempt to run the statistical profiler. Is start-profiling not exported?

* (in-package :cl-user)
* (require :sb-sprof)
* (sb-sprof:with-profiling (:report :flat) (bnb::solve))
; in: SB-SPROF:WITH-PROFILING (:REPORT :FLAT)
;     (SB-SPROF:START-PROFILING :MAX-DEPTH 4611686018427387903 :THREADS
;      (LIST SB-THREAD:*CURRENT-THREAD*))
;
; caught STYLE-WARNING:
;   undefined function: SB-SPROF:START-PROFILING
;
; compilation unit finished
;   Undefined function:
;     SB-SPROF:START-PROFILING
;   caught 1 STYLE-WARNING condition

debugger invoked on a UNDEFINED-FUNCTION in thread
#<THREAD "main thread" RUNNING {100292C913}>:
  The function SB-SPROF:START-PROFILING is undefined.

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [ABORT] Exit debugger, returning to top level.

Body:
It seems a problem with your distribution. please update to the last SBCL wich is

The most recent version is SBCL 1.3.18, released May 30, 2017

But if you take a look at the sources in github

git log -S start-profiling --source --all

commit 63f714af62d0ccdb9d4a793ab0245b036c3d8531 refs/tags/sbcl_1_0
Author: Juho Snellman <jsnell@iki.fi>
Date:   Fri Nov 17 02:15:47 2006 +0000

    0.9.18.58:
            Further SB-SPROF improvements.

            * Allocation profiling on gencgc. When the profiler is running in
              allocation profiling mode, the gc will signal profiler ticks
              when new allocation regions are opened.
            * Add :LOOP keyword argument to WITH-PROFILING, to allow specifying
              whether the body should be evaluated repeatedly until the maximum
              sample count is reached.
            * Improve merging of code-components with multiple debug-funs,
              better handling of multiple functions with the same name
            * More documentation
            * Also update the stepper documentation

commit 554397512eea9d6e30067c5edc2def42006a5327 refs/tags/sbcl_0_8_12
Author: Christophe Rhodes <csr21@cam.ac.uk>
Date:   Mon Jun 21 11:33:35 2004 +0000

    0.8.11.20:
            Add SB-SPROF contrib

That funcion was added a lot time ago, so please try the latest code and follow the manual

also if you inspect the code it has this mark

#-win32

So if you are using windows 32 bits this should not work


问:
Google Cloud Functions - Repository deployment - Reading Setting File
This might be more of a best practice question, but I am deploying a cloud function in GCloud via GitHub repo to multiple environments, each with their own secrets for database up that this cloud function will write to (elastic search). How do I get the function to access a settings file in their own respective environments? Using Node.js, FYI.</p>

答:
I think we were able to figure this out, so posting for other people.

I found a handy little npm package called cloud-functions-runtime-config (looks like this guy also had a similar issue, but it took a certain google passphrase for me to find it, so hoping for more exposure!)

https://github.com/fredriks/cloud-functions-runtime-config

There is a tool available in beta called Runtime Configurator which is uses:

https://cloud.google.com/deployment-manager/runtime-configurator/

Once we set that up using the following:

gcloud beta runtime-config configs create <CONFIG NAME>

And created variables using:

gcloud beta runtime-config configs variables set <VARIABLE NAME> <VARIABLE VALUE> --config-name <CONFIG NAME>

Calling it was a piece of cake. Thanks random internet guy for solving my issue!


问:
how to send notification on ios using c#
I am using this code which I mention below but I am getting an error:

Specified argument was out of the range of valid values.
  Parameter name: Your Certificate is not a valid certificate for connecting to Apple's APNS servers

I want to send notification using asp.net MVC to iOS device. I am using push sharp library to send a notification.

答:
here you go, also you need to pay attention if your certificate is Prod/Dev
depending that in the ApplePushChannelSettings method your first argument is true= if certificate is  production

false = if certificate is  development

```<code>broker = new PushBroker();
broker.OnNotificationSent += _broker_OnNotificationSentApple;
broker.OnChannelException += _broker_OnChannelExceptionApple;
broker.OnServiceException += _broker_OnServiceExceptionApple;
broker.OnNotificationFailed += _broker_OnNotificationFailedApple;
broker.OnDeviceSubscriptionExpired += _broker_OnDeviceSubscriptionExpiredApple;
broker.OnDeviceSubscriptionChanged += _broker_OnDeviceSubscriptionChangedApple;
broker.OnChannelCreated += _broker_OnChannelCreatedApple;
broker.OnChannelDestroyed += _broker_OnChannelDestroyedApple;

byte[] appleCert = File.ReadAllBytes(the path to the certificate);
broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(false,appleCert, appCertPassword,false),null);/

broker.QueueNotification(new AppleNotification()
                         .ForDeviceToken(yourDeviceToken)
                         .WithAlert(message)
                         .WithBadge(0));
</code>```

Body:
here you go, also you need to pay attention if your certificate is Prod/Dev
depending that in the ApplePushChannelSettings method your first argument is true= if certificate is  production

false = if certificate is  development

broker = new PushBroker();
broker.OnNotificationSent += _broker_OnNotificationSentApple;
broker.OnChannelException += _broker_OnChannelExceptionApple;
broker.OnServiceException += _broker_OnServiceExceptionApple;
broker.OnNotificationFailed += _broker_OnNotificationFailedApple;
broker.OnDeviceSubscriptionExpired += _broker_OnDeviceSubscriptionExpiredApple;
broker.OnDeviceSubscriptionChanged += _broker_OnDeviceSubscriptionChangedApple;
broker.OnChannelCreated += _broker_OnChannelCreatedApple;
broker.OnChannelDestroyed += _broker_OnChannelDestroyedApple;

byte[] appleCert = File.ReadAllBytes(the path to the certificate);
broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(false,appleCert, appCertPassword,false),null);/

broker.QueueNotification(new AppleNotification()
                         .ForDeviceToken(yourDeviceToken)
                         .WithAlert(message)
                         .WithBadge(0));


问:
Split a long text for paginated display
I'm building a website for a friend who's writing a novel, and want to display it, chapter by chapter, in a book-like display, with pages turning.

I have a frontend app in Angular 2 and a backend in Java (as they're the tools I'm more familiar with). A backoffice on the Angular app allows the user to add the text of a chapter, which is sent to the backend to be stored in the DB. Then the front of the Angular calls the backend to retrieve the chapter, and has to display it in the book-like display.

My problem is how can I split the text of the chapter into pages in order to display it. I could change the backoffice to force the user to add the text page by page. I could ask the user to put a specific marker in the text to indicate a page break. But I'ld like the process to be as transparent as possible for the user.

So I went for a solution by splitting the text on the backend. I estimated how many characters are on a line, and how many lines are on a page, then I cut the text accordingly (with some adjustments, as it's a HTML text with tags in it).
But it feels like a very strict approach, as I'm choosing the size of a page, regardless of the display interface size.

So I'm wondering if there is a better approach :
- a different splitting algorithm
- a tool front-side to display my text without splitting it
- something else

Does anyone had to face a similar problem ?

Thanks

答:
You are performing that action on server side that has no sense of the page length.

I assume that a better approach shall be to get the complete chapter from backend to front end; and have a front end function that will calculate :
- the number of characters per lines based on page size
- the number for line based on page size
- the number of chapter pages based on previous info

This is a way better approach than your full backend ones.

However; this is not a responsive approach.

Do you have interest and need within a responsive one ?

If yes; you may add a watch on the page length/height to recalculate the above values and re generated your pages

Title: Split a long text for paginated display


答:
When you want to define a type you must say GetType(Type) ex.: GetType(string)...

That's not true. Every time you do any of the following

```<code>class MyClass
{
///...
}

class MyChildClass : MyClass
{
}

struct MyStruct
{
///...
}
</code>```

you're defining a new type.

if the reason is because it is expecting a Type 'Type'... why isn't the conversion implicit... I mean, all the data is there...

One reason for this is polymorphism. For instance, if we were allowed to do the following:

```<code>MyChildClass x;

....GetType(x)
</code>```

GetType(x) could return MyChildClass, MyClass, or Object, since x is really an instance of all of those types.

It's also worth noting that Type is itself a class (ie, it inherits from Object), so you can inherit from it. Although I'm not sure why you'd want to do this other than overriding the default reflection behavior (for instance, to hide the internals from prying eyes).

Title: Definition of Type in .NET

Body:
This question gives me curiosity... When you want to define a type you must say GetType(Type) ex.: GetType(string), but ain't String a type itself?

Why do you need to use GetType in those situations? And, if the reason is because it is expecting a Type 'Type'... why isn't the conversion implicit... I mean, all the data is there...

Body:
When you want to define a type you must say GetType(Type) ex.: GetType(string)...

That's not true. Every time you do any of the following

class MyClass
{
///...
}

class MyChildClass : MyClass
{
}

struct MyStruct
{
///...
}

you're defining a new type.

if the reason is because it is expecting a Type 'Type'... why isn't the conversion implicit... I mean, all the data is there...

One reason for this is polymorphism. For instance, if we were allowed to do the following:

MyChildClass x;

....GetType(x)

GetType(x) could return MyChildClass, MyClass, or Object, since x is really an instance of all of those types.

It's also worth noting that Type is itself a class (ie, it inherits from Object), so you can inherit from it. Although I'm not sure why you'd want to do this other than overriding the default reflection behavior (for instance, to hide the internals from prying eyes).


问:
The name 'Drawline' does not exist in the current context
```<code>namespace MiniPaint
{
    public partial class Form1 : Form
    {
        Graphics g;
        Pen p = new Pen(Color.Black, 1);
        Point sp = new Point(0, 0);
        Point ep = new Point(0, 0);
        int k = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void red_Click(object sender, EventArgs e)
        {
            p.Color = red.BackColor;
            default1.BackColor = red.BackColor;
        }

        private void green_Click(object sender, EventArgs e)
        {
            p.Color = green.BackColor;
            default1.BackColor = green.BackColor;
        }

        private void blue_Click(object sender, EventArgs e)
        {
            p.Color = blue.BackColor;
            default1.BackColor = blue.BackColor;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            sp = e.Location;
            if (e.Button == MouseButtons.Left) ;
            k = 1;

        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            k = 0;

        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (k == 1)
            {
                ep = e.Location;
                g = this.CreateGraphics();
                g = DrawLine(p, sp, ep);
            }

            sp = ep;

        }
    }
}
</code>```

Hello guys! Im having a problem with this code and the title is my error. Im pretty new with c# and graphics too, I understand this code,(partially wrote it myself but this error is driving me crazy). Can anyone tell me where im mistaken and explain it to me? Thanks in advance! And btw is there an easy way for example via button to delete everything thats going to be painted on the form and how can i do that?

答:
DrawLine can be used on a Graphics object and also it returns void. So this:

```<code>g = DrawLine(p, sp, ep);
</code>```

Should be something like:

```<code>g.DrawLine(p, sp, ep);
</code>```

Body:
namespace MiniPaint
{
    public partial class Form1 : Form
    {
        Graphics g;
        Pen p = new Pen(Color.Black, 1);
        Point sp = new Point(0, 0);
        Point ep = new Point(0, 0);
        int k = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void red_Click(object sender, EventArgs e)
        {
            p.Color = red.BackColor;
            default1.BackColor = red.BackColor;
        }

        private void green_Click(object sender, EventArgs e)
        {
            p.Color = green.BackColor;
            default1.BackColor = green.BackColor;
        }

        private void blue_Click(object sender, EventArgs e)
        {
            p.Color = blue.BackColor;
            default1.BackColor = blue.BackColor;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            sp = e.Location;
            if (e.Button == MouseButtons.Left) ;
            k = 1;

        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            k = 0;

        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (k == 1)
            {
                ep = e.Location;
                g = this.CreateGraphics();
                g = DrawLine(p, sp, ep);
            }

            sp = ep;

        }
    }
}

Hello guys! Im having a problem with this code and the title is my error. Im pretty new with c# and graphics too, I understand this code,(partially wrote it myself but this error is driving me crazy). Can anyone tell me where im mistaken and explain it to me? Thanks in advance! And btw is there an easy way for example via button to delete everything thats going to be painted on the form and how can i do that?

Body:
DrawLine can be used on a Graphics object and also it returns void. So this:

g = DrawLine(p, sp, ep);

Should be something like:

g.DrawLine(p, sp, ep);


问:
Comparing a list against a tuple
I am trying to compare a list of values against a list of tuples. For example:

```<code>list = [1.0, 2.0]

list_of_tuples = [(3, 1.0, 'a'), (4, 2.0, 'b'), (5, 3.0, 'c')]
</code>```

Ideally what I am trying to do is take the list of tuples and check to see if all the values in that list are present in the other one. In the case of the example lists I provided above 1.0 and 2.0 are present but 3.0 is not. Another problem with this is that the location of the values in the list of tuples is going to be unknown when the comprehension takes place (which isn't the case in the example I provided above) so I'm not actually sure if it is possible to do what I am trying to do.

Any help with this would be appreciated, or an alternative solution would be helpful as well.

答:
```<code>flt=[]
for tup in list_of_tuples:
    flt.extend(tup)
for val in lst:
    if val in flt:
        print val
    else:
        print 'failed'
</code>```

Also, never call a var by a built-in name. call it lst, not list

Title: Comparing a list against a tuple

Body:
I am trying to compare a list of values against a list of tuples. For example:

list = [1.0, 2.0]

list_of_tuples = [(3, 1.0, 'a'), (4, 2.0, 'b'), (5, 3.0, 'c')]

Ideally what I am trying to do is take the list of tuples and check to see if all the values in that list are present in the other one. In the case of the example lists I provided above 1.0 and 2.0 are present but 3.0 is not. Another problem with this is that the location of the values in the list of tuples is going to be unknown when the comprehension takes place (which isn't the case in the example I provided above) so I'm not actually sure if it is possible to do what I am trying to do.

Any help with this would be appreciated, or an alternative solution would be helpful as well.

Body:
flt=[]
for tup in list_of_tuples:
    flt.extend(tup)
for val in lst:
    if val in flt:
        print val
    else:
        print 'failed'

Also, never call a var by a built-in name. call it lst, not list


问:
MySQL select 3 rows with the same value
In my "odds" table I have multiple rows with the same "match_id"
I would like to choose only 3 rows per match and then move for another match and again choose 3 rows for that and so on.

Imagine it like distinct but with 3 rows, not only 1.

Is there any way to do it without a loop in laravel 5?

Here is my query which takes multiple (more than 3) rows with the same match_id.

```<code>    \DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->get();
</code>```

Thanks.

答:
You can do this by generating rank for each record grouping on match_id.
Then you can retrieve only those records where rank<=3.

I have used one of my sample tables to write below sample query and it worked for me.(MYSQL)

Assume SurveyID is same as match_id in your case.
Query:

```<code>Select SurveyId,comments,val,paramid,rank1
From
(
SELECT SurveyId as SurveyId
,a.comments as comments
,a.val as val
,a.paramid as paramid,
(
     CASE SurveyId
     WHEN @curType
     THEN @curRow := @curRow + 1
     ELSE @curRow := 1 AND @curType := SurveyId END
     ) AS rank1
FROM test.sample_table a,
(SELECT @curRow := 0, @curType := '') r
) tmp
WHERE rank1 <=3
ORDER BY SurveyId ASC
</code>```

Title: MySQL select 3 rows with the same value

Body:
In my "odds" table I have multiple rows with the same "match_id"
I would like to choose only 3 rows per match and then move for another match and again choose 3 rows for that and so on.

Imagine it like distinct but with 3 rows, not only 1.

Is there any way to do it without a loop in laravel 5?

Here is my query which takes multiple (more than 3) rows with the same match_id.

    \DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->get();

Thanks.

Body:
You can do this by generating rank for each record grouping on match_id.
Then you can retrieve only those records where rank<=3.

I have used one of my sample tables to write below sample query and it worked for me.(MYSQL)

Assume SurveyID is same as match_id in your case.
Query:

Select SurveyId,comments,val,paramid,rank1
From
(
SELECT SurveyId as SurveyId
,a.comments as comments
,a.val as val
,a.paramid as paramid,
(
     CASE SurveyId
     WHEN @curType
     THEN @curRow := @curRow + 1
     ELSE @curRow := 1 AND @curType := SurveyId END
     ) AS rank1
FROM test.sample_table a,
(SELECT @curRow := 0, @curType := '') r
) tmp
WHERE rank1 <=3
ORDER BY SurveyId ASC


问:
Make single column editable in a UI5 smart table
I want to create a smart table with an editable column. I am using the metadata annotations to generate the table. The table property (editable = "true") makes all the columns editable. In my case, I want to make only a single column editable. I tried with the property sap:updatable="true" but it didn't work. Any ideas.
Thanks in advance.
This is my view by the way:

```<code><mvc:View
    xmlns="sap.m"
    xmlns:mvc="sap.ui.core.mvc"
    controllerName="QuickStartApplication3.controller.View1"
    xmlns:smartFilterBar="sap.ui.comp.smartfilterbar"
    xmlns:smartTable="sap.ui.comp.smarttable">
    <smartFilterBar:SmartFilterBar
        id="smartFilterBar"
        entityType="Product">
        <smartFilterBar:controlConfiguration>
            <smartFilterBar:ControlConfiguration
                key="ProductId"
                visibleInAdvancedArea="true"
                preventInitialDataFetchInValueHelpDialog="true" >
            </smartFilterBar:ControlConfiguration>
        </smartFilterBar:controlConfiguration>

        <smartFilterBar:controlConfiguration>
            <smartFilterBar:ControlConfiguration
               key="Name"
               visibleInAdvancedArea="true"
               preventInitialDataFetchInValueHelpDialog="true" >
            </smartFilterBar:ControlConfiguration>
        </smartFilterBar:controlConfiguration>

        <smartFilterBar:controlConfiguration>
            <smartFilterBar:ControlConfiguration
                key="Category"
                visibleInAdvancedArea="true"
                preventInitialDataFetchInValueHelpDialog="true" >
            </smartFilterBar:ControlConfiguration>
        </smartFilterBar:controlConfiguration>

    </smartFilterBar:SmartFilterBar>

    <smartTable:SmartTable
        id="smartTable_ResponsiveTable"
        smartFilterId="smartFilterBar"
        tableType="ResponsiveTable"
        editable="false"
        entitySet="Products"
        useVariantManagement="false"
        useTablePersonalisation="true"
        header="Products"
        showRowCount="true"
        useExportToExcel="true"
        enableAutoBinding="true">
    </smartTable:SmartTable>
</mvc:View>
</code>```

答:
Please have a look at the “Preview”-screenshot and the metadata.xml.

What happens if you set editable = "true" and annotate all properties of ‘Products’ with sap:updatable=”false”,
except for the single property that shall be editable, which you set to sap:updatable=”true”.

Don’t annotate entity set ‘Products’ with sap:updatable (or make sure that sap:updatable=”true”).

Body:
I want to create a smart table with an editable column. I am using the metadata annotations to generate the table. The table property (editable = "true") makes all the columns editable. In my case, I want to make only a single column editable. I tried with the property sap:updatable="true" but it didn't work. Any ideas.
Thanks in advance.
This is my view by the way:

<mvc:View
    xmlns="sap.m"
    xmlns:mvc="sap.ui.core.mvc"
    controllerName="QuickStartApplication3.controller.View1"
    xmlns:smartFilterBar="sap.ui.comp.smartfilterbar"
    xmlns:smartTable="sap.ui.comp.smarttable">
    <smartFilterBar:SmartFilterBar
        id="smartFilterBar"
        entityType="Product">
        <smartFilterBar:controlConfiguration>
            <smartFilterBar:ControlConfiguration
                key="ProductId"
                visibleInAdvancedArea="true"
                preventInitialDataFetchInValueHelpDialog="true" >
            </smartFilterBar:ControlConfiguration>
        </smartFilterBar:controlConfiguration>

        <smartFilterBar:controlConfiguration>
            <smartFilterBar:ControlConfiguration
               key="Name"
               visibleInAdvancedArea="true"
               preventInitialDataFetchInValueHelpDialog="true" >
            </smartFilterBar:ControlConfiguration>
        </smartFilterBar:controlConfiguration>

        <smartFilterBar:controlConfiguration>
            <smartFilterBar:ControlConfiguration
                key="Category"
                visibleInAdvancedArea="true"
                preventInitialDataFetchInValueHelpDialog="true" >
            </smartFilterBar:ControlConfiguration>
        </smartFilterBar:controlConfiguration>

    </smartFilterBar:SmartFilterBar>

    <smartTable:SmartTable
        id="smartTable_ResponsiveTable"
        smartFilterId="smartFilterBar"
        tableType="ResponsiveTable"
        editable="false"
        entitySet="Products"
        useVariantManagement="false"
        useTablePersonalisation="true"
        header="Products"
        showRowCount="true"
        useExportToExcel="true"
        enableAutoBinding="true">
    </smartTable:SmartTable>
</mvc:View>


问:
How to toggle on Monetise with ads option on YouTube with API
I am building an application that uploads videos to YouTube using PHP Google Client library. I was able to upload videos but couldn't toggle on the Monetise checkbox. There is very little information on the web.

I found this link to be helpful. http://www.techtonet.com/youtube-upload-videos-with-partner-api-in-php/#ipt_kb_toc_51_6

But I couldn't managed to do this.

Please help with this.

```<code>// Create a claim resource. Identify the video being claimed, the asset
 // that represents the claimed content, the type of content being claimed,
 // and the policy that you want to apply to the claimed video.
 $claim = new Google_Service_YouTubePartner_Claim();
 $claim->setAssetId($assetId);
 $claim->setVideoId($videoId);
 $claim->setPolicy($policy);
 $claim->setContentType("audiovisual");

 // Insert the created claim.
 $claimInsertResponse = $this->_youtubePartner->claims->insert($claim,
 array('onBehalfOfContentOwner' => $contentOwnerId));

 # Enable ads for the video. This example enables the TrueView ad format.
 $option = new Google_Service_YouTubePartner_VideoAdvertisingOption();
 //$option->setAdFormats(array("overlay", "trueview_instream", "standard_instream"));
 $option->setAdFormats(array("trueview_instream", "standard_instream"));
 $setAdvertisingResponse = $this->_youtubePartner->videoAdvertisingOptions->update(
 $videoId, $option, array('onBehalfOfContentOwner' => $contentOwnerId));
</code>```

答:
For me is working with this code

```<code>$youtubePartner = new \Google_Service_YouTubePartner($this->client);

$asset = new \Google_Service_YouTubePartner_Asset();
    $metadata = new \Google_Service_YouTubePartner_Metadata();
    $youtubePartner = new \Google_Service_YouTubePartner($this->client);
    $metadata->setTitle("Asset Title"));
    $metadata->setDescription("AssetDescription");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    $assetInsertResponse = $youtubePartner->assets->insert($asset, [
        'onBehalfOfContentOwner' => $this->contentOwnerId
    ]);

    $assetId = $assetInsertResponse['id'];

    $ratio = 100;
    $type = "exclude";
    $territories = [];

$owners = new \Google_Service_YouTubePartner_TerritoryOwners();
    $owners->setOwner($this->contentOwnerId);
    $owners->setRatio($ratio);
    $owners->setType($type);
    $owners->setTerritories($territories);
    $ownership = new \Google_Service_YouTubePartner_RightsOwnership();
    $ownership->setGeneral([$owners]);
    $youtubePartner->ownership->update($assetId, $ownership, ['onBehalfOfContentOwner' => $contentOwnerId]);

$policy = new \Google_Service_YouTubePartner_Policy();
    $policyRule = new \Google_Service_YouTubePartner_PolicyRule();
    $policyRule->setAction("monetize");
    $policy->setRules(array($policyRule));

$claim = new \Google_Service_YouTubePartner_Claim();
    $claim->setAssetId($assetId);
    $claim->setVideoId($videoId);
    $claim->setPolicy($policy);
    $claim->setContentType("audiovisual");

    $claimInsertResponse = $youtubePartner->claims->insert($claim, [
        'onBehalfOfContentOwner' => $contentOwnerId,
    ]);
</code>```

If is not working for you put all code here, after uploading video, once you have videoId from Youtube.
You only need to change $videoId and $contentOwnerId

Body:
I am building an application that uploads videos to YouTube using PHP Google Client library. I was able to upload videos but couldn't toggle on the Monetise checkbox. There is very little information on the web.

I found this link to be helpful. http://www.techtonet.com/youtube-upload-videos-with-partner-api-in-php/#ipt_kb_toc_51_6

But I couldn't managed to do this.

Please help with this.

// Create a claim resource. Identify the video being claimed, the asset
 // that represents the claimed content, the type of content being claimed,
 // and the policy that you want to apply to the claimed video.
 $claim = new Google_Service_YouTubePartner_Claim();
 $claim->setAssetId($assetId);
 $claim->setVideoId($videoId);
 $claim->setPolicy($policy);
 $claim->setContentType("audiovisual");

 // Insert the created claim.
 $claimInsertResponse = $this->_youtubePartner->claims->insert($claim,
 array('onBehalfOfContentOwner' => $contentOwnerId));

 # Enable ads for the video. This example enables the TrueView ad format.
 $option = new Google_Service_YouTubePartner_VideoAdvertisingOption();
 //$option->setAdFormats(array("overlay", "trueview_instream", "standard_instream"));
 $option->setAdFormats(array("trueview_instream", "standard_instream"));
 $setAdvertisingResponse = $this->_youtubePartner->videoAdvertisingOptions->update(
 $videoId, $option, array('onBehalfOfContentOwner' => $contentOwnerId));

Body:
For me is working with this code

$youtubePartner = new \Google_Service_YouTubePartner($this->client);

$asset = new \Google_Service_YouTubePartner_Asset();
    $metadata = new \Google_Service_YouTubePartner_Metadata();
    $youtubePartner = new \Google_Service_YouTubePartner($this->client);
    $metadata->setTitle("Asset Title"));
    $metadata->setDescription("AssetDescription");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    $assetInsertResponse = $youtubePartner->assets->insert($asset, [
        'onBehalfOfContentOwner' => $this->contentOwnerId
    ]);

    $assetId = $assetInsertResponse['id'];

    $ratio = 100;
    $type = "exclude";
    $territories = [];

$owners = new \Google_Service_YouTubePartner_TerritoryOwners();
    $owners->setOwner($this->contentOwnerId);
    $owners->setRatio($ratio);
    $owners->setType($type);
    $owners->setTerritories($territories);
    $ownership = new \Google_Service_YouTubePartner_RightsOwnership();
    $ownership->setGeneral([$owners]);
    $youtubePartner->ownership->update($assetId, $ownership, ['onBehalfOfContentOwner' => $contentOwnerId]);

$policy = new \Google_Service_YouTubePartner_Policy();
    $policyRule = new \Google_Service_YouTubePartner_PolicyRule();
    $policyRule->setAction("monetize");
    $policy->setRules(array($policyRule));

$claim = new \Google_Service_YouTubePartner_Claim();
    $claim->setAssetId($assetId);
    $claim->setVideoId($videoId);
    $claim->setPolicy($policy);
    $claim->setContentType("audiovisual");

    $claimInsertResponse = $youtubePartner->claims->insert($claim, [
        'onBehalfOfContentOwner' => $contentOwnerId,
    ]);

If is not working for you put all code here, after uploading video, once you have videoId from Youtube.
You only need to change $videoId and $contentOwnerId