问:
(Should be easy) Selenium chromedriver (java) no element found error
I tried this exact code on other websites and it seems to work fine. It's just on pizza hut that it can't even locate an element let alone click on it. Thread.sleep() doesn't make a difference. The problem is between the commented *, according to the compiler. Here's the code.</p>

```<code>package training;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PizzaHut {

WebDriver driver;
@Test
public void open() throws Exception {
        //SET UP WEBDRIVER AND OPEN WEBSITE
        System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.pizzahut.com/#/home");
        Thread.sleep(1000);

        //CLICK PIZZA
        Thread.sleep(5000);
        test("before");
        //**************PROBLEM*CODE**********************
        driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();
        //************************************************
        test("clicked pizza");

        //CLOSE BROWSER
        Thread.sleep(15000);
        driver.close();
    }

    public static void test(String x) {
        System.out.println(x);
    }
}
</code>```

答:
I just ran the code below and it worked just fine. No need for sleep or waits and I'm using Chrome also.</p>

```<code>driver.get("https://www.pizzahut.com");
driver.findElement(By.id("lg-nav-pizza")).click();
</code>```

Body:
I tried this exact code on other websites and it seems to work fine. It's just on pizza hut that it can't even locate an element let alone click on it. Thread.sleep() doesn't make a difference. The problem is between the commented *, according to the compiler. Here's the code.

package training;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PizzaHut {

WebDriver driver;
@Test
public void open() throws Exception {
        //SET UP WEBDRIVER AND OPEN WEBSITE
        System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.pizzahut.com/#/home");
        Thread.sleep(1000);

        //CLICK PIZZA
        Thread.sleep(5000);
        test("before");
        //**************PROBLEM*CODE**********************
        driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();
        //************************************************
        test("clicked pizza");

        //CLOSE BROWSER
        Thread.sleep(15000);
        driver.close();
    }

    public static void test(String x) {
        System.out.println(x);
    }
}

Body:
I just ran the code below and it worked just fine. No need for sleep or waits and I'm using Chrome also.

driver.get("https://www.pizzahut.com");
driver.findElement(By.id("lg-nav-pizza")).click();


来源: stackexchange

问:
Remove standard SAS libraries from GUI
I'd like to remove/delete/unassign the standard SAS libraries from my SAS 9.3 GUI.

I've tried two solutions to remove a library which haven't worked:

%sysfunc(libname(maps)) results in:

ERROR 180-322: Statement is not valid or it is used out of proper order.

Comment out the offending start up code in the file sasv9.cfg

I don't have permission to modify (C:\Program Files...) files in that directory

Thanks!

The libraries are:
 - Maps

Mapsgfk

Mapssas

Sashelp

Sasuser

答:
Not sure if you can remove them without changing your system wide config.sas file. But you could point the MAPS options to null devices so that they don't find any datasets. Here is output from PROC OPTIONS.

```<code> MAPS=!SASROOT/maps
                   Specifies the location of SAS/GRAPH map data sets.
 MAPSGFK=!SASROOT/mapsgfk
                   Specifies the location of GfK maps.
 MAPSSAS=!SASROOT/maps
                   Specifies the location of SAS map data sets.
</code>```

You can point these two different locations with command line options.

```<code>sas -maps /dev/nul  -mapsgfk /dev/nul -mapssas /dev/nul
</code>```

The libref will still be created but there won't be any members found.

You might do something similar for SASUSER, but then you would probably also want to add -rsasuser option so that SAS would know to create a WORK.PROFILE to use in place of the normal SASUSER.PROFILE catalog.

I don't think you would want to remove SASHELP libref as I think there are a number of things in SAS that would not work without being able to find things that are made available via that libref.

ContentLicense: CC BY-SA 3.0

Title: Remove standard SAS libraries from GUI

Body:
Not sure if you can remove them without changing your system wide config.sas file. But you could point the MAPS options to null devices so that they don't find any datasets. Here is output from PROC OPTIONS.

 MAPS=!SASROOT/maps
                   Specifies the location of SAS/GRAPH map data sets.
 MAPSGFK=!SASROOT/mapsgfk
                   Specifies the location of GfK maps.
 MAPSSAS=!SASROOT/maps
                   Specifies the location of SAS map data sets.

You can point these two different locations with command line options.

sas -maps /dev/nul  -mapsgfk /dev/nul -mapssas /dev/nul

The libref will still be created but there won't be any members found.

You might do something similar for SASUSER, but then you would probably also want to add -rsasuser option so that SAS would know to create a WORK.PROFILE to use in place of the normal SASUSER.PROFILE catalog.

I don't think you would want to remove SASHELP libref as I think there are a number of things in SAS that would not work without being able to find things that are made available via that libref.


问:
i cant do the min of a sum of values order by
im working in sql server 2005
i dont know how to get the min value of the column which this returns. i have tried different ways but dont get the solution. Thanks

```<code>select sum(c.duration)
from song c , disc d, have e
where d.cod = e.cod AND e.can = c.cod
group by d.name
</code>```

tables:

```<code>song          have       disc
--------    -------   -----------
cod(int)     can(int)  cod
title        cod       name
duration               date
</code>```

答:
If you just want the minimum from the summations, then a simple ordering will do.

```<code>select top 1 sum(c.duration) as SumDuration
    from song c
    inner join have e on e.can = c.cod
    inner join disc d on d.cod = e.cod
    group by d.name
    order by SumDuration asc
</code>```

If you want to output all the summed records that have that minimum, then using a CTE should work

```<code>; with
    CTE as (
        select d.name, sum(c.duration) as SumDuration
            from song c
            inner join have e on e.can = c.cod
            inner join disc d on d.cod = e.cod
            group by d.name
    )
select name, SumDuration
    from CTE
    where SumDuration = (
        select min(SumDuration)
            from CTE
    )
</code>```

Body:
im working in sql server 2005
i dont know how to get the min value of the column which this returns. i have tried different ways but dont get the solution. Thanks

select sum(c.duration)
from song c , disc d, have e
where d.cod = e.cod AND e.can = c.cod
group by d.name

tables:

song          have       disc
--------    -------   -----------
cod(int)     can(int)  cod
title        cod       name
duration               date

Body:
If you just want the minimum from the summations, then a simple ordering will do.

select top 1 sum(c.duration) as SumDuration
    from song c
    inner join have e on e.can = c.cod
    inner join disc d on d.cod = e.cod
    group by d.name
    order by SumDuration asc

If you want to output all the summed records that have that minimum, then using a CTE should work

; with
    CTE as (
        select d.name, sum(c.duration) as SumDuration
            from song c
            inner join have e on e.can = c.cod
            inner join disc d on d.cod = e.cod
            group by d.name
    )
select name, SumDuration
    from CTE
    where SumDuration = (
        select min(SumDuration)
            from CTE
    )


问:
dev_appengine cannot open a simple Hello World application
Suddenly after a system reboot, the dev_appengine stopped working properly.

Any access attempt to the application ends with an error, the admin server is working fine though.

I've also tried with a simple Hello World application but had no luck.

The error is here and the sample app is here.

Best regards

答:
The problem is nowhere except the app.yaml file, and that too in the line with url:

you could try the answer above
or

try removing the following:-
application: hello_world

version: 1

libraries:
-name: webapp2
 version: "2.5.2"

IT WORKED FOR ME

if you want to write favicon and ico then try adding a . after leading slash or changing the backslash after favicon


问:
Retrofit2.1.0 and okhttp3 offline caching not working
I'm trying to implement caching using Retrofit and OkHttp. I am getting '504 Unsatisfiable Request (only-if-cached)' as Error when offline.

```<code>OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(5, TimeUnit.SECONDS);

        if (isDebug) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        builder.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                .addInterceptor(OFFLINE_INTERCEPTOR)
                .cache(provideCache());

        OkHttpClient client = builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        reqinterface = retrofit.create(MyApiInterface.class);

  private static Cache provideCache(){
    Cache cache = null;
    try{

        cache = new Cache(new File(context.getCacheDir(),"baskin-cache"),
                10*1024*1024);
    }catch (Exception e){
        Log.i("zacharia","Could not create Cache");
    }
    return  cache;
}
  private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response originalResponse = chain.proceed(chain.request());
        String cacheControl = originalResponse.header("Cache-Control");

        if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + 120)
                    .build();
        } else {
            return originalResponse;
        }
    }
};

private static final Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (!isOnline()) {
            Log.d("zacharia", "rewriting request");

            int maxStale = 60 * 60 * 24 * 7; // tolerate 4-weeks stale
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return chain.proceed(request);
    }
};

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}
</code>```

When online, I am getting  'D/OkHttp: Cache-Control: public, max-age=120' in the log. When offline , 'D/OkHttp: <-- 504 Unsatisfiable Request (only-if-cached)'

答: You could try to debug methods okhttp3.internal.cache.CacheInterceptor#intercept(Chain) and okhttp3.Cache#get(Request) to see why previous response is not returned.

Body:
I'm trying to implement caching using Retrofit and OkHttp. I am getting '504 Unsatisfiable Request (only-if-cached)' as Error when offline.

OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(5, TimeUnit.SECONDS);

        if (isDebug) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        builder.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                .addInterceptor(OFFLINE_INTERCEPTOR)
                .cache(provideCache());

        OkHttpClient client = builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        reqinterface = retrofit.create(MyApiInterface.class);

  private static Cache provideCache(){
    Cache cache = null;
    try{

        cache = new Cache(new File(context.getCacheDir(),"baskin-cache"),
                10*1024*1024);
    }catch (Exception e){
        Log.i("zacharia","Could not create Cache");
    }
    return  cache;
}
  private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response originalResponse = chain.proceed(chain.request());
        String cacheControl = originalResponse.header("Cache-Control");

        if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + 120)
                    .build();
        } else {
            return originalResponse;
        }
    }
};

private static final Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (!isOnline()) {
            Log.d("zacharia", "rewriting request");

            int maxStale = 60 * 60 * 24 * 7; // tolerate 4-weeks stale
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return chain.proceed(request);
    }
};

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

When online, I am getting  'D/OkHttp: Cache-Control: public, max-age=120' in the log. When offline , 'D/OkHttp: <-- 504 Unsatisfiable Request (only-if-cached)'


问:
How to convert vertical list of data into horizontal in Excel
I'm trying to export contacts from my dad's old Nokia phone into an iPhone. Their old software Nokia PC Suite can export those contacts into CSV and into pure text which is formatted like this:

```<code>First Name: ...
Last Name: ...
Phone: ...

First Name: ...
Last Name: ...
Phone: ...

...
</code>```

Note#1: Sometimes there isn't first name, just last and phone number. They are spaced out with line break.

The problem with CSV is that the encoding is messed up and I can't find out what it is. I would like to know how can I export the contacts into the CSV or even vCard from this pure text.

Expected result:

```<code>First Name | Last Name | Phone
FirstName1 | LastName1 | #####1
FirstName2 | LastName2 | #####2
FirstName3 | LastName3 | #####3
</code>```

edit: Note #2: There are over 600 contacts.

edit#2:
'
Here's an example. Left side is source, right side is how I need it for the CSV file. BTW don't mind those "A"s, it's just a priority thing that my father uses...

答:
I figured a way to get it done without a VBA macro/UDF.

It's one basic formula, with a slight change per column.

Here's the layout I tested with:

So, with your data starting in A1, and with a break between each "block", you can do this in C2:

=RIGHT(OFFSET($A1,(ROW()-2)*3,0),LEN(OFFSET($A1,(ROW()-2)*3,0))-SEARCH(":",OFFSET($A1,(ROW()-2)*3,0))) and drag down.

Then, use that same formula in D2, except change $A1 to $A2 wherever $A1 appears.

In E2, same formula, but change $A1 to $A3 each time $A1 appears and drag down.

Edit: Or, you can place this in C2, and drag over and down. It's one formula that doesn't need to be edited each column:

```<code>=RIGHT(OFFSET(INDIRECT("$A"&ROW()-1+COLUMN()-3),(ROW()-2)*3,0),LEN(OFFSET(INDIRECT("$A"&ROW()-1+COLUMN()-3),(ROW()-2)*3,0))-SEARCH(":",OFFSET(INDIRECT("$A"&ROW()-1+COLUMN()-3),(ROW()-2)*3,0)))
</code>```

Body:
I'm trying to export contacts from my dad's old Nokia phone into an iPhone. Their old software Nokia PC Suite can export those contacts into CSV and into pure text which is formatted like this:

First Name: ...
Last Name: ...
Phone: ...

First Name: ...
Last Name: ...
Phone: ...

...

Note#1: Sometimes there isn't first name, just last and phone number. They are spaced out with line break.

The problem with CSV is that the encoding is messed up and I can't find out what it is. I would like to know how can I export the contacts into the CSV or even vCard from this pure text.

Expected result:

First Name | Last Name | Phone
FirstName1 | LastName1 | #####1
FirstName2 | LastName2 | #####2
FirstName3 | LastName3 | #####3

edit: Note #2: There are over 600 contacts.

edit#2:
'
Here's an example. Left side is source, right side is how I need it for the CSV file. BTW don't mind those "A"s, it's just a priority thing that my father uses...

Body:
I figured a way to get it done without a VBA macro/UDF.

It's one basic formula, with a slight change per column.

Here's the layout I tested with:

So, with your data starting in A1, and with a break between each "block", you can do this in C2:

=RIGHT(OFFSET($A1,(ROW()-2)*3,0),LEN(OFFSET($A1,(ROW()-2)*3,0))-SEARCH(":",OFFSET($A1,(ROW()-2)*3,0))) and drag down.

Then, use that same formula in D2, except change $A1 to $A2 wherever $A1 appears.

In E2, same formula, but change $A1 to $A3 each time $A1 appears and drag down.

Edit: Or, you can place this in C2, and drag over and down. It's one formula that doesn't need to be edited each column:

=RIGHT(OFFSET(INDIRECT("$A"&ROW()-1+COLUMN()-3),(ROW()-2)*3,0),LEN(OFFSET(INDIRECT("$A"&ROW()-1+COLUMN()-3),(ROW()-2)*3,0))-SEARCH(":",OFFSET(INDIRECT("$A"&ROW()-1+COLUMN()-3),(ROW()-2)*3,0)))


问:
Can I have a generic method in a injectable class?
Like:

```<code>@Injectable()
class ApiService {
  Future<T> fetch<T>(String path) {
    ...
  }
}
</code>```

this doesn't seem to work

答:
It seems that it was fixed within the analyzer package 0.29:

https://github.com/dart-lang/sdk/blob/master/pkg/analyzer/CHANGELOG.md

However, if you do:

```<code>T aa<T>() {
  print(T.toString());
}
</code>```

you will get a "dynamic" instead of the original class, which, very unfortunately, doesn't help me

Body:
Like:

@Injectable()
class ApiService {
  Future<T> fetch<T>(String path) {
    ...
  }
}

this doesn't seem to work

Body:
It seems that it was fixed within the analyzer package 0.29:

https://github.com/dart-lang/sdk/blob/master/pkg/analyzer/CHANGELOG.md

However, if you do:

T aa<T>() {
  print(T.toString());
}

you will get a "dynamic" instead of the original class, which, very unfortunately, doesn't help me


问:
Callback function on Vuejs
I am trying to make a process run in a synchronous way. However, as I have ajax calls, which are naturally asynchronous, I'm having problems because my array is only populated after it has been called. To solve this problem, I'm trying to do a callback function. But I'm not having success.

Here's my code:

(click action calls this function):

```<code>VmUser.executa(user,this.addTodos)
</code>```

The functions that are called:

```<code>executa(user, callback) {
  this.montaTodos(user, { complete: callback })
},

addTodos() {
  const VmUser = this
  VmUser.details = VmUser.todos.map(user => {
    VmUser.$bus.$emit('add-user', { user: user })
  })
},

montaTodos(user) {
  const VmUser = this
  axios
    .get(`api/gethierarquia/${user.cod_usuario}`)
    .then(res => {
      if (res.data.usuarios.length !== 0){
        //VmUser.$bus.$emit('add-user', { user: user})
        VmUser.todos.push(user)
        VmUser.supervisores = res.data.usuarios
        VmUser.details = VmUser.supervisores.map(user => {
          VmUser.todos.push(user)
          axios
            .get(`api/gethierarquia/${user.cod_usuario}`)
            .then(res => {
              if (res.data.usuarios.length !== 0){
                VmUser.funcionarios = res.data.usuarios
                VmUser.details = VmUser.funcionarios.map(user => {
                  VmUser.todos.push(user)
                })
              }
            })
        })
      }
    })
},
</code>```

答:
You can use a Promise to wait until the asynchronous request is finished to call the addTodos method.

I'm not sure why you are making two requests to api/gethierarquia. However, I think in your case it would look something like this:

```<code>executa(user, callback) {
  this.montaTodos(user).then((response) => {
    this.addTodos; // gets here when the promise is resolved
  }, (error) => {
    console.error(error); // gets here when the promise is rejected
  });
},

montaTodos(user) {
  return new Promise((resolve, reject) => {
    axios
      .get(`api/gethierarquia/${user.cod_usuario}`)
      .then((response) => {
        // logic to handle response

        resolve(response); // the request was successfull
      })
      .catch((error) => {
        reject(error); // the request failed
      });
  });
},
</code>```

Title: Callback function on Vuejs

Body:
I am trying to make a process run in a synchronous way. However, as I have ajax calls, which are naturally asynchronous, I'm having problems because my array is only populated after it has been called. To solve this problem, I'm trying to do a callback function. But I'm not having success.

Here's my code:

(click action calls this function):

VmUser.executa(user,this.addTodos)

The functions that are called:

executa(user, callback) {
  this.montaTodos(user, { complete: callback })
},

addTodos() {
  const VmUser = this
  VmUser.details = VmUser.todos.map(user => {
    VmUser.$bus.$emit('add-user', { user: user })
  })
},

