问:
Searching for max value in an array of JSON objects
I have an array of JSON Objects that looks like the below sample:

```<code>    [ { _id: 58d98fc46cb2342d6848ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58d880126fb5087d684c8de4,
    updateNumber: '2',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 18:06:00 GMT-0400 (EDT),
    update: 'update 2',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58c23ae21bt2743d6328ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test2',
    impact: 'test2',
    incidentNumber: '23456',
    wasNew: true,
    __v: 0 } ]
</code>```

What I need to be able to do is for each incidentnumber, grab the latest update. Each incidentNumber will have multiple updates and I want to be able to retrieve the latest update (In the above example that is update 2 for incidentNumber 12345 and update 1 for incidentNumber 23456)

So far I have tried variations of _.max which will only work for one incidentNumber and not multiple.

I have searched extensively and so far have not found any questions that involved the same dataset I have.

Can anyone point me in the right direction on how to start solving this problem?

Thanks

答:
You can do this by first selecting the items with the incidentNumber that you want and then getting the one with the max updateNumber from those.
In es6 syntax it would look something like this, assuming your data is in a data variable

```<code>data
 .filter(d => d.incidentNumber === '12345')
 .reduce((o, e) => o.updateNumber && o.updateNumber > e.updateNumber ? o : e, {})
</code>```

In es5 syntax it's a bit more verbose

```<code>data
  .filter(function(d) { return d.incidentNumber === '12345'; })
  .reduce(function(o, e) { return  o.updateNumber && o.updateNumber > e.updateNumber ? o : e}, {})
</code>```

Or you could do the filtering and getting max in one pass

```<code>data.reduce(function(o, e) { return (e.incidentNumber === '12345' &&  o.updateNumber && o.updateNumber > e.updateNumber) ? o : e}, {})
</code>```

To get the object with the max updateNumber for each unique incident number you could maintain a hash of objects indexed by the incident number while you reduce

```<code>var results = data.reduce(function (m, e) {
    if (e.updateNumber && (!m[e.incidentNumber] || m[e.incidentNumber].updateNumber < e.updateNumber)) {
        m[e.incidentNumber] = e;
    }
    return m;
}, {});

Object.values(results); // will contain the array of objects with max updateNumber
</code>```

Body:
I have an array of JSON Objects that looks like the below sample:

    [ { _id: 58d98fc46cb2342d6848ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58d880126fb5087d684c8de4,
    updateNumber: '2',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 18:06:00 GMT-0400 (EDT),
    update: 'update 2',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58c23ae21bt2743d6328ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test2',
    impact: 'test2',
    incidentNumber: '23456',
    wasNew: true,
    __v: 0 } ]

What I need to be able to do is for each incidentnumber, grab the latest update. Each incidentNumber will have multiple updates and I want to be able to retrieve the latest update (In the above example that is update 2 for incidentNumber 12345 and update 1 for incidentNumber 23456)

So far I have tried variations of _.max which will only work for one incidentNumber and not multiple.

I have searched extensively and so far have not found any questions that involved the same dataset I have.

Can anyone point me in the right direction on how to start solving this problem?

Thanks

Body:
You can do this by first selecting the items with the incidentNumber that you want and then getting the one with the max updateNumber from those.
In es6 syntax it would look something like this, assuming your data is in a data variable

data
 .filter(d => d.incidentNumber === '12345')
 .reduce((o, e) => o.updateNumber && o.updateNumber > e.updateNumber ? o : e, {})

In es5 syntax it's a bit more verbose

data
  .filter(function(d) { return d.incidentNumber === '12345'; })
  .reduce(function(o, e) { return  o.updateNumber && o.updateNumber > e.updateNumber ? o : e}, {})

Or you could do the filtering and getting max in one pass

data.reduce(function(o, e) { return (e.incidentNumber === '12345' &&  o.updateNumber && o.updateNumber > e.updateNumber) ? o : e}, {})

To get the object with the max updateNumber for each unique incident number you could maintain a hash of objects indexed by the incident number while you reduce

var results = data.reduce(function (m, e) {
    if (e.updateNumber && (!m[e.incidentNumber] || m[e.incidentNumber].updateNumber < e.updateNumber)) {
        m[e.incidentNumber] = e;
    }
    return m;
}, {});

Object.values(results); // will contain the array of objects with max updateNumber


来源: stackexchange

问:
Drop all table with name like TABLE_REPO_%_<SYSDATE-2>, TABLE_REPO_%_<SYSDATE-3>, TABLE_REPO_%_<SYSDATE-4> and so on.
As a part of my script i create tables to take backup of data everyday and create tables with name sysdate -1. But i dont want to load my DB with such tables so i am dropping those tables also once they are 2 days old. This helps me to keep the data for 1 day. The table names will be like:
    TABLE_REPO_CR_SYSDATE-1
    TABLE_REPO_DRP_SYSDATE-1
    TABLE_REPO_UPD_SYSDATE-1

so suppose today is Mar 28th and i run my script the backup tables will be created as:

```<code>TABLE_REPO_CR_20170327
TABLE_REPO_DRP_20170327
TABLE_REPO_UPD_20170327
</code>```

And tomorrow (Mar 29th) when i run job the tables from today and tomorrow will be:
    TABLE_REPO_CR_20170328
    TABLE_REPO_DRP_20170328
    TABLE_REPO_UPD_20170328
On 30th Mar when i run script there will be:
    TABLE_REPO_CR_20170329
    TABLE_REPO_DRP_20170329
    TABLE_REPO_UPD_20170329

Now my question is i want to delete all tables which have name like TABLE_REPO_%_(SYSDATE-2 and less) eg all tables other than TABLE_REPO_%_(sysdate-1)

Individual i can delete as under, but how to delete all??

```<code> BEGIN

  FOR t in (SELECT tname FROM tab  WHERE tname like 'TABLE_REPO_%' || to_char(sysdate-2,'yyyymmdd'))
  LOOP
    EXECUTE immediate 'drop table ' || t.tname;
  END LOOP;
  EXCEPTION  WHEN OTHERS THEN
        IF SQLCODE != -942 THEN
             RAISE;
        END IF;
  END;
  /
 COMMIT;
</code>```

Thanks!

答:
You could just change your cursor query to find all matching tables except those for today or yesterday:

```<code>FOR t in (
  SELECT table_name as tname FROM user_tables
  WHERE table_name like 'TABLE_REPO_%'
  AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate-1,'yyyymmdd')
  AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate,'yyyymmdd')
)
LOOP
</code>```

If your mail tables also start with TABLE_REPO_ you could either exclude those explicitly as well:

```<code>  AND table_name NOT IN ('TABLE_REPO_CR', ...)
</code>```

or look for any that end with eight numeric digits (which is an assumption that will always be a date...):

```<code>  WHERE regexp_like(table_name, '^TABLE_REPO_.*\d{8}$')
</code>```

(I've also switch to look for user_tables.table_name instead of tab.tname, as that is more commonly used. In the docs it says "TAB is included for compatibility. Oracle recommends that you do not use this view.")

Quick demo to show what would be found (and dropped):

```<code>with user_tables (table_name) as (
  select 'TABLE_REPO_CR' from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate - 3, 'yyyymmdd') from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate - 2, 'yyyymmdd') from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate - 1, 'yyyymmdd') from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate, 'yyyymmdd') from dual
)
SELECT table_name as tname FROM user_tables
WHERE regexp_like(table_name, '^TABLE_REPO_.*\d{8}$')
AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate-1,'yyyymmdd')
AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate,'yyyymmdd');

TNAME
----------------------
TABLE_REPO_CR_20170326
TABLE_REPO_CR_20170327
</code>```

Incidentally, you may also want to check that tables for today and/or yesterday do exist, in case there has been a problem or a delay or whatever that could leave you with no backups.

ContentLicense: CC BY-SA 3.0

Body:
As a part of my script i create tables to take backup of data everyday and create tables with name sysdate -1. But i dont want to load my DB with such tables so i am dropping those tables also once they are 2 days old. This helps me to keep the data for 1 day. The table names will be like:
    TABLE_REPO_CR_SYSDATE-1
    TABLE_REPO_DRP_SYSDATE-1
    TABLE_REPO_UPD_SYSDATE-1

so suppose today is Mar 28th and i run my script the backup tables will be created as:

TABLE_REPO_CR_20170327
TABLE_REPO_DRP_20170327
TABLE_REPO_UPD_20170327

And tomorrow (Mar 29th) when i run job the tables from today and tomorrow will be:
    TABLE_REPO_CR_20170328
    TABLE_REPO_DRP_20170328
    TABLE_REPO_UPD_20170328
On 30th Mar when i run script there will be:
    TABLE_REPO_CR_20170329
    TABLE_REPO_DRP_20170329
    TABLE_REPO_UPD_20170329

Now my question is i want to delete all tables which have name like TABLE_REPO_%_(SYSDATE-2 and less) eg all tables other than TABLE_REPO_%_(sysdate-1)

Individual i can delete as under, but how to delete all??

 BEGIN

  FOR t in (SELECT tname FROM tab  WHERE tname like 'TABLE_REPO_%' || to_char(sysdate-2,'yyyymmdd'))
  LOOP
    EXECUTE immediate 'drop table ' || t.tname;
  END LOOP;
  EXCEPTION  WHEN OTHERS THEN
        IF SQLCODE != -942 THEN
             RAISE;
        END IF;
  END;
  /
 COMMIT;

Thanks!

Body:
You could just change your cursor query to find all matching tables except those for today or yesterday:

FOR t in (
  SELECT table_name as tname FROM user_tables
  WHERE table_name like 'TABLE_REPO_%'
  AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate-1,'yyyymmdd')
  AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate,'yyyymmdd')
)
LOOP

