问:
Symbol addresses during load-time linking vs run-time linking in Linux
I am trying to understand the difference in the mechanisms underlying load-time linking (using gcc -l) versus run-time linking (using dlopen(), dlsym()) of dynamic libraries in Linux, and how these mechanisms affect the state of the library and the addresses of its symbols.

The experiment

I have three simple files:

libhello.c:

```<code>int var;
int func() {
    return 7;
}
</code>```

libhello.h:

```<code>extern int var;
int func();
</code>```

main.c:

```<code>#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include "libhello.h"

int main() {
    void* h = dlopen("libhello.so", RTLD_NOW);
    printf("Address  Load-time linking    Run-time linking\n");
    printf("-------  -----------------    ----------------\n");
    printf("&var     0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&var , (uintptr_t)dlsym(h, "var" ));
    printf("&func    0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&func, (uintptr_t)dlsym(h, "func"));
}
</code>```

I compile libhello.c with the command gcc -shared -o libhello.so -fPIC libhello.c

I compile main.c with the command gcc main.c -L. -lhello -ldl

The observation

Running the main.c executable prints something like this:

```<code>Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x0000000000601060   0x00007fdb4acb1034
&func    0x0000000000400700   0x00007fdb4aab0695
</code>```

The load-time linking addresses remain the same, but the run-time linking addresses change every run.

The questions

Why do the run-time addresses change every run? Do they change due to Address space layout randomization?

If this is the case, why don't addresses change for load-time linking? Isn't load-time linking vulnerable to the same attacks that address randomization aims to protect against?

In the above program, the same library is loaded twice - once at load-time and then at run-time using dlopen(). The second load does not copy the state of the first load. I.e. if the value of var is changed before dlopen(), this value isn't reflected in the version of var loaded via dlsym(). Is there any way to retain this state during the second load?

答:
In my opinion, I would say that:

When you compile the library directly with the executable (static linking) think as if the functions would be directly injected into the source code. If you examine the executable file, you'll see that each section (code, data, ...) will have a fixed "virtual memory" address. If I remember well, each Linux executable will start at the default address of 0x100000, so you'll see that each static linked function will have a fixed address of (0x100000 + fixed offset) and that will never change. Each time the executable is loaded, each specific function will be loaded at that precise address in "virtual memory", meaning that the OS will decide which physical address is used but you won't see that. In your example, the var variable will always have the virtual address of 0x0000000000601060 but you'll never know where in physical memory it will reside.

When you load at runtime a dynamic library, the OS has already loaded the executable into memory so you won't have a virtual fixed address. Instead the OS reserves in the executable address space a range of virtual addresses starting at 0x00007fxxxxxxxxxx where it will load and map the newly loaded symbols and functions. Depending of what has already been loaded and memory randomization algorithms, those addresses can be different in each run.

Given this brief explanation, it's simple to assume that the two values you're comparing in your point 3) are completely different variables (each one loaded at a different memory location) so they have different values and don't interact.

Body:
I am trying to understand the difference in the mechanisms underlying load-time linking (using gcc -l) versus run-time linking (using dlopen(), dlsym()) of dynamic libraries in Linux, and how these mechanisms affect the state of the library and the addresses of its symbols.

The experiment

I have three simple files:

libhello.c:

int var;
int func() {
    return 7;
}

libhello.h:

extern int var;
int func();

main.c:

#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include "libhello.h"

int main() {
    void* h = dlopen("libhello.so", RTLD_NOW);
    printf("Address  Load-time linking    Run-time linking\n");
    printf("-------  -----------------    ----------------\n");
    printf("&var     0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&var , (uintptr_t)dlsym(h, "var" ));
    printf("&func    0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&func, (uintptr_t)dlsym(h, "func"));
}

I compile libhello.c with the command gcc -shared -o libhello.so -fPIC libhello.c

I compile main.c with the command gcc main.c -L. -lhello -ldl

The observation

Running the main.c executable prints something like this:

Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x0000000000601060   0x00007fdb4acb1034
&func    0x0000000000400700   0x00007fdb4aab0695

The load-time linking addresses remain the same, but the run-time linking addresses change every run.

The questions

Why do the run-time addresses change every run? Do they change due to Address space layout randomization?

If this is the case, why don't addresses change for load-time linking? Isn't load-time linking vulnerable to the same attacks that address randomization aims to protect against?

In the above program, the same library is loaded twice - once at load-time and then at run-time using dlopen(). The second load does not copy the state of the first load. I.e. if the value of var is changed before dlopen(), this value isn't reflected in the version of var loaded via dlsym(). Is there any way to retain this state during the second load?


来源: stackexchange

问:
Android Create Corner swipe Menu Like Omni Swipe
I want to create Corner swipe menu like Omni Swipe

or Android Pie Control (http://www.apkthing.com/tools/10052-pie-control.html)

I tried the sample here but not suitable for my requirement: https://github.com/sephiroth74/OverlayMenu

答:
You can achieve this using CircularFloatingActionMenu :

Link : https://github.com/oguzbilgener/CircularFloatingActionMenu

Further you can add android BoomMenu to it :

Link :
https://github.com/Nightonke/BoomMenu

ContentLicense: CC BY-SA 3.0


问:
Data gets garbled when writing to csv with fputcsv() / fgetcsv()
There seems to be an encoding issue or bug in PHP with fputcsv() and fgetcsv().

The following PHP code:

```<code>$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before);

rewind($fh);

$row_after = fgetcsv($fh);

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);
</code>```

Gives me this output:

```<code>BEFORE:
array (
  0 => 'A',
  1 => '["a","\\\\","b"]',
  2 => 'B',
)

AFTER:
array (
  0 => 'A',
  1 => '["a","\\\\',
  2 => 'b""]"',
  3 => 'B',
)
</code>```

So clearly, the data is damaged on the way. Originally there were just 3 cells in the row, afterwards there are 4 cells in the row. The middle cell is split thanks to the backslash that is also used as an escape character.

See also
https://3v4l.org/nc1oE
Or here, with explicit values for delimiter, enclosure, escape_char: https://3v4l.org/Svt7m

Is there any way I can sanitize / escape my data before writing to CSV, to guarantee that the data read from the file will be exactly the same?

Is CSV a fully reversible format?

EDIT: The goal would be a mechanism to properly write and read ANY data as csv, so that after one round trip the data is still the same.

EDIT: I realize that I do not really understand the $escape_char parameter. See also fgetcsv/fputcsv $escape parameter fundamentally broken Maybe an answer to this would also bring us closer to a solution.

答:
As in php, \\ used to escape the backslash(link for PHP manual escape sequence),so for making it as string u need to use one more single quote('  ').

so your input array should be...

```<code>$row_before = ['A', json_encode(['a', "'\\'", 'b']), 'B'];
</code>```

Body:
There seems to be an encoding issue or bug in PHP with fputcsv() and fgetcsv().

The following PHP code:

$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before);

rewind($fh);

$row_after = fgetcsv($fh);

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);

Gives me this output:

BEFORE:
array (
  0 => 'A',
  1 => '["a","\\\\","b"]',
  2 => 'B',
)

AFTER:
array (
  0 => 'A',
  1 => '["a","\\\\',
  2 => 'b""]"',
  3 => 'B',
)

So clearly, the data is damaged on the way. Originally there were just 3 cells in the row, afterwards there are 4 cells in the row. The middle cell is split thanks to the backslash that is also used as an escape character.

See also
https://3v4l.org/nc1oE
Or here, with explicit values for delimiter, enclosure, escape_char: https://3v4l.org/Svt7m

Is there any way I can sanitize / escape my data before writing to CSV, to guarantee that the data read from the file will be exactly the same?

Is CSV a fully reversible format?

EDIT: The goal would be a mechanism to properly write and read ANY data as csv, so that after one round trip the data is still the same.

EDIT: I realize that I do not really understand the $escape_char parameter. See also fgetcsv/fputcsv $escape parameter fundamentally broken Maybe an answer to this would also bring us closer to a solution.

Body:
As in php, \\ used to escape the backslash(link for PHP manual escape sequence),so for making it as string u need to use one more single quote('  ').

so your input array should be...

$row_before = ['A', json_encode(['a', "'\\'", 'b']), 'B'];


问:
How do I convert a JSON string to a function in javascript?
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

```<code>json = { "one": 700, "two": "function(e){alert(e);}" }
</code>```

Then in my code:

```<code>parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})
</code>```

答:
Example: http://jsfiddle.net/patrick_dw/vs83H/

```<code>var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
var parameters = JSON.parse( json );
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"
</code>```

You'll need to load the JSON library in browsers that don't support it.

Or do two separate evals:

Example: http://jsfiddle.net/patrick_dw/vs83H/1/

```<code>var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
eval( 'var parameters = ' + json );
eval( 'var func = ' + parameters.two );
func( 'test' );
</code>```

I assume you're aware of the dangers of eval.

ContentLicense: CC BY-SA 2.5

Body:
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

json = { "one": 700, "two": "function(e){alert(e);}" }

Then in my code:

parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})

