问:
Convert date-time string to class Date
I have a data frame with a character column of date-times.

When I use as.Date, most of my strings are parsed correctly, except for a few instances.  The example below will hopefully show you what is going on.

```<code># my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
                str_locate(prods.all$Date, " ")[1]-1),
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
#                    Date      Date2
# 1925  10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15
</code>```

As you can see, the year of some of the dates is inaccurate.  The pattern seems to occur when the day is double digit.

Any help you can provide will be greatly appreciated.

答:
You may be overcomplicating things, is there any reason you need the stringr package? You can use as.Date and its format argument to specify the input format of your string.

```<code> df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, format =  "%m/%d/%Y %H:%M:%S")
 # [1] "2009-10-09" "2009-10-15"
</code>```

Note the Details section of ?as.Date:

Character strings are processed as far as necessary for the format specified: any trailing characters are ignored

Thus, this also works:

```<code>as.Date(df$Date, format =  "%m/%d/%Y")
# [1] "2009-10-09" "2009-10-15"
</code>```

All the conversion specifications that can be used to specify the input format are found in the Details section in ?strptime. Make sure that the order of the conversion specification as well as any separators correspond exactly with the format of your input string.

More generally and if you need the time component as well, use as.POSIXct or strptime:

```<code>as.POSIXct(df$Date, "%m/%d/%Y %H:%M:%S")
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
</code>```

I'm guessing at what your actual data might look at from the partial results you give.

ContentLicense: CC BY-SA 4.0

Title: Convert date-time string to class Date

Body:
I have a data frame with a character column of date-times.

When I use as.Date, most of my strings are parsed correctly, except for a few instances.  The example below will hopefully show you what is going on.

# my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
                str_locate(prods.all$Date, " ")[1]-1),
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
#                    Date      Date2
# 1925  10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15

As you can see, the year of some of the dates is inaccurate.  The pattern seems to occur when the day is double digit.

Any help you can provide will be greatly appreciated.

Body:
You may be overcomplicating things, is there any reason you need the stringr package? You can use as.Date and its format argument to specify the input format of your string.

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, format =  "%m/%d/%Y %H:%M:%S")
 # [1] "2009-10-09" "2009-10-15"

Note the Details section of ?as.Date:

Character strings are processed as far as necessary for the format specified: any trailing characters are ignored

Thus, this also works:

as.Date(df$Date, format =  "%m/%d/%Y")
# [1] "2009-10-09" "2009-10-15"

All the conversion specifications that can be used to specify the input format are found in the Details section in ?strptime. Make sure that the order of the conversion specification as well as any separators correspond exactly with the format of your input string.

More generally and if you need the time component as well, use as.POSIXct or strptime:

as.POSIXct(df$Date, "%m/%d/%Y %H:%M:%S")
strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.


来源: stackexchange

问:
F# exists where function?
I have a function processing a DataTable looking for any row that has a column with a certain value. It looks like this:

```<code>let exists =
    let mutable e = false
    for row in dt.Rows do
        if row.["Status"] :?> bool = false
            then e <- true
    e
</code>```

I'm wondering if there is a way to do this in a single expression.  For example, Python has the "any" function which would do it something like this:

```<code>exists = any(row for row in dt.Rows if not row["Status"])
</code>```

Can I write a similar one-liner in F# for my exists function?

答:
You can use the Seq.exists function, which takes a predicate and returns true if the predicate holds for at least one element of the sequence.

```<code>let xs = [1;2;3]
let contains2 = xs |> Seq.exists (fun x -> x = 2)
</code>```

But in your specific case, it won't work right away, because DataTable.Rows is of type DataRowCollection, which only implements IEnumerable, but not IEnumerable<T>, and so it won't be considered a "sequence" in F# sense, which means that Seq.* functions won't work on it. To make them work, you have to first cast the sequence to the correct type with Seq.cast:

```<code>let exists =
   dt.Rows |>
   Seq.cast<DataRow> |>
   Seq.exists (fun r -> not (r.["Status"] :?> bool) )
</code>```

ContentLicense: CC BY-SA 3.0

Title: F# exists where function?

Body:
I have a function processing a DataTable looking for any row that has a column with a certain value. It looks like this:

let exists =
    let mutable e = false
    for row in dt.Rows do
        if row.["Status"] :?> bool = false
            then e <- true
    e

I'm wondering if there is a way to do this in a single expression.  For example, Python has the "any" function which would do it something like this:

exists = any(row for row in dt.Rows if not row["Status"])

Can I write a similar one-liner in F# for my exists function?

Body:
You can use the Seq.exists function, which takes a predicate and returns true if the predicate holds for at least one element of the sequence.

let xs = [1;2;3]
let contains2 = xs |> Seq.exists (fun x -> x = 2)

But in your specific case, it won't work right away, because DataTable.Rows is of type DataRowCollection, which only implements IEnumerable, but not IEnumerable<T>, and so it won't be considered a "sequence" in F# sense, which means that Seq.* functions won't work on it. To make them work, you have to first cast the sequence to the correct type with Seq.cast:

let exists =
   dt.Rows |>
   Seq.cast<DataRow> |>
   Seq.exists (fun r -> not (r.["Status"] :?> bool) )


问:
Google's version of amazon lex
I'm intrigued by Amazon LEX for building a bot but at the same time love the ease of Firebase. Is there a similar product on Google? Maybe accessible via Google Cloud Function?</p>

答:
Google owns api.ai.  That seems to provide the closest functionality to Lex.  Hopefully that gives you something to look into.

Also, I haven't done this personally, but it seems like an article that might help you:
http://glaforge.appspot.com/article/a-tight-develop-test-loop-for-developing-bots-with-api-ai-the-google-cloud-function-emulator-node-js-and-ngrok

Title: Google's version of amazon lex


问:
how can i download and extract single file from http using sharpziplib in c#?
anybody know how could i do that? i tried remake this code but it does not work.  Unpack a zip using ZipInputStream (eg for Unseekable input streams)</p>

答:
You can do it without external dependency. Add System.IO.Compression.dll and use it like this

```<code>using (var client = new System.Net.Http.HttpClient())
using (var stream = client.GetStreamAsync("https://github.com/frictionlessdata/specs/archive/master.zip").Result)
{
    var basepath = Path.Combine(Path.GetTempPath() + "myzip");
    System.IO.Directory.CreateDirectory(basepath);

    var ar = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Read);
    foreach (var entry in ar.Entries)
    {
        var path = Path.Combine(basepath, entry.FullName);

        if (string.IsNullOrEmpty(entry.Name))
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
            continue;
        }

        using (var entryStream = entry.Open())
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var file = File.Create(path))
            {
                entryStream.CopyTo(file);
            }
        }
    }
}
</code>```

You can replace HttpClient by WebClient or HttpRequest if you want.

If you want to extract only one file, replace foreach (var entry in ar.Entries) by :

```<code>var entry = ar.Entries.FirstOrDefault(e => e.FullName.EndWith("myFile.txt"));
if(entry == null)
    return;
</code>```

Body:
You can do it without external dependency. Add System.IO.Compression.dll and use it like this

using (var client = new System.Net.Http.HttpClient())
using (var stream = client.GetStreamAsync("https://github.com/frictionlessdata/specs/archive/master.zip").Result)
{
    var basepath = Path.Combine(Path.GetTempPath() + "myzip");
    System.IO.Directory.CreateDirectory(basepath);

    var ar = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Read);
    foreach (var entry in ar.Entries)
    {
        var path = Path.Combine(basepath, entry.FullName);

        if (string.IsNullOrEmpty(entry.Name))
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
            continue;
        }

        using (var entryStream = entry.Open())
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var file = File.Create(path))
            {
                entryStream.CopyTo(file);
            }
        }
    }
}

You can replace HttpClient by WebClient or HttpRequest if you want.

If you want to extract only one file, replace foreach (var entry in ar.Entries) by :

var entry = ar.Entries.FirstOrDefault(e => e.FullName.EndWith("myFile.txt"));
if(entry == null)
    return;


问:
Makefile with two C++ files : How can I choose the file to compile?
Let's say I have two C++ main files, project.cpp, and projectgraph.cpp.
They both use the same header file functions.h, as well as the file functions.cpp.

To compile project.cpp, I'm using the following makefile :

```<code>CXX = g++
CXXFLAGS= -std=c++11 -w -Wall -g

project: project.o functions.o
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o

functions.o: functions.h

clean:
    rm -rf *.o
</code>```

I would like to be able to choose between project.cpp and projectgraph.cpp to be compiled using the make command in the terminal. For example :

If I type make in the terminal : project.cpp would be compiled.

If I type make graph in the terminal : projectgraph.cpp would be compiled.

How can I change the makefile to get this result ?

Thanks !

答:
Just add a target for the additional program. Also, functions.cpp needs to be in the dependency list for functions.o, and functions.h should be in the dependency list of project and projectgraph.

```<code>CXX = g++
CXXFLAGS= -std=c++11 -w -Wall -g

project: project.o functions.o functions.h
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o

functions.o: functions.cpp functions.h

projectgraph: projectgraph.o functions.o functions.h
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o

clean:
    rm -rf *.o
</code>```

Then you can use

```<code>make projectgraph
</code>```

Body:
Let's say I have two C++ main files, project.cpp, and projectgraph.cpp.
They both use the same header file functions.h, as well as the file functions.cpp.

To compile project.cpp, I'm using the following makefile :

CXX = g++
CXXFLAGS= -std=c++11 -w -Wall -g

project: project.o functions.o
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o

functions.o: functions.h

clean:
    rm -rf *.o

I would like to be able to choose between project.cpp and projectgraph.cpp to be compiled using the make command in the terminal. For example :

If I type make in the terminal : project.cpp would be compiled.