If your mail tables also start with TABLE_REPO_ you could either exclude those explicitly as well:

  AND table_name NOT IN ('TABLE_REPO_CR', ...)

or look for any that end with eight numeric digits (which is an assumption that will always be a date...):

  WHERE regexp_like(table_name, '^TABLE_REPO_.*\d{8}$')

(I've also switch to look for user_tables.table_name instead of tab.tname, as that is more commonly used. In the docs it says "TAB is included for compatibility. Oracle recommends that you do not use this view.")

Quick demo to show what would be found (and dropped):

with user_tables (table_name) as (
  select 'TABLE_REPO_CR' from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate - 3, 'yyyymmdd') from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate - 2, 'yyyymmdd') from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate - 1, 'yyyymmdd') from dual
  union all select 'TABLE_REPO_CR_' || to_char(sysdate, 'yyyymmdd') from dual
)
SELECT table_name as tname FROM user_tables
WHERE regexp_like(table_name, '^TABLE_REPO_.*\d{8}$')
AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate-1,'yyyymmdd')
AND table_name NOT like 'TABLE_REPO_%' || to_char(sysdate,'yyyymmdd');

TNAME
----------------------
TABLE_REPO_CR_20170326
TABLE_REPO_CR_20170327

Incidentally, you may also want to check that tables for today and/or yesterday do exist, in case there has been a problem or a delay or whatever that could leave you with no backups.


问:
Instantiating a class using companion object
Using companion object throws ambiguous reference error in REPL (spark-shell 2.1.0) when an instance of class is initialized (issue 4165 in 1.x.x closed).
I see this error in Spark 2.1.0 (see below).

```<code>scala> :pas
// Entering paste mode (ctrl-D to finish)

class X {
  var m : Long =0
  def add(x: Long): X = {
    m += x
    this
  }
}
object X {
  def apply(x:Long) = new X().add(x)
}

// Exiting paste mode, now interpreting.

defined class X
defined object X

scala> val v = X(2)
<console>:26: error: reference to X is ambiguous;
it is imported twice in the same scope by
import $line14$read.X
and import INSTANCE.X
       val v = X(2)
               ^
</code>```

Am I missing something?
Thanks

答:
You cannot define companion object like this in shell. You need either an object wrapper</p>

```<code>object myWrapper {
  class X {
    var m: Long = 0
    def add(x: Long): X = {
      m += x
      this
    }
  }

  object X {
    def apply(x:Long) = new X().add(x)
  }
}

import myWrapper._
</code>```

Body:
Using companion object throws ambiguous reference error in REPL (spark-shell 2.1.0) when an instance of class is initialized (issue 4165 in 1.x.x closed).
I see this error in Spark 2.1.0 (see below).

scala> :pas
// Entering paste mode (ctrl-D to finish)

class X {
  var m : Long =0
  def add(x: Long): X = {
    m += x
    this
  }
}
object X {
  def apply(x:Long) = new X().add(x)
}

// Exiting paste mode, now interpreting.

defined class X
defined object X

scala> val v = X(2)
<console>:26: error: reference to X is ambiguous;
it is imported twice in the same scope by
import $line14$read.X
and import INSTANCE.X
       val v = X(2)
               ^

Am I missing something?
Thanks

Body:
You cannot define companion object like this in shell. You need either an object wrapper

object myWrapper {
  class X {
    var m: Long = 0
    def add(x: Long): X = {
      m += x
      this
    }
  }

  object X {
    def apply(x:Long) = new X().add(x)
  }
}

import myWrapper._


问:
AutoHotKey FileCopy Error 1
I am creating AHK script that copy file to startup location but I can't get it to work.

```<code>#Warn
#NoEnv
appdata := A_AppData
username := A_Username
FileCopy, C:\Users\%username%\AppData\Local\file.exe, %appdata%\Microsoft\Windows\Start Menu\Programs\Startup\file.exe
msgbox, 0, lol, %errorlevel%
</code>```

I added temp line msgbox, 0, lol, %errorlevel% To see why it's not working. It always show me Error 1.

I was searching what means error 1 and i found this:

ERROR_INVALID_FUNCTION 1 (0x1) Incorrect function.

Can you help me I dont know what function it means.

Don't ask me why i cant do It manually.

(compiled using default Ahk2Exe convertor)

Sorry if my English is wrong, it's not my natural language.

答:
Your script seemed to work for me.

I suggest that you use IfExist to ensure both paths exist, like this:

```<code>ifnotexist, C:\Users\%username%\AppData\Local\file.exe
  msgbox, local path isn't correct

ifnotexist, %appdata%\Microsoft\Windows\Start Menu\Programs\Startup\
  msgbox, roaming path is not correct

ifnotexist, %appdata%\Microsoft\Windows\Start Menu\Programs\Startup\file.exe
  msgbox, file.exe already exists`, please use the overwrite switch
</code>```

If none of msgboxs appear, I'm betting the file in question either is being locked for reading, or some security feature is preventing you from copying the file.

Title: AutoHotKey FileCopy Error 1

Body:
I am creating AHK script that copy file to startup location but I can't get it to work.

#Warn
#NoEnv
appdata := A_AppData
username := A_Username
FileCopy, C:\Users\%username%\AppData\Local\file.exe, %appdata%\Microsoft\Windows\Start Menu\Programs\Startup\file.exe
msgbox, 0, lol, %errorlevel%

I added temp line msgbox, 0, lol, %errorlevel% To see why it's not working. It always show me Error 1.

I was searching what means error 1 and i found this:

ERROR_INVALID_FUNCTION 1 (0x1) Incorrect function.

Can you help me I dont know what function it means.

Don't ask me why i cant do It manually.

(compiled using default Ahk2Exe convertor)

Sorry if my English is wrong, it's not my natural language.

Body:
Your script seemed to work for me.

I suggest that you use IfExist to ensure both paths exist, like this:

ifnotexist, C:\Users\%username%\AppData\Local\file.exe
  msgbox, local path isn't correct

ifnotexist, %appdata%\Microsoft\Windows\Start Menu\Programs\Startup\
  msgbox, roaming path is not correct

ifnotexist, %appdata%\Microsoft\Windows\Start Menu\Programs\Startup\file.exe
  msgbox, file.exe already exists`, please use the overwrite switch

If none of msgboxs appear, I'm betting the file in question either is being locked for reading, or some security feature is preventing you from copying the file.


问:
How send post request from php to python?
I want send post request from php to python and get answer
I write this script which the send post

```<code>$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);
</code>```

I'm use custom python server

```<code>from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
</code>```

And python script which the takes post request

```<code>print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("<p>TEXT_2: {}</p>".format(text2))
</code>```

And then I get

```<code>write() argument must be str, not bytes\r\n'
</code>```

How can it be solved?
P.S Sorry for my bad english

答:
Check curl extension for php http://php.net/manual/en/book.curl.php</p>

```<code><?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://localhost:8080/cgi-bin/file.py");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "postvar1=value1&postvar2=value2&postvar3=value3");

// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
//          http_build_query(array('postvar1' => 'value1')));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);
</code>```

Body:
I want send post request from php to python and get answer
I write this script which the send post

$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);

I'm use custom python server

from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

And python script which the takes post request