Body:
Example: http://jsfiddle.net/patrick_dw/vs83H/

var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
var parameters = JSON.parse( json );
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"

You'll need to load the JSON library in browsers that don't support it.

Or do two separate evals:

Example: http://jsfiddle.net/patrick_dw/vs83H/1/

var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
eval( 'var parameters = ' + json );
eval( 'var func = ' + parameters.two );
func( 'test' );

I assume you're aware of the dangers of eval.


问:
How to find delimiter from string in Console Application
```<code>Console.WriteLine("Enter a string");
string str = Console.ReadLine();
</code>```

Note: User can enter any delimiter like , @ # $ % * &  ; : etc.

Example: For input: 1*2*5*9 the delimiter is *

答:
You can try guessing with a help of regular expressions; let's split the input not by unknown delimiter(s), but by main text items (integers?) and we'll get the delimiters as the result:

```<code>  string source = @"1*2*5*9";

  // Main text pattent; user is supposed to input integers numbers and delimiters
  string bodyPattern =
    @"-?[0-9]+";

  var delimiters = Regex
    .Split(source, bodyPattern)
    .Select(item => item.Trim())
    .Where(item => !string.IsNullOrEmpty(item))
    .Distinct()
    .ToArray();

 Console.Write(string.Join(Environment.NewLine, delimiters));
</code>```

Outcome:

```<code> *
</code>```

Please, notice that in case of "1*2#5%9" input you'll get ["*", "#", "%"] delimiters.

Edit: Do you really want delimiter(s)? The much more natural problem is to extract main text items. If it's your case, you can solve it with regular expressions as well:

```<code> // ["1", "2", "5", "9"]
 var items = Regex
   .Matches(source, bodyPattern)
   .OfType<Match>()
   .Select(match => match.Value)
   .ToString();
</code>```

Body:
Console.WriteLine("Enter a string");
string str = Console.ReadLine();

Note: User can enter any delimiter like , @ # $ % * &  ; : etc.

Example: For input: 1*2*5*9 the delimiter is *

Body:
You can try guessing with a help of regular expressions; let's split the input not by unknown delimiter(s), but by main text items (integers?) and we'll get the delimiters as the result:

  string source = @"1*2*5*9";

  // Main text pattent; user is supposed to input integers numbers and delimiters
  string bodyPattern =
    @"-?[0-9]+";

  var delimiters = Regex
    .Split(source, bodyPattern)
    .Select(item => item.Trim())
    .Where(item => !string.IsNullOrEmpty(item))
    .Distinct()
    .ToArray();

 Console.Write(string.Join(Environment.NewLine, delimiters));

Outcome:

 *

Please, notice that in case of "1*2#5%9" input you'll get ["*", "#", "%"] delimiters.

Edit: Do you really want delimiter(s)? The much more natural problem is to extract main text items. If it's your case, you can solve it with regular expressions as well:

 // ["1", "2", "5", "9"]
 var items = Regex
   .Matches(source, bodyPattern)
   .OfType<Match>()
   .Select(match => match.Value)
   .ToString();


问:
How do you set the icon of a Dialog control Java FX/Java 8
I might be missing something very obvious, but I can't find out how to set the Icon for a Dialog component (ProgressDialog to be more precise). I know how to do that for a Stage:

```<code>this.primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon/Logo.png")));
</code>```

But I don't find anything for the Dialog family. And somehow, setting the Stage Icon does not influence the Dialog Icon.

Thanks

答:
Just Do like this:

```<code>Alert(AlertType.ERROR, "Erreur de connexion! Verifiez vos Identifiants",FINISH); //Cancel..
setTitle("XNotes FX Erreur");
stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("indiza/XnotesErrorIdz.png")); // To add an icon
showAndWait();
</code>```

Here is the result

**My friends, is it computer science that we do? : No, we do crafts
**

ContentLicense: CC BY-SA 4.0

Body:
I might be missing something very obvious, but I can't find out how to set the Icon for a Dialog component (ProgressDialog to be more precise). I know how to do that for a Stage:

this.primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon/Logo.png")));

But I don't find anything for the Dialog family. And somehow, setting the Stage Icon does not influence the Dialog Icon.

Thanks

Body:
Just Do like this:

Alert(AlertType.ERROR, "Erreur de connexion! Verifiez vos Identifiants",FINISH); //Cancel..
setTitle("XNotes FX Erreur");
stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("indiza/XnotesErrorIdz.png")); // To add an icon
showAndWait();

Here is the result

**My friends, is it computer science that we do? : No, we do crafts
**


问:
log4j properties DailyRollingFileAppender does not work
I want daily logs with the log file appended with the date in yyyy-dd-mm format. When I use DailyRollingFileAppender, a new log file is not created. The logs are written to the same log file. Also, the date Pattern provided is not considered. The log file created is LoggerFile.log. And every content(even on the next day) is written to this file.

I am using the log4j-1.2.17 jar. I am developing in Netbeans 7.3.1 in Java.

Is there anyone using this JAR and facing such a problem. Please help!

Here is the content of the properties file I use:

```<code># Root logger option
log4j.rootLogger=ERROR,FILE,stdout

# Define the file appender
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender

log4j.appender.FILE.File=.//..//logs//LoggerFile.log

# Define the layout for file appender
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz} %5p     %c{1}:%L - %m%n

log4j.appender.FILE.MaxFileSize=10MB

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L -  %m%n`
</code>```

答:
I had similar requirements of daily log file rotation.. (Though the question is older, thought the answer would help others)..

Key points:

First of all, we can avoid using DailyRollingFileAppender. Why? DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender. Reference: Documentation of Daily Rolling File Appender

Apache extras log4j, Would suggest to use org.apache.log4j.rolling.RollingFileAppender with the Time based rolling policy

May find a sample configuration for time based rotation of log.

Hope this helps.

Body:
I want daily logs with the log file appended with the date in yyyy-dd-mm format. When I use DailyRollingFileAppender, a new log file is not created. The logs are written to the same log file. Also, the date Pattern provided is not considered. The log file created is LoggerFile.log. And every content(even on the next day) is written to this file.

I am using the log4j-1.2.17 jar. I am developing in Netbeans 7.3.1 in Java.

Is there anyone using this JAR and facing such a problem. Please help!

Here is the content of the properties file I use:

# Root logger option
log4j.rootLogger=ERROR,FILE,stdout

# Define the file appender
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender

log4j.appender.FILE.File=.//..//logs//LoggerFile.log

# Define the layout for file appender
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz} %5p     %c{1}:%L - %m%n

log4j.appender.FILE.MaxFileSize=10MB

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L -  %m%n`


答:
The following should help</p>

```<code>char[] delimiter  = {'@','#','&', '*'};
foreach (char c in str)
{
    if(delimiter.Contains(c)
        //You found your char
}
</code>```

Title: How to find delimiter from string in Console Application

Body:
The following should help