montaTodos(user) {
  const VmUser = this
  axios
    .get(`api/gethierarquia/${user.cod_usuario}`)
    .then(res => {
      if (res.data.usuarios.length !== 0){
        //VmUser.$bus.$emit('add-user', { user: user})
        VmUser.todos.push(user)
        VmUser.supervisores = res.data.usuarios
        VmUser.details = VmUser.supervisores.map(user => {
          VmUser.todos.push(user)
          axios
            .get(`api/gethierarquia/${user.cod_usuario}`)
            .then(res => {
              if (res.data.usuarios.length !== 0){
                VmUser.funcionarios = res.data.usuarios
                VmUser.details = VmUser.funcionarios.map(user => {
                  VmUser.todos.push(user)
                })
              }
            })
        })
      }
    })
},

Body:
You can use a Promise to wait until the asynchronous request is finished to call the addTodos method.

I'm not sure why you are making two requests to api/gethierarquia. However, I think in your case it would look something like this:

executa(user, callback) {
  this.montaTodos(user).then((response) => {
    this.addTodos; // gets here when the promise is resolved
  }, (error) => {
    console.error(error); // gets here when the promise is rejected
  });
},

montaTodos(user) {
  return new Promise((resolve, reject) => {
    axios
      .get(`api/gethierarquia/${user.cod_usuario}`)
      .then((response) => {
        // logic to handle response

        resolve(response); // the request was successfull
      })
      .catch((error) => {
        reject(error); // the request failed
      });
  });
},


问:
Does kernel32 always load from System32?