print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("
TEXT_2: {}
".format(text2))

And then I get

write() argument must be str, not bytes\r\n'

How can it be solved?
P.S Sorry for my bad english

Body:
Check curl extension for php http://php.net/manual/en/book.curl.php

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://localhost:8080/cgi-bin/file.py");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "postvar1=value1&postvar2=value2&postvar3=value3");

// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
//          http_build_query(array('postvar1' => 'value1')));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);


问:
laravel 5.2 valid ajax request
How can we check in Laravel 5.2 if a request is a valid ajax request. In codeigniter ,we could check it like $this->input->is_ajax_request(). Does, Laravel 5.2 has something similar?

Also, I would like to know that how can we validate a request for csrf token. Is it fine if I let my webpage render through the 'web' middleware generating a csrf token and then pass this token as ajax request parameter? Would Laravel take care of validating the token or is there an alternate way around this?

I have checked the laravel 5.2 documentation, and since this is the first time I am dealing with laravel framework, it seems like the documentation assumes that the reader already has a familiarity with earlier versions of the framework. To a new comer like me this is little overwhelming.

Thanks in advance. Please let me know if you need more inputs from me.

Prakhar

答:
Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware will be able to validate the request.

To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function:

So to use AJAX request with POST method, you need to pass hidden CSRF token field along with ajax data:

```<code><script>

var token="<?php echo csrf_token(); ?>";

$.ajax({

  url:url,
  method:'POST',
  data:{
    '_token':token,
    'id':1
  }

})

</script>
</code>```

Title: laravel 5.2 valid ajax request

Body:
Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware will be able to validate the request.

To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function:

So to use AJAX request with POST method, you need to pass hidden CSRF token field along with ajax data:

<script>

var token="<?php echo csrf_token(); ?>";

$.ajax({

  url:url,
  method:'POST',
  data:{
    '_token':token,
    'id':1
  }

})

</script>


问:
Removing an object is causing freezes
[For clarification, 'monsters' is a list of NPCs that when shot by an object 'bullet' are removed from the list. ]

Error at start:

```<code>W/System.err: java.util.ConcurrentModificationException
W/System.err:     at java.util.ArrayList$Itr.next(ArrayList.java:831)
W/System.err:     at com.companyname.product.GameplayScene.update(GameplayScene.java:113)
//...
</code>```

I believe this means that it is trying to perform an action on something in the list that isn't there. So my question is could I please get some help identifying the point where an object is being called that isn't there, as I can't seem to find it. I know which class it is in as the first line references it for each error.

```<code>        for (Bullet bullet : player.getList())
            if (npcManager.bulletCollide(bullet)) { //checks for a collision between all npcs and all bullets
                 player.getList().remove(bullet);//npc is removed in method above

        }

       if (!gameOver) {
        npcManager.update(); //updates movement of npcs
        if (npcManager.playerCollideNPC(player)) {
            //end game
        }
    }

    for (RectNPC NPC : npcManager.getList())
        if (obstacleManager.NPCCollide(NPC)) { //checks collision between npcs and other objects
            //
        }

        int i = 0;
        //checks collisions between NPCs themselves
        while (i < (Constants.NUMBER_ENEMIES - 1)) {
            if (npcManager.getList().size() <= 1)
                return;
            if (Rect.intersects(npcManager.getList().get(i).getRectangle(), npcManager.getList().get(i + 1).getRectangle()))
                npcManager.getList().get(i).setRectangle(200);
            i += 1;
        }
    }
</code>```

(Above) I imagine the issue will be with calling something in the update (shown above) where the object is no longer available, is there an issue with any of how I am removing the NPCs?

```<code> public boolean bulletCollide(Bullet bullet) {
    for(RectNPC npc : monsters) {
        if(npc.bulletCollideNPC(bullet)) {
            monsters.remove(npc);
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }
    return false;
}
</code>```

(Above) Code where I am removing the NPC, I've included incase it is helpful - however it does do what it's meant to so I don't believe this is the problem.

My main question is, is there anything here that would be causing this error (the game stopping for a few frames and giving the error at the top) - or is there something/somewhere else in specific I should be looking at? Also I know some of my syntax isn't great, I apologise it's my first Java project.

Current Iterators:

```<code>for(Iterator<RectNPC> iterator = monsters.iterator(); iterator.hasNext();) {
        if(iterator.next().bulletCollideNPC(bullet)) {
            iterator.remove();
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }
</code>```

and

```<code>for (Iterator<Bullet> iterator = player.getList().iterator(); iterator.hasNext(); ) {
            if (npcManager.bulletCollide(iterator.next())) {
                iterator.remove();
                //
            }
        }
</code>```

答:
Use Iterator for a safe way to remove your Elements.

Note that Iterator.remove is the only safe way to modify a collection
  during iteration; the behavior is unspecified if the underlying
  collection is modified in any other way while the iteration is in
  progress.
  From Java SE documentation

```<code>static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}
</code>```

Example

Title: Removing an object is causing freezes

Body:
[For clarification, 'monsters' is a list of NPCs that when shot by an object 'bullet' are removed from the list. ]

Error at start:

W/System.err: java.util.ConcurrentModificationException
W/System.err:     at java.util.ArrayList$Itr.next(ArrayList.java:831)
W/System.err:     at com.companyname.product.GameplayScene.update(GameplayScene.java:113)
//...

I believe this means that it is trying to perform an action on something in the list that isn't there. So my question is could I please get some help identifying the point where an object is being called that isn't there, as I can't seem to find it. I know which class it is in as the first line references it for each error.

        for (Bullet bullet : player.getList())
            if (npcManager.bulletCollide(bullet)) { //checks for a collision between all npcs and all bullets
                 player.getList().remove(bullet);//npc is removed in method above

        }

       if (!gameOver) {
        npcManager.update(); //updates movement of npcs
        if (npcManager.playerCollideNPC(player)) {
            //end game
        }
    }

    for (RectNPC NPC : npcManager.getList())
        if (obstacleManager.NPCCollide(NPC)) { //checks collision between npcs and other objects
            //
        }

        int i = 0;
        //checks collisions between NPCs themselves
        while (i < (Constants.NUMBER_ENEMIES - 1)) {
            if (npcManager.getList().size() <= 1)
                return;
            if (Rect.intersects(npcManager.getList().get(i).getRectangle(), npcManager.getList().get(i + 1).getRectangle()))
                npcManager.getList().get(i).setRectangle(200);
            i += 1;
        }
    }