char[] delimiter  = {'@','#','&', '*'};
foreach (char c in str)
{
    if(delimiter.Contains(c)
        //You found your char
}


问:
android SQLite register won't save data
I'm trying to make simple android SQLite register but when i try to save data the app crash

Database code:

```<code>public class RegistrationDB extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "registration.db";
    private static final String TABLE_NAME = "profile";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_EMAIL = "email";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";

    private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT, " + ")";

    private String DROP_TAPLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public RegistrationDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL(DROP_TAPLE);
        onCreate(sqLiteDatabase);

    }

    public long addUser(String email, String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COLUMN_EMAIL, email); // Email
        values.put(COLUMN_USERNAME, username); // username
        values.put(COLUMN_PASSWORD, password); // password

        // Inserting Row
//        long id = db.insert(TABLE_NAME, null, values);
        db.insert(TABLE_NAME, null, values);
        db.close(); // Closing database connection
        return 0;
    }

}
</code>```

I'm sorry but I get error when I try to type code here that's why I use image

答:
Change

```<code>private static final String COLUMN_ID = "id";
</code>```

To

```<code>private static final String COLUMN_ID = "_id";
</code>```

And also change..

```<code>private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT, " + ")";
</code>```

To

```<code>private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT)";
</code>```

When this is done, clear app data, or uninstall and reinstall and then run again.

Title: android SQLite register won't save data

Body:
I'm trying to make simple android SQLite register but when i try to save data the app crash

Database code:

public class RegistrationDB extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "registration.db";
    private static final String TABLE_NAME = "profile";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_EMAIL = "email";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";

    private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT, " + ")";

    private String DROP_TAPLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public RegistrationDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL(DROP_TAPLE);
        onCreate(sqLiteDatabase);

    }

    public long addUser(String email, String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COLUMN_EMAIL, email); // Email
        values.put(COLUMN_USERNAME, username); // username
        values.put(COLUMN_PASSWORD, password); // password

        // Inserting Row
//        long id = db.insert(TABLE_NAME, null, values);
        db.insert(TABLE_NAME, null, values);
        db.close(); // Closing database connection
        return 0;
    }

}

I'm sorry but I get error when I try to type code here that's why I use image

Body:
Change

private static final String COLUMN_ID = "id";

To

private static final String COLUMN_ID = "_id";

And also change..

private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT, " + ")";

To

private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT)";

When this is done, clear app data, or uninstall and reinstall and then run again.


问:
Access Env variables within php
How to access environment variables located in  ~/.bash_profile from within PHP running with apache localhost (Mac)? I tried getenv() but no luck. Is there anything I need to change with php.ini?</p>

答: Use $_SERVER Variables and $_ENV to get all you need. Do an print_r of each of them to see what they contain. </p>

Title: Access Env variables within php


问:
WPF/XAML compiles but errors show in XAML
With a colleague, we try to make a POC of a WPF application. We created a new project with a page and a resx file to test internationalization (we are French). The application work well, no error on the compile and the resx file give good data.
but in the XAML file, we have a lot of errors.

Here is the XAML header:

```<code><Window x:Class="MAPPrintProcessEditor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:res="clr-namespace:MAPPrintProcessEditor.Properties"
        mc:Ignorable="d"
        Title="MAP Print Process Editor"
        WindowStartupLocation="CenterScreen"
        Height="{Binding SystemParameters.PrimaryScreenHeight}" Width="{Binding SystemParameters.PrimaryScreenWidth}">
</code>```

Here, is a line marked in error:

```<code><MenuItem Header="{x:Static res:Resources.MenuItemHeaderClose}">
    <MenuItem.Icon>
        <Image Source="pack://application:,,,/Resources/Close-16.png"/>
    </MenuItem.Icon>
</MenuItem>
</code>```

Visual Studio underline only this part:

```<code>Header="{x:Static
</code>```

And finally, here is the error message:

The name "Resources" does not exist in the namespace "clr-namespace:PrintProcessEditor.Properties"

What is wrong in this code?

We use VS2017 and .Net 4.6.1.

答: If the you can build correctly than just ignore that message and use BLEND to design your app.</p>

Body:
With a colleague, we try to make a POC of a WPF application. We created a new project with a page and a resx file to test internationalization (we are French). The application work well, no error on the compile and the resx file give good data.
but in the XAML file, we have a lot of errors.

Here is the XAML header:

<Window x:Class="MAPPrintProcessEditor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:res="clr-namespace:MAPPrintProcessEditor.Properties"
        mc:Ignorable="d"
        Title="MAP Print Process Editor"
        WindowStartupLocation="CenterScreen"
        Height="{Binding SystemParameters.PrimaryScreenHeight}" Width="{Binding SystemParameters.PrimaryScreenWidth}">

Here, is a line marked in error:

<MenuItem Header="{x:Static res:Resources.MenuItemHeaderClose}">
    <MenuItem.Icon>
        <Image Source="pack://application:,,,/Resources/Close-16.png"/>
    </MenuItem.Icon>
</MenuItem>

Visual Studio underline only this part:

Header="{x:Static

And finally, here is the error message:

The name "Resources" does not exist in the namespace "clr-namespace:PrintProcessEditor.Properties"

What is wrong in this code?

We use VS2017 and .Net 4.6.1.


问:
Need advice before I develop a bad habit
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

```<code>//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}
</code>```

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

```<code>@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            IDSubcategory
        </th>
        <th>
            IDCity
        </th>
        <th>
            IDPerson
        </th>
        <th>
            Title
        </th>
        <th>
            TextBody
        </th>
        <th>
            ContactNumber
        </th>
        <th>
            AskingPrice
        </th>
        <th>
            AddressDirection
        </th>
        <th>
            LatestUpdateDate
        </th>
        <th>
            VisitCount
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
        <td>
            @item.IDSubcategory
        </td>
        <td>
            @item.IDCity
        </td>
        <td>
            @item.IDPerson
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @item.TextBody
        </td>
        <td>
            @item.ContactNumber
        </td>
        <td>
            @String.Format("{0:F}", item.AskingPrice)
        </td>
        <td>
            @item.AddressDirection
        </td>
        <td>
            @String.Format("{0:g}", item.LatestUpdateDate)
        </td>
        <td>
            @item.VisitCount
        </td>
    </tr>
}

</table>
</code>```

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

答:
You have to do branching somewhere, so it's probably more of a preference question.

The way I would handle it is to have a single method, and have it take in the category name as the parameter.  Since strings are nullable, if one is not specified it will be null.  My one action method would probably look something like:

```<code>public ActionResult Index(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();

    if(String.IsNullOrEmpty(categoryName) == false)
      auctions = auctions.Where(c => c.Subcategory.Category.Name == categoryName);

    return View(auctions);
}
</code>```

OwnerDisplayName: delete

LastEditorDisplayName: delete

Body:
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            IDSubcategory

            IDCity

            IDPerson

            Title

            TextBody

            ContactNumber

            AskingPrice

            AddressDirection

            LatestUpdateDate

            VisitCount

@foreach (var item in Model) {

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

            @item.IDSubcategory

            @item.IDCity

            @item.IDPerson

            @item.Title

            @item.TextBody

            @item.ContactNumber

            @String.Format("{0:F}", item.AskingPrice)

            @item.AddressDirection

            @String.Format("{0:g}", item.LatestUpdateDate)

            @item.VisitCount

}

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

Body:
You have to do branching somewhere, so it's probably more of a preference question.

The way I would handle it is to have a single method, and have it take in the category name as the parameter.  Since strings are nullable, if one is not specified it will be null.  My one action method would probably look something like:

public ActionResult Index(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();

    if(String.IsNullOrEmpty(categoryName) == false)
      auctions = auctions.Where(c => c.Subcategory.Category.Name == categoryName);

    return View(auctions);
}


问:
jQuery UI dialog positioning
I am trying to use the jQuery dialog UI library in order to position a dialog next to some text when it is hovered over.  The jQuery dialog takes a position parameter which is measured from the top left corner of the current viewport (in other words, [0, 0] will always put it in the upper left hand corner of your browser window, regardless of where you are currently scrolled to).  However, the only way I know to retrieve the location is of the element relative to the ENTIRE page.