If I type make graph in the terminal : projectgraph.cpp would be compiled.

How can I change the makefile to get this result ?

Thanks !

Body:
Just add a target for the additional program. Also, functions.cpp needs to be in the dependency list for functions.o, and functions.h should be in the dependency list of project and projectgraph.

CXX = g++
CXXFLAGS= -std=c++11 -w -Wall -g

project: project.o functions.o functions.h
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o

functions.o: functions.cpp functions.h

projectgraph: projectgraph.o functions.o functions.h
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o

clean:
    rm -rf *.o

Then you can use

make projectgraph


问:
Ruby on Rails NameError: uninitialized constant
I just set up a new migration and model relationships, and in console when testing the relationship between tables I get the following error: NameError: uninitialized constant.

Does anyone have any idea what is wrong?

Thank you

Edit:

Here's the error

```<code>NameError: uninitialized constant Profile::ProfileNotification
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2199:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2195:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `send'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `klass'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:187:in `quoted_table_name'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/has_many_association.rb:97:in `construct_sql'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:21:in `initialize'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `new'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `profile_notifications'
  from (irb):3
</code>```

Code from the ProfileNotification migration:

```<code>class CreateProfileNotifications < ActiveRecord::Migration
  def self.up
    create_table :profile_notifications do |t|
      t.integer :profile_id, :null => false
      t.integer :notification_id, :null => false
      t.string :notification_text
      t.boolean :checked, :default => false
      t.boolean :update_reply, :default => false
      t.boolean :opinion_reply, :default => false
      t.boolean :message_reply, :default => false
      t.boolean :pm, :default => false
      t.boolean :accepted_friend, :default => false
      t.boolean :accepted_supporter, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :profile_notifications
  end
end
</code>```

答: Well, I figured out the problem. When I was running ruby script/generate model, I was typing ruby script/generate model ProfileNotifications. When I typed ruby script/generate model ProfileNotification (singular) it worked. Naming conventions kill me. Thanks for all the help.</p>

ContentLicense: CC BY-SA 2.5

Body:
I just set up a new migration and model relationships, and in console when testing the relationship between tables I get the following error: NameError: uninitialized constant.

Does anyone have any idea what is wrong?

Thank you

Edit:

Here's the error

NameError: uninitialized constant Profile::ProfileNotification
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2199:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2195:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `send'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `klass'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:187:in `quoted_table_name'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/has_many_association.rb:97:in `construct_sql'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:21:in `initialize'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `new'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `profile_notifications'
  from (irb):3

Code from the ProfileNotification migration:

class CreateProfileNotifications < ActiveRecord::Migration
  def self.up
    create_table :profile_notifications do |t|
      t.integer :profile_id, :null => false
      t.integer :notification_id, :null => false
      t.string :notification_text
      t.boolean :checked, :default => false
      t.boolean :update_reply, :default => false
      t.boolean :opinion_reply, :default => false
      t.boolean :message_reply, :default => false
      t.boolean :pm, :default => false
      t.boolean :accepted_friend, :default => false
      t.boolean :accepted_supporter, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :profile_notifications
  end
end


问:
Bukkit event for hunger?
I am trying to make a plugin that removes hunger from Minecraft.  However, I cannot find the event for it!

Is there an event called when a player loses hunger?

Something like PlayerHungerChangeEvent?

答:
I believe you are looking for the FoodLevelChangeEvent

It is very oddly named, for future reference, refer to the bukkit documentation :)

Title: Bukkit event for hunger?


问:
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

答:
The simplest (Fastest, and none destructive) way would be to use a map object, like this:</p>

```<code>function getLatest(arr) {
  map = {};
    arr.forEach(item => {
    var i = item.incidentNumber;
    if (!map[i] || map[i].updateNumber<item.updateNumber) {
        map[i] = item;
    }
  })
  return Object.keys(map).map(key => map[key])
}
</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:
The simplest (Fastest, and none destructive) way would be to use a map object, like this:

function getLatest(arr) {
  map = {};
    arr.forEach(item => {
    var i = item.incidentNumber;
    if (!map[i] || map[i].updateNumber<item.updateNumber) {
        map[i] = item;
    }
  })
  return Object.keys(map).map(key => map[key])
}


问:
Can't start an extern process in Unity
I'm starting a process by using Process class in unity. </p>

```<code>Process myProcess = new Process();
        myProcess.StartInfo.FileName = path;
        myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
        myProcess.StartInfo.Arguments = JsonConvert.SerializeObject(params);
        myProcess.Start();
</code>```

<p>I'm using unity for OSx. I tested it by creating a new console application sending the same string arguments and using the same path, and it actually works fine. When I try to start the process from unity it just does not work and does not send any error even the code below the process call works, so I think it succeed but nothing happens. I can't get why.
By the way I start the process call in a unity button event. </p>

答:
I used this method to call external process in Unity.

```<code>public static void ExecProcess(string name, string args)
{
    Process p = new Process();
    p.StartInfo.FileName = name;
    p.StartInfo.Arguments = args;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.UseShellExecute = false;
    p.Start();

    string log = p.StandardOutput.ReadToEnd();
    string errorLog = p.StandardError.ReadToEnd();

    p.WaitForExit();
    p.Close();
}
</code>```

For async version you'll need light modification.

Title: Can't start an extern process in Unity

Body:
I'm starting a process by using Process class in unity.

Process myProcess = new Process();
        myProcess.StartInfo.FileName = path;
        myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
        myProcess.StartInfo.Arguments = JsonConvert.SerializeObject(params);
        myProcess.Start();

I'm using unity for OSx. I tested it by creating a new console application sending the same string arguments and using the same path, and it actually works fine. When I try to start the process from unity it just does not work and does not send any error even the code below the process call works, so I think it succeed but nothing happens. I can't get why.
By the way I start the process call in a unity button event.

Body:
I used this method to call external process in Unity.

public static void ExecProcess(string name, string args)
{
    Process p = new Process();
    p.StartInfo.FileName = name;
    p.StartInfo.Arguments = args;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.UseShellExecute = false;
    p.Start();

    string log = p.StandardOutput.ReadToEnd();
    string errorLog = p.StandardError.ReadToEnd();

    p.WaitForExit();
    p.Close();
}

For async version you'll need light modification.


问:
R subset of data frame for cohort analysis
I have following data in the data frame df

```<code>persons  year
personA  2015
personB  2016
personC  2015
personB  2015
</code>```

how do I use subset function in R to filter personB who is in 2015 and 2016
I am using following Code, but does not work

```<code>df1 <- subset(df, (year==2015 & year ==2016))
</code>```

答:
An example using data.table (and unique to handle multiple rows of same person in same year):

```<code>library(data.table)
dt <- structure(list(persons = c("personA", "personB", "personC", "personB"
), year = c(2015L, 2016L, 2015L, 2015L)), .Names = c("persons",
"year"), row.names = c(NA, -4L), class = "data.frame")
setDT(dt)
years <- c("2015", "2016")
# Filter by years and make sure all rows are unique combinations of persons and
# thoese years. Then set in_all_years to TRUE of number of rows is equal to
# number of years
out <- unique(dt[year %in% years])[, in_all_years := .N == length(years),
  by = persons]

> out
   persons year in_all_years
1: personA 2015        FALSE
2: personB 2016         TRUE
3: personC 2015        FALSE
4: personB 2015         TRUE
</code>```

Body:
I have following data in the data frame df

persons  year
personA  2015
personB  2016
personC  2015
personB  2015

how do I use subset function in R to filter personB who is in 2015 and 2016
I am using following Code, but does not work

df1 <- subset(df, (year==2015 & year ==2016))

Body:
An example using data.table (and unique to handle multiple rows of same person in same year):

library(data.table)
dt <- structure(list(persons = c("personA", "personB", "personC", "personB"
), year = c(2015L, 2016L, 2015L, 2015L)), .Names = c("persons",
"year"), row.names = c(NA, -4L), class = "data.frame")
setDT(dt)
years <- c("2015", "2016")
# Filter by years and make sure all rows are unique combinations of persons and
# thoese years. Then set in_all_years to TRUE of number of rows is equal to
# number of years
out <- unique(dt[year %in% years])[, in_all_years := .N == length(years),
  by = persons]

> out
   persons year in_all_years
1: personA 2015        FALSE
2: personB 2016         TRUE
3: personC 2015        FALSE
4: personB 2015         TRUE


问:
gettar attribute error - Python
I keep getting the following error when trying to use "getattr":

AttributeError: 'str' object has no attribute 'displayTime'

Here is the code I am using:

```<code>    getattr(className,"displayTime")(self)
</code>```

where "className" refers to a string that I have taken from a list and is also the name of a subclass I have in my program. "displayTime" is a method within that subclass.

I tried to test it by inputing the name of the subclass directly into it:

```<code>    getattr(seconds,"displayTime")(self)
</code>```

and this worked fine. Does anyone have any ideas what I am doing wrong?

Thank you.

答:
You are doing the getattr correctly. Your problem is that you need to convert from a string to an object - in this case, a reference to a class object.

There are two ways to identify classes. First, you can identify them using their parent module, something like abc.ABCMeta. To do this, start with the sys.modules dictionary, and look up modules and submodules (that is: look up 'abc'). Then you will have a module, which will have the last part of the name ('ABCMeta') as one of its children. You can use getattr to extract the child from the module, and then use getattr again to get whatever member you want.

```<code>import sys
mod = sys.modules['abc']
cls = getattr(mod, 'ABCMeta')
method = getattr(cls, 'displayTime') # Won't work, not available on class
</code>```

The second approach is to assume that you have a name in your global namespace in whatever module you are using. For example, if you did something like:

```<code>from abc import ABCMeta as chicken
</code>```

You could then refer to a global symbol, chicken, in your code, and it would mean the same thing. In this case, if you have already done the import, you can simply look up 'chicken' in the globals() dictionary, as @Jim Fasarakis Hilliard suggested in a comment:

```<code>clsname = 'chicken'
cls = globals()[clsname]
method = getattr(cls, 'displayTime')
</code>```

Title: gettar attribute error - Python

Body:
I keep getting the following error when trying to use "getattr":

AttributeError: 'str' object has no attribute 'displayTime'

Here is the code I am using:

    getattr(className,"displayTime")(self)

where "className" refers to a string that I have taken from a list and is also the name of a subclass I have in my program. "displayTime" is a method within that subclass.

I tried to test it by inputing the name of the subclass directly into it:

    getattr(seconds,"displayTime")(self)

and this worked fine. Does anyone have any ideas what I am doing wrong?

Thank you.

Body:
You are doing the getattr correctly. Your problem is that you need to convert from a string to an object - in this case, a reference to a class object.

There are two ways to identify classes. First, you can identify them using their parent module, something like abc.ABCMeta. To do this, start with the sys.modules dictionary, and look up modules and submodules (that is: look up 'abc'). Then you will have a module, which will have the last part of the name ('ABCMeta') as one of its children. You can use getattr to extract the child from the module, and then use getattr again to get whatever member you want.

import sys
mod = sys.modules['abc']
cls = getattr(mod, 'ABCMeta')
method = getattr(cls, 'displayTime') # Won't work, not available on class

The second approach is to assume that you have a name in your global namespace in whatever module you are using. For example, if you did something like:

from abc import ABCMeta as chicken

You could then refer to a global symbol, chicken, in your code, and it would mean the same thing. In this case, if you have already done the import, you can simply look up 'chicken' in the globals() dictionary, as @Jim Fasarakis Hilliard suggested in a comment:

clsname = 'chicken'
cls = globals()[clsname]
method = getattr(cls, 'displayTime')


问:
Validate field not in model by Django rest
I have a model:

```<code>class EventTracker(models.Model):
"""
Track events of user's behaviors
"""
class Meta:
    verbose_name = "EventTracker"
    verbose_name_plural = "EventTrackers"
    unique_together = ("application", "label")