Copy kernel32.dll from System32 (or SysWOW64 if you're testing with a 32-bit application) to the directory containing your EXE file

Run the EXE file

Process Monitor shows it doesn't even bother to check the local folder for kernel32.dll first

This seems to contradict what I've always thought is the default behaviour of DLLs, that is to load from the local application directory first and if it's not there load from the PATH environment variable. However, for certain DLLs like ntdll or kernel32, Windows always seems to check System32 first. Is this expected behaviour? Can it be overridden?

(I'm aware that overriding this would be bad practice, but want to know if it's actually possible, for science!)

答:
The KnownDLLs feature in Windows is supposed to help loading common DLLs faster but it also forces all DLLs on the list to load from system32.

On top of this, kernel32.dll and ntdll.dll are given special treatment in most versions of Windows and are loaded early inside CreateProcess because the real entry point of a usermode process is in one of those modules.

You can use .local and manifest redirection to override some of these.


问:
How to display contact us form echo result
code is working and I'm getting when I try to send mail from website contact us form but when I click Send button on website it redirects me and getting echo result that message have successfully sent but I want to display that echo in same page.

PHP code:

```<code> <?php
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");

if(isset($_POST['btn-send']))
echo "Thank you for your message"; ?>
</code>```

HTML code:

```<code><div class="second_third">
  <h6 class="title" style="padding-left: 45px;">Contact Us</h6>
  <ul class="nospace linklist">
   <form class="form1" method="post" action="send.php">
    Mail<br />
    <input type="email" id="input-email" class="input1" name="email">
    <br />
    Message
   <textarea name="message" class="textarea1" id="input-message"></textarea>
  <br />
   <input type="submit" value="Send" id="input-submit" class="input1" name="btn-send">
  </form>
</code>```

What I have to add or how to do it ?

Thank you.

答:
Right now it'll run even if you don't submit the form, assuming send.php contains the HTML form as well. Do this style thing:</p>

```<code><?php

if(isset($_POST['btn-send'])){
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");
echo "Thank you for your message";
}

 ?>
<form class="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
</code>```

Body:
code is working and I'm getting when I try to send mail from website contact us form but when I click Send button on website it redirects me and getting echo result that message have successfully sent but I want to display that echo in same page.

PHP code:

 <?php
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");

if(isset($_POST['btn-send']))
echo "Thank you for your message"; ?>

HTML code:

Contact Us

   <form class="form1" method="post" action="send.php">
    Mail

    <input type="email" id="input-email" class="input1" name="email">

    Message
   <textarea name="message" class="textarea1" id="input-message"></textarea>

   <input type="submit" value="Send" id="input-submit" class="input1" name="btn-send">
  </form>

What I have to add or how to do it ?

Thank you.

Body:
Right now it'll run even if you don't submit the form, assuming send.php contains the HTML form as well. Do this style thing:

<?php

if(isset($_POST['btn-send'])){
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");
echo "Thank you for your message";
}

 ?>
<form class="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


问:
Portably use special characters in parameter expansion, with or without double quotes
In all of the following shells:

bash

ksh

zsh

dash

and without a way to influence either the choice of shell or of shell
settings, my goal is to use the default string value (y!) whenever
the variable named x is unset or null. I.e., I want the shell to
perform parameter expansion producing (y!) where y stands for some
text not involving any special characters. So, naively,

```<code>${x:-(y!)}
</code>```

There may be double quotes. A number of differences become apparent, then, among the shells
interpreting this or a variation. In an attempt to
approach portability, I tried variants adding zero to three \s. I then also
tried the effects of spaces, but I'll exclude that for now.

```<code>${x:-(y!)}, ... , ${x:-\(y\!\)}
</code>```

One of the differences shown by the shells would, I guess, be related to a shell's
overloading of ! for history events. (Try !echo in zsh.)
Other differences remain when a variant occurs between double quotes.
A solution would ideally work between double quotes, as I cannot really
expect a scheme not to be used in this context.

E.g., given comand echo "$0: ${x:-\(y\!\)}", i.e., with all of (, !,
and ) preceded by \, the shells respond:

```<code>-bash: \(y\!\)
ksh: \(y\!\)
zsh: \(y!\)
dash: \(y\!\)
</code>```

So, the Z Shell begs to differ.  It turns out that the following seems
to be working alike in bash, ksh, zsh, and dash:

```<code>$ echo "${x:-$(echo \(y\!\))}"
(y!)
</code>```

But involving another command substitution (echo, even if
built-in(?)) seems overkill. Is there a better way? At all? Am I
missing something?

(Zsh seems to use !{...}, so not \, to “insulate a history
reference from adjacent characters (if necessary)” (zshexpn(1)). Maybe that explains why it responds differently?)

答:
Using the octal code for the ! char seems to work:

```<code>/bin/echo -e "'${x:-(y\0041)}'"
</code>```

The builtin echo commands for the various shells are inconsistent, (two require the -e switch, but dash doesn't understand it), so /bin/echo is more reliable.  Test the four shells:

```<code>unset x
for f in dash bash zsh ksh ; do
     echo -en "$f:\t"
     $f -c "/bin/echo -e \"'\${x:-(y\0041)}'\""
done
</code>```

Output:

```<code>dash:   '(y!)'
bash:   '(y!)'
zsh:    '(y!)'
ksh:    '(y!)'
</code>```

Body:
In all of the following shells:

bash

ksh

zsh

dash

and without a way to influence either the choice of shell or of shell
settings, my goal is to use the default string value (y!) whenever
the variable named x is unset or null. I.e., I want the shell to
perform parameter expansion producing (y!) where y stands for some
text not involving any special characters. So, naively,

${x:-(y!)}

There may be double quotes. A number of differences become apparent, then, among the shells
interpreting this or a variation. In an attempt to
approach portability, I tried variants adding zero to three \s. I then also
tried the effects of spaces, but I'll exclude that for now.

${x:-(y!)}, ... , ${x:-\(y\!\)}

One of the differences shown by the shells would, I guess, be related to a shell's
overloading of ! for history events. (Try !echo in zsh.)
Other differences remain when a variant occurs between double quotes.
A solution would ideally work between double quotes, as I cannot really
expect a scheme not to be used in this context.

E.g., given comand echo "$0: ${x:-\(y\!\)}", i.e., with all of (, !,
and ) preceded by \, the shells respond:

-bash: \(y\!\)
ksh: \(y\!\)
zsh: \(y!\)
dash: \(y\!\)

So, the Z Shell begs to differ.  It turns out that the following seems
to be working alike in bash, ksh, zsh, and dash:

$ echo "${x:-$(echo \(y\!\))}"
(y!)

But involving another command substitution (echo, even if
built-in(?)) seems overkill. Is there a better way? At all? Am I
missing something?

(Zsh seems to use !{...}, so not \, to “insulate a history
reference from adjacent characters (if necessary)” (zshexpn(1)). Maybe that explains why it responds differently?)

Body:
Using the octal code for the ! char seems to work:

/bin/echo -e "'${x:-(y\0041)}'"

The builtin echo commands for the various shells are inconsistent, (two require the -e switch, but dash doesn't understand it), so /bin/echo is more reliable.  Test the four shells:

unset x
for f in dash bash zsh ksh ; do
     echo -en "$f:\t"
     $f -c "/bin/echo -e \"'\${x:-(y\0041)}'\""
done

Output:

dash:   '(y!)'
bash:   '(y!)'
zsh:    '(y!)'
ksh:    '(y!)'


问:
How do I tree shake Three.js using WebPack or Rollup?
I've got a Three.js scene that only uses a portion of the library.

```<code>import {
    Scene,
    PerspectiveCamera,
    WebGLRenderer,
    BoxGeometry,
    MeshBasicMaterial,
    Mesh} from 'three';
</code>```

But I still end up getting most, if not all, of the entire library (~500Kb minified). Has anyone had any luck with this? I have an example GitHub that shows the code I'm using.

答:
I believe your problem is that you need to run your import from the THREE src/ tree which is not in the build/ dir, you'd need to clone THREE to have a local src/ tree against which your application runs.

In particular, you could use src/Three.js which is a giant exporter of all the THREE modules. Or simply change your imports to refer to the src//module.js.

Then rollup would have the individual modules against which to run and thus omit unused code.

Edit: see https://github.com/mrdoob/three.js/issues/10328#issuecomment-290233801 for more

Body:
I've got a Three.js scene that only uses a portion of the library.

import {
    Scene,
    PerspectiveCamera,
    WebGLRenderer,
    BoxGeometry,
    MeshBasicMaterial,
    Mesh} from 'three';

But I still end up getting most, if not all, of the entire library (~500Kb minified). Has anyone had any luck with this? I have an example GitHub that shows the code I'm using.


问:
How should I store a long list of IDs in redis?
I want to store a list of IDs (>100,000 of them) in redis.

So the list might look like: 332 99 91 78 10 98989 18221

I'll also need to be able to check to see if multiple IDs exist within this list as well.

e.g. I'd need to be able to check at once whether 99 and 332 and 41 exists on the list.

How would I go about storing this type of data?

答:
Use a Hash in which each field is an id and the value is the empty string, e.g.

```<code>HMSET ids 332 "" 99 "" 91"" 78 "" 10 98989 "" 18221 ""
</code>```

To perform the membership check:

```<code>HMGET ids 99 332 41
</code>```

The reply will have an empty string for each existing value, and a null for the non-existing ones.

Body:
Use a Hash in which each field is an id and the value is the empty string, e.g.

HMSET ids 332 "" 99 "" 91"" 78 "" 10 98989 "" 18221 ""

To perform the membership check:

HMGET ids 99 332 41

The reply will have an empty string for each existing value, and a null for the non-existing ones.


问:
OpenCV extended image processing - filters
How do I access the OpenCV extended image process module? I need one filter specifically: fastGlobalSmootherFilter.

I have OpenCV 3.2.0 incorporated into my C++ project. I'm looking for this method:
http://docs.opencv.org/master/da/d17/group__ximgproc__filters.html#gaf8673fe9147160ad96ac6053fac3c106

which is in this module:
http://docs.opencv.org/master/df/d2d/group__ximgproc.html.

I found it through the research page here:
https://sites.google.com/site/globalsmoothing/

I've tried searching through the OpenCV header files, but none reference this function. I can't find edge_filter.hpp which is supposed to house some of these filters. How does one actually call the method?

答:
At OpenCV developer site, you will find instructions for building the contrib modules (or extras)

https://github.com/opencv/opencv_contrib/blob/master/README.md

By default, they are not included in your build.


问:
Decimal type is read as double or int from In-memory Sqlite database
I don't have too much experience with Sqlite in .Net, but the behaviour I see is rather strange. Let's say we have a .Net core app with following project.json:

```<code>{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.Data.Sqlite": "1.0.0",
    "Dapper": "1.50.2"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}
</code>```

Also we have a simple class Item:

```<code>public class Item
{
    public Item() { }

    public Item(int id, string name, decimal price)
    {
        this.Id = id;
        this.Name = name;
        this.Price = price;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
</code>```

Then I create an in-memory database and populate it with data (using Dapper):

```<code>var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
connection.Execute("CREATE TABLE IF NOT EXISTS Items(Id INT, Name NVARCHAR(50), Price DECIMAL)");

var items = new List<Item>
{
    new Item(1, "Apple", 3m),
    new Item(2, "Banana", 1.4m)
};
connection.Execute("INSERT INTO Items(Id, Name, Price) VALUES (@Id, @Name, @Price)", items);
</code>```

Then I try to read from the Items table:

```<code>var dbItems = connection.Query<Item>("SELECT Id, Name, Price FROM Items").ToList();
</code>```

When I run the solution, I get the following exception:

Unhandled Exception: System.InvalidOperationException: Error parsing
  column 2 (Price=1.4 - Double) ---> System.Invali dCastException:
  Unable to cast object of type 'System.Double' to type 'System.Int64'.

Ok, then I tried to use Microsoft.Data.Sqlite to get the data:

```<code>var command = connection.CreateCommand();
command.CommandText = "SELECT Price FROM Items";
var reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(reader[0].GetType());
}
</code>```

As a result I get:

```<code>System.Int64 // Price = 3
System.Double // Price = 1.4
</code>```

I tried running query on real database with decimal price, the data type returned is correct and is always decimal (as expected).

What direction should I dig further? Is something wrong with my in-memory database? How to make it consistent with decimals?

答:
In SQLite, if you create a Table with a Numeric/Decimal Column datatype, it's associated to Numeric type affinity and its default behavior is to store an integer if a value has no decimals, or to store a real number if value contains decimals. This helps to save bytes storage because the most used integer values (less than a million value for small to medium applications) needs less bytes than real data type:

Integer (approx):

± 128 > 1 byte (2^8-1)

± 32,768 > 2 bytes (2^16-1)

± 8,388,608 > 3 bytes (2^24-1)

± 2,147,483,648 > 4 bytes (2^32-1)

± 140,737,488,355,328 > 6 bytes (2^48-1)

± 9,223,372,036,854,780,000 > 8 bytes (2^64-1)

Against 8 byte real IEEE datatype

If you need to store a real number always, it's necessary to declare a float/real datatype in order to be considered as real type affinity, thus even if you send an integer number to SQLite it would be stored as real

Source: https://sqlite.org/datatype3.html

I know real could be imprecise, but I've made some test using C# Decimal datatype and SQLite with database in disk in wal mode, and I've never had a rounding error if all operations are made in C#. But when I made some calculations directly in SQLite I got some rounding errors and some bad calculations because of 2 integer division

I use EF6 and Dapper to read/write Numeric values (integer/real from SQLite) and never got an error.

Now, I'm planning to take advantage of SQLite numeric behavior to save disk space with dapper TypeHandler, thus I may replicate SQL Server Money implementation (internally, SQL Server saves an 8 byte integer and it's divided by 10000 when it loads into memory):

```<code>public class NumericTypeHandler : SqlMapper.TypeHandler<decimal>
{
    public override void SetValue(IDbDataParameter parameter, decimal value)
    {
        parameter.Value = (long)(value / 10000);
    }

    public override decimal Parse(object value)
    {
        return ((decimal)value)/10000M;
    }
}
</code>```

Additionally, I set up datetime UnixEpoch implementation to save diskspace and enhance performance

Note:

SQLite may handle dozens of users in a low demand asp.net application, the trick is tune-up SQLite with pragmas directives and other things:

WAL mode: helps to manage better concurrency and performance

Page size: if matches the file system's cluster size, enhances performance

Shared Cache Mode: implements table locks instead database locks when it's acceded in several threads

Datetime UnixEpoch: saves seconds (4 bytes) instead of text ISO datetime ("2012-12-21T17:30:24" = 20 bytes).

Cache size: saved I/O access keeping last accessed pages in memory

Also I made some enhancements in C# side:

I made a custom DateTime struct for DateTime values in order to save data as integer overriding ToString method and loads into memory as DateTime with constructor overload.

I Made a custom Numeric struct in C#, (like DateTime one), to save money as cents overriding ToString method and loads into memory as Decimal with constructor overload

avoid save unnecessary data (Error logs, email html text)

I think you should use an ORM like EFx or Dapper if you plan to use SQLite as backend. With dapper you would need to create your own micro framework to save development time (basic CRUD functionality and Linq queries transformation).

The best tool that I´ve found is https://github.com/linq2db/linq2db, you use linq for accessing database with very good speed and easiness of linq. And it is possible to make CRUD functionality.

I'll be happy if this answer helps

regards

Body:
I don't have too much experience with Sqlite in .Net, but the behaviour I see is rather strange. Let's say we have a .Net core app with following project.json:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.Data.Sqlite": "1.0.0",
    "Dapper": "1.50.2"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

Also we have a simple class Item:

public class Item
{
    public Item() { }

    public Item(int id, string name, decimal price)
    {
        this.Id = id;
        this.Name = name;
        this.Price = price;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Then I create an in-memory database and populate it with data (using Dapper):

var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
connection.Execute("CREATE TABLE IF NOT EXISTS Items(Id INT, Name NVARCHAR(50), Price DECIMAL)");

var items = new List<Item>
{
    new Item(1, "Apple", 3m),
    new Item(2, "Banana", 1.4m)
};
connection.Execute("INSERT INTO Items(Id, Name, Price) VALUES (@Id, @Name, @Price)", items);

Then I try to read from the Items table:

var dbItems = connection.Query<Item>("SELECT Id, Name, Price FROM Items").ToList();

When I run the solution, I get the following exception:

Unhandled Exception: System.InvalidOperationException: Error parsing
  column 2 (Price=1.4 - Double) ---> System.Invali dCastException:
  Unable to cast object of type 'System.Double' to type 'System.Int64'.

Ok, then I tried to use Microsoft.Data.Sqlite to get the data:

var command = connection.CreateCommand();
command.CommandText = "SELECT Price FROM Items";
var reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(reader[0].GetType());
}

As a result I get:

System.Int64 // Price = 3
System.Double // Price = 1.4

I tried running query on real database with decimal price, the data type returned is correct and is always decimal (as expected).

What direction should I dig further? Is something wrong with my in-memory database? How to make it consistent with decimals?

Body:
In SQLite, if you create a Table with a Numeric/Decimal Column datatype, it's associated to Numeric type affinity and its default behavior is to store an integer if a value has no decimals, or to store a real number if value contains decimals. This helps to save bytes storage because the most used integer values (less than a million value for small to medium applications) needs less bytes than real data type:

Integer (approx):

± 128 > 1 byte (2^8-1)

± 32,768 > 2 bytes (2^16-1)

± 8,388,608 > 3 bytes (2^24-1)

± 2,147,483,648 > 4 bytes (2^32-1)

± 140,737,488,355,328 > 6 bytes (2^48-1)

± 9,223,372,036,854,780,000 > 8 bytes (2^64-1)

Against 8 byte real IEEE datatype

If you need to store a real number always, it's necessary to declare a float/real datatype in order to be considered as real type affinity, thus even if you send an integer number to SQLite it would be stored as real

Source: https://sqlite.org/datatype3.html

I know real could be imprecise, but I've made some test using C# Decimal datatype and SQLite with database in disk in wal mode, and I've never had a rounding error if all operations are made in C#. But when I made some calculations directly in SQLite I got some rounding errors and some bad calculations because of 2 integer division

I use EF6 and Dapper to read/write Numeric values (integer/real from SQLite) and never got an error.

Now, I'm planning to take advantage of SQLite numeric behavior to save disk space with dapper TypeHandler, thus I may replicate SQL Server Money implementation (internally, SQL Server saves an 8 byte integer and it's divided by 10000 when it loads into memory):

public class NumericTypeHandler : SqlMapper.TypeHandler<decimal>
{
    public override void SetValue(IDbDataParameter parameter, decimal value)
    {
        parameter.Value = (long)(value / 10000);
    }

    public override decimal Parse(object value)
    {
        return ((decimal)value)/10000M;
    }
}

Additionally, I set up datetime UnixEpoch implementation to save diskspace and enhance performance

Note:

SQLite may handle dozens of users in a low demand asp.net application, the trick is tune-up SQLite with pragmas directives and other things:

WAL mode: helps to manage better concurrency and performance

Page size: if matches the file system's cluster size, enhances performance

Shared Cache Mode: implements table locks instead database locks when it's acceded in several threads

Datetime UnixEpoch: saves seconds (4 bytes) instead of text ISO datetime ("2012-12-21T17:30:24" = 20 bytes).

Cache size: saved I/O access keeping last accessed pages in memory

Also I made some enhancements in C# side:

I made a custom DateTime struct for DateTime values in order to save data as integer overriding ToString method and loads into memory as DateTime with constructor overload.

I Made a custom Numeric struct in C#, (like DateTime one), to save money as cents overriding ToString method and loads into memory as Decimal with constructor overload

avoid save unnecessary data (Error logs, email html text)

I think you should use an ORM like EFx or Dapper if you plan to use SQLite as backend. With dapper you would need to create your own micro framework to save development time (basic CRUD functionality and Linq queries transformation).

The best tool that I´ve found is https://github.com/linq2db/linq2db, you use linq for accessing database with very good speed and easiness of linq. And it is possible to make CRUD functionality.

I'll be happy if this answer helps

regards


问:
Scroll to bottom in UITableView
I have a chatScreen built using UITableView. I want to scroll to bottom of UITableView, the moment the screen is opened from some other view controller.However using trivial scroll to bottom functions, shows a jerk if the chat is long.Is there an alternative?

```<code>- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    dispatch_async(dispatch_get_main_queue(), ^{

        NSIndexPath* lastIndexPath = [NSIndexPath indexPathForRow:_messagesArray.count-1  inSection:0];
        [_tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    });
}
</code>```

答:
I think this is what you want:</p>

```<code>extension UITableView {

    func scrollToBottom() {
        scrollToRow(at: IndexPath(row: numberOfRows(inSection: numberOfSections-1)-1, section: numberOfSections-1),
                    at: .bottom, animated: true)
    }
}
</code>```

Title: Scroll to bottom in UITableView

Body:
I have a chatScreen built using UITableView. I want to scroll to bottom of UITableView, the moment the screen is opened from some other view controller.However using trivial scroll to bottom functions, shows a jerk if the chat is long.Is there an alternative?

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    dispatch_async(dispatch_get_main_queue(), ^{

        NSIndexPath* lastIndexPath = [NSIndexPath indexPathForRow:_messagesArray.count-1  inSection:0];
        [_tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    });
}

Body:
I think this is what you want:

extension UITableView {

    func scrollToBottom() {
        scrollToRow(at: IndexPath(row: numberOfRows(inSection: numberOfSections-1)-1, section: numberOfSections-1),
                    at: .bottom, animated: true)
    }
}


问:
Java TreeSet contains() gives false results
I am trying to code a little bit of math with java. What I am trying to do, is to put cyclotomic cosets to the TreeSet. A coset has an index and a set of integer numbers. A coset is equal to other coset if the set has the same elements. If sets differ, then coset is ordered by its index.

For example:

```<code>C1 = [1, 2, 4, 8]
C3 = [3, 6, 9, 12]
C9 = [3, 6, 9, 12]

C1 is less than C3
C3 is equal to C9
</code>```

Well enough math. I chose to put cosets to TreeSet because I do not need duplicate elements and I need to have them sorted by index.

The problem is even TreeSet.contains() returns false, I can still find one element in the TreeSet which is equal when using compareTo() and equals() methods.

This is the actual printout of the program:

```<code>cosets = [C0, C1, C3, C5, C7]
cosets.contains(C9) = false
C0.compareTo(C9) = -1, C0.equals(C9) = false
C1.compareTo(C9) = -1, C1.equals(C9) = false
C3.compareTo(C9) = 0, C3.equals(C9) = true
C5.compareTo(C9) = -1, C5.equals(C9) = false
C7.compareTo(C9) = -1, C7.equals(C9) = false
</code>```

I am attaching the code below. I did not want to make code any simplier, because I found that it does some magic. If you change MAGIC_INDEX value to 7 or less in the code, it starts to work. It seems like a JVM bug to me.

http://2m.lt/files/Main.java

http://2m.lt/files/Coset.java

Any suggestions?

答:
Your compareTo() and equals() methods are not consistent, and therfore the TreeSet cannot work correctly with them.

From the API doc:

Note that the ordering maintained by a
  set (whether or not an explicit
  comparator is provided) must be
  consistent with equals if it is to
  correctly implement the Set interface.
  (See Comparable or Comparator for a
  precise definition of consistent with
  equals.) This is so because the Set
  interface is defined in terms of the
  equals operation, but a TreeSet
  instance performs all element
  comparisons using its compareTo (or
  compare) method, so two elements that
  are deemed equal by this method are,
  from the standpoint of the set, equal.
  The behavior of a set is well-defined
  even if its ordering is inconsistent
  with equals; it just fails to obey the
  general contract of the Set interface.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to code a little bit of math with java. What I am trying to do, is to put cyclotomic cosets to the TreeSet. A coset has an index and a set of integer numbers. A coset is equal to other coset if the set has the same elements. If sets differ, then coset is ordered by its index.

For example:

C1 = [1, 2, 4, 8]
C3 = [3, 6, 9, 12]
C9 = [3, 6, 9, 12]

C1 is less than C3
C3 is equal to C9

Well enough math. I chose to put cosets to TreeSet because I do not need duplicate elements and I need to have them sorted by index.

The problem is even TreeSet.contains() returns false, I can still find one element in the TreeSet which is equal when using compareTo() and equals() methods.

This is the actual printout of the program:

cosets = [C0, C1, C3, C5, C7]
cosets.contains(C9) = false
C0.compareTo(C9) = -1, C0.equals(C9) = false
C1.compareTo(C9) = -1, C1.equals(C9) = false
C3.compareTo(C9) = 0, C3.equals(C9) = true
C5.compareTo(C9) = -1, C5.equals(C9) = false
C7.compareTo(C9) = -1, C7.equals(C9) = false

I am attaching the code below. I did not want to make code any simplier, because I found that it does some magic. If you change MAGIC_INDEX value to 7 or less in the code, it starts to work. It seems like a JVM bug to me.

http://2m.lt/files/Main.java

http://2m.lt/files/Coset.java

Any suggestions?


问:
Why python datetime replace timezone is returning different timezone?
I am working on Python/Django project. I am trying to let user select date and time using jQuery plugin datetimepicker add-on. So when I select now option and post data django is saving the time in UTC offset. This is what is saved in database, 2017-03-30 13:38:00+00:00. I need to convert this time from user's timezone and save it in system as utc. Because later I will have script running which will look for data in database which is less than the utc time.

Actually the script is to let user post information on website and let them chose the publish date and time. So for example, If use posted an article which will be published on April 2nd 1pm Chicago time, I don't want other users to read the article before this time. So people around the world can read article as soon as it is April 2nd and 1PM in Chicago. So how can I make this functionality work?

My solution was to get the time and remove it's timezone information using replace(tzinfo=pytz.timezone('America/Chicago')) and when I print the time, I am getting 2017-03-30 13:38:00-05:51. The actual offset right now is -05:00. Can anyone help me to and tell me what I am doing wrong?

What I am doing for form is that I have publish_date object in my model and I am using django forms to create form. I have added class as an attribute in it and using jquery plugin,

```<code>$('.datepicker').datetimepicker({
                timeFormat: 'HH:mm',
                stepHour: 1,
                stepMinute: 1,
            });
</code>```

So when User submits the form, on post method this my code,

```<code>form = PublishForm(request.POST)

if form.is_valid():

                f = form.save(commit=False)
                f.created_by_user_id = request.user.id
                f.save()
</code>```

and than to get the date all I am doing is f.publish_date and the other  options I have used lice replace and localize are pretty standard.

Thanks

答:
As noted in the comments, you appear to have two problems. First is that the datetimepicker is saving a date and time with a UTC timezone offset, when it should be applying a different timezone or leaving off the timezone offset entirely. Second is that pytz is using the wrong offset.

I don't know how to fix the first problem, but I can help you with the second. You need to use pytz's localize function. This only works when the datetime doesn't have a timezone attached, but since you know the timezone is incorrect anyway you can delete it first.

```<code>tz = pytz.timezone('America/Chicago')
dt = tz.localize(dt.replace(tzinfo=None))
</code>```

Body:
I am working on Python/Django project. I am trying to let user select date and time using jQuery plugin datetimepicker add-on. So when I select now option and post data django is saving the time in UTC offset. This is what is saved in database, 2017-03-30 13:38:00+00:00. I need to convert this time from user's timezone and save it in system as utc. Because later I will have script running which will look for data in database which is less than the utc time.

Actually the script is to let user post information on website and let them chose the publish date and time. So for example, If use posted an article which will be published on April 2nd 1pm Chicago time, I don't want other users to read the article before this time. So people around the world can read article as soon as it is April 2nd and 1PM in Chicago. So how can I make this functionality work?

My solution was to get the time and remove it's timezone information using replace(tzinfo=pytz.timezone('America/Chicago')) and when I print the time, I am getting 2017-03-30 13:38:00-05:51. The actual offset right now is -05:00. Can anyone help me to and tell me what I am doing wrong?

What I am doing for form is that I have publish_date object in my model and I am using django forms to create form. I have added class as an attribute in it and using jquery plugin,

$('.datepicker').datetimepicker({
                timeFormat: 'HH:mm',
                stepHour: 1,
                stepMinute: 1,
            });

So when User submits the form, on post method this my code,

form = PublishForm(request.POST)

if form.is_valid():

                f = form.save(commit=False)
                f.created_by_user_id = request.user.id
                f.save()

and than to get the date all I am doing is f.publish_date and the other  options I have used lice replace and localize are pretty standard.

Thanks

Body:
As noted in the comments, you appear to have two problems. First is that the datetimepicker is saving a date and time with a UTC timezone offset, when it should be applying a different timezone or leaving off the timezone offset entirely. Second is that pytz is using the wrong offset.

I don't know how to fix the first problem, but I can help you with the second. You need to use pytz's localize function. This only works when the datetime doesn't have a timezone attached, but since you know the timezone is incorrect anyway you can delete it first.

tz = pytz.timezone('America/Chicago')
dt = tz.localize(dt.replace(tzinfo=None))


问:
Generating new columns as a full-combination of other columns
Could not find similar cases here.
Suppose, i have a DataFrame

```<code>df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})
</code>```

So it is:

```<code>    A   B   C   I   II
0   2   2   3   1   0
1   2   2   3   0   1
2   1   3   3   0   0
3   2   3   4   1   1
</code>```

I want to make a full pairwise combination between {A,B,C} and {I,II}, so i get {I-A,I-B,I-C,II-A,II-B,II-C}:

Each of a new column is just an elementwise multiplication of corresponding base columns

```<code>    I-A I-B I-C II-A  II-B  II-C
 0   2   2   3    0    0      0
 1   0   0   0    2    2      3
 2   0   0   0    0    0      0
 3   2   3   4    2    3      4
</code>```

ATM i dont have any working solution. I'am trying to use loops(not succeding in this), but i hope there's more sufficient way.

答:
Here is a solution without for loops for your specific example:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})
cross_vals=np.tile(df[df.columns[:3]].values,(1,2))*np.repeat(df[df.columns[3:]].values,3,axis=1)
cros_cols=np.repeat(df.columns[3:].values,3)+np.array('-')+np.tile(df.columns[:3].values,(1,2))
new_df=pd.DataFrame(cross_vals,columns=cros_cols[0])
</code>```

Then new_df is

```<code>   I-A  I-B I-C II-A II-B II-C
0   2    2   3   0    0    0
1   0    0   0   2    2    3
2   0    0   0   0    0    0
3   2    3   4   2    3    4
</code>```

You could generalize it to any size as long as the columns A,B,C,... are consecutive and similarly the columns I,II,... are consecutive.

For the general case, if the columns are not necessarily consecutive, you can do the following:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[2,2,1,2],
                       'B':[2,2,3,3],
                       'C':[3,3,3,4],
                       'I':[1,0,0,1],
                       'II':[0,1,0,1]})
let=np.array(['A','B','C'],dtype=object)
num=np.array(['I','II'],dtype=object)
cross_vals=np.tile(df[let].values,(1,len(num)))*np.repeat(df[num].values,len(let),axis=1)
cros_cols=np.repeat(num,len(let))+np.array('-')+np.tile(let,(1,len(num)))
new_df=pd.DataFrame(cross_vals,columns=cros_cols[0])
</code>```