(Above) I imagine the issue will be with calling something in the update (shown above) where the object is no longer available, is there an issue with any of how I am removing the NPCs?

 public boolean bulletCollide(Bullet bullet) {
    for(RectNPC npc : monsters) {
        if(npc.bulletCollideNPC(bullet)) {
            monsters.remove(npc);
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }
    return false;
}

(Above) Code where I am removing the NPC, I've included incase it is helpful - however it does do what it's meant to so I don't believe this is the problem.

My main question is, is there anything here that would be causing this error (the game stopping for a few frames and giving the error at the top) - or is there something/somewhere else in specific I should be looking at? Also I know some of my syntax isn't great, I apologise it's my first Java project.

Current Iterators:

for(Iterator<RectNPC> iterator = monsters.iterator(); iterator.hasNext();) {
        if(iterator.next().bulletCollideNPC(bullet)) {
            iterator.remove();
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }

and

for (Iterator<Bullet> iterator = player.getList().iterator(); iterator.hasNext(); ) {
            if (npcManager.bulletCollide(iterator.next())) {
                iterator.remove();
                //
            }
        }

Body:
Use Iterator for a safe way to remove your Elements.

Note that Iterator.remove is the only safe way to modify a collection
  during iteration; the behavior is unspecified if the underlying
  collection is modified in any other way while the iteration is in
  progress.
  From Java SE documentation

static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}

Example


问:
Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443
I am working on a corporate network.

Trying to install npm. But I'm getting this error again and again.

```<code>$ npm install
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program     Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v6.1.0
npm ERR! npm  v3.8.6
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! syscall getaddrinfo

npm ERR! network getaddrinfo ENOTFOUND registry.npmjs.org    registry.npmjs.org:443
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Angular-test\angular-phonecat\npm-debug.log
</code>```

Tried this also: npm config set registry https://registry.npmjs.org/

Still getting the same error.

答:
First, edit NetworkManager.conf file:

```<code>vim /etc/NetworkManager/NetworkManager.conf
</code>```

Comment this line:

```<code>#dns=dnsmasq
</code>```

Finally

```<code>sudo service network-manager restart
sudo service docker restart
</code>```

Body:
I am working on a corporate network.

Trying to install npm. But I'm getting this error again and again.

$ npm install
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program     Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v6.1.0
npm ERR! npm  v3.8.6
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! syscall getaddrinfo

npm ERR! network getaddrinfo ENOTFOUND registry.npmjs.org    registry.npmjs.org:443
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Angular-test\angular-phonecat\npm-debug.log

Tried this also: npm config set registry https://registry.npmjs.org/

Still getting the same error.

Body:
First, edit NetworkManager.conf file:

vim /etc/NetworkManager/NetworkManager.conf

Comment this line:

#dns=dnsmasq

Finally

sudo service network-manager restart
sudo service docker restart


问:
SimpleDateFormat converting UTC to timezone incorrectly
I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

```<code>SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");
</code>```

The date object output has a date that looks like this

```<code>Fri Sep 01 01:00:00 MDT 2017
</code>```

When I should get an output of

```<code>Fri Sep 01 01:00:00 UTC 2017
</code>```

OR

```<code>Fri Aug 31 19:00:00 MDT 2017
</code>```

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.

答:
You should use the java.time classes for handling dates in modern Java.

Date doesn't store a timezone, and Date.toString() uses the system default timezone when rendering.

Body:
I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");

The date object output has a date that looks like this

Fri Sep 01 01:00:00 MDT 2017

When I should get an output of

Fri Sep 01 01:00:00 UTC 2017

OR

Fri Aug 31 19:00:00 MDT 2017

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.


问:
Excel Macro to Change Color of a Row Based on Column and Cell Value
I have the below code and would like it to be modified to work on all worksheets in the active workbook. Also, it currently does the entire row, but is there a way to modify it to only highlight the row until the data stops (example: A-J or A-C etc. not A-~)?</p>

```<code>Sub ChangeColor()

lRow = Range("A" & Rows.Count).End(xlUp).Row
Set MR = Range("A2:K2" & lRow)
For Each cell In MR
    If cell.Value = "CENTRL DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 10
    If cell.Value = "KC DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 3
    If cell.Value = "NE DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 11
    If cell.Value = "SE DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 30
    If cell.Value = "ST LOUIS DIST" Then cell.EntireRow.Interior.ColorIndex = 12
    If cell.Value = "SW DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 13
Next

End Sub
</code>```

答:
This should work for you. You can set a begin and end point to your liking just by changing the letters, which is a reference to the column letters. Range("A" & n, "G" & n) This is a simpler way to get what you want.

Hope I helped.

```<code>    Sub ChangeColor()
    Dim nlast As Long

    Sheets("sheetname").Activate
    Set sht = ActiveWorkbook.ActiveSheet
        nlast = Cells(Rows.Count, "A").End(xlUp).Row

                For n = nlast To 1 Step -1
                 If sht.Cells(n, "A").Value = "CENTRL DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 10
                 If sht.Cells(n, "A").Value = "KC DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 3
                 If sht.Cells(n, "A").Value = "NE DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 11
                 If sht.Cells(n, "A").Value = "SE DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 30
                 If sht.Cells(n, "A").Value = "ST DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 12
                 If sht.Cells(n, "A").Value = "SW DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 13
            Next n
     End Sub
</code>```

Body:
I have the below code and would like it to be modified to work on all worksheets in the active workbook. Also, it currently does the entire row, but is there a way to modify it to only highlight the row until the data stops (example: A-J or A-C etc. not A-~)?

Sub ChangeColor()

lRow = Range("A" & Rows.Count).End(xlUp).Row
Set MR = Range("A2:K2" & lRow)
For Each cell In MR
    If cell.Value = "CENTRL DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 10
    If cell.Value = "KC DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 3
    If cell.Value = "NE DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 11
    If cell.Value = "SE DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 30
    If cell.Value = "ST LOUIS DIST" Then cell.EntireRow.Interior.ColorIndex = 12
    If cell.Value = "SW DISTRICT" Then cell.EntireRow.Interior.ColorIndex = 13
Next

End Sub

Body:
This should work for you. You can set a begin and end point to your liking just by changing the letters, which is a reference to the column letters. Range("A" & n, "G" & n) This is a simpler way to get what you want.

Hope I helped.

    Sub ChangeColor()
    Dim nlast As Long

    Sheets("sheetname").Activate
    Set sht = ActiveWorkbook.ActiveSheet
        nlast = Cells(Rows.Count, "A").End(xlUp).Row

                For n = nlast To 1 Step -1
                 If sht.Cells(n, "A").Value = "CENTRL DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 10
                 If sht.Cells(n, "A").Value = "KC DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 3
                 If sht.Cells(n, "A").Value = "NE DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 11
                 If sht.Cells(n, "A").Value = "SE DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 30
                 If sht.Cells(n, "A").Value = "ST DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 12
                 If sht.Cells(n, "A").Value = "SW DISTRICT" Then sht.Range("A" & n, "G" & n).Interior.ColorIndex = 13
            Next n
     End Sub


问:
Laravel 5.4 $request->fullURL returning non https version of URL
I am pretty sure my issue is server related but I am just not 100% sure how to fix this.

Currently I am using Laravel Forge and Envoyer.
I have 3 servers:
 - 1 Load Balancer
 - 2 App Servers.

The Load Balancer is setup with the SSL certs.

Do all my app servers need to have the certs?

When i try to clone one of the domain certs to my App servers it crashes everything.

500 server errors, too many redirects. Also it is trying to load the parent domain cert when i really want to load another specific domain cert.

Let me know if I need to clarify this.

Update:

I have one code base with multiple potential domains: domain1.com, domain2.com, domain3.com etc. Some of them could have https, while some others could go without it.

Thanks in advance,

Citti

答:
Cheers to Taylor himself for this answer via email.

What I ended up needing was the following package: fideloper/trustedproxy

I installed this and added my Front end LB as the proxie and I am good to go.

Thanks again to Taylor for helping me out with this. Laravel FTW.

Citti


问:
How to change background color of jQuery UI Dialog?
I am having tough time figure out how to change background color of jQuery UI Dialog.

I've seen many reference how to change/remove title bar but not entire background including those curvy corner.

Here is my try:

http://jsfiddle.net/dEvKb/11/

The problem is .ui-widget-content only applies to square area within the dialog but not including curvy corner.

I found a class .ui-corner-all class hoping it will color the entire background but only half of the dialog is colored. (you can see this in the jsfiddle)

Has anyone done this before?

答:
If you want to target a specific dialog you can do it this way: </p>

```<code>$('#yourDialog').dialog(
{
    autoOpen: false,
    open: function(e) {
        $(e.target).parent().css('background-color','orangered');
    }
});
</code>```

Body:
If you want to target a specific dialog you can do it this way:

$('#yourDialog').dialog(
{
    autoOpen: false,
    open: function(e) {
        $(e.target).parent().css('background-color','orangered');
    }
});


问:
Hooking Up Visual Studio Team Project to Azure New Portal Only Showing GIT Projects
I am a bit baffled
In the old Azure portal I was able to hook up my TFVC project on VSTS for continuous deployment. Today I tried to hook up a new project to find that Azure is only listing my GIT based team projects. How do I get at TFVC projects now?

my workflow is as follows
AppServices, select site > Options > Continuous Deployment > Choose Source, Visual Studio Team Services > Choose Account, My Account, Choose Project, *Only GITs are listed.

答:
I don't know why but currently this appears to be by design.
On the Kudu wiki which handles continuous deployments for webapps for azure - one of the troubleshooting steps is:

Is your project a git project? We only support linking with VSTS git project.

https://github.com/projectkudu/kudu/wiki/Setting-up-a-VSTS-account-so-it-can-deploy-to-a-Web-App

An option to accomplish the same goal is to create a Release in VSTS that publishes to the App service. It is really simple because it can automatically pull down the Subscription and apps from Azure to configure it.


问:
Facebook Graph API PHP SDK 5.0 - 500 Error on getLoginUrl()
I am building a WordPress plugin that connects to the Facebook Graph API and will eventually be used to post to Facebook pages. I have followed their docs and I am getting a 500 server error when I click on "Log In With Facebook" The code="token" comes back in the url however there is a 500 server error.

I am running..

PHP: 5.4

Mbstring is enabled

If I take everything out of the fb-callback.php file and just echo 'working' it shows on the page and nothing breaks, but when I just have the facebook connect below it breaks... and I get the 500 error.

```<code>$fb = new Facebook\Facebook([
  'app_id' => 'my-secret',
  'app_secret' => 'my-id',
  'default_graph_version' => 'v2.8',
  ]);
</code>```

Here is the rest of the code. Keep in mind this is a WordPress Plugin and I it is my first one I am developing so I am sure it is a bit chaotic in its organization.

Settings Page:

```<code><?php
    session_start();
    $fb = new Facebook\Facebook([
      'app_id' => 'my-id',
      'app_secret' => 'my-secret',
      'default_graph_version' => 'v2.8',
    ]);

    $helper = $fb->getRedirectLoginHelper();

    $permissions = ['email', 'manage_pages', 'publish_pages', 'user_posts']; // Optional permissions

    $loginUrl = $helper->getLoginUrl('http://p11socialplugin.p11.com/wp-content/plugins/p11-social/fb-callback.php', $permissions);

    echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';

    ?>
</code>```

Here is the entire fb-callback.php

```<code><?php
$fb = new Facebook\Facebook([
  'app_id' => 'my-app-id ', // Replace {app-id} with your app id
  'app_secret' => 'my-app-secret',
  'default_graph_version' => 'v2.8',
  ]);

$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId({app-id}); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
    exit;
  }

  echo '<h3>Long-lived</h3>';
  var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://p11socialplugin.p11.com/wp-admin');

?>
</code>```

Error Log

```<code>[30-Jan-2017 22:03:28 UTC] PHP Warning:  session_start(): Cannot send session cookie - headers already sent by (output started at /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/header.php:16) in /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/facebook.php on line 2
    [30-Jan-2017 22:03:28 UTC] PHP Warning:  session_start(): Cannot send session cache limiter - headers already sent (output started at /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/header.php:16) in /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/facebook.php on line 2
    [30-Jan-2017 22:03:58 UTC] PHP Warning:  session_start(): Cannot send session cookie - headers already sent by (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
    [30-Jan-2017 22:03:58 UTC] PHP Warning:  session_start(): Cannot send session cache limiter - headers already sent (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
    [30-Jan-2017 22:04:08 UTC] PHP Warning:  session_start(): Cannot send session cookie - headers already sent by (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
    [30-Jan-2017 22:04:08 UTC] PHP Warning:  session_start(): Cannot send session cache limiter - headers already sent (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
</code>```

答:
You need to call session_start() at the beginning of fb-callback.php as well.

And you will also need to pass an additional argument to the Facebook\Facebook constructor, 'persistent_data_handler' => 'session', otherwise you will get CSRF exception.

```<code>new Facebook([
        'app_id' => '{app-id}',
        'app_secret' => '{app-secret-key}',
        'default_graph_version' => 'v2.8',
        'persistent_data_handler'=> 'session'
    ]);
</code>```

Body:
I am building a WordPress plugin that connects to the Facebook Graph API and will eventually be used to post to Facebook pages. I have followed their docs and I am getting a 500 server error when I click on "Log In With Facebook" The code="token" comes back in the url however there is a 500 server error.

I am running..

PHP: 5.4

Mbstring is enabled

If I take everything out of the fb-callback.php file and just echo 'working' it shows on the page and nothing breaks, but when I just have the facebook connect below it breaks... and I get the 500 error.

$fb = new Facebook\Facebook([
  'app_id' => 'my-secret',
  'app_secret' => 'my-id',
  'default_graph_version' => 'v2.8',
  ]);

Here is the rest of the code. Keep in mind this is a WordPress Plugin and I it is my first one I am developing so I am sure it is a bit chaotic in its organization.

Settings Page:

<?php
    session_start();
    $fb = new Facebook\Facebook([
      'app_id' => 'my-id',
      'app_secret' => 'my-secret',
      'default_graph_version' => 'v2.8',
    ]);

    $helper = $fb->getRedirectLoginHelper();

    $permissions = ['email', 'manage_pages', 'publish_pages', 'user_posts']; // Optional permissions

    $loginUrl = $helper->getLoginUrl('http://p11socialplugin.p11.com/wp-content/plugins/p11-social/fb-callback.php', $permissions);

    echo 'Log in with Facebook!';

    ?>

Here is the entire fb-callback.php

<?php
$fb = new Facebook\Facebook([
  'app_id' => 'my-app-id ', // Replace {app-id} with your app id
  'app_secret' => 'my-app-secret',
  'default_graph_version' => 'v2.8',
  ]);

$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
echo '
Access Token
';
var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '
Metadata
';
var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId({app-id}); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "
Error getting long-lived access token: " . $helper->getMessage() . "
\n\n";
    exit;
  }

  echo '