application = models.ForeignKey(Application, related_name='events')
label = models.CharField(max_length=50)
count = models.PositiveIntegerField(default=0)
value = models.IntegerField(null=True)

def __str__(self):
    return "[{}] {}".format(self.application, self.label)
</code>```

This is my serializer for this model:

```<code>class EventTrackerSerializer(serializers.ModelSerializer):
subscriber_id = serializers.IntegerField(min_value=1)

class Meta:
    model = EventTracker
    fields = ('id', 'application', 'label', 'count', 'value', 'subscriber_id')
    write_only_fields = ('subscriber_id', )
    read_only_fields = ('count',)
</code>```

subscriber_id is a field that doesn't belong to this model. But request data must have subscriber_id to do a thing. So I want to validate it in serializer. I don't know how to validate it. I tried like above, it threw error:

```<code>This may be because you have a writable field on the serializer class that is not a valid argument to.....
</code>```

So what can I do ?

答:
First, you should probably be more explicit about what you want to do. We don't know what that field is for nor if it's readable nether what/how you want to validate it, so I'd do some guesswork.

Assuming it's write only:

```<code>subscriber_id = serializers.IntegerField(min_value=1, write_only=True)
</code>```

Note that the write_only_fields has been removed for some time.
Next, you'll have to write manually the serializer's create/update. Example for the create:

```<code>class EventTrackerSerializer(serializers.ModelSerializer):
    ...
    def create(self, validated_data):
        subscriber_id = validated_data.pop('subscriber_id')
        instance = EventTracker.objects.create(**validated_data)
        return instance
</code>```

Body:
I have a model:

class EventTracker(models.Model):
"""
Track events of user's behaviors
"""
class Meta:
    verbose_name = "EventTracker"
    verbose_name_plural = "EventTrackers"
    unique_together = ("application", "label")

application = models.ForeignKey(Application, related_name='events')
label = models.CharField(max_length=50)
count = models.PositiveIntegerField(default=0)
value = models.IntegerField(null=True)

def __str__(self):
    return "[{}] {}".format(self.application, self.label)

This is my serializer for this model:

class EventTrackerSerializer(serializers.ModelSerializer):
subscriber_id = serializers.IntegerField(min_value=1)

class Meta:
    model = EventTracker
    fields = ('id', 'application', 'label', 'count', 'value', 'subscriber_id')
    write_only_fields = ('subscriber_id', )
    read_only_fields = ('count',)

subscriber_id is a field that doesn't belong to this model. But request data must have subscriber_id to do a thing. So I want to validate it in serializer. I don't know how to validate it. I tried like above, it threw error:

This may be because you have a writable field on the serializer class that is not a valid argument to.....

So what can I do ?

Body:
First, you should probably be more explicit about what you want to do. We don't know what that field is for nor if it's readable nether what/how you want to validate it, so I'd do some guesswork.

Assuming it's write only:

subscriber_id = serializers.IntegerField(min_value=1, write_only=True)

Note that the write_only_fields has been removed for some time.
Next, you'll have to write manually the serializer's create/update. Example for the create:

class EventTrackerSerializer(serializers.ModelSerializer):
    ...
    def create(self, validated_data):
        subscriber_id = validated_data.pop('subscriber_id')
        instance = EventTracker.objects.create(**validated_data)
        return instance


答:
You can use FoodLevelChangeEvent.</p>

```<code>@EventHandler
public void onFoodChange(FoodLevelChangeEvent e) {
    Player foodChangedPlayer = (Player) e.getEntity();

    //Cancelling event, thus cancelling hunger
    e.setCancelled(true);
}
</code>```

Title: Bukkit event for hunger?

Body:
I am trying to make a plugin that removes hunger from Minecraft.  However, I cannot find the event for it!

Is there an event called when a player loses hunger?

Something like PlayerHungerChangeEvent?

Body:
You can use FoodLevelChangeEvent.

@EventHandler
public void onFoodChange(FoodLevelChangeEvent e) {
    Player foodChangedPlayer = (Player) e.getEntity();

    //Cancelling event, thus cancelling hunger
    e.setCancelled(true);
}


问:
React Native WebView Generating invalid render method, says undefined
I'm trying to use Canvas taken from https://github.com/iddan/react-native-canvas
However, when trying to generate, it seems that the WebView creates the following error:

```<code>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'Canvas'
</code>```

I've attached A snippet from the index.ios.js containing Canvas. Any help as to why the WebView generates this error would be super helpful (It works if you remove WebView and just leave View).

```<code>import React, { PropTypes, Component, WebView } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Platform,
  Image,
  TouchableHighlight,
} from 'react-native';
import {
  StackNavigator,
} from 'react-navigation';
import SignatureCapture from 'react-native-signature-capture';
const Sound = require('react-native-sound');

// TEST
class Canvas extends Component {

  propTypes: {
    context: React.PropTypes.object,
    render: React.PropTypes.func.isRequired
  };

  render() {

    var contextString = JSON.stringify(this.props.context);
    var renderString = this.props.render.toString();

    return (
      <View>
        <WebView
          automaticallyAdjustContentInsets={false}
          contentInset={{top: 0, right: 0, bottom: 0, left: 0}}
          html={'<style>*{margin:0;padding:0;}canvas{position:absolute;transform:translateZ(0);}</style><canvas></canvas><script>var canvas = document.querySelector("canvas");(" + renderString + ").call(" + contextString + ", canvas);</script>'}
          opaque={false}
          underlayColor={'transparent'}
          style={this.props.style}/>
      </View>
    );
  };
};
</code>```

答: What version of RN are you using? On 0.42 it says html prop is deprecated so you would have to use source={html: string, baseUrl: string}. Also I think it might be having trouble defining one of your jsx elements, I'm thinking it might be the

Body:
I'm trying to use Canvas taken from https://github.com/iddan/react-native-canvas
However, when trying to generate, it seems that the WebView creates the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'Canvas'

I've attached A snippet from the index.ios.js containing Canvas. Any help as to why the WebView generates this error would be super helpful (It works if you remove WebView and just leave View).

import React, { PropTypes, Component, WebView } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Platform,
  Image,
  TouchableHighlight,
} from 'react-native';
import {
  StackNavigator,
} from 'react-navigation';
import SignatureCapture from 'react-native-signature-capture';
const Sound = require('react-native-sound');

// TEST
class Canvas extends Component {

  propTypes: {
    context: React.PropTypes.object,
    render: React.PropTypes.func.isRequired
  };

  render() {

    var contextString = JSON.stringify(this.props.context);
    var renderString = this.props.render.toString();

    return (
      <View>
        <WebView
          automaticallyAdjustContentInsets={false}
          contentInset={{top: 0, right: 0, bottom: 0, left: 0}}
          html={'<canvas></canvas>'}
          opaque={false}
          underlayColor={'transparent'}
          style={this.props.style}/>
      </View>
    );
  };
};


问:
C# GUI Programming Starting
So....I've never really done much in the way of GUI programming apps. Namely because for school ive been stuck in C++ land. But since Im graduating in December I thought it'd be nice (while im looking for a job) to study something I've wanted to look into for awhile. And please dont mark this as "subjective" im just simply asking what I need to "know" to get started.

Namely GUI programming. Im not used to it....nor have I really ever been. It's not something they focus on in school (for instance my senior design was a webcam mouse thing, but had very little in the way of GUI)

I've seen alot about C# being the superior GUI programming tool for fast development.....but I dont really know whats out there. I know "of" QT, and Im used to C++. However Im not too familiar with what the "choice" GUI language is. I do like programming on Windows however most of my stuff has been in Unix here lately (Mostly because of my OS class).

I dont know anything about .net, and i've heard of something called WPF? Is that part of .net.....or.....what? Im just a bit confused at where to start.

Thanks

答:
Microsoft has some good resources for getting started on their platform with .NET.

Try these...

Development for Beginners

Welcome to the Windows Development track. This is the best place to learn how to create software for Windows. Windows applications can take advantage of your computer's sound,  graphics, and other capabilities. You will learn how to write software for Windows XP,  Vista, or Windows Server using Visual Basic, Visual C#, or Visual C++ Express Editions.

Ramp Up

Ramp Up is a free, online, community-based learning program that will help you build professional development skills. Join Ramp Up (it's free!) and help advance your career...

Creating Your First Visual C# Application -
This link contains three samples:

How to: Create a C# Console Application

How to: Create a C# Windows Forms Application

How to: Create a C# WPF Application

Visual C# Guided Tour

The Visual C# Guided Tour presents a series of lessons that introduce you to the Visual C# Express Edition integrated development environment (IDE), creating your first application, and designing the user interface of an application.

Learn .NET Framework on MSDN

Start here to get a conceptual overview of the key features of the .NET Framework, including the common language runtime, the .NET Framework class library, and more.

Title: C# GUI Programming Starting


答:
I believe all you need to do is : </p>

```<code>graph : project.o functions.o
    $(CXX) $(CXXFLAGS) -o projectgraph projectgraph.o functions.o