The following is what I have currently.  position.top is calculated to be something like 1200 or so, which puts the dialog well below the rest of the content on the page.

```<code>$(".mytext").mouseover(function() {
    position = $(this).position();
    $("#dialog").dialog('option', 'position', [position.top, position.left]);
}
</code>```

How can I find the correct position?

Thanks!

答:
You ca set top position in style for display on center,  saw that the code:

.ui-dialog{top: 100px !important;}

This style should show dialog box 100px bellow from top.

Title: jQuery UI dialog positioning

Body:
I am trying to use the jQuery dialog UI library in order to position a dialog next to some text when it is hovered over.  The jQuery dialog takes a position parameter which is measured from the top left corner of the current viewport (in other words, [0, 0] will always put it in the upper left hand corner of your browser window, regardless of where you are currently scrolled to).  However, the only way I know to retrieve the location is of the element relative to the ENTIRE page.

The following is what I have currently.  position.top is calculated to be something like 1200 or so, which puts the dialog well below the rest of the content on the page.

$(".mytext").mouseover(function() {
    position = $(this).position();
    $("#dialog").dialog('option', 'position', [position.top, position.left]);
}

How can I find the correct position?

Thanks!


问:
Make hive returns the value only
I want to make hive only returns the value only! not other words like information about the processing!

```<code>hive> select max(temp) from temp where dtime like '2014-07%' ;
Query ID = hduser_20170608003255_d35b8a43-8cc5-4662-89ce-9ee5f87d3ba0
Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks determined at compile time: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapreduce.job.reduces=<number>
Starting Job = job_1496864651740_0008, Tracking URL = http://localhost:8088/proxy/application_1496864651740_0008/
Kill Command = /home/hduser/hadoop/bin/hadoop job  -kill job_1496864651740_0008
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 1
2017-06-08 00:33:01,955 Stage-1 map = 0%,  reduce = 0%
2017-06-08 00:33:08,187 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 4.13 sec
2017-06-08 00:33:14,414 Stage-1 map = 100%,  reduce = 100%, Cumulative CPU 5.91 sec
MapReduce Total cumulative CPU time: 5 seconds 910 msec
Ended Job = job_1496864651740_0008
MapReduce Jobs Launched:
Stage-Stage-1: Map: 1  Reduce: 1   Cumulative CPU: 5.91 sec   HDFS Read: 853158 HDFS Write: 5 SUCCESS
Total MapReduce CPU Time Spent: 5 seconds 910 msec
OK
44.4
Time taken: 20.01 seconds, Fetched: 1 row(s)
</code>```

I want it to return  the value only which is  44.4

Thanks in advance...

答:
You can put result into variable in a shell script. max_temp variable will contain the result only:</p>

```<code>max_temp=$(hive -e " set hive.cli.print.header=false; select max(temp) from temp where dtime like '2014-07%';")

echo "$max_temp"
</code>```

Title: Make hive returns the value only

Body:
I want to make hive only returns the value only! not other words like information about the processing!

hive> select max(temp) from temp where dtime like '2014-07%' ;
Query ID = hduser_20170608003255_d35b8a43-8cc5-4662-89ce-9ee5f87d3ba0
Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks determined at compile time: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapreduce.job.reduces=<number>
Starting Job = job_1496864651740_0008, Tracking URL = http://localhost:8088/proxy/application_1496864651740_0008/
Kill Command = /home/hduser/hadoop/bin/hadoop job  -kill job_1496864651740_0008
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 1
2017-06-08 00:33:01,955 Stage-1 map = 0%,  reduce = 0%
2017-06-08 00:33:08,187 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 4.13 sec
2017-06-08 00:33:14,414 Stage-1 map = 100%,  reduce = 100%, Cumulative CPU 5.91 sec
MapReduce Total cumulative CPU time: 5 seconds 910 msec
Ended Job = job_1496864651740_0008
MapReduce Jobs Launched:
Stage-Stage-1: Map: 1  Reduce: 1   Cumulative CPU: 5.91 sec   HDFS Read: 853158 HDFS Write: 5 SUCCESS
Total MapReduce CPU Time Spent: 5 seconds 910 msec
OK
44.4
Time taken: 20.01 seconds, Fetched: 1 row(s)

I want it to return  the value only which is  44.4

Thanks in advance...

Body:
You can put result into variable in a shell script. max_temp variable will contain the result only:

max_temp=$(hive -e " set hive.cli.print.header=false; select max(temp) from temp where dtime like '2014-07%';")

echo "$max_temp"


问:
WPF: Get an item's position index within CollectionViewSource and not on the bound source
I've got a view model that exposes a CollectionViewSource built around my observable collection. I also have a command for deleting items:

```<code>public ObservableCollection<FooViewModel> Foos { get; set; }
public ICollectionView FooCollectionView { get; set; }
public ICommand DeleteFooCommand { get; set; }

private FooViewModel _SelectedFoo;
public FooViewModel SelectedFoo
{
    get { return _SelectedFoo; }
    set
    {
        if (value != _SelectedFoo)
        {
            _SelectedFoo = value;
            OnPropertyChanged();
        }
    }
}

public MyViewModel()
{
    Foos = new ObservableCollection<FooViewModel>();
    FooCollectionView = CollectionViewSource.GetDefaultView(Patches);
    FooCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
    DeleteFooCommand = new RelayCommand(DeleteFoo);
}

private void DeleteFoo(object parameter)
{
    var collection = parameter as IEnumerable;
    if (collection == null) return;

    var itemsToDelete = collection.OfType<FooViewModel>().ToList();
    if (!itemsToDelete.Any()) return;

    SelectedFoo = null;

    // TODO: Figure out what the next SelectedFoo should be after deleting)

    foreach (var item in itemsToDelete)
        Foos.Remove(item);
}
</code>```

In the spirit of MVVM, I don't want to know whether or not my CollectionViewSource was bound to a ListBox, ListView, etc. I simply expect one or more FooViewModels in my command parameter (via [control].SelectedItems). However, I want to set the new SelectedFoo to what I think would be the next logical item that should be selected. I know there is IndexOf() of my source collection, but that index won't match the index after the sort of my CollectionViewSource. Is there a way to get the index of the item on the view and not the source? I can do what I want if I pass the bound ListBox as my command parameter, but I'd rather not know about the bound control.

答:
Try this code:</p>

```<code>public static int IndexOf<TItem>(this ICollectionView collectionView, TItem item)
{
    int result = 0;

    foreach (var i in collectionView.OfType<TItem>())
    {
        if (i == item)
            return result;

        result++;
    }

    return -1;
}
</code>```

Body:
I've got a view model that exposes a CollectionViewSource built around my observable collection. I also have a command for deleting items:

public ObservableCollection<FooViewModel> Foos { get; set; }
public ICollectionView FooCollectionView { get; set; }
public ICommand DeleteFooCommand { get; set; }

private FooViewModel _SelectedFoo;
public FooViewModel SelectedFoo
{
    get { return _SelectedFoo; }
    set
    {
        if (value != _SelectedFoo)
        {
            _SelectedFoo = value;
            OnPropertyChanged();
        }
    }
}

public MyViewModel()
{
    Foos = new ObservableCollection<FooViewModel>();
    FooCollectionView = CollectionViewSource.GetDefaultView(Patches);
    FooCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
    DeleteFooCommand = new RelayCommand(DeleteFoo);
}

private void DeleteFoo(object parameter)
{
    var collection = parameter as IEnumerable;
    if (collection == null) return;

    var itemsToDelete = collection.OfType<FooViewModel>().ToList();
    if (!itemsToDelete.Any()) return;

    SelectedFoo = null;

    // TODO: Figure out what the next SelectedFoo should be after deleting)

    foreach (var item in itemsToDelete)
        Foos.Remove(item);
}

In the spirit of MVVM, I don't want to know whether or not my CollectionViewSource was bound to a ListBox, ListView, etc. I simply expect one or more FooViewModels in my command parameter (via [control].SelectedItems). However, I want to set the new SelectedFoo to what I think would be the next logical item that should be selected. I know there is IndexOf() of my source collection, but that index won't match the index after the sort of my CollectionViewSource. Is there a way to get the index of the item on the view and not the source? I can do what I want if I pass the bound ListBox as my command parameter, but I'd rather not know about the bound control.

Body:
Try this code:

public static int IndexOf<TItem>(this ICollectionView collectionView, TItem item)
{
    int result = 0;

    foreach (var i in collectionView.OfType<TItem>())
    {
        if (i == item)
            return result;

        result++;
    }

    return -1;
}


问:
how to show the UI Slider value in two different fields?
i am tying to show the UI range slider value in input box. i have done this but i want show the same value on another  also, that span is in another .

here i am getting the slider value on this input box but the same value must reflect on another div's  also.

How do i do it , help me out of this

$("#slider").slider({
    range: "min",
    value: 1,
    step: 10,
    min: 210,
    max: 850,
    slide: function (event, ui) {
        $(".inputCount").val(ui.value);
        $(".borrowMonth").val(ui.value);
    }
});
$(".inputCount").change(function () {
    $("#slider").slider("value",this.value);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="slider"></div>
<label>£</label>
<input type="text" value="200" class="inputCount"/>

<div class="borrowMonth">£ <span>200</span> </div></code>```

答:
You using the wrang method - "val" for the element. And you need chnage the selector. This is working variant:

```<code>$(".borrowMonth span").text(ui.value);
</code>```

Full example here: http://jsfiddle.net/s1hfkgr2/

Body:
i am tying to show the UI range slider value in input box. i have done this but i want show the same value on another  also, that span is in another .

here i am getting the slider value on this input box but the same value must reflect on another div's  also.

How do i do it , help me out of this

$("#slider").slider({
    range: "min",
    value: 1,
    step: 10,
    min: 210,
    max: 850,
    slide: function (event, ui) {
        $(".inputCount").val(ui.value);
        $(".borrowMonth").val(ui.value);
    }
});
$(".inputCount").change(function () {
    $("#slider").slider("value",this.value);
});

£
<input type="text" value="200" class="inputCount"/>

£ 200

Body:
You using the wrang method - "val" for the element. And you need chnage the selector. This is working variant:

$(".borrowMonth span").text(ui.value);

Full example here: http://jsfiddle.net/s1hfkgr2/


问:
Loop inside function definition gets executed
In one of my projects I'm using API to get data from other website but to get all of the data I would need to write 8 blocks of the same code just with two diffrent variables. So obviously I want to define function and use it.

Function takes two arguments, one is object and other one is id. Inside the function I loop through the object to get all of the data I need using object.length. Loop gets executed inside function definition and I get Uncaught TypeError: Cannot read property 'length' of undefined error in console.

Here's my code:

```<code>function listAll(objectProp, destination) {
    for (var i = 0; objectProp.length > i; i++ ) {
        var option = document.createElement("option");
        var value = document.createTextNode(objectProp.name);
        option.appendChild(value);
        document.getElementById(destination).appendChild(option);
    }
}
</code>```

I've been looking for solution but I couldn't find the same problem. Can anyone explain it to me why it's happening?

Thanks!

Update:
That's how code should look like.

```<code>function listAll(objectProp, destination) {
    if ( typeof(objectProp) != 'undefined' ) {
        for (var i = 0; objectProp.length > i; i++ ) {
            var option = document.createElement("option");
            var value = document.createTextNode(objectProp[i].name);
            option.appendChild(value);
            document.getElementById(destination).appendChild(option);
        }
    }
}
</code>```

Thanks for help!

答: You can't get the length of an Object in JavaScript using .length. You will need to either store the data in an array or use a solution such as this one: Length of a JavaScript object

Body:
In one of my projects I'm using API to get data from other website but to get all of the data I would need to write 8 blocks of the same code just with two diffrent variables. So obviously I want to define function and use it.

Function takes two arguments, one is object and other one is id. Inside the function I loop through the object to get all of the data I need using object.length. Loop gets executed inside function definition and I get Uncaught TypeError: Cannot read property 'length' of undefined error in console.

Here's my code:

function listAll(objectProp, destination) {
    for (var i = 0; objectProp.length > i; i++ ) {
        var option = document.createElement("option");
        var value = document.createTextNode(objectProp.name);
        option.appendChild(value);
        document.getElementById(destination).appendChild(option);
    }
}

I've been looking for solution but I couldn't find the same problem. Can anyone explain it to me why it's happening?

Thanks!

Update:
That's how code should look like.

function listAll(objectProp, destination) {
    if ( typeof(objectProp) != 'undefined' ) {
        for (var i = 0; objectProp.length > i; i++ ) {
            var option = document.createElement("option");
            var value = document.createTextNode(objectProp[i].name);
            option.appendChild(value);
            document.getElementById(destination).appendChild(option);
        }
    }
}

Thanks for help!


问:
Prevent universal links from opening in `WKWebView`/`UIWebView`
When user tap on a universal link in WKWebView, the corresponding app will be opened (if installed).

This is described in Apple Search Programming Guide

If you instantiate a SFSafariViewController, WKWebView, or UIWebView object to handle a universal link, iOS opens your website in Safari instead of opening your app. However, if the user taps a universal link from within an embedded SFSafariViewController, WKWebView, or UIWebView object, iOS opens your app.

In my app, I have a WKWebView, but I don't want the user to go out of my app. I want to handle the link within my WKWebView.

How do I prevent universal link from opening? Or can I know if a URL could be handle by other apps?

答:
+[LSAppLink openWithURL:completionHandler:]
this is how universal link open corresponding app.
you can exchange its implementations with yourself method
but be carefule,this is private API.

you can check LSAppLink head file here


问:
How can I make TypeScript avoid rewriting files if the content has not been changed between compilations?
There are a lot of utilities who rely on file timestamps and their cache gets cleared if they find out the file modified time has been changed.

Therefore, I want to skip rewriting files on TypeScript's emit phase, on basis of comparing files' contents. If the compiler is going to rewrite the same file with the same content, potentially it should be able to skip rewrite, why not?

Is there any parameter, CLI flag, bug on Github, pull request that addresses this problem?

答:
Currently, the best way is to use the tsc --watch feature.
You can create a script listening to the compile completion and then do whatever you want.

For example,

```<code>'use strict';

const cp = require('child_process');

cp.spawn('tsc', ['-w'], { shell: true })
  .stdout.on('data', data => {
    const text = data.toString()
    process.stdout.write(text)
    if (/.*Compilation complete/.test(text)) {
      cp.spawnSync('npm', ['run', 'lint'], {
        stdio: 'inherit',
        shell: true
      })
    }
  })
</code>```

@noomorph has created a grunt plugin: https://github.com/noomorph/grunt-ts-watch

Body:
Currently, the best way is to use the tsc --watch feature.
You can create a script listening to the compile completion and then do whatever you want.

For example,

'use strict';

const cp = require('child_process');

cp.spawn('tsc', ['-w'], { shell: true })
  .stdout.on('data', data => {
    const text = data.toString()
    process.stdout.write(text)
    if (/.*Compilation complete/.test(text)) {
      cp.spawnSync('npm', ['run', 'lint'], {
        stdio: 'inherit',
        shell: true
      })
    }
  })

@noomorph has created a grunt plugin: https://github.com/noomorph/grunt-ts-watch


问:
Autowired class from the jar file outside the classes
How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.

SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

code:

```<code>package com.path.controller;
import org.quartz.Scheduler;

@Controller
public class MyController{

   @Autowired
   Scheduler scheduler;
}
</code>```

This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,

<context:component-scan base-package="com.path" />

答:
As the exception complains "No qualifying bean of type [org.quartz.Scheduler]" , we will have to define the bean of type org.quartz.Scheduler, But that is not possible without any concrete implementation of the same, So , we will have to get a concrete implementation from the Factory class org.quartz.impl.StdSchedulerFactory and it's non static method getScheduler().

Hence, you will have to add following two lines in you context xml file and it will work , I have verified the same with the same version of spring which you are using :

```<code><bean id="schedulerFactory"   class="org.quartz.impl.StdSchedulerFactory" />

<bean id="scheduler" class="org.quartz.Scheduler"  factory-bean="schedulerFactory" factory-method="getScheduler" />
</code>```

A console output after printing the initialized bean gives this :

```<code>  scheduler=org.quartz.impl.StdScheduler@536aaa8d
</code>```

Body:
How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.

SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

code:

package com.path.controller;
import org.quartz.Scheduler;

@Controller
public class MyController{

   @Autowired
   Scheduler scheduler;
}

This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,

<context:component-scan base-package="com.path" />

Body:
As the exception complains "No qualifying bean of type [org.quartz.Scheduler]" , we will have to define the bean of type org.quartz.Scheduler, But that is not possible without any concrete implementation of the same, So , we will have to get a concrete implementation from the Factory class org.quartz.impl.StdSchedulerFactory and it's non static method getScheduler().

Hence, you will have to add following two lines in you context xml file and it will work , I have verified the same with the same version of spring which you are using :

<bean id="schedulerFactory"   class="org.quartz.impl.StdSchedulerFactory" />

<bean id="scheduler" class="org.quartz.Scheduler"  factory-bean="schedulerFactory" factory-method="getScheduler" />

A console output after printing the initialized bean gives this :

  scheduler=org.quartz.impl.StdScheduler@536aaa8d


问:
OWIN Authentication:async method lacks 'await' operators
I have implemented OWIN authentication in my project.But when I try to build the project, it is showing some errors.

The methods which are showing errors :

```<code> public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
    //code
   }
  public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
  //code
    }
</code>```

The showing error is

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

How can I fix this issue?

答:
async is not part of the signature. Just because you're overriding an async method doesn't mean that you have to mark your override as async.

So, if you don't have any awaits in your code, just remove the async mark.

```<code>public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//code
}
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//code
}
</code>```

Body:
I have implemented OWIN authentication in my project.But when I try to build the project, it is showing some errors.

The methods which are showing errors :

 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
    //code
   }
  public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
  //code
    }

The showing error is

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

How can I fix this issue?

Body:
async is not part of the signature. Just because you're overriding an async method doesn't mean that you have to mark your override as async.

So, if you don't have any awaits in your code, just remove the async mark.

public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//code
}
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//code
}


问:
Having multiple versions of Rails installed on OS X
OS X 10.6 has Rails 2.2.2 installed by default.

How to upgrade to Rails 2.3.8?

Since Rails 3 is out, is it possible to have multiple versions of Rails (like 2.3.8 and 3) installed on OS X?

(For example, I could be working on two Rails projects, one is Rails 2.x and the other is Rails 3.x).

答:
Use rvm

RVM is a command line tool which allows us to easily install, manage and work with multiple ruby environments from interpreters to sets of gems...

RVM allows users to deploy each project with its own completely self-contained and dedicated environment--from the specific version of ruby all the way down to the precise set of required gems to run the application. Having a precise set of gems also avoids the issue of version conflicts between projects, causing difficult-to-trace errors and hours of hair loss. With RVM, NO OTHER GEMS than those required are installed. This makes working with multiple complex applications where each has a long list of gem dependencies efficient. RVM allows us to easily test gem upgrades by switching to a new clean set of gems to test with while leaving our original set intact. It is flexible enough to even have a set of gems per environment or development branch--or even individual developer's taste...


问:
How to place progressbar on a layout element like a textview or an imageview in android
I am loading a list from server using Retrofit.
Can anyone help me how to load ProgressBar at each element of the CardViewin the RecyclerView?
 Below I am posting an image of what I want to do.

Edit:

```<code> <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/viewMargin"
            android:id="@+id/rvRecyclerViewCustom"
            >
  </android.support.v7.widget.RecyclerView>