Long-lived
';
  var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://p11socialplugin.p11.com/wp-admin');

?>

Error Log

[30-Jan-2017 22:03:28 UTC] PHP Warning:  session_start(): Cannot send session cookie - headers already sent by (output started at /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/header.php:16) in /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/facebook.php on line 2
    [30-Jan-2017 22:03:28 UTC] PHP Warning:  session_start(): Cannot send session cache limiter - headers already sent (output started at /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/header.php:16) in /Users/garrett/Development/wp-playground/wp-content/themes/twentyseventeen/facebook.php on line 2
    [30-Jan-2017 22:03:58 UTC] PHP Warning:  session_start(): Cannot send session cookie - headers already sent by (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
    [30-Jan-2017 22:03:58 UTC] PHP Warning:  session_start(): Cannot send session cache limiter - headers already sent (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
    [30-Jan-2017 22:04:08 UTC] PHP Warning:  session_start(): Cannot send session cookie - headers already sent by (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103
    [30-Jan-2017 22:04:08 UTC] PHP Warning:  session_start(): Cannot send session cache limiter - headers already sent (output started at /Users/garrett/Development/wp-playground/wp-admin/includes/template.php:1995) in /Users/garrett/Development/wp-playground/wp-content/plugins/p11-social/class.p11-social.php on line 103

Body:
You need to call session_start() at the beginning of fb-callback.php as well.

And you will also need to pass an additional argument to the Facebook\Facebook constructor, 'persistent_data_handler' => 'session', otherwise you will get CSRF exception.

new Facebook([
        'app_id' => '{app-id}',
        'app_secret' => '{app-secret-key}',
        'default_graph_version' => 'v2.8',
        'persistent_data_handler'=> 'session'
    ]);


问:
Retrieving the COM class factory for component failed. Access is denied. HRESULT: 0x80070005 E_ACCESSDENIED
While trying to open Outlook for attachment in mail, via IIS asp.net website got this error. Assign IIS USR and Network with full permissions in DCOMCnfg to Microsoft OutLook component but nothing work.

Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

```<code>using System;
using Outlook = Microsoft.Office.Interop.Outlook;

// Create the Outlook application.
                Outlook.Application oApp = new Outlook.Application();
                // Create a new mail item.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
                // Set HTMLBody.
                //add the body of the email
                oMsg.HTMLBody = "Hello, This is test for sending pdf attachment using OutLook";
                //Add an attachment.
                String sDisplayName = "MyAttachment";
                int iPosition = (int)oMsg.Body.Length + 1;
                int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
                //now attached the file
                Outlook.Attachment oAttach = oMsg.Attachments.Add(Server.MapPath("~/TestSendFile.pdf"), iAttachType, iPosition, sDisplayName);
                //Subject line
                oMsg.Subject = "Your Subject will go here.";
                // Add a recipient.
                Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
                // Change the recipient in the next line if necessary.
                Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("user1@comecompany.com");
                oRecip.Resolve();
                // Send.

                oMsg.Display();
</code>```

答:
Outlook Object Model (just like any other Office app) cannot be used from a service (such as IIS).
More than that, you are attempting to display a message on the server side where nobody will ever see it.

You can use either

Exchange Web Services (in case of an Exchange mailbox)

Extended MAPI (C++ or Delphi only)

Redemption (I am its author) - it wraps Extended MAPI and its RDO family of objects can be used from a service. It can be used from any language, including C#.

If you are attempting to display a message on the client side, your choices are

mailto url - does not allow HTML or attachments

Use Outlook Object Model from the client side Java Script. Your site must be trusted and you can ony use COM in IE.

Generate an EML (MIME) file and provide a link to it - Outlook will be happy to open from the browser and display it.

Body:
While trying to open Outlook for attachment in mail, via IIS asp.net website got this error. Assign IIS USR and Network with full permissions in DCOMCnfg to Microsoft OutLook component but nothing work.

Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

using System;
using Outlook = Microsoft.Office.Interop.Outlook;

// Create the Outlook application.
                Outlook.Application oApp = new Outlook.Application();
                // Create a new mail item.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
                // Set HTMLBody.
                //add the body of the email
                oMsg.HTMLBody = "Hello, This is test for sending pdf attachment using OutLook";
                //Add an attachment.
                String sDisplayName = "MyAttachment";
                int iPosition = (int)oMsg.Body.Length + 1;
                int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
                //now attached the file
                Outlook.Attachment oAttach = oMsg.Attachments.Add(Server.MapPath("~/TestSendFile.pdf"), iAttachType, iPosition, sDisplayName);
                //Subject line
                oMsg.Subject = "Your Subject will go here.";
                // Add a recipient.
                Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
                // Change the recipient in the next line if necessary.
                Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("user1@comecompany.com");
                oRecip.Resolve();
                // Send.

                oMsg.Display();

ContentLicense: CC BY-SA 4.0


问:
How can i put a logo partially over an image and then have text over the image
I have a theme that has markup like this:

```<code><div class="logo">
   <a id="logo" href="http://test.rudtek.com" title="test">
        <img class="logo-main scale-with-grid" src="/wp-content/uploads/2017/03/seasons_management_logo.jpg" alt="seasons_management_logo">
    </a>
    <div class="containerBox">
        <img class="img-responsive" <img="" src="/wp-content/uploads/revslider/slider-home-4/img-slider-4-3-825x510.jpg">
        <div class="text-box">
            <p class="dataNumber">Home 4</p>
        </div>
    </div>
</div>
</code>```

This gives me an image like this:

BUt what I really want it to look like is this:

Size ratio isn't the most important here, but I can't fiture out how to get the seasons logo to go over the dear image.

This is my css:

```<code>.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}
</code>```

答:
You can absolutely position #logo over .containerBox and give #logo a z-index so it will stack on top, then use a margin-left on .containerBox to push it to the right.

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

/* added these styles */
.logo {
  position: relative;
}
#logo {
  position: absolute;
  top: 1em; left: 0;
  z-index: 1;
  background: white;
}
.containerBox {
  margin-left: 100px;
}

/* you don't need this, just for this pepsi logo which is huge */
#logo img {
  max-width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="logo">

    <img class="logo-main scale-with-grid" src="https://s-media-cache-ak0.pinimg.com/originals/f7/aa/ed/f7aaed9fcacfe6df89cef0a16cf06266.png" alt="seasons_management_logo">

  <div class="containerBox">
    <img class="img-responsive" src="http://kenwheeler.github.io/slick/img/fonz1.png">
    <div class="text-box">
      <p class="dataNumber">Home 4</p>
    </div>
  </div>
</div></code>```

Body:
I have a theme that has markup like this:

        <img class="img-responsive"

Home 4

This gives me an image like this:

BUt what I really want it to look like is this:

Size ratio isn't the most important here, but I can't fiture out how to get the seasons logo to go over the dear image.

This is my css:

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

Body:
You can absolutely position #logo over .containerBox and give #logo a z-index so it will stack on top, then use a margin-left on .containerBox to push it to the right.

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

/* added these styles */
.logo {
  position: relative;
}
#logo {
  position: absolute;
  top: 1em; left: 0;
  z-index: 1;
  background: white;
}
.containerBox {
  margin-left: 100px;
}

/* you don't need this, just for this pepsi logo which is huge */
#logo img {
  max-width: 200px;
}

<div class="logo">
  <a id="logo" href="http://test.rudtek.com" title="test">
    <img class="logo-main scale-with-grid" src="https://s-media-cache-ak0.pinimg.com/originals/f7/aa/ed/f7aaed9fcacfe6df89cef0a16cf06266.png" alt="seasons_management_logo">
  </a>
  <div class="containerBox">
    <img class="img-responsive" src="http://kenwheeler.github.io/slick/img/fonz1.png">
    <div class="text-box">
      <p class="dataNumber">Home 4</p>
    </div>
  </div>
</div>


问:
Drivers for Classes in Java “Rectangle"
I’ve never used a separate file for a driver in Java.  I’m used to just using a main method.  I’ve used separate files in Python but Java is new.  Below is my code for each class (“Rectangle” and “Driver”), each from separate files.

Update with the methods changed to static:  Don’t pay attention to the change in class names or formatting…I’m just tweaking so it will work with MyProgrammingLab.  I still have to add in parameters for length and width being between 0.0 and 20.0 only (easy if-else statements).

```<code>import java.util.Scanner;
</code>```

public class Driver{

```<code>public static void main(String[] args) {

    Scanner input = new Scanner( System.in);

    System.out.print("Enter length of rectangle:");
    double length = input.nextDouble();
    System.out.print("Enter width of rectangle:");
    double width = input.nextDouble();

    Rectangle  Perimeter = new Rectangle(length, width);
    Perimeter.getPerimeter();
    Rectangle  Area = new Rectangle(length, width);
    Area.getArea();

    System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());

}
</code>```

}

final class Rectangle {

```<code>private static double mLength;
private static double mWidth;

public Rectangle(double length, double width){
    mLength = length;
    mWidth = width;
}
public double getLength(){
    return mLength;
}

public double getWidth(){
    return mWidth;
}

public static double getArea(){
    double area = mWidth*mLength;
    return area;
}
public static double getPerimeter(){
    double perimeter = (mWidth*2)+(mLength*2);
    return perimeter;

}
</code>```

}

答:
The default constructor is provided by compiler if there are no constructor written explicitly.

But if you explicitly write any constructor in the class, then whenever you call a constructor, be it no-argument or with arguments, it will always look for explicitly defined constructor in class.

And, this is logically correct since, if you want to block creation of objects without any data in it, adding a constructor with argiment is the way to go.

So either explicitly write a no argument constructor in Rectangle and use setter to set its attributs, or just use the argument constructor in your method.

Add to Rectangle.class an empty constructor :

```<code>public Rectangle() {

}
</code>```

Or Use constructor declared with parameters in your method

```<code>Rectangle rectangle = new Rectangle(length, width);
</code>```

In your case you are using the rectangle object wrong.
I think what you looking to do is this :

```<code>Rectangle  rectangle = new Rectangle(length , width );
System.out.printf("Area: %.1f, Perimeter: %.1f",rectangle.getArea() ,rectangle.getPerimeter());
</code>```

Title: Drivers for Classes in Java “Rectangle"

Body:
I’ve never used a separate file for a driver in Java.  I’m used to just using a main method.  I’ve used separate files in Python but Java is new.  Below is my code for each class (“Rectangle” and “Driver”), each from separate files.

Update with the methods changed to static:  Don’t pay attention to the change in class names or formatting…I’m just tweaking so it will work with MyProgrammingLab.  I still have to add in parameters for length and width being between 0.0 and 20.0 only (easy if-else statements).

import java.util.Scanner;

public class Driver{

public static void main(String[] args) {

    Scanner input = new Scanner( System.in);

    System.out.print("Enter length of rectangle:");
    double length = input.nextDouble();
    System.out.print("Enter width of rectangle:");
    double width = input.nextDouble();

    Rectangle  Perimeter = new Rectangle(length, width);
    Perimeter.getPerimeter();
    Rectangle  Area = new Rectangle(length, width);
    Area.getArea();

    System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());

}

}

final class Rectangle {

private static double mLength;
private static double mWidth;

public Rectangle(double length, double width){
    mLength = length;
    mWidth = width;
}
public double getLength(){
    return mLength;
}

public double getWidth(){
    return mWidth;
}

public static double getArea(){
    double area = mWidth*mLength;
    return area;
}
public static double getPerimeter(){
    double perimeter = (mWidth*2)+(mLength*2);
    return perimeter;

}

}

Body:
The default constructor is provided by compiler if there are no constructor written explicitly.

But if you explicitly write any constructor in the class, then whenever you call a constructor, be it no-argument or with arguments, it will always look for explicitly defined constructor in class.

And, this is logically correct since, if you want to block creation of objects without any data in it, adding a constructor with argiment is the way to go.

So either explicitly write a no argument constructor in Rectangle and use setter to set its attributs, or just use the argument constructor in your method.

Add to Rectangle.class an empty constructor :

public Rectangle() {

}

Or Use constructor declared with parameters in your method

Rectangle rectangle = new Rectangle(length, width);

In your case you are using the rectangle object wrong.
I think what you looking to do is this :

Rectangle  rectangle = new Rectangle(length , width );
System.out.printf("Area: %.1f, Perimeter: %.1f",rectangle.getArea() ,rectangle.getPerimeter());


问:
How to stop my reciept stop repeating itself
This is a program which asks a user to input a barcode , then my program finds the specified product , asks the user how many of a product they would like to purchase , if they would like to continue , calculates the total price and then is SUPPOSED to print out a reciept,howevery my problem is that the reciept repeats its values and is not rounded too two decimal places.

```<code>press 0 to stop shopping and print your reciept or press 1 to continue shopping0
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '2.80']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '0', '0']
</code>```

I am pretty sure this is where the code is messing up (my reciept code)

```<code>def quantity():
    fileOne = open('receipt.csv', 'a')
    writer = csv.writer(fileOne)
    global total_price
    product_data = read_csv_file()
    matches = search_user_input(product_data)
    if matches: # Will not be True if search_user_input returned None
        print("apple")
        product, price = matches[0], matches[1]
        order = int(input("How much of {} do you want?".format(product)))
        values = [str(product), str(price), str(order*price)]
        price = str(round(price,2))
        writer.writerows((values,))
        total_price.append(order * price)
    continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
    if (continue_shopping == 0):
        fileOne.close()
        fileTwo = open("receipt.csv" , "r")
        reader = csv.reader(fileTwo)
        for row in reader:
            if row != None:
                print(row)
    elif continue_shopping==1:
        quantity()