</code>```

<p>At least,  that is what I have done int he past.    There is a whole lot more you can do to make project the default etc but the above should be what you asked for. </p>

Title: Makefile with two C++ files : How can I choose the file to compile?

Body:
I believe all you need to do is :

graph : project.o functions.o
    $(CXX) $(CXXFLAGS) -o projectgraph projectgraph.o functions.o

At least,  that is what I have done int he past.    There is a whole lot more you can do to make project the default etc but the above should be what you asked for.


问:
Is the output of R quantile function "inclusive"?
I've got a vector (which I've called x1) of random observations from a binomial distribution with mean 55 and p = 47/55.

When I run quantile(x1, c(0.025, 0.975)), the output is:

2.5% 97.5%

42   52

My question is whether the interval which covers 95% of my generated values is [42, 52] or (42, 52). I've searched all over, but have found nothing.

答:
Yes, it is exclusive by default.

This is pretty easy to check:

```<code>quantile(1:1000, c(0.025, 0.975))
</code>```

Returns

```<code>2.5%   97.5%
25.975 975.025
</code>```

So R is returning (25.975, 975.025), which corresponds on this set to [26, 975]

Body:
Yes, it is exclusive by default.

This is pretty easy to check:

quantile(1:1000, c(0.025, 0.975))

Returns

2.5%   97.5%
25.975 975.025

So R is returning (25.975, 975.025), which corresponds on this set to [26, 975]


问:
Expose element of parent component to child
I have a main component that handles the toolbar and sidnav of my angular application.  I would like to make a div inside the toolbar available to child components (and controllers) to customize so that they can do things like change the toolbar title text and add contextual buttons.  This feels sort of like the opposite of transposition where a parent component can customize part of a child component (e.g. a menu component customizing the content of a button).  One option would be to have the toolbar managed by a service, but even then I can't think of a great way to customize the content of the toolbar without doing a decent amount of javascript that builds up dom elements (one of the things I always try to avoid in angular).</p>

答:
In Angular 1.6.x components use isolate scope only:

Components only control their own View and Data: Components should
  never modify any data or DOM that is out of their own scope. Normally,
  in AngularJS it is possible to modify data anywhere in the application
  through scope inheritance and watches. This is practical, but can also
  lead to problems when it is not clear which part of the application is
  responsible for modifying the data. That is why component directives
  use an isolate scope, so a whole class of scope manipulation is not
  possible.

So, to make this work you would need to use a directive instead of a component. The div you want to include would need to be a directive itself to be able to alter the parent scope of the toolbar directive. What you would be doing is transcluding one directive inside another, and using shared scope to alter the parent scope.

This article is a really good resource for what you are trying to accomplish. I would start here: https://www.airpair.com/angularjs/posts/transclusion-template-scope-in-angular-directives

I have altered the example Codepen from that article to show you how it might work: http://codepen.io/jdoyle/pen/aJQpYo

If you select items in the list you can see that the header name changes to whatever is selected.

```<code>angular.module("ot-components", [])

.controller("AppController",($scope)=> {
  //Normally, this data would be wrapped in a service. For example only.
  $scope.header = "Marketing";
  $scope.areas = {
    list: [
      "Floorplan",
      "Combinations",
      "Schedule",
      "Publish"
    ],
    current: "Floorplan"
  };
})

.directive("otList", ()=> {
  return {
    scope: false,  // this is one of the major changes
    template:
    `<ul class="ot-list">
      <li class="ot-list--item"
        ng-repeat="item in items"
        ng-bind="item"
        ng-class="{'ot-selected': item === selected}"
        ng-click="selectItem(item)">
       </li>
    </ul>`,
    link: (scope, elem, attrs) => {
      scope.items = JSON.parse(attrs.items);
      scope.selected = attrs.selected;

      scope.selectItem = (item) => {
        scope.selected = item;
        scope.$parent.header = item;  // this is the other major change
      };
    }
  };
})

.directive("otSite", ()=> {
  return {
    scope: true,  // another major change
    transclude: true,
    template:
    `<div class="ot-site">
        <div class="ot-site--head">
          <img class="ot-site--logo" src="//guestcenter.opentable.com/Content/img/icons/icon/2x/ot-logo-2x.png">
        <h1>{{header}}</h1>
        </div>
        <div class="ot-site--menu">
        </div>
        <div class="ot-site--body" ng-transclude>
        </div>
        <div class="ot-site--foot">
          © 2015 OpenTable, Inc.
        </div>
      </div>`
  };
});
</code>```

Body:
In Angular 1.6.x components use isolate scope only:

Components only control their own View and Data: Components should
  never modify any data or DOM that is out of their own scope. Normally,
  in AngularJS it is possible to modify data anywhere in the application
  through scope inheritance and watches. This is practical, but can also
  lead to problems when it is not clear which part of the application is
  responsible for modifying the data. That is why component directives
  use an isolate scope, so a whole class of scope manipulation is not
  possible.

So, to make this work you would need to use a directive instead of a component. The div you want to include would need to be a directive itself to be able to alter the parent scope of the toolbar directive. What you would be doing is transcluding one directive inside another, and using shared scope to alter the parent scope.

This article is a really good resource for what you are trying to accomplish. I would start here: https://www.airpair.com/angularjs/posts/transclusion-template-scope-in-angular-directives

I have altered the example Codepen from that article to show you how it might work: http://codepen.io/jdoyle/pen/aJQpYo

If you select items in the list you can see that the header name changes to whatever is selected.

angular.module("ot-components", [])

.controller("AppController",($scope)=> {
  //Normally, this data would be wrapped in a service. For example only.
  $scope.header = "Marketing";
  $scope.areas = {
    list: [
      "Floorplan",
      "Combinations",
      "Schedule",
      "Publish"
    ],
    current: "Floorplan"
  };
})

.directive("otList", ()=> {
  return {
    scope: false,  // this is one of the major changes
    template:
    `<ul class="ot-list">
      <li class="ot-list--item"
        ng-repeat="item in items"
        ng-bind="item"
        ng-class="{'ot-selected': item === selected}"
        ng-click="selectItem(item)">
       </li>
    </ul>`,
    link: (scope, elem, attrs) => {
      scope.items = JSON.parse(attrs.items);
      scope.selected = attrs.selected;

      scope.selectItem = (item) => {
        scope.selected = item;
        scope.$parent.header = item;  // this is the other major change
      };
    }
  };
})

.directive("otSite", ()=> {
  return {
    scope: true,  // another major change
    transclude: true,
    template:
    `<div class="ot-site">
        <div class="ot-site--head">
          <img class="ot-site--logo" src="//guestcenter.opentable.com/Content/img/icons/icon/2x/ot-logo-2x.png">
        <h1>{{header}}</h1>
        </div>
        <div class="ot-site--menu">
        </div>
        <div class="ot-site--body" ng-transclude>
        </div>
        <div class="ot-site--foot">
          &copy; 2015 OpenTable, Inc.
        </div>
      </div>`
  };
});


问:
Linear Search technique
I am writing a programe that read in file containing a square matrix of N rows by N columns of integers.The first line of the file contains a single value specifying the "size" of N for the rest of the grid. for example if the first line contains "10" then the remainder of the lines form a 10x10 matrix. my program should display the total number of comparisons needed to find (or not find) the given element by using a "brute force" linear technique O(N^2).
Sample c:\temp\input.txt:

10

1   5   8  13  16  18  22  23  28  29

6   9  14  19  20  22  23  27  33  34

11  14  15  20  24  26  27  31  34  39

16  21  23  28  30  34  35  36  39  44

17  25  26  32  36  41  43  47  49  53

19  28  30  35  40  43  44  49  53  56

23  31  33  38  43  48  52  58  60  61

27  34  35  41  44  52  55  59  61  65

29  38  40  44  45  54  60  65  66  67

33  41  46  47  51  59  61  69  70  80

Examples (as a Java App):

java program.class c:\temp\infile.txt 59

58 found in 68 comparisons using a linear search

this is my code

```<code>   public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {

    int[][] matrix = null;
    String line;
    int size = buffer.read();
    int row=0;
    while ((line = buffer.readLine()) != null) {
    String[] vals = line.trim().split("\\s+");
    if (matrix == null) {
    public static void main(String[] args)
    {
    BufferedReader buffer = new BufferedReader(new FileReader(args[0]));
    int size = buffer.read();
    int[][] matrix = new int[100][100];
    matrix = create2DIntMatrixFromFile(args[0]);
    search1(matrix, size,args[1]);
    matrix = new int[size][size];
    }
    for (int col = 0; col < size; col++) {
    matrix[row][col] = Integer.parseInt(vals[col]);
     }
    }
    row++;
    }
    return matrix;
    }
    void search1(int [][]matrix,int size,int x)
    {
    int count=0,comp=0;
    for(int i=0;i<size;i++)
    { for(int j=0;j<=size;j++)
    if(matrix[i][j]==x) count++;
    comp++;
    }
    System.out.println(count+" found in" + comp + "comparisons using a linear search");
     }