</code>```

答:
You can try this way</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>
</code>```

Body:
I am loading a list from server using Retrofit.
Can anyone help me how to load ProgressBar at each element of the CardViewin the RecyclerView?
 Below I am posting an image of what I want to do.

Edit:

 <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/viewMargin"
            android:id="@+id/rvRecyclerViewCustom"
            >
  </android.support.v7.widget.RecyclerView>

Body:
You can try this way

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>


问:
How to get index of row when MouseHover in Radgridview
i want to get index of any row that my mouse is above and not necessarily from the selected row.

```<code> Private Sub RadGridView1_MouseHover(sender As Object, e As EventArgs) Handles RadGridView1.MouseHover
            Try
                toolidx = RadGridView1.CurrentCell.RowIndex
                strphone = dsOrders.Tables(0).Rows(toolidx)("DeliveryPhone")

            Catch ex As Exception
                RadMessageBox.Show(ex.Message, projectName, MessageBoxButtons.OK, RadMessageIcon.Error)
                errlog.WriteLog(ex.Message.ToString, Me.Name, System.Reflection.MethodBase.GetCurrentMethod().Name.ToString())
            End Try
        End Sub
</code>```

the code above does what i want but for the selected row i want to  get the index of row when my mouse is over this row. Can anyone help?

答:
My real problem was... I wanted to add a tooltip in specific column and tooltip show the value of another column here is the code to do this.</p>