</code>```

And this is the whole code as a entity

```<code>import csv
import locale
continue_shopping = 0
total_price = []

locale.setlocale( locale.LC_ALL, '' )
def read_csv_file():
    global total_price
    """ reads csv data and appends each row to list """
    csv_data = []
    with open("task2.csv") as csvfile:
         spamreader = csv.reader(csvfile, delimiter=",", quotechar="|")
         for row in spamreader:
             csv_data.append(row)
    return csv_data

def get_user_input():
    global total_price
    """ get input from user """
    while True:
        try:
            GTIN = int(input("input your gtin-8 number: "))
            return GTIN # Breaks the loop and returns the value
        except:
            print ("Oops! That was not a valid number.  Try again")

def search_user_input(product_data):
    global total_price
    repeat=""
    # Pass the csv data as an argument
    """ search csv data for string """
    keep_searching = True

    while keep_searching:
        gtin = get_user_input()
        for row in product_data:
            if row[0] == str(gtin):
                product = row[1]
                price = round(float(row[2]),2)
                return(product, price)
        while True:
            try:
                repeat = input("not in there? search again? If so (y), else press enter to continue")
                break
            except:
                print("please make sure you enter a valid string")
        if repeat != 'y':
            keep_searching = False
            return None

def quantity():
    fileOne = open('receipt.csv', 'a')
    writer = csv.writer(fileOne)
    global total_price
    product_data = read_csv_file()
    matches = search_user_input(product_data)
    if matches: # Will not be True if search_user_input returned None
        print("apple")
        product, price = matches[0], matches[1]
        order = int(input("How much of {} do you want?".format(product)))
        values = [str(product), str(price), str(order*price)]
        writer.writerows((values,))
        total_price.append(order * price)
    continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
if continue_shopping !=0 and continue_shopping !=1:
    if (continue_shopping == 0):
        fileOne.close()
        fileTwo = open("receipt.csv" , "r")
        reader = csv.reader(fileTwo)
        for row in reader:
            if row != None:
                print(row)
    elif continue_shopping==1:
        search_user_input()
        quantity()