</code>```

the problem is i keep getting syntax error on my main method that search1 method isn't correct and I couldn't fix it. any help I appreciate

答: First thing you should do is give well formatted code. From what I was able to understand your problem is probably that you call non static method from static main, so either make search1 static or call it from class constructor(you need to create one).</p>

Title: Linear Search technique

Body:
I am writing a programe that read in file containing a square matrix of N rows by N columns of integers.The first line of the file contains a single value specifying the "size" of N for the rest of the grid. for example if the first line contains "10" then the remainder of the lines form a 10x10 matrix. my program should display the total number of comparisons needed to find (or not find) the given element by using a "brute force" linear technique O(N^2).
Sample c:\temp\input.txt:

10

1   5   8  13  16  18  22  23  28  29

6   9  14  19  20  22  23  27  33  34

11  14  15  20  24  26  27  31  34  39

16  21  23  28  30  34  35  36  39  44

17  25  26  32  36  41  43  47  49  53

19  28  30  35  40  43  44  49  53  56

23  31  33  38  43  48  52  58  60  61

27  34  35  41  44  52  55  59  61  65

29  38  40  44  45  54  60  65  66  67

33  41  46  47  51  59  61  69  70  80

Examples (as a Java App):

java program.class c:\temp\infile.txt 59

58 found in 68 comparisons using a linear search

this is my code

   public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {

    int[][] matrix = null;
    String line;
    int size = buffer.read();
    int row=0;
    while ((line = buffer.readLine()) != null) {
    String[] vals = line.trim().split("\\s+");
    if (matrix == null) {
    public static void main(String[] args)
    {
    BufferedReader buffer = new BufferedReader(new FileReader(args[0]));
    int size = buffer.read();
    int[][] matrix = new int[100][100];
    matrix = create2DIntMatrixFromFile(args[0]);
    search1(matrix, size,args[1]);
    matrix = new int[size][size];
    }
    for (int col = 0; col < size; col++) {
    matrix[row][col] = Integer.parseInt(vals[col]);
     }
    }
    row++;
    }
    return matrix;
    }
    void search1(int [][]matrix,int size,int x)
    {
    int count=0,comp=0;
    for(int i=0;i<size;i++)
    { for(int j=0;j<=size;j++)
    if(matrix[i][j]==x) count++;
    comp++;
    }
    System.out.println(count+" found in" + comp + "comparisons using a linear search");
     }

the problem is i keep getting syntax error on my main method that search1 method isn't correct and I couldn't fix it. any help I appreciate


问:
Marklogic JSON document field index
I have a ML database with all json documents.. I am having an issue with field creation for this documents.. Say I have a document

```<code>{
    "id": "1452016",
    "name": "ALEXA488",
    "identifyingInfo": {
        "preparation": {
            "chemicalConjugations": [{
                "name": "ALEXA 488"
            }]
        }
    }
}
</code>```

I created a field for top level json element name ..

```<code>{
 "field-name": "concept_name",
 "field-path": [
  {
    "path": "/name",
    "weight": 1
  }
  ],
  "word-lexicon" :["http://marklogic.com/collation/en/S1"]
}
</code>```

I created a field range index as well on this field..

Now when I do the search like this

```<code>xquery version "1.0-ml";
import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

let $search := ' (concept_name:(*ALEXA*))'

let $options :=
   <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="collection">
        <collection prefix=""/>
    </constraint>
    <constraint name="concept_name">
        <word>
            <field name="concept_name" collation="http://marklogic.com/collation/en/S1"/>
        </word>
    </constraint>
    <term>
        <term-option>case-insensitive</term-option>
        <term-option>punctuation-insensitive</term-option>
        <term-option>whitespace-insensitive</term-option>
        <term-option>wildcarded</term-option>
    </term>
    <return-facets>false</return-facets>
    <return-values>false</return-values>
    <return-constraints>false</return-constraints>
    <return-frequencies>false</return-frequencies>
    <return-qtext>false</return-qtext>
    <search-option>format-json</search-option>
    <search-option>score-simple</search-option>
</options>

let $start := 1
let $page-length :=1

 let $result := search:search($search, $options, $start, $page-length)

return $result
</code>```

The search is matching the top level name and also identifyingInfo/preparation/chemicalConjugations/name..

What should be the field path, so that it only matches the top level json element, in this case name ?

答:
Your field path looks fine.  You can check that with

```<code>cts:field-value-match("concept_name", "*")
</code>```

But you're trying to use wildcards.  Did you enable "trailing wildcard searches" on your field?  Do you also want "one/two/three character searches" enabled?

Title: Marklogic JSON document field index

Body:
I have a ML database with all json documents.. I am having an issue with field creation for this documents.. Say I have a document

{
    "id": "1452016",
    "name": "ALEXA488",
    "identifyingInfo": {
        "preparation": {
            "chemicalConjugations": [{
                "name": "ALEXA 488"
            }]
        }
    }
}

I created a field for top level json element name ..

{
 "field-name": "concept_name",
 "field-path": [
  {
    "path": "/name",
    "weight": 1
  }
  ],
  "word-lexicon" :["http://marklogic.com/collation/en/S1"]
}

I created a field range index as well on this field..

Now when I do the search like this

xquery version "1.0-ml";
import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

let $search := ' (concept_name:(*ALEXA*))'

let $options :=
   <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="collection">
        <collection prefix=""/>
    </constraint>
    <constraint name="concept_name">
        <word>
            <field name="concept_name" collation="http://marklogic.com/collation/en/S1"/>
        </word>
    </constraint>
    <term>
        <term-option>case-insensitive</term-option>
        <term-option>punctuation-insensitive</term-option>
        <term-option>whitespace-insensitive</term-option>
        <term-option>wildcarded</term-option>
    </term>
    <return-facets>false</return-facets>
    <return-values>false</return-values>
    <return-constraints>false</return-constraints>
    <return-frequencies>false</return-frequencies>
    <return-qtext>false</return-qtext>
    <search-option>format-json</search-option>
    <search-option>score-simple</search-option>
</options>

let $start := 1
let $page-length :=1

 let $result := search:search($search, $options, $start, $page-length)

return $result

The search is matching the top level name and also identifyingInfo/preparation/chemicalConjugations/name..

What should be the field path, so that it only matches the top level json element, in this case name ?

Body:
Your field path looks fine.  You can check that with

cts:field-value-match("concept_name", "*")

But you're trying to use wildcards.  Did you enable "trailing wildcard searches" on your field?  Do you also want "one/two/three character searches" enabled?


问:
How to disassemble, modify and then reassemble a Linux executable?
Is there anyway this can be done? I've used objdump but that doesn't produce assembly output that will be accepted by any assembler that I know of. I'd like to be able to change instructions within an executable and then test it afterwards.</p>

答:
For changing code inside of an binary assembly, there are generally 3 ways to do it.

If it is just some trivial thing like a constant, then you just change the location with a hex editor. Assuming you can find it to begin with.

If you need to alter code, then utilize the LD_PRELOAD to overwrite some function in your program. That doesn't work if the function is not in the function tables though.

Hack the code at the function you want to fix to be a direct jump to a function you load via LD_PRELOAD and then jump back to the same location (This is a combi of the above two)

Ofcourse only the 2nd one will work, if the assembly does any kind of self-integrity-check.

Edit: If it isn't obvious then playing around with binary assemblies is VERY high-level developer stuff, and you will have a hard time asking about it here, unless it is really specific things you ask.


问:
Reversing order of divs depending on width
I'm currently working on a menu consisting of two parts (see image). On mobile, I'd like to show these menu items stacked from top to bottom, but starting with the bottom menu and ending with the top menu. Is there any (clean) way to do this with CSS or will I have to create two menus and show the correct one depending on page width?

EDIT: To clarify, the image is just to show an example of what I mean. I'm wondering in a more general sense if it's possible to somehow reverse the divs in CSS (without absolute positioning etc).

EDIT 2: Apologies for not adding any code. Here's a small pen that shows the situation: https://codepen.io/anon/pen/GWwrMW

```<code><div class="nav">
  <ul class="nav__top">
    <li>Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul>
  <ul class="nav__primary">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</div>

.nav__top,
.nav__primary {
  list-style: none;
  margin: 0 0 20px 0;
  text-align: right;
  li {
    display: inline-block;
    padding: 10px;
    background-color: #ccc;
  }
}
</code>```

On mobile, I want the sub items to be displayed underneath the main items.

答:
You can do this with flex and flex-direction: column-reverse, or for more control, using the order property on flex children. But with your example, flex-direction: column-reverse would work.

.nav__top li,
.nav__primary li {
  display: inline-block;
  padding: 10px;
  background-color: #ccc;
}

@media (max-width: 420px) {
  .nav {
    display: flex;
    flex-direction: column-reverse;
  }
  .nav li {
    display: list-item;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul class="nav__top">
    <li>Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul>
  <ul class="nav__primary">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</div></code>```