```<code>Private Sub RadGridView1_ToolTipTextNeeded(sender As Object, e As ToolTipTextNeededEventArgs) Handles RadGridView1.ToolTipTextNeeded
        Try
            Dim cell As GridDataCellElement = TryCast(sender, GridDataCellElement)

            If cell IsNot Nothing AndAlso cell.ColumnInfo.Name = "DeliveryName" Then
                e.ToolTipText = cell.RowInfo.Cells.Item("DeliveryPhone").Value

            End If
        Catch ex As Exception
            RadMessageBox.Show(ex.Message, projectName, MessageBoxButtons.OK, RadMessageIcon.Error)
            errlog.WriteLog(ex.Message.ToString, Me.Name, System.Reflection.MethodBase.GetCurrentMethod().Name.ToString())
        End Try
    End Sub
</code>```

Body:
i want to get index of any row that my mouse is above and not necessarily from the selected row.

 Private Sub RadGridView1_MouseHover(sender As Object, e As EventArgs) Handles RadGridView1.MouseHover
            Try
                toolidx = RadGridView1.CurrentCell.RowIndex
                strphone = dsOrders.Tables(0).Rows(toolidx)("DeliveryPhone")

            Catch ex As Exception
                RadMessageBox.Show(ex.Message, projectName, MessageBoxButtons.OK, RadMessageIcon.Error)
                errlog.WriteLog(ex.Message.ToString, Me.Name, System.Reflection.MethodBase.GetCurrentMethod().Name.ToString())
            End Try
        End Sub

the code above does what i want but for the selected row i want to  get the index of row when my mouse is over this row. Can anyone help?

Body:
My real problem was... I wanted to add a tooltip in specific column and tooltip show the value of another column here is the code to do this.

Private Sub RadGridView1_ToolTipTextNeeded(sender As Object, e As ToolTipTextNeededEventArgs) Handles RadGridView1.ToolTipTextNeeded
        Try
            Dim cell As GridDataCellElement = TryCast(sender, GridDataCellElement)

            If cell IsNot Nothing AndAlso cell.ColumnInfo.Name = "DeliveryName" Then
                e.ToolTipText = cell.RowInfo.Cells.Item("DeliveryPhone").Value

            End If
        Catch ex As Exception
            RadMessageBox.Show(ex.Message, projectName, MessageBoxButtons.OK, RadMessageIcon.Error)
            errlog.WriteLog(ex.Message.ToString, Me.Name, System.Reflection.MethodBase.GetCurrentMethod().Name.ToString())
        End Try
    End Sub