And the result is the same as above.

Body:
Could not find similar cases here.
Suppose, i have a DataFrame

df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})

So it is:

    A   B   C   I   II
0   2   2   3   1   0
1   2   2   3   0   1
2   1   3   3   0   0
3   2   3   4   1   1

I want to make a full pairwise combination between {A,B,C} and {I,II}, so i get {I-A,I-B,I-C,II-A,II-B,II-C}:

Each of a new column is just an elementwise multiplication of corresponding base columns

    I-A I-B I-C II-A  II-B  II-C
 0   2   2   3    0    0      0
 1   0   0   0    2    2      3
 2   0   0   0    0    0      0
 3   2   3   4    2    3      4

ATM i dont have any working solution. I'am trying to use loops(not succeding in this), but i hope there's more sufficient way.

Body:
Here is a solution without for loops for your specific example:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})
cross_vals=np.tile(df[df.columns[:3]].values,(1,2))*np.repeat(df[df.columns[3:]].values,3,axis=1)
cros_cols=np.repeat(df.columns[3:].values,3)+np.array('-')+np.tile(df.columns[:3].values,(1,2))
new_df=pd.DataFrame(cross_vals,columns=cros_cols[0])

Then new_df is

   I-A  I-B I-C II-A II-B II-C
0   2    2   3   0    0    0
1   0    0   0   2    2    3
2   0    0   0   0    0    0
3   2    3   4   2    3    4