quantity()
</code>```

I would appreciate any help with my program or a general pointer to the right direction. Thank you!

答:
first try removing all the "global total_price" definitions in your functions.. (it would reset the variable each time)
Secondly in your function search_user_input() i would change the line price = round(float(row[2]),2) into price = float(row[2]) (you can later use format to display the final float value in the desired format).
Thirdly in your function quantity() you should change the line if continue_shopping !=0 and continue_shopping !=1: into if continue_shopping ==0 or continue_shopping ==1: , good luck

Body:
This is a program which asks a user to input a barcode , then my program finds the specified product , asks the user how many of a product they would like to purchase , if they would like to continue , calculates the total price and then is SUPPOSED to print out a reciept,howevery my problem is that the reciept repeats its values and is not rounded too two decimal places.

press 0 to stop shopping and print your reciept or press 1 to continue shopping0
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '2.80']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.20']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '1.4', '32.199999999999996']
[]
['celery', '0', '0']

I am pretty sure this is where the code is messing up (my reciept code)

def quantity():
    fileOne = open('receipt.csv', 'a')
    writer = csv.writer(fileOne)
    global total_price
    product_data = read_csv_file()
    matches = search_user_input(product_data)
    if matches: # Will not be True if search_user_input returned None
        print("apple")
        product, price = matches[0], matches[1]
        order = int(input("How much of {} do you want?".format(product)))
        values = [str(product), str(price), str(order*price)]
        price = str(round(price,2))
        writer.writerows((values,))
        total_price.append(order * price)
    continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
    if (continue_shopping == 0):
        fileOne.close()
        fileTwo = open("receipt.csv" , "r")
        reader = csv.reader(fileTwo)
        for row in reader:
            if row != None:
                print(row)
    elif continue_shopping==1:
        quantity()

And this is the whole code as a entity

import csv
import locale
continue_shopping = 0
total_price = []

locale.setlocale( locale.LC_ALL, '' )
def read_csv_file():
    global total_price
    """ reads csv data and appends each row to list """
    csv_data = []
    with open("task2.csv") as csvfile:
         spamreader = csv.reader(csvfile, delimiter=",", quotechar="|")
         for row in spamreader:
             csv_data.append(row)
    return csv_data

def get_user_input():
    global total_price
    """ get input from user """
    while True:
        try:
            GTIN = int(input("input your gtin-8 number: "))
            return GTIN # Breaks the loop and returns the value
        except:
            print ("Oops! That was not a valid number.  Try again")

def search_user_input(product_data):
    global total_price
    repeat=""
    # Pass the csv data as an argument
    """ search csv data for string """
    keep_searching = True

    while keep_searching:
        gtin = get_user_input()
        for row in product_data:
            if row[0] == str(gtin):
                product = row[1]
                price = round(float(row[2]),2)
                return(product, price)
        while True:
            try:
                repeat = input("not in there? search again? If so (y), else press enter to continue")
                break
            except:
                print("please make sure you enter a valid string")
        if repeat != 'y':
            keep_searching = False
            return None

def quantity():
    fileOne = open('receipt.csv', 'a')
    writer = csv.writer(fileOne)
    global total_price
    product_data = read_csv_file()
    matches = search_user_input(product_data)
    if matches: # Will not be True if search_user_input returned None
        print("apple")
        product, price = matches[0], matches[1]
        order = int(input("How much of {} do you want?".format(product)))
        values = [str(product), str(price), str(order*price)]
        writer.writerows((values,))
        total_price.append(order * price)
    continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
if continue_shopping !=0 and continue_shopping !=1:
    if (continue_shopping == 0):
        fileOne.close()
        fileTwo = open("receipt.csv" , "r")
        reader = csv.reader(fileTwo)
        for row in reader:
            if row != None:
                print(row)
    elif continue_shopping==1:
        search_user_input()
        quantity()
quantity()

I would appreciate any help with my program or a general pointer to the right direction. Thank you!


问:
How to implement mod_rewrite after PHP redirection?
I have a lot of old urls I need to redirect to certain categories.

www.example.com/some-requested-product -> www.example.com/index.php?categories=some-requested-product

www.example.com/some-requested-article -> www.example.com/index.php?articles=some-requested-article

www.example.com/some-requested-user -> www.example.com/index.php?users=some-requested-user

And so on - I hope you get the point. (Actually there's no hint in the URL about the content type.)

I've created a redirection, now I can reach the content I need:

RewriteRule ^([a-zA-Z0-9-]+)$ /index.php%{REQUEST_URI}

In the PHP I can query now the urls to see what type of content it is:

if ($_SERVER['REQUEST_URI'] == "/some-requested-content") { Redirect($BaseURL."/index.php?category_type=some-requested-content", false); }

Redirection is made, content is fetched. (I know it's not safe etc. just for testing.)

My main problem is now, how can I mask the URL after these events?

I would like to see the same URL originally requested ( www.example.com/some-requested-content ) in the address bar of the browser, not the one it is redirected to.

Is it possible?
Or can you think about another solution?

答:
You're looking for query string append (QSA)

```<code>RewriteCond %{REQUEST_URI} ^/some-requested-article$
RewriteRule ^(.*)$ index.php?articles=$1 [L,QSA]

RewriteCond %{REQUEST_URI} ^/some-requested-product
RewriteRule ^(.*)$ index.php?categories=$1 [L,QSA]
</code>```

and so on, you'd make the regex cover each case of query string, like category, articles, users, and so on.

The L means last to process in the rewrite rules, that's very important to use.

This preserves the visible URI, but internally passes the page processing the request the desired query string data.

So you aren't really 'masking' the url, the url is basically simply filling in the desired query string data, which is then sent to the file processing the request. This is a common method, it's how a lot of blogging and cms platforms handle search engine friendly urls, for example.

Note however that because you didn't provide a more accurate example of your real urls in each case, the solution I am posting would require regex that handles the variable values. If there is no actual pattern difference between the types, then you can't use this method, you'd have to go down the list of exact values/urls per query string type and list them as possible matches using the [OR] option in the RewriteCond tests. That works as long as there aren't too many pages involved.

Like so:

```<code>RewriteCond %{REQUEST_URI} ^/beans-are-fun$ [OR]
RewriteCond %{REQUEST_URI} ^/rice-is-fun$ [OR]
RewriteCond %{REQUEST_URI} ^/fun-with-rice-and-beans$
RewriteRule ^(.*)$ index.php?articles=$1 [L,QSA]
</code>```

Body:
You're looking for query string append (QSA)

RewriteCond %{REQUEST_URI} ^/some-requested-article$
RewriteRule ^(.*)$ index.php?articles=$1 [L,QSA]

RewriteCond %{REQUEST_URI} ^/some-requested-product
RewriteRule ^(.*)$ index.php?categories=$1 [L,QSA]

and so on, you'd make the regex cover each case of query string, like category, articles, users, and so on.

The L means last to process in the rewrite rules, that's very important to use.

This preserves the visible URI, but internally passes the page processing the request the desired query string data.

So you aren't really 'masking' the url, the url is basically simply filling in the desired query string data, which is then sent to the file processing the request. This is a common method, it's how a lot of blogging and cms platforms handle search engine friendly urls, for example.

Note however that because you didn't provide a more accurate example of your real urls in each case, the solution I am posting would require regex that handles the variable values. If there is no actual pattern difference between the types, then you can't use this method, you'd have to go down the list of exact values/urls per query string type and list them as possible matches using the [OR] option in the RewriteCond tests. That works as long as there aren't too many pages involved.

Like so:

RewriteCond %{REQUEST_URI} ^/beans-are-fun$ [OR]
RewriteCond %{REQUEST_URI} ^/rice-is-fun$ [OR]
RewriteCond %{REQUEST_URI} ^/fun-with-rice-and-beans$
RewriteRule ^(.*)$ index.php?articles=$1 [L,QSA]


问:
Trouble with header files in c++: linker command failed
Apologizing ahead of time for what I'm certain is a very simple problem, but I've been unable to find a solution for this. I'm putting a very simple C++ project together, but having trouble using a header file appropriately.

The directory structure is below:

```<code>.
├── mainGraph
│   └── hnsw.cpp
└── utils
    ├── distances.cpp
    └── distances.h
</code>```

The distances header file (distances.h):

```<code>#ifndef DISTANCES
#define DISTANCES

#include <vector>

enum class Metric { Cosine, Euclidean};

double distance(const std::vector<double>& A, const std::vector<double>& B, Metric metric);
double similarity(const std::vector<double>& A, const std::vector<double>& B, Metric metric);

#endif
</code>```

And finally hnsw.cpp:

```<code>#include "../utils/distances.h"
#include <vector>
#include <iostream>

int main(){
    std::vector<double> A = {0.1, 0.5, 0.7, 1.1};
    std::vector<double> B = {0.5, 0.3, 0.8, 0.9};

    std::cout << distance(A, B, Metric::Cosine) << '\n';
}
</code>```

Now, when I actually try to compile hnsw.cpp with the following command: g++ hnsw.cpp --std=c++11 I get the following error:

```<code>Undefined symbols for architecture x86_64:
  "distance(std::__1::vector<double, std::__1::allocator<double> > const&, std::__1::vector<double, std::__1::allocator<double> > const&, Metric)", referenced from:
      _main in hnsw-ad0e05.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

If I move the main into the distances.cpp file then everything works smoothly. For the purposes of brevity I'm not posting that whole file as it's sizable and I'm fairly certain it's not relevant. If there are any resources about understanding the general process here that would also be very helpful.

答:
If you don't want to build individual object files for later linking, but instead build the whole executable file in one go, you need to specify all the participating translation units on the command line:

```<code>g++ -std=c++11 hnsw.cpp ../utils/distances.cpp
</code>```

The output file will be called a.out, unless you also override that name with the -o flag.

Usually you would compile translation units separately and link them in a separate step:

g++ -std=c++11 mainGraph/hnsw.cpp -c -o mainGraph/hnsw.o
g++ -std=c++11 utils/distances.cpp -c -o utils/distances.o

g++ -std=c++11 mainGraph.hnsw.o utils/distances.o -o myprog
```

You also wouldn't maintain these commands by hand, but stick them into a Makefile, or some equivalent build system. The key point is that you don't need to recompile translation units that haven't changed just because you changed some part of your source code.

Body:
Apologizing ahead of time for what I'm certain is a very simple problem, but I've been unable to find a solution for this. I'm putting a very simple C++ project together, but having trouble using a header file appropriately.

The directory structure is below:

.
├── mainGraph
│   └── hnsw.cpp
└── utils
    ├── distances.cpp
    └── distances.h

The distances header file (distances.h):

#ifndef DISTANCES
#define DISTANCES

#include <vector>

enum class Metric { Cosine, Euclidean};

double distance(const std::vector<double>& A, const std::vector<double>& B, Metric metric);
double similarity(const std::vector<double>& A, const std::vector<double>& B, Metric metric);

#endif

And finally hnsw.cpp:

#include "../utils/distances.h"
#include <vector>
#include <iostream>

int main(){
    std::vector<double> A = {0.1, 0.5, 0.7, 1.1};
    std::vector<double> B = {0.5, 0.3, 0.8, 0.9};

    std::cout << distance(A, B, Metric::Cosine) << '\n';
}

Now, when I actually try to compile hnsw.cpp with the following command: g++ hnsw.cpp --std=c++11 I get the following error:

Undefined symbols for architecture x86_64:
  "distance(std::__1::vector<double, std::__1::allocator<double> > const&, std::__1::vector<double, std::__1::allocator<double> > const&, Metric)", referenced from:
      _main in hnsw-ad0e05.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

If I move the main into the distances.cpp file then everything works smoothly. For the purposes of brevity I'm not posting that whole file as it's sizable and I'm fairly certain it's not relevant. If there are any resources about understanding the general process here that would also be very helpful.

Body:
If you don't want to build individual object files for later linking, but instead build the whole executable file in one go, you need to specify all the participating translation units on the command line:

g++ -std=c++11 hnsw.cpp ../utils/distances.cpp

The output file will be called a.out, unless you also override that name with the -o flag.

Usually you would compile translation units separately and link them in a separate step:

g++ -std=c++11 mainGraph/hnsw.cpp -c -o mainGraph/hnsw.o
g++ -std=c++11 utils/distances.cpp -c -o utils/distances.o

g++ -std=c++11 mainGraph.hnsw.o utils/distances.o -o myprog

You also wouldn't maintain these commands by hand, but stick them into a Makefile, or some equivalent build system. The key point is that you don't need to recompile translation units that haven't changed just because you changed some part of your source code.


问:
Missing CodeLens references count in Visual Studio Community edition 2015 and 2017

Is there a reason why the references count (code lens) is missing in Visual Studio Community edition?

Is is possible to enable it in the options?

Here is a screenshot of Visual Studio 2015 and 2017 Community edition:

Here is a screenshot of Visual Studio 2013:

source: dailydotnettips.com

答:
This feature has been disabled in Visual Studio Community 2017, although it sounds like it was temporarily available in pre-release versions.

The Visual Studio Team issued this statement on the 14th of March 2017:

An authoring error in the SQL Server Data Tools resulted in the
  capability temporarily showing up incorrectly in Visual Studio
  Community when installed; the change you see is a result of correcting
  that mistake.

Also, on the Compare Visual Studio 2017 Offerings page CodeLens appears to not be available in the Community edition.


问:
What is the best way to support night mode?
I implemented the night mode (with the help of Chris Banes's post about DayNight https://medium.com/@chrisbanes/appcompat-v23-2-daynight-d10f90c83e94) in the latest app I'm working on but even if it's working, I'm not sure it's the best way to do it.

To summarize, I added a switch button in my settings to enable/disable it just like in the twitter app. But when the user do it, it doesn't directly switch the them from night to day or from day to night.

To force that, when the user switch, I restart the activity this way (because using activity.recreate is displaying a transition :

```<code>finish();
startActivity({currentActivity});
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
</code>```

And as it's a second level activity, when I go back to my root activity, I also have to restart it the same way I showed before.

Do you achieve day/night mode more or less the same way I do or do you have a cleaner to do it ?

答: As far as I'm aware this is more or less the standard way since restarting the activity is necessary for theme changes. I did some browsing, and it appears to be standard.</p>

Body:
I implemented the night mode (with the help of Chris Banes's post about DayNight https://medium.com/@chrisbanes/appcompat-v23-2-daynight-d10f90c83e94) in the latest app I'm working on but even if it's working, I'm not sure it's the best way to do it.

To summarize, I added a switch button in my settings to enable/disable it just like in the twitter app. But when the user do it, it doesn't directly switch the them from night to day or from day to night.

To force that, when the user switch, I restart the activity this way (because using activity.recreate is displaying a transition :

finish();
startActivity({currentActivity});
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

And as it's a second level activity, when I go back to my root activity, I also have to restart it the same way I showed before.

Do you achieve day/night mode more or less the same way I do or do you have a cleaner to do it ?


问:
Using index in DSE graph
I'm trying to get the list of persons in a datastax graph that have the same address with other persons and the number of persons is between 3 and 5.
This is the query:

```<code>g.V().hasLabel('person').match(__.as('p').out('has_address').as('a').dedup().count().as('nr'),__.as('p').out('has_address').as('a')).select('nr').is(inside(3,5)).select('p','a','nr').range(0,20)
</code>```

At first run I've noticed this error messages:

Could not find an index to answer query clause and graph.allow_scan is
  disabled: ((label = person))

I've enabled graph.allow_scan=true and now it's working

I'm wondering how can I create an index to be able to run this query without enabling allow_scan=true ?

Thanks

答:
You can create an index by adding it to the schema using a command like this:

```<code>schema.vertexLabel('person').index('address').materialized().by('has_address').add()
</code>```

Full documentation on adding indexes is available here: https://docs.datastax.com/en/latest-dse/datastax_enterprise/graph/using/createIndexes.html

You should not enable graph.allow_scan=true as under the covers it is turning on ALLOW FILTERING on the CQL queries.  This will cause a lot of cluster scans and will inevitably time out with any real amount of data in the system.  You should never enable this in any sort of production environment.

Title: Using index in DSE graph

Body:
I'm trying to get the list of persons in a datastax graph that have the same address with other persons and the number of persons is between 3 and 5.
This is the query:

g.V().hasLabel('person').match(__.as('p').out('has_address').as('a').dedup().count().as('nr'),__.as('p').out('has_address').as('a')).select('nr').is(inside(3,5)).select('p','a','nr').range(0,20)

At first run I've noticed this error messages:

Could not find an index to answer query clause and graph.allow_scan is
  disabled: ((label = person))

I've enabled graph.allow_scan=true and now it's working

I'm wondering how can I create an index to be able to run this query without enabling allow_scan=true ?

Thanks

Body:
You can create an index by adding it to the schema using a command like this:

schema.vertexLabel('person').index('address').materialized().by('has_address').add()

Full documentation on adding indexes is available here: https://docs.datastax.com/en/latest-dse/datastax_enterprise/graph/using/createIndexes.html

You should not enable graph.allow_scan=true as under the covers it is turning on ALLOW FILTERING on the CQL queries.  This will cause a lot of cluster scans and will inevitably time out with any real amount of data in the system.  You should never enable this in any sort of production environment.


问:
Swift 3 closure overload resolution
I'm confused by function overload resolution with closures in Swift 3.

For example, in the code:

```<code>func f<T>(_ a: T) {
    print("Wide")
}

func f(_ a: (Int)->(Int)) {
    print("Narrow")
}

f({(a: Int) -> Int in return a + 1})
</code>```

I expect Narrow, not Wide, to be printed to the console. Can anyone explain why the more specific overload gets chosen for non-closure arguments but not for closures or is this a compiler bug?

Swift 2 exhibited the expected behavior.

答:
This is probably due to the change in the default "escaping" behaviour for closure parameters.

If you change the specific function to:

```<code>func f(_ a:@escaping (Int)->Int)
{
    print("Narrow")
}
</code>```

it will print "Narrow" as expected (this is the same change that you probably had to make in several other places that were more obvious)

Title: Swift 3 closure overload resolution

Body:
I'm confused by function overload resolution with closures in Swift 3.

For example, in the code:

func f<T>(_ a: T) {
    print("Wide")
}

func f(_ a: (Int)->(Int)) {
    print("Narrow")
}

f({(a: Int) -> Int in return a + 1})

I expect Narrow, not Wide, to be printed to the console. Can anyone explain why the more specific overload gets chosen for non-closure arguments but not for closures or is this a compiler bug?

Swift 2 exhibited the expected behavior.

Body:
This is probably due to the change in the default "escaping" behaviour for closure parameters.

If you change the specific function to:

func f(_ a:@escaping (Int)->Int)
{
    print("Narrow")
}

it will print "Narrow" as expected (this is the same change that you probably had to make in several other places that were more obvious)