问:
Select2 ajax processing results
I am using select2 with ajax searhc queries to DB. Everything is working just fine but I have 1 little problem.

Lets say I am looking through IDs in database and When I start writing to select2 ID: 111 - record is found - 1 row but I have there 2 rows with the 111 on the top which I wrote.

Here is javascript:

```<code>$(".select2-ajax").select2({
            minimumInputLength: 1,
            tags: [],
            ajax: {
                url: "ajax/" + uri,
                dataType: 'json',
                type: "GET",
                quietMillis: 50,
                data: function (term) {
                    return {
                        q: term.term
                    }
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });
</code>```

Screen of result:

Expected result:

The same as on the image but without the 1st option where is only 111

答:
Solved, it was caused by tags: []

```<code>$(".select2-ajax").select2({
            minimumInputLength: 1,
            ajax: {
                url: "ajax/" + uri,
                dataType: 'json',
                type: "GET",
                quietMillis: 50,
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                cache: true
            }
        });
</code>```

Title: Select2 ajax processing results

Body:
I am using select2 with ajax searhc queries to DB. Everything is working just fine but I have 1 little problem.

Lets say I am looking through IDs in database and When I start writing to select2 ID: 111 - record is found - 1 row but I have there 2 rows with the 111 on the top which I wrote.

Here is javascript:

$(".select2-ajax").select2({
            minimumInputLength: 1,
            tags: [],
            ajax: {
                url: "ajax/" + uri,
                dataType: 'json',
                type: "GET",
                quietMillis: 50,
                data: function (term) {
                    return {
                        q: term.term
                    }
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });

Screen of result:

Expected result:

The same as on the image but without the 1st option where is only 111

Body:
Solved, it was caused by tags: []

$(".select2-ajax").select2({
            minimumInputLength: 1,
            ajax: {
                url: "ajax/" + uri,
                dataType: 'json',
                type: "GET",
                quietMillis: 50,
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                cache: true
            }
        });


问:
CKEditor has Empty Value on asp:textbox
I have implemented CKEditor on my Visual Studio 2013 and it has been showed clearly with asp:TextBox element.

But somehow while I fetch the value it returns empty.

This is my code:

```<code><div class="row">
  <div class="col-md-11">
    <asp:TextBox ID="bodyMessageTextBox" runat="server"/>
    <script type="text/javascript">
      CKEDITOR.replace("ctl00_ContentPlaceHolder1_bodyMessageTextBox");
    </script>
  </div>
</div>
</code>```

I fetch with this method;

```<code>_msemailsetup.BodyMessage = this.bodyMessageTextBox.Text;
</code>```

Can someone help me solve this?

答:
You will get the data with below code :

Inspect (press f12 on browser) the browser and then check the name of editor

 var editorText = CKEDITOR.instances.bodyMessageTextBox.getData();
 _msemailsetup.BodyMessage = editorText ;
```

Title: CKEditor has Empty Value on asp:textbox

Body:
I have implemented CKEditor on my Visual Studio 2013 and it has been showed clearly with asp:TextBox element.

But somehow while I fetch the value it returns empty.

This is my code:

    <asp:TextBox ID="bodyMessageTextBox" runat="server"/>

I fetch with this method;

_msemailsetup.BodyMessage = this.bodyMessageTextBox.Text;

Can someone help me solve this?


问:
How to Redirect to a certain route based on condition in Angular 2.
I am creating one angular2-meteor app.

```<code>export const routes: Route[] = [{
    path: '',
    redirectTo: "login",
    pathMatch: "full"
},
{
    path: 'login',
    component: LoginComponent
},
{
    path: 'csvtemplate',
    component: TemplateComponent,
    canActivate: ['canActivateForLoggedIn'],
    children: [{
        path: '',
        redirectTo: 'dashboard' <----how to add condition for multiple path
    },
    {
        path:'dashboard',
        component: DashboardComponent
    },
    {
        path: 'csvtimeline/:month/:year',
        component: CsvTimelineComponent
    }, {
        path: 'csvjson',
        component: CsvJsonComponent
    }]
}];
</code>```

When i login to my app using LoginComponent it will go to TemplateComponent which have three child components

dashboard

csvtimeline

csvjson

Now i have by default set redirectTo to my dashboard component. but in place of this redirect i want to redirect to csvjson component or csvtimeline component based on login user profile.

Suppose

If Login User is "Admin" he should be redirectTo - > dashboard Component

If Login User is "Guest" then he should be redirectTo - > csvjson component

i know we can do this in ngOnInit() of dashboard component for redirect.

```<code>if (this.user && this.user.profile.role == 'Guest') {
             this._router.navigate(['csvtemplate/csvjson']);
        }
</code>```

but i am looking for better option so i don't have to open dashboard component each time and it will directly go to csvjson component.

答:
Here is the better solution: Guard the admin feature according to Angular guide.

Using CanActivate hook
Steps:

1) Add auth-guard.service.ts file

```<code>import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';
import { Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
    canActivate() {
        //Your redirect logic/condition. I use this.

        if (this.user && this.user.profile.role == 'Guest') {
         this.router.navigate(['dashboard']);
        }
        console.log('AuthGuard#canActivate called');
        return true;
    }
    //Constructor
    constructor(private router: Router) { }
}
</code>```

2) Update the routing file, in my case it's app.module.ts

```<code>import { AuthGuard } from './auth-guard.service';
import { AdminComponent } from './admin/admin.component';
@NgModule({
  declarations: [
    AppComponent,
    AdminComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,

    RouterModule.forRoot([
        {
          path: 'admin',
          component: AdminComponent,
          canActivate:[AuthGuard]
        },
        {
        path: '',
        redirectTo: '/dashboard',
        pathMatch: 'full'
       }
    ])
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

**Reference **
https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

Body:
I am creating one angular2-meteor app.

export const routes: Route[] = [{
    path: '',
    redirectTo: "login",
    pathMatch: "full"
},
{
    path: 'login',
    component: LoginComponent
},
{
    path: 'csvtemplate',
    component: TemplateComponent,
    canActivate: ['canActivateForLoggedIn'],
    children: [{
        path: '',
        redirectTo: 'dashboard' <----how to add condition for multiple path
    },
    {
        path:'dashboard',
        component: DashboardComponent
    },
    {
        path: 'csvtimeline/:month/:year',
        component: CsvTimelineComponent
    }, {
        path: 'csvjson',
        component: CsvJsonComponent
    }]
}];

When i login to my app using LoginComponent it will go to TemplateComponent which have three child components

dashboard

csvtimeline

csvjson

Now i have by default set redirectTo to my dashboard component. but in place of this redirect i want to redirect to csvjson component or csvtimeline component based on login user profile.

Suppose

If Login User is "Admin" he should be redirectTo - > dashboard Component

If Login User is "Guest" then he should be redirectTo - > csvjson component

i know we can do this in ngOnInit() of dashboard component for redirect.

if (this.user && this.user.profile.role == 'Guest') {
             this._router.navigate(['csvtemplate/csvjson']);
        }

but i am looking for better option so i don't have to open dashboard component each time and it will directly go to csvjson component.

Body:
Here is the better solution: Guard the admin feature according to Angular guide.

Using CanActivate hook
Steps:

1) Add auth-guard.service.ts file

import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';
import { Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
    canActivate() {
        //Your redirect logic/condition. I use this.

        if (this.user && this.user.profile.role == 'Guest') {
         this.router.navigate(['dashboard']);
        }
        console.log('AuthGuard#canActivate called');
        return true;
    }
    //Constructor
    constructor(private router: Router) { }
}

2) Update the routing file, in my case it's app.module.ts

import { AuthGuard } from './auth-guard.service';
import { AdminComponent } from './admin/admin.component';
@NgModule({
  declarations: [
    AppComponent,
    AdminComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,

    RouterModule.forRoot([
        {
          path: 'admin',
          component: AdminComponent,
          canActivate:[AuthGuard]
        },
        {
        path: '',
        redirectTo: '/dashboard',
        pathMatch: 'full'
       }
    ])
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

**Reference **
https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard


答: It's a feature of MVC that the view and controller are independent. You could equally use shared or partial views for the same thing, if anything I'd say it's a good thing because you're writing re-usable code and making use of it.</p>

Title: Need advice before I develop a bad habit

Body:
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            IDSubcategory

            IDCity

            IDPerson

            Title

            TextBody

            ContactNumber

            AskingPrice

            AddressDirection

            LatestUpdateDate

            VisitCount

@foreach (var item in Model) {

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

            @item.IDSubcategory

            @item.IDCity

            @item.IDPerson

            @item.Title

            @item.TextBody

            @item.ContactNumber

            @String.Format("{0:F}", item.AskingPrice)

            @item.AddressDirection

            @String.Format("{0:g}", item.LatestUpdateDate)

            @item.VisitCount

}

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.


问:
Fastest way to compute e^x?
What is the fastest way to compute e^x, given x can be a floating point value.

Right now I have used the python's math library to compute this, below is the complete code where in result = -0.490631 + 0.774275 * math.exp(0.474907 * sum) is the main logic, rest is file handling code which the question demands.

```<code>import math
import sys

def sum_digits(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

def _print(string):
    fo = open("output.txt", "w+")
    fo.write(string)
    fo.close()

try:
    f = open('input.txt')
except IOError:
    _print("error")
    sys.exit()
data = f.read()
num = data.split('\n', 1)[0]
try:
   val = int(num)
except ValueError:
    _print("error")
    sys.exit()

sum = sum_digits(int(num))
f.close()

if (sum == 2):
    _print("1")
else:
    result = -0.490631 + 0.774275 * math.exp(0.474907 * sum)
    _print(str(math.ceil(result)))
</code>```

The rvalue of result is the equation of curve (which is the solution to a programming problem) which I derived from wolfarm-mathematica using my own data set.

But this doesn't seem to pass the par criteria of the assessment !

I have also tried the newton-raphson way but the convergence for larger x is causing the problem, other than that, calculating the natural log ln(x) is a challenge there again !

I don't have any language constraint so any solution is acceptable. Also if the python's math library is fastest as some of the comments says then can anyone give an insight on the time complexity and execution time of this program, in short the efficiency of the program ?

答:
I don't know if the exponential curve math is accurate in this code, but it certainly isn't the slow point.

First, you read the input data in one read call. It does have to be read, but that loads the entire file. The next step takes the first line only, so it would seem more appropriate to use readline. That split itself is O(n) where n is the file size, at least, which might include data you were ignoring since you only process one line.

Second, you convert that line into an int. This probably requires Python's long integer support, but the operation could be O(n) or O(n^2). A single pass algorithm would multiply the accumulated number by 10 for each digit, allocating one or two new (longer) longs each time.

Third, sum_digits breaks that long int down into digits again. It does so using division, which is expensive, and two operations as well, rather than using divmod. That's O(n^2), because each division has to process every higher digit for each digit. And it's only needed because of the conversion you just did.

Summing the digits found in a string is likely easier done with something like sum(int(c) for c in l if c.isdigit()) where l is the input line. It's not particularly fast, as there's quite a bit of overhead in the digit conversions and the sum might grow large, but it does make a single pass with a fairly tight loop; it's somewhere between O(n) and O(n log n), depending on the length of the data, because the sum might grow large itself.

As for the unknown exponential curve, the existence of an exception for a low number is concerning. There's likely some other option that's both faster and more accurate if the answer's an integer anyway.

Lastly, you have at least four distinct output data formats: error, 2, 3.0, 3e+20. Do you know which of these is expected? Perhaps you should be using formatted output rather than str to convert your numbers.

One extra note: If the data is really large, processing it in chunks will definitely speed things up (instead of running out of memory, needing to swap, etc). As you're looking for a digit sum your size complexity can be reduced from O(n) to O(log n).

Title: Fastest way to compute e^x?

Body:
What is the fastest way to compute e^x, given x can be a floating point value.

Right now I have used the python's math library to compute this, below is the complete code where in result = -0.490631 + 0.774275 * math.exp(0.474907 * sum) is the main logic, rest is file handling code which the question demands.

import math
import sys

def sum_digits(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

def _print(string):
    fo = open("output.txt", "w+")
    fo.write(string)
    fo.close()

try:
    f = open('input.txt')
except IOError:
    _print("error")
    sys.exit()
data = f.read()
num = data.split('\n', 1)[0]
try:
   val = int(num)
except ValueError:
    _print("error")
    sys.exit()

sum = sum_digits(int(num))
f.close()

if (sum == 2):
    _print("1")
else:
    result = -0.490631 + 0.774275 * math.exp(0.474907 * sum)
    _print(str(math.ceil(result)))

The rvalue of result is the equation of curve (which is the solution to a programming problem) which I derived from wolfarm-mathematica using my own data set.

But this doesn't seem to pass the par criteria of the assessment !

I have also tried the newton-raphson way but the convergence for larger x is causing the problem, other than that, calculating the natural log ln(x) is a challenge there again !

I don't have any language constraint so any solution is acceptable. Also if the python's math library is fastest as some of the comments says then can anyone give an insight on the time complexity and execution time of this program, in short the efficiency of the program ?


问:
Insert variable between ''
I've developed an MQTT application based on phpMQTT. It subscribes to a series of topics, on a given namespace.

I need to make the namespace variable, getting it from an ENV variable. The ENV stuff works fine. However, when I try to insert the variable in the topic in order to subscribe, it doesn't work. I am suspecting it has to do with the '' but I'm not sure.

```<code>//defining the variable - would be $namespace = getenv(NAMESPACE)
$namespace = "name/space";
//set the topics and subscribe
$topics['".$namespace."'/raw/#'] = array("qos"=>0, "function"=>"dostuff");
</code>```

So how do I insert this variable as needed? Thanks.

答:
Do it like this:</p>

```<code>$topics[$namespace . '/raw/#'] = array("qos"=>0, "function"=>"dostuff");
</code>```

Title: Insert variable between ''

Body:
I've developed an MQTT application based on phpMQTT. It subscribes to a series of topics, on a given namespace.

I need to make the namespace variable, getting it from an ENV variable. The ENV stuff works fine. However, when I try to insert the variable in the topic in order to subscribe, it doesn't work. I am suspecting it has to do with the '' but I'm not sure.

//defining the variable - would be $namespace = getenv(NAMESPACE)
$namespace = "name/space";
//set the topics and subscribe
$topics['".$namespace."'/raw/#'] = array("qos"=>0, "function"=>"dostuff");

So how do I insert this variable as needed? Thanks.

Body:
Do it like this:

$topics[$namespace . '/raw/#'] = array("qos"=>0, "function"=>"dostuff");


答:
There you go:

http://jsfiddle.net/hallleron/MD3mX/1813/

The change has to be done here:

```<code>$(".borrowMonth span").html(ui.value);
</code>```

Refer to the span inside your .borrowMonth class and pass the value as html, not as val. A span doesn't have a val attribute,

Title: how to show the UI Slider value in two different fields?

Body:
i am tying to show the UI range slider value in input box. i have done this but i want show the same value on another  also, that span is in another .

here i am getting the slider value on this input box but the same value must reflect on another div's  also.

How do i do it , help me out of this

$("#slider").slider({
    range: "min",
    value: 1,
    step: 10,
    min: 210,
    max: 850,
    slide: function (event, ui) {
        $(".inputCount").val(ui.value);
        $(".borrowMonth").val(ui.value);
    }
});
$(".inputCount").change(function () {
    $("#slider").slider("value",this.value);
});

£
<input type="text" value="200" class="inputCount"/>

£ 200

Body:
There you go:

http://jsfiddle.net/hallleron/MD3mX/1813/

The change has to be done here:

$(".borrowMonth span").html(ui.value);

Refer to the span inside your .borrowMonth class and pass the value as html, not as val. A span doesn't have a val attribute,