You could generalize it to any size as long as the columns A,B,C,... are consecutive and similarly the columns I,II,... are consecutive.

For the general case, if the columns are not necessarily consecutive, you can do the following:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[2,2,1,2],
                       'B':[2,2,3,3],
                       'C':[3,3,3,4],
                       'I':[1,0,0,1],
                       'II':[0,1,0,1]})
let=np.array(['A','B','C'],dtype=object)
num=np.array(['I','II'],dtype=object)
cross_vals=np.tile(df[let].values,(1,len(num)))*np.repeat(df[num].values,len(let),axis=1)
cros_cols=np.repeat(num,len(let))+np.array('-')+np.tile(let,(1,len(num)))
new_df=pd.DataFrame(cross_vals,columns=cros_cols[0])

And the result is the same as above.


问:
Explanation about return object of class example
I have this example ,and i need to know if the object class (ob2) in the second method came as argument from return object in the first method??

can anyone explain this example to me?

```<code>public class C {

  public B getObject(){

   B ob2 = new B ();

   return ob2; //return type
   }

   public void f3(A ob2){

   ob2.f1 (); //local variable or argument
}}
</code>```

答:
ob2 in method f3 comes from argument. For example:</p>

```<code>C c = new C();
A ob2 = new A();
c.f3(ob2)
</code>```

Body:
I have this example ,and i need to know if the object class (ob2) in the second method came as argument from return object in the first method??

can anyone explain this example to me?

public class C {