Body:
I'm currently working on a menu consisting of two parts (see image). On mobile, I'd like to show these menu items stacked from top to bottom, but starting with the bottom menu and ending with the top menu. Is there any (clean) way to do this with CSS or will I have to create two menus and show the correct one depending on page width?

EDIT: To clarify, the image is just to show an example of what I mean. I'm wondering in a more general sense if it's possible to somehow reverse the divs in CSS (without absolute positioning etc).

EDIT 2: Apologies for not adding any code. Here's a small pen that shows the situation: https://codepen.io/anon/pen/GWwrMW

Sub Item 1

Sub Item 2

Item 1

Item 2

Item 3

Item 4

.nav__top,
.nav__primary {
  list-style: none;
  margin: 0 0 20px 0;
  text-align: right;
  li {
    display: inline-block;
    padding: 10px;
    background-color: #ccc;
  }
}

On mobile, I want the sub items to be displayed underneath the main items.

Body:
You can do this with flex and flex-direction: column-reverse, or for more control, using the order property on flex children. But with your example, flex-direction: column-reverse would work.

.nav__top li,
.nav__primary li {
  display: inline-block;
  padding: 10px;
  background-color: #ccc;
}

@media (max-width: 420px) {
  .nav {
    display: flex;
    flex-direction: column-reverse;
  }
  .nav li {
    display: list-item;
  }
}

<div class="nav">
  <ul class="nav__top">
    <li>Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul>
  <ul class="nav__primary">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</div>


问:
Can I center some cells in a table and left align others?
I'm a really really new beginner.  I have been tasked with making an email signature by my boss and I cannot figure out how to produce it.  I'm using dreamweaver and have written really basic HTML emails that sent successfully, so my code isn't the absolute worst.

I'm trying to recreate this (made in word):

I want the four lines to the right of the logo to be left-aligned, and the bottom two lines to be centered.  I don't have any alignment defined in table {} or tbody tr td {}.

Here is how it looks in the chrome preview:

I will comment to show you how it looks in dreamweaver

in style:

```<code>    table {
    border-collapse: collapse;
    border-spacing: 0;
}

    tbody tr td {
    font-family: sans-serif;
    font-style: bold;
    color: black;
    font-size: 13px;
}

.B {font-size: 14px;
    text-align: left !important;
}

.smallcaps {
    font-variant: small-caps;
    font-size: 14px;
    text-align: left !important;
}

.bcorp {
    font-variant: small-caps;
    font-size: 14px;
    text-align: center;
}

.pad {
    padding-left: 12px;
    padding-right: 12px;
    vertical-align: bottom;
    text-align: center;
    }

    a {
        text-decoration: none;
        text-align: center;
    }
</code>```

And in table>tbody:

```<code><tr>
        <td width="96" rowspan="6"><a><img src="http:///wp-content/uploads/2016/09/Logo-01.jpg"  alt="Logo" width="96" height="90"/></a></td>
      <td height="1" colspan="2"> </td>
    </tr>
    <tr>
      <td height="9" colspan="2"><span class="B">Name Here, Position Title</span></td>
    </tr>
    <tr>
      <td height="20" colspan="2"><span class=smallcaps>Company Name</span>.</td>
    </tr>
    <tr>
      <td height="20" colspan="2">12345 SW 22 P<span class=smallcaps>kwy</span> | P<span class=smallcaps>ortland</span>, OR 97111 | S<span class=smallcaps>te</span> 123</td>
    </tr>
    <tr>
      <td height="7" colspan="2">D<span class=smallcaps>esk</span>: 503.123.4567 | C<span class=smallcaps>ell</span>: 503.987.6543</td>
    </tr>
    <tr>
      <td height="1" colspan="2"> </td>
    </tr>
    <tr>
      <td colspan="2" cellpadding="5">
      <a href="https://www.facebook.com/">
      <img class="pad" src="small-icons-03-03-[1].jpg" width="25" height="25" alt="Facebook" href="https://www.facebook.com/"/>
      </a>
      <a href="https://www.facebook.com/">
      <img class="pad" src="small-icons-03-03-[1].jpg" width="25" height="25" alt="Facebook" href="https://www.facebook.com/"/>
      </a>
      <a href="https://www.facebook.com/">
      <img class="pad" src="small-icons-03-03-[1].jpg" width="25" height="25" alt="Facebook" href="https://www.facebook.com/"/>
      </a>
      <a href="https://www.facebook.com/">
      <img class="pad" src="small-icons-03-03-[1].jpg" width="25" height="25" alt="Facebook" href="https://www.facebook.com/"/>
      </a>
      <a href="https://www.facebook.com/">
      <img class="pad" src="small-icons-03-03-[1].jpg" width="25" height="25" alt="Facebook" href="https://www.facebook.com/"/>
      </a>
      </td>
      <td> </td>
    </tr>
    <tr>
        <td height="30" colspan="2"><span class=bcorp>A Certified B Corporation®</span></td>
      <td width="101"> </td>
    </tr>
</code>```

Edited: added code - hope it's clear enough to help

答:
Ok, please check this and see if this will help you. About the table issue.
Some Email program don't render Inline-CSS to the body of email. You may consider use the style attributes to support what Table design is missing. I used to do this when generating newsletter.

          Logo Here

Name Here, Position Title

Company Name

Stress address wrapped around here

Desk: 123.456.789 | Cell: 123.456.789

                 Icon1
                 Icon2
                 Icon3
                 Icon4
                 Icon5

            A Certified B Corporation ®

```

Body:
I'm a really really new beginner.  I have been tasked with making an email signature by my boss and I cannot figure out how to produce it.  I'm using dreamweaver and have written really basic HTML emails that sent successfully, so my code isn't the absolute worst.

I'm trying to recreate this (made in word):

I want the four lines to the right of the logo to be left-aligned, and the bottom two lines to be centered.  I don't have any alignment defined in table {} or tbody tr td {}.

Here is how it looks in the chrome preview:

I will comment to show you how it looks in dreamweaver

in style:

    table {
    border-collapse: collapse;
    border-spacing: 0;
}

    tbody tr td {
    font-family: sans-serif;
    font-style: bold;
    color: black;
    font-size: 13px;
}

.B {font-size: 14px;
    text-align: left !important;
}

.smallcaps {
    font-variant: small-caps;
    font-size: 14px;
    text-align: left !important;
}

.bcorp {
    font-variant: small-caps;
    font-size: 14px;
    text-align: center;
}

.pad {
    padding-left: 12px;
    padding-right: 12px;
    vertical-align: bottom;
    text-align: center;
    }

    a {
        text-decoration: none;
        text-align: center;
    }

And in table>tbody:

      Name Here, Position Title

      Company Name.

      12345 SW 22 Pkwy | Portland, OR 97111 | Ste 123

      Desk: 503.123.4567 | Cell: 503.987.6543

        A Certified B Corporation®

Edited: added code - hope it's clear enough to help

Body:
Ok, please check this and see if this will help you. About the table issue.
Some Email program don't render Inline-CSS to the body of email. You may consider use the style attributes to support what Table design is missing. I used to do this when generating newsletter.

<table width="400" cellspacing="0" cellpadding="0" border="0" style="background:#EEE;font:small-caps 400 14px sans-serif;color:#444;">
  <tr>
    <td>
      <table cellspacing="0" cellpadding="0" border="0">
        <tr>
          <td valign="middle" align="center" width="125" bgcolor="#DDDDDD">Logo Here</td>
          <td style="line-height:1.6;padding: 5px 15px;">
            <div>Name Here, Position Title</div>
            <div>Company Name</div>
            <div>Stress address wrapped around here</div>
            <div>Desk: 123.456.789 | Cell: 123.456.789</div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td style="padding: 5px;">
      <table width="100%" cellspacing="0" cellpadding="5" border="0">
        <tr>
          <td align="center">
            <table align="center" width="50%" cellspacing="0" cellpadding="5" border="0">
              <tr>
                <td> <a href="#">Icon1</a> </td>
                <td> <a href="#">Icon2</a> </td>
                <td> <a href="#">Icon3</a> </td>
                <td> <a href="#">Icon4</a> </td>
                <td> <a href="#">Icon5</a> </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td align="center">
            A Certified B Corporation <sup>&reg;</sup>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>


问:
How can i change AVPlayer Video Quality while playing
I used this library for playing video from URL, and I am able to play video.

Now I want to change the currently playing video quality like (low, medium, high).

Library uses AVPlayer and how can i change quality with AVPlayer?

I listen about preferredPeakBitRate but I have no idea about it.

Please help me how can i do that?

答:
You cannot set video quality directly on the AVPlayer, however, you can do this by accessing videoComposition property on AVPlayerItem which is then supplied to AVPlayer (via for example replaceCurrentItem: method or on AVPlayer initialization). So:

Create or get you AVPlayerItem's AVVideoComposition instance, and set it's frameDuration, renderSize and renderScale properties. Take a look in docs for more info.

Set it to your "movie" videoComposition property, AVPlayerItem instance (again, look in docs for details).

Play that in your player.

If you want to do this on the fly while playing movie, adjustments of time for player item should be done I guess.


答:
This added CSS will reverse the order in the second menu:

```<code>.nav__primary {
  display: flex;
  flex-direction: row-reverse;
}
</code>```

You can put it in a media query.

https://codepen.io/anon/pen/ryQjdg

ADDITION: I overread the wish of it to be stacked horizontally. In this case you need

```<code>.nav__primary {
  display: flex;
  flex-direction: column-reverse;
}
</code>```

Title: Reversing order of divs depending on width

Body:
This added CSS will reverse the order in the second menu:

.nav__primary {
  display: flex;
  flex-direction: row-reverse;
}

You can put it in a media query.

https://codepen.io/anon/pen/ryQjdg

ADDITION: I overread the wish of it to be stacked horizontally. In this case you need

.nav__primary {
  display: flex;
  flex-direction: column-reverse;
}


问:
How do I reference my own class in an Android content XML file?
I'm using Android Studio and in my content XML file, I was referencing android.support.v4.view.ViewPager.  Instead of the ViewPager class, I want to use my own VerticalViewPager class.

How would I do that? Here is what I have now:

```<code><android.support.v4.view.ViewPager
 android:id="@+id/pager"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_alignParentStart="true"
 android:layout_below="@+id/tab_layout"
 app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</code>```

Thanks,
Terry

答:
On the design screen for the content XML, the following was shown:

I then clicked on "Change to" and that fixed it.  I compiled and it executed properly.

Body:
I'm using Android Studio and in my content XML file, I was referencing android.support.v4.view.ViewPager.  Instead of the ViewPager class, I want to use my own VerticalViewPager class.

How would I do that? Here is what I have now:

<android.support.v4.view.ViewPager
 android:id="@+id/pager"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_alignParentStart="true"
 android:layout_below="@+id/tab_layout"
 app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

Thanks,
Terry


问:
$(window).load(function() inside a statement?
Not sure if I can have  $(window).load(function() inside a statement? Is this correct?

```<code>    else if (isAndroid){
      $('.apple, .bottomcta, .bottomapple, .cta, .cta2').hide();
      $('.android').show();

      $(window).load(function() {

    if ($('.yes2, .YES2').css('display') == 'none') {
      $('#bottombadge > p, #badge > p, .bottomandroid, .android, .bottomapple, .apple').remove();
      $('#button, .cta, .bottomcta').show();
      }

    else if ($('.no, .NO').css('display') == 'block') {
      $('.bottomapple, .apple').remove();
      }

      }
      );

    }