  public B getObject(){

   B ob2 = new B ();

   return ob2; //return type
   }

   public void f3(A ob2){

   ob2.f1 (); //local variable or argument
}}

Body:
ob2 in method f3 comes from argument. For example:

C c = new C();
A ob2 = new A();
c.f3(ob2)


问:
How can I scrape/parse this data using regular expressions?
I'm really a beginner when it comes to regular expressions, and I'm not really sure where to start. I have some html code scraped from a web page and stored in a variable, and it looks something like this:

```<code><thead><tr>
<th></th>
<th>GENERAL INFORMATION</th>
<th></th>
<th>DETAILED DATA</th>
</tr></thead>
<tbody><tr>
<th>ID</th>
<td>123456789ABCD</td>
<th>Field1</th>
<td>6 = (Some-Specification (3 or more details))</td>

</tr></tbody>
<tbody><tr>
<th>AGL</th>
<td>1 - United States ; TH - Some Data</td>
<th>Field2</th>
<td>7 = (Option/Other Option)</td>
</tr></tbody>
<tbody><tr>
<th>MANUFACTURER</th>
<td>2010 SPECIFICATION  (ADSD: HMKC)</td>
<th>Field3</th>

<td>8 = (My Type)</td>
</tr></tbody>
<tbody><tr>
<th>MODEL</th>
<td>6X4 MY-MODEL/SOME_SPECS LONG SPECIFICATION, BLAH</td>
<th>Field4</th>
<td>9 = (STUFF/OTHER STUFF)</td>
</tr></tbody>
<tbody>
</code>```

And then there is more of the same... I would like to parse the data from these cells into variables. (e.g. parse "123456789ABCD" into an ID variable) I'm working in ColdFusion and was thinking of using methods like REFindNoCase, REReplaceNoCase, SpanExcluding... Any idea how I can accomplish this? Or if you're not familiar with ColdFusion, even just the regular expressions necessary to parse this data would be very useful.

答:
I agree with the main opinion on this platform that parsing HTML with regexes is not the "golden path". But in some cases it is just the easiest way to go and it just does what it needs to do.

This regex should do what you need:

```<code><th>((?!</th>).)*</th>\s*<td>((?!</td>).)*</td>
</code>```

Use the capturing group 1 for the key and group 2 for the value.

I dont know ColdFusion so I can not tell you how to apply it.

Body:
I'm really a beginner when it comes to regular expressions, and I'm not really sure where to start. I have some html code scraped from a web page and stored in a variable, and it looks something like this:

GENERAL INFORMATION

DETAILED DATA

ID
123456789ABCD
Field1
6 = (Some-Specification (3 or more details))

AGL
1 - United States ; TH - Some Data
Field2
7 = (Option/Other Option)

MANUFACTURER
2010 SPECIFICATION  (ADSD: HMKC)
Field3

8 = (My Type)

MODEL
6X4 MY-MODEL/SOME_SPECS LONG SPECIFICATION, BLAH
Field4
9 = (STUFF/OTHER STUFF)

And then there is more of the same... I would like to parse the data from these cells into variables. (e.g. parse "123456789ABCD" into an ID variable) I'm working in ColdFusion and was thinking of using methods like REFindNoCase, REReplaceNoCase, SpanExcluding... Any idea how I can accomplish this? Or if you're not familiar with ColdFusion, even just the regular expressions necessary to parse this data would be very useful.

Body:
I agree with the main opinion on this platform that parsing HTML with regexes is not the "golden path". But in some cases it is just the easiest way to go and it just does what it needs to do.

This regex should do what you need:

<th>((?!</th>).)*</th>\s*<td>((?!</td>).)*</td>

Use the capturing group 1 for the key and group 2 for the value.

I dont know ColdFusion so I can not tell you how to apply it.


问:
py2exe term not recognized
I'm trying to make a .exe with py2exe running python 2.7.13

I used EXACTLY the files in the tutorial, hello.py, setup.py

next --> python setup.py py2exe

The "hello.exe" is in the dist folder, A-OK.
I try to run it from PowerShell,
C:\users\me\python\dist> hello.exe
and I get this error.

```<code>The term 'hello.exe' is not recognized as the name of a cmdlet, funtion,
script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.

At line:1 char:10
+ hello.exe <<<<

         + CategoryInfo          : ObjectNotFound: (hello.exe:String) [], CommandNotFoundException
         + FullyQualifiedErrorId : CommandNotFoundException

Suggestion [3,General]: The command hello.exe was not found, but does exist
in the current location. Windows Powershell does not load commands from the
current location by default. If you trust this command, instead type
".\hello.exe". See "get-help about_Command_Precedence" for more details.
</code>```

It does run if I type ".\hello.exe" into powershell.
It does not run when I double-click on the executable.

Am I doing something wrong? Do I need another .dll file?

EDIT: The nice people of stackoverflow have spoken. I was being slow(quite literally). Everything worked fine. Thank you all.

答:
It's been a long time since I used py2exe but when I used it after the main functionality of the program was complete it would simply exit.  This means that once your program is finished executing, which I think for the file names would be just printing hello world or something, it will exit.

Opening a window printing to it and exiting is actually really quick and might be too quick to draw to the screen.  I'll bet that is what is happening for you.  If you add a statement like time.sleep(30) or raw_input("Press any key to exit...") I'll bet that it would 'run' properly and you'd see an actual program.

I would also suggest becoming accustom to running things from the command line as you get the output of the results, with programs like this, and you can usually tell if something went wrong.

Title: py2exe term not recognized

Body:
I'm trying to make a .exe with py2exe running python 2.7.13

I used EXACTLY the files in the tutorial, hello.py, setup.py

next --> python setup.py py2exe

The "hello.exe" is in the dist folder, A-OK.
I try to run it from PowerShell,
C:\users\me\python\dist> hello.exe
and I get this error.

The term 'hello.exe' is not recognized as the name of a cmdlet, funtion,
script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.

At line:1 char:10
+ hello.exe <<<<

         + CategoryInfo          : ObjectNotFound: (hello.exe:String) [], CommandNotFoundException
         + FullyQualifiedErrorId : CommandNotFoundException

Suggestion [3,General]: The command hello.exe was not found, but does exist
in the current location. Windows Powershell does not load commands from the
current location by default. If you trust this command, instead type
".\hello.exe". See "get-help about_Command_Precedence" for more details.

It does run if I type ".\hello.exe" into powershell.
It does not run when I double-click on the executable.

Am I doing something wrong? Do I need another .dll file?

EDIT: The nice people of stackoverflow have spoken. I was being slow(quite literally). Everything worked fine. Thank you all.


问:
Populating JTextField based on latest KeyStroke
The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox populate jTextField1 if the checkbox is selected, and populate the other if it is not selected or vice versa which is working perfectly.

But I would like to explore if this can be done without the checkbox.

As in, if I type something in jtextfield1 and double click the item in list to complete the text, the item clicked should be appended to jtextfield1 based on fetching the latest KeyStroke I used.

Is there are any way to do this?

答:
As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.

Code:

```<code>String LastFocusLost = null;

jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
 {
  public void focusLost(java.awt.event.FocusEvent evt)
     {
      LastFocusLost = "jTextField1";
     }
 });

jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
 {
  public void focusLost(java.awt.event.FocusEvent evt)
     {
      LastFocusLost = "jTextField2";
     }
 });
</code>```

In the mouseListener add a if-else then:

```<code>if ("jTextField1".equals(LastFocusLost))
 {
   //;
 }

else if ("jTextField2".equals(LastFocusLost))
 {
  //;
 }
</code>```

Body:
As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.

Code:

String LastFocusLost = null;

jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
 {
  public void focusLost(java.awt.event.FocusEvent evt)
     {
      LastFocusLost = "jTextField1";
     }
 });

jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
 {
  public void focusLost(java.awt.event.FocusEvent evt)
     {
      LastFocusLost = "jTextField2";
     }
 });

In the mouseListener add a if-else then:

if ("jTextField1".equals(LastFocusLost))
 {
   //;
 }

else if ("jTextField2".equals(LastFocusLost))
 {
  //;
 }


问:
Speeding up sklearn logistic regression
I have a model I'm trying to build using LogisticRegression in sklearn that has a couple thousand features and approximately 60,000 samples.  I'm trying to fit the model and it's been running for about 10 mins now.  The machine I'm running it on has gigabytes of RAM and several cores at its disposal and I was wondering if there is any way to speed the process up

EDIT
The machine has 24 cores and here is the output of top to give an idea of memory

```<code>Processes: 94 total, 8 running, 3 stuck, 83 sleeping, 583 threads      20:10:19
Load Avg: 1.49, 1.25, 1.19  CPU usage: 4.34% user, 0.68% sys, 94.96% idle
SharedLibs: 1552K resident, 0B data, 0B linkedit.
MemRegions: 51959 total, 53G resident, 46M private, 676M shared.
PhysMem: 3804M wired, 57G active, 1042M inactive, 62G used, 34G free.
VM: 350G vsize, 1092M framework vsize, 52556024(0) pageins, 85585722(0) pageouts
Networks: packets: 172806918/25G in, 27748484/7668M out.
Disks: 14763149/306G read, 26390627/1017G written.
</code>```

I'm trying to train the model with the following

```<code>classifier = LogisticRegression(C=1.0, class_weight = 'auto')
classifier.fit(train, response)
</code>```

train has rows that are approximately 3000 long (all floating point) and each row in  response is either 0 or 1.  I have approximately 50,000 observations

答:
Worth noting that now LogisticRegression() accepts num_jobs as input and defaults to 1.

Would have commented on the accepted answer, but not enough points.

Title: Speeding up sklearn logistic regression

Body:
I have a model I'm trying to build using LogisticRegression in sklearn that has a couple thousand features and approximately 60,000 samples.  I'm trying to fit the model and it's been running for about 10 mins now.  The machine I'm running it on has gigabytes of RAM and several cores at its disposal and I was wondering if there is any way to speed the process up

EDIT
The machine has 24 cores and here is the output of top to give an idea of memory

Processes: 94 total, 8 running, 3 stuck, 83 sleeping, 583 threads      20:10:19
Load Avg: 1.49, 1.25, 1.19  CPU usage: 4.34% user, 0.68% sys, 94.96% idle
SharedLibs: 1552K resident, 0B data, 0B linkedit.
MemRegions: 51959 total, 53G resident, 46M private, 676M shared.
PhysMem: 3804M wired, 57G active, 1042M inactive, 62G used, 34G free.
VM: 350G vsize, 1092M framework vsize, 52556024(0) pageins, 85585722(0) pageouts
Networks: packets: 172806918/25G in, 27748484/7668M out.
Disks: 14763149/306G read, 26390627/1017G written.

I'm trying to train the model with the following

classifier = LogisticRegression(C=1.0, class_weight = 'auto')
classifier.fit(train, response)

train has rows that are approximately 3000 long (all floating point) and each row in  response is either 0 or 1.  I have approximately 50,000 observations


问:
ASP NET Core Identity with Entity Framework custom DbContext
I've tried reading the docs on ASP.NET Core Identity and Entity Framework. But I feel still non the wiser.

I don't want to have anything to do with IdentityDbContext, IdentityUser, IdentityRole. I just want to use my own DbContext implementation and work happily with UserManager, UserStore, RoleManager, SignInManager, and what other classes involved with signing in.

So that been said, having created a the default ASP.NET Core project that uses "Individual User Accounts".  Now I want to figure out what DI wire up is required for that controller to "work".

Looking at the account controller constructor:

```<code>public AccountController(UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        IOptions<IdentityCookieOptions> identityCookieOptions,
        IEmailSender emailSender,
        ISmsSender smsSender,
        ILoggerFactory loggerFactory)
</code>```

Along with that, the following related classes are generated:

```<code>public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    ...
}
</code>```

And some related DI configuration:

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...
    app.UseIdentity();
}
</code>```

Digging around in the source code for ASP.NET Core Identity, UserStore forces the constraint on IdentityUser.

```<code>public class UserStore : UserStore<IdentityUser<string>>
</code>```

For what I want to work is with something like the following - for starters:

```<code>public class AuthenticationDbContext : DbContext
{
    public AuthenticationDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<ApplicationRole> ApplicationRoles { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>(te =>
          te.HasKey(user => user.Id));

        builder.Entity<ApplicationRole>(te =>
          te.HasKey(role => role.Id));
     }
}

public class ApplicationRole
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

public class ApplicationUser
{
    public int Id { get; set; }
    public Guid Guid { get; set; }
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public string MiddleName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
}
</code>```

If I listed the issues I have had, exceptions et al, this post would be too long.

The question is, how do I wire this up with DI configuration?

答:
OK.  Following on from keeping my AuthenticationDbContext the same, I can provide an implementation of IUserStore, IRoleStore and configure the DI as follows.

```<code>public class ApplicationUserStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>
{
    private readonly AuthenticationDbContext _dbContext;

    public ApplicationUserStore(AuthenticationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    ...
</code>```

OK, so I need to provide implementations of 10 or 11 methods here which needs a little figuring out.  The same for ApplicationRoleStore.

```<code>public class ApplicationRoleStore : IRoleStore<ApplicationRole>
{
    private AuthenticationDbContext _dbContext;

    public ApplicationRoleStore(AuthenticationDbContext context, IdentityErrorDescriber describer = null)
    {
        _dbContext = context;
    }

    ...
</code>```

Then this can be wired up with:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddUserStore<ApplicationUserStore>()
        .AddRoleStore<ApplicationRoleStore>()
        .AddDefaultTokenProviders();

     services.AddTransient(c =>
            new AuthenticationDbContext(
                new DbContextOptionsBuilder()
                    .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).Options));
</code>```

So signing in via Account Controller/Login view now invokes my ApplicationUserStore.FindByNameAsync when I click on Login.

Whether this is or isn't the "proper" remains to be seen.  I just feel strongly that the ASP.NET Identity should work with "any" data store implementation, therefore you shouldn't have to be constrained to using IdentityUser.  The above should work for non-Entity Framework implementations I feel.

Body:
I've tried reading the docs on ASP.NET Core Identity and Entity Framework. But I feel still non the wiser.

I don't want to have anything to do with IdentityDbContext, IdentityUser, IdentityRole. I just want to use my own DbContext implementation and work happily with UserManager, UserStore, RoleManager, SignInManager, and what other classes involved with signing in.

So that been said, having created a the default ASP.NET Core project that uses "Individual User Accounts".  Now I want to figure out what DI wire up is required for that controller to "work".

Looking at the account controller constructor:

public AccountController(UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        IOptions<IdentityCookieOptions> identityCookieOptions,
        IEmailSender emailSender,
        ISmsSender smsSender,
        ILoggerFactory loggerFactory)

Along with that, the following related classes are generated:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    ...
}

And some related DI configuration:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...
    app.UseIdentity();
}

Digging around in the source code for ASP.NET Core Identity, UserStore forces the constraint on IdentityUser.

public class UserStore : UserStore<IdentityUser<string>>

For what I want to work is with something like the following - for starters:

public class AuthenticationDbContext : DbContext
{
    public AuthenticationDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<ApplicationRole> ApplicationRoles { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>(te =>
          te.HasKey(user => user.Id));

        builder.Entity<ApplicationRole>(te =>
          te.HasKey(role => role.Id));
     }
}

public class ApplicationRole
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

public class ApplicationUser
{
    public int Id { get; set; }
    public Guid Guid { get; set; }
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public string MiddleName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
}

If I listed the issues I have had, exceptions et al, this post would be too long.

The question is, how do I wire this up with DI configuration?

Body:
OK.  Following on from keeping my AuthenticationDbContext the same, I can provide an implementation of IUserStore, IRoleStore and configure the DI as follows.

public class ApplicationUserStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>
{
    private readonly AuthenticationDbContext _dbContext;

    public ApplicationUserStore(AuthenticationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    ...

OK, so I need to provide implementations of 10 or 11 methods here which needs a little figuring out.  The same for ApplicationRoleStore.

public class ApplicationRoleStore : IRoleStore<ApplicationRole>
{
    private AuthenticationDbContext _dbContext;

    public ApplicationRoleStore(AuthenticationDbContext context, IdentityErrorDescriber describer = null)
    {
        _dbContext = context;
    }

    ...

Then this can be wired up with:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddUserStore<ApplicationUserStore>()
        .AddRoleStore<ApplicationRoleStore>()
        .AddDefaultTokenProviders();

     services.AddTransient(c =>
            new AuthenticationDbContext(
                new DbContextOptionsBuilder()
                    .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).Options));

So signing in via Account Controller/Login view now invokes my ApplicationUserStore.FindByNameAsync when I click on Login.

Whether this is or isn't the "proper" remains to be seen.  I just feel strongly that the ASP.NET Identity should work with "any" data store implementation, therefore you shouldn't have to be constrained to using IdentityUser.  The above should work for non-Entity Framework implementations I feel.


问:
Can Python with turtle and tkinter replace NetLogo? Which is worth more the time?
I never went too far into NetLogo, and being a novice in Python I started looking into the turtle module, aiming towards ABM. I have seen some simple implementations of the turtle module (turtledemo and YouTube) but none were comparable to NetLogo library's examples. I went over (once) the mesa tutorials and it seemed interesting but, as it says, more advanced stuff require Javascript. I've also read that NetLogo is fast to pick up.

Considering the above, and adding your own experience, could NetLogo be a better choice than Python? Could you estimate how hard each path would be? Do you have any other suggestions?

答:
I teach ABM. I used to use Python for my course,
using a module that provides some NetLogo-like functionality:

https://raw.githubusercontent.com/alan-isaac/econpy/master/abm/gridworld/gridworld.py

I gave that up.  Although Python is a great language for
teaching programming, NetLogo is a much better language for
teaching ABM.  (Both started out as teaching languages,
very roughly speaking, and became much more.)  It is very
easy to get started with NetLogo.  It's builtin facilities
also support very sophisticated model building.  These facilities
can be extended when needed.