</code>```

Any thoughts please?

答:
Yes, you can do it.

After all, you are just using jQuery to attach an event handler to the load event of the window object.

But, it is not so useful because, as @Siphalor has commented:

the code never gets executed because the page should have allready
  been loaded

Instead, you should do something like:

```<code>$(window).load(function() {
    if (isAndroid){
         $('.apple, .bottomcta, .bottomapple, .cta, .cta2').hide();
         $('.android').show();
         // more code
</code>```

Body:
Not sure if I can have  $(window).load(function() inside a statement? Is this correct?

    else if (isAndroid){
      $('.apple, .bottomcta, .bottomapple, .cta, .cta2').hide();
      $('.android').show();

      $(window).load(function() {

    if ($('.yes2, .YES2').css('display') == 'none') {
      $('#bottombadge > p, #badge > p, .bottomandroid, .android, .bottomapple, .apple').remove();
      $('#button, .cta, .bottomcta').show();
      }

    else if ($('.no, .NO').css('display') == 'block') {
      $('.bottomapple, .apple').remove();
      }

      }
      );

    }

Any thoughts please?

Body:
Yes, you can do it.

After all, you are just using jQuery to attach an event handler to the load event of the window object.

But, it is not so useful because, as @Siphalor has commented:

the code never gets executed because the page should have allready
  been loaded

Instead, you should do something like:

$(window).load(function() {
    if (isAndroid){
         $('.apple, .bottomcta, .bottomapple, .cta, .cta2').hide();
         $('.android').show();
         // more code


问:
xmlwriter writedoctype formatting
I'm trying to generate this doctype string:

```<code><!DOCTYPE games SYSTEM "transform.dtd">
</code>```

This is what I've been trying:

```<code>$writer.WriteDocType("games", $null , "transform.dtd", $null )
</code>```

I'm not entirely sure how to get that exact line.

答:
There's a known bug in PowerShell: passing null to a string parameter results in a String.Empty instead of null.

You can work around it like this:

```<code># Given an XML writer of some sort ...
$writer = [system.xml.xmlwriter]::create("$pwd\test.xml")

# Set up the parameters you want to pass to the method:
$params = @("games",$null,"transform.dtd",$null)

# And invoke it using .Net reflection:
$writer.GetType().GetMethod("WriteDocType").Invoke($writer,$params)

# Eventually, close the writer:
$writer.Close()
</code>```

Title: xmlwriter writedoctype formatting

Body:
I'm trying to generate this doctype string:

<!DOCTYPE games SYSTEM "transform.dtd">

This is what I've been trying:

$writer.WriteDocType("games", $null , "transform.dtd", $null )

I'm not entirely sure how to get that exact line.

Body:
There's a known bug in PowerShell: passing null to a string parameter results in a String.Empty instead of null.

You can work around it like this:

# Given an XML writer of some sort ...
$writer = [system.xml.xmlwriter]::create("$pwd\test.xml")

# Set up the parameters you want to pass to the method:
$params = @("games",$null,"transform.dtd",$null)

# And invoke it using .Net reflection:
$writer.GetType().GetMethod("WriteDocType").Invoke($writer,$params)

# Eventually, close the writer:
$writer.Close()


问:
how to store javascript variables with cookies js
I'm trying to make a simple program that stores the h1 value in a variable and then store it in a cookie. But whenever I reload the page the h1 value always goes back to 0 and is not being saved. Can someone please explain how I can save the variable in a cookie so when I reload the page it stays there.

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>
    <div class="container">
        <h1 id="hs">1 </h1> <img src="image01.jpg" width="960" height="640" />
        <button onclick="increase()" id="d">Increase value of cookie</button>
    </div>
    <script src="cookies.min.js"></script>
    <script>
        Cookies.set('name', 'leo');
        Cookies.set('nams', 'ddleo');
        var h = document.getElementById("hs");

        function increase() {
            var values = parseInt(document.getElementById('hs').innerHTML, 10);
            values++;
            Cookies.set("name", values);
            document.getElementById('hs').innerHTML = Cookies.get("name", values);
        }
    </script>
</body>

</html>
</code>```

答:
When you refresh the page, the DOM doesn't know anything about the value of that cookie. It needs to be explicitly set.

This line:

```<code>document.getElementById('hs').innerHTML=Cookies.get("name",values);
</code>```

should be run on page load, before you define the function increase:

```<code>var h = document.getElementById("hs");

# initial setting of h1:
var initialValue = Cookies.get("name",values);

if(initialValue) {
  h.innerHTML = initialValue;
}

function increase(){
  # dynamic setting of h1 (via the click handler you set up)
}
</code>```

Body:
I'm trying to make a simple program that stores the h1 value in a variable and then store it in a cookie. But whenever I reload the page the h1 value always goes back to 0 and is not being saved. Can someone please explain how I can save the variable in a cookie so when I reload the page it stays there.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

1

        <button onclick="increase()" id="d">Increase value of cookie</button>

Body:
When you refresh the page, the DOM doesn't know anything about the value of that cookie. It needs to be explicitly set.

This line:

document.getElementById('hs').innerHTML=Cookies.get("name",values);

should be run on page load, before you define the function increase:

var h = document.getElementById("hs");

# initial setting of h1:
var initialValue = Cookies.get("name",values);

if(initialValue) {
  h.innerHTML = initialValue;
}

function increase(){
  # dynamic setting of h1 (via the click handler you set up)
}


问:
Sum in an ArrayList with HashMap or with other method
I can't figure it out.

```<code>List<String[]> dogList = new ArrayList<String[]>();

dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});
</code>```

I would like to put in an other ArrayList sum by breed and rank

```<code>List<String[]> dogTotal = new ArrayList<String[]>();
</code>```

To get an output like this if i iterate over dogTotal

```<code>"Akita", "First", "2"
"Beagle", "First", "1"
"Beagle", "Second", "1"
</code>```

I have tried to use HashMap without success.

答:
Implement a Comparator<String[]> to check if two elements are equal. Then you can have two for-loops to check for a specific dog if there are also other dogs with the same breed and rank (a simple algo would be O(n^2)) or you can find a way to use this Comparator in an system-implemented method.

Try sorting the dogs by breed and rank and then do a for-loop to add them in the dogsTotal. This would take O(nlogn). You can also try to create your own algo based on the symmetry of your data.

Body:
I can't figure it out.

List<String[]> dogList = new ArrayList<String[]>();

dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});

I would like to put in an other ArrayList sum by breed and rank

List<String[]> dogTotal = new ArrayList<String[]>();

To get an output like this if i iterate over dogTotal

"Akita", "First", "2"
"Beagle", "First", "1"
"Beagle", "Second", "1"

I have tried to use HashMap without success.


问:
Android loop problem
I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?</p>

```<code>> package com.android.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
>
>
> import android.view.View; import
> android.view.Window;
>
> public class Android extends Activity
> { int x,y=10;
>
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
>
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
>
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
>
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }
</code>```

答:
onDraw is intended for rendering the display - once.  It's probably a bad idea to try and do this loop in onDraw.

Rather than using a loop, you might want to try using animation.  Do a google search for "Android animate tutorial" or something similar.

Title: Android loop problem

Body:
I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?

> package com.android.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
>
>
> import android.view.View; import
> android.view.Window;
>
> public class Android extends Activity
> { int x,y=10;
>
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
>
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
>
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
>
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }


答:
You can achieve the required alignment in the cells using CSS properties: text-align:center and text-align:left. By the way, a row defaults to text-align:left so if you don't put the alignment then it by default goes to left alignment.

And for merging the cells, you can use rowspan and colspan attribute in the  tag inside HTML.

I am posting a working example with complete CSS and HTML code for your consideration here: https://jsfiddle.net/rahuldhangar/0s5usofv/

HTML code:

```<code><table width="400" cellspacing="0" cellpadding="0" border="0" style="background:#EEE;font:small-caps 400 14px sans-serif;color:#444;">
  <tr>
    <td>
      <table cellspacing="0" cellpadding="0" border="0">
        <tr>
          <td valign="middle" align="center" width="125" bgcolor="#DDDDDD">Logo Here</td>
          <td style="line-height:1.6;padding: 5px 15px;">
            <div>Name Here, Position Title</div>
            <div>Company Name</div>
            <div>Stress address wrapped around here</div>
            <div>Desk: 123.456.789 | Cell: 123.456.789</div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td style="padding: 5px;">
      <table width="100%" cellspacing="0" cellpadding="5" border="0">
        <tr>
          <td align="center">
            <ul style="list-style:none;margin:0;padding:0;">
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
            </ul>
          </td>
        </tr>
        <tr>
          <td align="center">
            A Certified B Corporation <sup>®</sup>
          </td>
        </tr>
      </table>
    </td>
</code>```

Title: Can I center some cells in a table and left align others?

Body:
You can achieve the required alignment in the cells using CSS properties: text-align:center and text-align:left. By the way, a row defaults to text-align:left so if you don't put the alignment then it by default goes to left alignment.

And for merging the cells, you can use rowspan and colspan attribute in the  tag inside HTML.

I am posting a working example with complete CSS and HTML code for your consideration here: https://jsfiddle.net/rahuldhangar/0s5usofv/

HTML code:

<table width="400" cellspacing="0" cellpadding="0" border="0" style="background:#EEE;font:small-caps 400 14px sans-serif;color:#444;">
  <tr>
    <td>
      <table cellspacing="0" cellpadding="0" border="0">
        <tr>
          <td valign="middle" align="center" width="125" bgcolor="#DDDDDD">Logo Here</td>
          <td style="line-height:1.6;padding: 5px 15px;">
            <div>Name Here, Position Title</div>
            <div>Company Name</div>
            <div>Stress address wrapped around here</div>
            <div>Desk: 123.456.789 | Cell: 123.456.789</div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td style="padding: 5px;">
      <table width="100%" cellspacing="0" cellpadding="5" border="0">
        <tr>
          <td align="center">
            <ul style="list-style:none;margin:0;padding:0;">
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
              <li style="display:inline-block;padding:0 5px;"> Icon </li>
            </ul>
          </td>
        </tr>
        <tr>
          <td align="center">
            A Certified B Corporation <sup>&reg;</sup>
          </td>
        </tr>
      </table>
    </td>


问:
Check if user is authenticated with Cognito
I'm using Cognito User Pool and Federated Identities in my Android app to manage my users and their connection to other AWS services. I've been able to implement the authentication successfully and even sign out users with this code:

```<code>public void logOut() {
    credentialsProvider.clearCredentials();
    getUserPool().getCurrentUser().signOut();
}
</code>```

However, I have no idea how to check if there is a user currently logged in. I can't see how I can check if the current user from the user pool is logged in, since CognitoUser.getSession() automatically triggers the authentication workflow. And I can't see if there are cached credentials in the credentials provider because CognitoCachingCredentialsProvider.getCredentials() automatically does a network request if credentials are not present.

Am I missing something?

答: The session have a "isValid()" method, you can validate against that.</p>

Body:
I'm using Cognito User Pool and Federated Identities in my Android app to manage my users and their connection to other AWS services. I've been able to implement the authentication successfully and even sign out users with this code:

public void logOut() {
    credentialsProvider.clearCredentials();
    getUserPool().getCurrentUser().signOut();
}

However, I have no idea how to check if there is a user currently logged in. I can't see how I can check if the current user from the user pool is logged in, since CognitoUser.getSession() automatically triggers the authentication workflow. And I can't see if there are cached credentials in the credentials provider because CognitoCachingCredentialsProvider.getCredentials() automatically does a network request if credentials are not present.

Am I missing something?


问:
Creating a range relative to a booelan index using Pandas Dataframe
What's a good way to select a range based on the reference point of a boolean index?

For example, suppose I have the following dataframe, df:

```<code>dates = pd.date_range('1/1/2000', periods=10)
df = pd.DataFrame(np.empty([10, 3]), index=dates, columns=['A', 'B','C'])
df.iloc[:3,0] = 100
df.iloc[3:7,0] = 200
df.iloc[7:,0] = 300
df.iloc[:5,1] = 400
df.iloc[5:,1] = 500
df.iloc[:7,2] = 600
df.iloc[7:,2] = 700
</code>```

and the boolean dataframe:

```<code>df1 = [df!=df.shift(1)]
</code>```

I would like to populate a range of 3 cells prior where the booleans are True.

Is there not a single-line method to get a boolean range relative to a reference?  The result would look something like this:

```<code>                A      B      C
2000-01-01  False  False  False
2000-01-02   True  False  False
2000-01-03   True  False  False
2000-01-04   True   True  False
2000-01-05  False   True  False
2000-01-06   True   True   True
2000-01-07   True  False   True
2000-01-08   True  False   True
2000-01-09  False  False  False
2000-01-10  False  False  False
</code>```

答:
You might use the bfill (backward fill) method with a limit parameter:

```<code>df.shift().where(df.diff() != 0, pd.np.nan).bfill(limit=2).fillna(0).astype(bool)
</code>```

Body:
What's a good way to select a range based on the reference point of a boolean index?

For example, suppose I have the following dataframe, df:

dates = pd.date_range('1/1/2000', periods=10)
df = pd.DataFrame(np.empty([10, 3]), index=dates, columns=['A', 'B','C'])
df.iloc[:3,0] = 100
df.iloc[3:7,0] = 200
df.iloc[7:,0] = 300
df.iloc[:5,1] = 400
df.iloc[5:,1] = 500
df.iloc[:7,2] = 600
df.iloc[7:,2] = 700

and the boolean dataframe:

df1 = [df!=df.shift(1)]

I would like to populate a range of 3 cells prior where the booleans are True.

Is there not a single-line method to get a boolean range relative to a reference?  The result would look something like this:

                A      B      C
2000-01-01  False  False  False
2000-01-02   True  False  False
2000-01-03   True  False  False
2000-01-04   True   True  False
2000-01-05  False   True  False
2000-01-06   True   True   True
2000-01-07   True  False   True
2000-01-08   True  False   True
2000-01-09  False  False  False
2000-01-10  False  False  False

Body:
You might use the bfill (backward fill) method with a limit parameter:

df.shift().where(df.diff() != 0, pd.np.nan).bfill(limit=2).fillna(0).astype(bool)


问:
implement react-router within typescript app
I have a working copy of the same code only differs come from typescript.
And this the code below somehow and exception message..

```<code>import * as React from 'react';
import Home from '../Home/Home';
import User from '../User/User';
import {
  BrowserRouter as Router,Route,Link,Switch} from 'react-router-dom'

class Layout extends React.Component<{},{}> {
  render() {
    return (
    <Router>
      <div className="App">
        <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/user/:id" userid="25" component={User}/>
        <Route component={Notfound}/>
        </Switch>
      </div>
  </Router>
    );
  }
}
</code>```

and one of my component, home.tsx:

```<code>import * as React from 'react';

class Home extends React.Component<{},{}> {
  render() {
    return (
      <div className="App">

        Welcome Home Page!
      </div>
    );
  }
}
</code>```

Whats wrong here ?

答:
Here is how I fixed the problem. As a commenter explained, there is some confusion for the compiler on how to explicitly handle passing in props.

App.tsx:

```<code>import * as React from 'react';

import './App.css';

interface State { }

// tslint:disable-next-line
class App extends React.Component<any, State> {
  render() {
    return (
      <div className="App">
        HIIIII
      </div>
    );
  }
}

export default App;
</code>```

index.tsx:

```<code>...

ReactDOM.render(
  <Router>
    <div>
      <Route path="/" component={App} />
    </div>
  </Router>,
  document.getElementById('root') as HTMLElement
);
</code>```

I have not found a better solution yet. But this will indeed work.

Body:
I have a working copy of the same code only differs come from typescript.
And this the code below somehow and exception message..

import * as React from 'react';
import Home from '../Home/Home';
import User from '../User/User';
import {
  BrowserRouter as Router,Route,Link,Switch} from 'react-router-dom'

class Layout extends React.Component<{},{}> {
  render() {
    return (
    <Router>

        <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/user/:id" userid="25" component={User}/>
        <Route component={Notfound}/>
        </Switch>

  </Router>
    );
  }
}

and one of my component, home.tsx:

import * as React from 'react';

class Home extends React.Component<{},{}> {
  render() {
    return (

        Welcome Home Page!

    );
  }
}

Whats wrong here ?

Body:
Here is how I fixed the problem. As a commenter explained, there is some confusion for the compiler on how to explicitly handle passing in props.

App.tsx:

import * as React from 'react';

import './App.css';

interface State { }

// tslint:disable-next-line
class App extends React.Component<any, State> {
  render() {
    return (
      <div className="App">
        HIIIII
      </div>
    );
  }
}

export default App;

index.tsx:

...

ReactDOM.render(
  <Router>
    <div>
      <Route path="/" component={App} />
    </div>
  </Router>,
  document.getElementById('root') as HTMLElement
);

I have not found a better solution yet. But this will indeed work.


问:
Element 'script' cannot be nested inside element html
I'm making a flask application and just stuffed it all into a Visual Studio pyproj file and am just reviewing all the edit suggestions the IDE is proposing. One of them is where I put the

答:
Looks like it's a simple matter of malformatted html, by standard/design I'm guessing. According to https://www.w3schools.com/js/js_whereto.asp ...

JavaScript in  or

You can place
  any number of scripts in an HTML document.

Scripts can be placed in the , or in the  section of an HTML page, or in both.

Body:
Looks like it's a simple matter of malformatted html, by standard/design I'm guessing. According to https://www.w3schools.com/js/js_whereto.asp ...

JavaScript in <head> or <body>

You can place
  any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.