问:
Take the string from an listView with a contextmenuinfo
I have a project from an Android application and I want that when I click on an option in a contextMenu I see the String of that position.

```<code>String[] datos = {"Victor","Silvia","Manolo","Carlos","Ana"};
        ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, datos);

    milista.setAdapter(adaptador);
</code>```

And this is the method to do something by click an intem of the context menu

```<code> @Override
public boolean onContextItemSelected(MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()){

        case R.id.action_mostrar:
            Toast.makeText(getApplicationContext(),info.position+": Opción mostrar" , Toast.LENGTH_LONG).show();
            return true;

        case R.id.action_eliminar:
            Toast.makeText(getApplicationContext(), info.position+": Opción eliminar", Toast.LENGTH_LONG).show();
            return true;

        default:
            return false;

    }
}
</code>```

How should I do it?

Edit:

the problem is solved, I leave the code solved:

```<code>@Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        String selectedWord = ((TextView) info.targetView).getText().toString();
        switch (item.getItemId()){

            case R.id.action_mostrar:
                Toast.makeText(getApplicationContext(),selectedWord+": Opción mostrar" , Toast.LENGTH_LONG).show();
                return true;

            case R.id.action_eliminar:
                Toast.makeText(getApplicationContext(), selectedWord+": Opción eliminar" , Toast.LENGTH_LONG).show();
                return true;

            default:
                return false;

        }
    }
</code>```

Thank you

答:
You can also use the position to retrieve the string from your string array like this</p>

```<code>@Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId()){

            case R.id.action_mostrar:
                Toast.makeText(getApplicationContext(),datos[info.position]+": Opción mostrar" , Toast.LENGTH_LONG).show();
                return true;

            case R.id.action_eliminar:
                Toast.makeText(getApplicationContext(), datos[info.position]+": Opción eliminar" , Toast.LENGTH_LONG).show();
                return true;

            default:
                return false;

        }
    }
</code>```

Body:
I have a project from an Android application and I want that when I click on an option in a contextMenu I see the String of that position.

String[] datos = {"Victor","Silvia","Manolo","Carlos","Ana"};
        ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, datos);

    milista.setAdapter(adaptador);

And this is the method to do something by click an intem of the context menu

 @Override
public boolean onContextItemSelected(MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()){

        case R.id.action_mostrar:
            Toast.makeText(getApplicationContext(),info.position+": Opción mostrar" , Toast.LENGTH_LONG).show();
            return true;

        case R.id.action_eliminar:
            Toast.makeText(getApplicationContext(), info.position+": Opción eliminar", Toast.LENGTH_LONG).show();
            return true;

        default:
            return false;

    }
}

How should I do it?

Edit:

the problem is solved, I leave the code solved:

@Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        String selectedWord = ((TextView) info.targetView).getText().toString();
        switch (item.getItemId()){

            case R.id.action_mostrar:
                Toast.makeText(getApplicationContext(),selectedWord+": Opción mostrar" , Toast.LENGTH_LONG).show();
                return true;

            case R.id.action_eliminar:
                Toast.makeText(getApplicationContext(), selectedWord+": Opción eliminar" , Toast.LENGTH_LONG).show();
                return true;

            default:
                return false;

        }
    }

Thank you

Body:
You can also use the position to retrieve the string from your string array like this

@Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId()){

            case R.id.action_mostrar:
                Toast.makeText(getApplicationContext(),datos[info.position]+": Opción mostrar" , Toast.LENGTH_LONG).show();
                return true;

            case R.id.action_eliminar:
                Toast.makeText(getApplicationContext(), datos[info.position]+": Opción eliminar" , Toast.LENGTH_LONG).show();
                return true;

            default:
                return false;

        }
    }


来源: stackexchange

问:
AutoCAD to Excel
Hi How can I access a spreadsheet from AutoCad and take a value from there and use it on AutoCAd
Here is my code but it does not get the value , it's always empty. Don't know what's wrong</p>

```<code>Sub move()
Dim EXCELApplication As Object
Dim ExcelWorksheet As Object

Set EXCELApplication = CreateObject("Excel.Application")
EXCELApplication.workbooks.Open AcadToExcel
EXCELApplication.Visible = True
Set ExcelWorksheet = EXCELApplication.ActiveWorkbook.Sheets("Sheet1")

modelsize = ExcelWorksheet.Cells(21, 3).Value

Size = modelsize

End Sub
</code>```

答:
I just tested this and it works just fine for me:

```<code>Public Sub GetFromExcel()
  Dim sFile As String
  sFile = "C:\Users\" & Environ$("Username") & "\Desktop\Test2.xlsx"
  Dim EXCELApplication As Object
  Dim ExcelWorksheet As Object
  Dim sValue As String

  Set EXCELApplication = CreateObject("Excel.Application")
  EXCELApplication.workbooks.Add sFile
  EXCELApplication.Visible = True
  Set ExcelWorksheet = EXCELApplication.ActiveWorkbook.Sheets("Sheet1")

  sValue = ExcelWorksheet.Range("A1").Value

  MsgBox sValue

End Sub
</code>```

If it doesnt work for you, then the problem is your filename.

ContentLicense: CC BY-SA 3.0

Title: AutoCAD to Excel

Body:
Hi How can I access a spreadsheet from AutoCad and take a value from there and use it on AutoCAd
Here is my code but it does not get the value , it's always empty. Don't know what's wrong

Sub move()
Dim EXCELApplication As Object
Dim ExcelWorksheet As Object

Set EXCELApplication = CreateObject("Excel.Application")
EXCELApplication.workbooks.Open AcadToExcel
EXCELApplication.Visible = True
Set ExcelWorksheet = EXCELApplication.ActiveWorkbook.Sheets("Sheet1")

modelsize = ExcelWorksheet.Cells(21, 3).Value

Size = modelsize

End Sub

Body:
I just tested this and it works just fine for me:

Public Sub GetFromExcel()
  Dim sFile As String
  sFile = "C:\Users\" & Environ$("Username") & "\Desktop\Test2.xlsx"
  Dim EXCELApplication As Object
  Dim ExcelWorksheet As Object
  Dim sValue As String

  Set EXCELApplication = CreateObject("Excel.Application")
  EXCELApplication.workbooks.Add sFile
  EXCELApplication.Visible = True
  Set ExcelWorksheet = EXCELApplication.ActiveWorkbook.Sheets("Sheet1")

  sValue = ExcelWorksheet.Range("A1").Value

  MsgBox sValue

End Sub

If it doesnt work for you, then the problem is your filename.


问:
Shebang not working when file executed directly from containing folder
I am trying to run a function from a php file and run it from cli without having to type php deploy so have added a shebang so the cli knows how to run the script.

e.g.

```<code>#!/usr/bin/env php
<?php

if (PHP_SAPI !== 'cli') {
  echo 'bin/deployer must be run as a CLI application' . "\n";
  exit(1);
}

function deploy(){
  echo "Deploying" . "\n";
}

foreach ($argv AS $arg){
  function_exists($arg) AND call_user_func($arg);
}
</code>```

File: deployer

This does work fine from root directory and running bin/deployer deploy works as expected. I'm just curious as to why if run from the directory bin: deployer deploy i get -bash: deployer: command not found

答:
try this in inside the bin/ directory:

```<code>./deployer deploy
</code>```

If you omit the ./ in front of your file, your shell will look for the command deployer in your path ($PATH), instead of treating it as a path to the file to execute.

The $PATH is a list of directories, where your shell will look for the command you typed.
To see what is in your path, try:

```<code>echo $PATH
</code>```

Body:
I am trying to run a function from a php file and run it from cli without having to type php deploy so have added a shebang so the cli knows how to run the script.

e.g.

#!/usr/bin/env php
<?php

if (PHP_SAPI !== 'cli') {
  echo 'bin/deployer must be run as a CLI application' . "\n";
  exit(1);
}

function deploy(){
  echo "Deploying" . "\n";
}

foreach ($argv AS $arg){
  function_exists($arg) AND call_user_func($arg);
}

File: deployer

This does work fine from root directory and running bin/deployer deploy works as expected. I'm just curious as to why if run from the directory bin: deployer deploy i get -bash: deployer: command not found

Body:
try this in inside the bin/ directory:

./deployer deploy

If you omit the ./ in front of your file, your shell will look for the command deployer in your path ($PATH), instead of treating it as a path to the file to execute.

The $PATH is a list of directories, where your shell will look for the command you typed.
To see what is in your path, try:

echo $PATH


问:
When i have build or to run ionic app at that time generate below error
Error: cmd: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

What went wrong:
A problem occurred configuring root project 'android'.

You have not accepted the license agreements of the following SDK components:
  [Android SDK Platform 26].
  Before building your project, you need to accept the license agreements and complete the installation of the missing components using the Android Studio SDK Manager.
  Alternatively, to learn how to transfer the license agreements from one workstation to another, go to http://d.android.com/r/studio-ui/export-licenses.html

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

答:
I have not been able to get the various proposed solutions to work.

```<code>cd "%ANDROID_HOME%\tools\bin"
sdkmanager --licenses
</code>```

no longer works.

I found that running

```<code>sdkmanager --update
</code>```

asked me to accept the license

and then failed due to the tools folder being in use.

Notwithstanding, the license problem seemed to be fixed.

The contents of the license file is now:

```<code>8933bad161af4178b1185d1a37fbf41ea5269c55
d56f5187479451eabf01fb78af6dfcb131a6481e
</code>```

Hope this helps others that have wasted as much time as I on this.

Body:
I have not been able to get the various proposed solutions to work.

cd "%ANDROID_HOME%\tools\bin"
sdkmanager --licenses

no longer works.

I found that running

sdkmanager --update

asked me to accept the license

and then failed due to the tools folder being in use.

Notwithstanding, the license problem seemed to be fixed.

The contents of the license file is now:

8933bad161af4178b1185d1a37fbf41ea5269c55
d56f5187479451eabf01fb78af6dfcb131a6481e

Hope this helps others that have wasted as much time as I on this.


问:
Selecting columns using query statement in pandas dataframe
I have the following pandas dataframe. Each point is combined with 'n' class points of each class, and each combination has a value of 0 or 1.
Now for each point, I want to get the class which has the highest number of '0'.
Output :
Pt.1 - a
Pt.2 -b

I have tried with hash table, but its being a bit cumbersome. What can be an elegant pandas dataframe query for this?

+------+-------+-------+--+--+--+
| Pt.  | class | value |  |  |  |
+------+-------+-------+--+--+--+
| Pt.1 | a     |     0 |  |  |  |
| Pt.1 | a     |     0 |  |  |  |
| Pt.1 | a     |     1 |  |  |  |
| Pt.1 | b     |     0 |  |  |  |
| Pt.1 | b     |     1 |  |  |  |
| pt.1 | b     |     1 |  |  |  |
| Pt.2 | a     |     1 |  |  |  |
| Pt.2 | a     |     1 |  |  |  |
| Pt.2 | a     |     1 |  |  |  |
| Pt.2 | b     |     0 |  |  |  |
| Pt.2 | b     |     0 |  |  |  |
| Pt.2 | b     |     0 |  |  |  |
|      |       |       |  |  |  |
+------+-------+-------+--+--+--+
```

答:
First filter only 0 rows by boolean indexing and then count by groupby with value_counts which sorts output, so is necessary seelct first index value by indexing:

```<code>df = (df[df['value'] == 0].groupby('Pt.')['class']
                          .apply(lambda x: x.value_counts().index[0])
                          .reset_index(name='top1'))
print (df)
    Pt. top1
0  Pt.1    a
1  Pt.2    b
</code>```

Similar alternative with query for filtering:

```<code>df = (df.query("value == 0")
        .groupby('Pt.')['class']
        .apply(lambda x: x.value_counts().index[0])
        .reset_index(name='top1'))
print (df)
    Pt. top1
0  Pt.1    a
1  Pt.2    b
</code>```

Body:
First filter only 0 rows by boolean indexing and then count by groupby with value_counts which sorts output, so is necessary seelct first index value by indexing:

df = (df[df['value'] == 0].groupby('Pt.')['class']
                          .apply(lambda x: x.value_counts().index[0])
                          .reset_index(name='top1'))
print (df)
    Pt. top1
0  Pt.1    a
1  Pt.2    b

Similar alternative with query for filtering:

df = (df.query("value == 0")
        .groupby('Pt.')['class']
        .apply(lambda x: x.value_counts().index[0])
        .reset_index(name='top1'))
print (df)
    Pt. top1
0  Pt.1    a
1  Pt.2    b


问:
Linq Groupby Elapsed Time
I need to group by a list by owner, town and "timeout".
I will explain "timeout":

```<code>public class Ticket
{
    public int pk { get; set; }
    public string owner { get; set; }
    public string reffering { get; set; }
    public DateTime? created_time { get; set; }
}
</code>```

And I got a List.
I want to create a List> where each sublist contains a list of tickets where created_time is less than 10 seconds.

Here is a sample list of tickets :

```<code>pk   owner   reffering   created_time
#1   John    Sam         15/11/2017 11:33:20
#2   John    Sam         15/11/2017 11:33:21
#3   Pat     Jerry       15/11/2017 11:33:27
#4   John    Sam         15/11/2017 11:33:28
#6   Pat     Jerry       15/11/2017 11:33:35
#5   John    Sam         15/11/2017 11:34:00
</code>```

And I need to get a list of list with

```<code>   pk   owner   reffering   created_time
---#1 Sub List ---
    #1   John    Sam         15/11/2017 11:33:20
    #2   John    Sam         15/11/2017 11:33:21
    #4   John    Sam         15/11/2017 11:33:28
---#2 Sub List ---
    #5   John    Sam         15/11/2017 11:34:00
---#3 Sub List ---
    #3   Pat     Jerry       15/11/2017 11:33:27
    #6   Pat     Jerry       15/11/2017 11:33:35
</code>```

Here my starting code but I can find out how to do this..

```<code>List<List<Ticket>> result = tickets.OrderBy(p => p.created_time).GroupBy(p => new { p.owner, p.reffering }).Select(g => g.ToList()).ToList();
</code>```

Hope some can help especially with the elapsed time.. it makes me crazy!

答:
Here is something that could help.
It is grouping the entries by fixed buckets of 10 seconds.

```<code>void Main()
{
    var ticketsList = new List<Ticket>();
    ticketsList.Add(new Ticket { pk = 1, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 33, 20) });
    ticketsList.Add(new Ticket { pk = 2, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 33, 21) });
    ticketsList.Add(new Ticket { pk = 3, owner="Pat" , reffering="Jerry", created_time = new DateTime(2017, 11, 15, 11, 33, 27) });
    ticketsList.Add(new Ticket { pk = 4, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 33, 28) });
    ticketsList.Add(new Ticket { pk = 6, owner="Pat" , reffering="Jerry", created_time = new DateTime(2017, 11, 15, 11, 33, 35) });
    ticketsList.Add(new Ticket { pk = 5, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 34, 00) });

    var now = DateTime.Now;

    var orderedList = ticketsList.OrderBy(p => p.created_time).GroupBy(p => new { p.owner, p.reffering }).Select(g => g.ToList());

    // Here is the 10 seconds grouping. I'm basically creating a new date
    // starting at the beginning of a 10 seconds interval. I will then
    // use this new date to perform the grouping.
    var normalizedGroupKeysList = ticketsList.Select(t => new { ticket = t, groupKey = t.created_time.HasValue ? t.created_time.Value.AddSeconds(-t.created_time.Value.Second % 10) : now });

    var result = normalizedGroupKeysList.GroupBy(t => t.groupKey, t => t.ticket);
}

public class Ticket
{
    public int pk { get; set; }
    public string owner { get; set; }
    public string reffering { get; set; }

    public DateTime? created_time { get; set; }
}
</code>```

The output is:

```<code>Key=    11/15/2017 11:33:20 AM
pk  owner   reffering   created_time
1   John    Sam 11/15/2017 11:33:20 AM
2   John    Sam 11/15/2017 11:33:21 AM
3   Pat Jerry   11/15/2017 11:33:27 AM
4   John    Sam 11/15/2017 11:33:28 AM

Key=    11/15/2017 11:33:30 AM
pk  owner   reffering   created_time
6   Pat Jerry   11/15/2017 11:33:35 AM

Key=    11/15/2017 11:34:00 AM
pk  owner   reffering   created_time
5   John    Sam 11/15/2017 11:34:00 AM
</code>```

If you want to dynamically group your tickets dynamically by group of 10 seconds in dynamic buckets, you should need some clustering algorithm to find the best partition of your data.

Title: Linq Groupby Elapsed Time

Body:
I need to group by a list by owner, town and "timeout".
I will explain "timeout":

public class Ticket
{
    public int pk { get; set; }
    public string owner { get; set; }
    public string reffering { get; set; }
    public DateTime? created_time { get; set; }
}

And I got a List.
I want to create a List> where each sublist contains a list of tickets where created_time is less than 10 seconds.

Here is a sample list of tickets :

pk   owner   reffering   created_time
#1   John    Sam         15/11/2017 11:33:20
#2   John    Sam         15/11/2017 11:33:21
#3   Pat     Jerry       15/11/2017 11:33:27
#4   John    Sam         15/11/2017 11:33:28
#6   Pat     Jerry       15/11/2017 11:33:35
#5   John    Sam         15/11/2017 11:34:00

And I need to get a list of list with

   pk   owner   reffering   created_time
---#1 Sub List ---
    #1   John    Sam         15/11/2017 11:33:20
    #2   John    Sam         15/11/2017 11:33:21
    #4   John    Sam         15/11/2017 11:33:28
---#2 Sub List ---
    #5   John    Sam         15/11/2017 11:34:00
---#3 Sub List ---
    #3   Pat     Jerry       15/11/2017 11:33:27
    #6   Pat     Jerry       15/11/2017 11:33:35

Here my starting code but I can find out how to do this..

List<List<Ticket>> result = tickets.OrderBy(p => p.created_time).GroupBy(p => new { p.owner, p.reffering }).Select(g => g.ToList()).ToList();

Hope some can help especially with the elapsed time.. it makes me crazy!

Body:
Here is something that could help.
It is grouping the entries by fixed buckets of 10 seconds.

void Main()
{
    var ticketsList = new List<Ticket>();
    ticketsList.Add(new Ticket { pk = 1, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 33, 20) });
    ticketsList.Add(new Ticket { pk = 2, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 33, 21) });
    ticketsList.Add(new Ticket { pk = 3, owner="Pat" , reffering="Jerry", created_time = new DateTime(2017, 11, 15, 11, 33, 27) });
    ticketsList.Add(new Ticket { pk = 4, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 33, 28) });
    ticketsList.Add(new Ticket { pk = 6, owner="Pat" , reffering="Jerry", created_time = new DateTime(2017, 11, 15, 11, 33, 35) });
    ticketsList.Add(new Ticket { pk = 5, owner="John", reffering="Sam"  , created_time = new DateTime(2017, 11, 15, 11, 34, 00) });

    var now = DateTime.Now;

    var orderedList = ticketsList.OrderBy(p => p.created_time).GroupBy(p => new { p.owner, p.reffering }).Select(g => g.ToList());

    // Here is the 10 seconds grouping. I'm basically creating a new date
    // starting at the beginning of a 10 seconds interval. I will then
    // use this new date to perform the grouping.
    var normalizedGroupKeysList = ticketsList.Select(t => new { ticket = t, groupKey = t.created_time.HasValue ? t.created_time.Value.AddSeconds(-t.created_time.Value.Second % 10) : now });

    var result = normalizedGroupKeysList.GroupBy(t => t.groupKey, t => t.ticket);
}

public class Ticket
{
    public int pk { get; set; }
    public string owner { get; set; }
    public string reffering { get; set; }

    public DateTime? created_time { get; set; }
}

The output is:

Key=    11/15/2017 11:33:20 AM
pk  owner   reffering   created_time
1   John    Sam 11/15/2017 11:33:20 AM
2   John    Sam 11/15/2017 11:33:21 AM
3   Pat Jerry   11/15/2017 11:33:27 AM
4   John    Sam 11/15/2017 11:33:28 AM

Key=    11/15/2017 11:33:30 AM
pk  owner   reffering   created_time
6   Pat Jerry   11/15/2017 11:33:35 AM

Key=    11/15/2017 11:34:00 AM
pk  owner   reffering   created_time
5   John    Sam 11/15/2017 11:34:00 AM

If you want to dynamically group your tickets dynamically by group of 10 seconds in dynamic buckets, you should need some clustering algorithm to find the best partition of your data.


问:
regex to count english words as single char inside char count of asian words
need some help from a regex jedi master:

If I have a string of mb chars (specifically, Japanese, Korean or Chinese) with English words sprinkled throughout, I would like to count:

asian characters as 1 per single char

english "words" (no dictionary check needed - just a string of consecutive english letters) as a single char.

English only is fine - don't worry about special spanish, swedish, etc. chars.

I am searching for a regex pattern I can use to count these strings, that will function in php and js.

Example:

これは猫です、けどKittyも大丈夫。

should count as 13 chars.

thanks for your help!

jeff

答:
OK, so I would do two runs: First count the occurrences of the English words and then of the Asian ones. This is a JS example, it might be different in PHP. In JS, only ASCII chars match \w.

```<code>string = "これは猫です、けどKittyも大丈夫";
var m = string.match(/\w+/gm);
var e_count = m.length; // is 1
</code>```

Next count the Asian chars.

```<code>m = string.match(/([^\w\s\d])/gm); // any non-whitespace, non-word, non-digit chars
var a_count = m.length; // is 13
</code>```

You might have to tweak it a bit. But in JS, you can add up e_count and a_count, and you should be good to go.

Also check out Rubular: http://www.rubular.com

Johannes

ContentLicense: CC BY-SA 2.5

Body:
OK, so I would do two runs: First count the occurrences of the English words and then of the Asian ones. This is a JS example, it might be different in PHP. In JS, only ASCII chars match \w.

string = "これは猫です、けどKittyも大丈夫";
var m = string.match(/\w+/gm);
var e_count = m.length; // is 1

Next count the Asian chars.

m = string.match(/([^\w\s\d])/gm); // any non-whitespace, non-word, non-digit chars
var a_count = m.length; // is 13

You might have to tweak it a bit. But in JS, you can add up e_count and a_count, and you should be good to go.

Also check out Rubular: http://www.rubular.com

Johannes


问:
detailed guide for pgadmin deployment - Windows 7
I am an absolute new to postgresql, pgadmin and all it's tools. And with no python knowledge. I need to deploy pgadmin in as a web application on windows 7 os.
I have been trying the pgadmin's documentation from the official site , with no results. always errors, they ask u to do 1 2 3 but without where and how to check and so on....
I need a detailed guide for pgadmin 4 v 2 installation and deployment as a web application - with or without postgreSql.

Thanks...

答:
For pgAdmin 4 v2.0 on Ubuntu, according to the download page:

Install dependencies, create a virtual environment, download, install & configure

sudo apt-get install virtualenv python-pip libpq-dev python-dev

cd
virtualenv pgadmin4
cd pgadmin4
source bin/activate

pip install https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v2.0/pip/pgadmin4-2.0-py2.py3-none-any.whl
```

<h3>Configure</h3>

<p>Override default paths and set it to single-user mode in the local configuration file:</p>

```nano lib/python2.7/site-packages/pgadmin4/config_local.py
```

<p>Write:</p>

```import os
DATA_DIR = os.path.realpath(os.path.expanduser(u'~/.pgadmin/'))
LOG_FILE = os.path.join(DATA_DIR, 'pgadmin4.log')
SQLITE_PATH = os.path.join(DATA_DIR, 'pgadmin4.db')
SESSION_DB_PATH = os.path.join(DATA_DIR, 'sessions')
STORAGE_DIR = os.path.join(DATA_DIR, 'storage')
SERVER_MODE = False
```

<h3>Run</h3>

```python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py
```

<h3>Access</h3>

<p>Access at http://localhost:5050</p>

<h3>Exit</h3>

<p>Exit with Ctrl-C</p>

<h3>Run again</h3>

```cd ~/pgadmin4
source bin/activate
python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py
```

<h3>Make a shortcut</h3>

```touch ~/pgadmin4/pgadmin4
chmod +x ~/pgadmin4/pgadmin4
nano ~/pgadmin4/pgadmin4
```

<p>Write:</p>

```#!/bin/bash
cd ~/pgadmin4
source bin/activate
python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py
```

<p>Now you can just run it with a simpler command:</p>

```~/pgadmin4/pgadmin4
```

Ref: link

Body:
For pgAdmin 4 v2.0 on Ubuntu, according to the download page:

Install dependencies, create a virtual environment, download, install & configure

sudo apt-get install virtualenv python-pip libpq-dev python-dev

cd
virtualenv pgadmin4
cd pgadmin4
source bin/activate

pip install https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v2.0/pip/pgadmin4-2.0-py2.py3-none-any.whl

Configure

Override default paths and set it to single-user mode in the local configuration file:

nano lib/python2.7/site-packages/pgadmin4/config_local.py

Write:

import os
DATA_DIR = os.path.realpath(os.path.expanduser(u'~/.pgadmin/'))
LOG_FILE = os.path.join(DATA_DIR, 'pgadmin4.log')
SQLITE_PATH = os.path.join(DATA_DIR, 'pgadmin4.db')
SESSION_DB_PATH = os.path.join(DATA_DIR, 'sessions')
STORAGE_DIR = os.path.join(DATA_DIR, 'storage')
SERVER_MODE = False

Run

python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py

Access

Access at http://localhost:5050

Exit

Exit with Ctrl-C

Run again

cd ~/pgadmin4
source bin/activate
python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py

Make a shortcut

touch ~/pgadmin4/pgadmin4
chmod +x ~/pgadmin4/pgadmin4
nano ~/pgadmin4/pgadmin4

Write:

#!/bin/bash
cd ~/pgadmin4
source bin/activate
python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py

Now you can just run it with a simpler command:

~/pgadmin4/pgadmin4

Ref: link


问:
timepicker selected value text size
I want to change the selected text value size of a time picker.

Do we have any libraries for the same?

As I searched we do not have any customization in android. Need to develop a UI similar to iOS time picker.

答:
For android brucetoo/PickView similar to IOS,

This is a helper lib for us to pick date or province like IOS system WheelView widget.

Added feature to pick time with WheelView Widget

Dependencies

```<code>   compile 'com.brucetoo.pickview:library:1.2.3'
</code>```

to use

```<code> DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(MainActivity.this, new DatePickerPopWin.OnDatePickedListener() {
                       @Override
                       public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                           Toast.makeText(MainActivity.this, dateDesc, Toast.LENGTH_SHORT).show();
                       }
                    }).textConfirm("CONFIRM") //text of confirm button
                           .textCancel("CANCEL") //text of cancel button
                           .btnTextSize(16) // button text size
                           .viewTextSize(25) // pick view text size
                           .colorCancel(Color.parseColor("#999999")) //color of cancel button
                           .colorConfirm(Color.parseColor("#009900"))//color of confirm button
                           .minYear(1990) //min year in loop
                           .maxYear(2550) // max year in loop
                           .showDayMonthYear(true) // shows like dd mm yyyy (default is false)
                           .dateChose("2013-11-11") // date chose when init popwindow
                           .build();
</code>```

Title: timepicker selected value text size

Body:
For android brucetoo/PickView similar to IOS,

This is a helper lib for us to pick date or province like IOS system WheelView widget.

Added feature to pick time with WheelView Widget

Dependencies

   compile 'com.brucetoo.pickview:library:1.2.3'

to use

 DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(MainActivity.this, new DatePickerPopWin.OnDatePickedListener() {
                       @Override
                       public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                           Toast.makeText(MainActivity.this, dateDesc, Toast.LENGTH_SHORT).show();
                       }
                    }).textConfirm("CONFIRM") //text of confirm button
                           .textCancel("CANCEL") //text of cancel button
                           .btnTextSize(16) // button text size
                           .viewTextSize(25) // pick view text size
                           .colorCancel(Color.parseColor("#999999")) //color of cancel button
                           .colorConfirm(Color.parseColor("#009900"))//color of confirm button
                           .minYear(1990) //min year in loop
                           .maxYear(2550) // max year in loop
                           .showDayMonthYear(true) // shows like dd mm yyyy (default is false)
                           .dateChose("2013-11-11") // date chose when init popwindow
                           .build();


问:
How to change session values in php
i am trying to change the value of a session var in php.

```<code><?php
session_start();

if(isset($_POST["submit"])) {
    $_SESSION["registratie_data"]["straat"] = $_POST["straat"];
    $_SESSION["registratie_data"]["nummer"] = $_POST["nummer"];
    $_SESSION["registratie_data"]["gemeente"] = $_POST["gemeente"];
    $_SESSION["registratie_data"]["postcode"] = $_POST["postcode"];
}
$registratie_data    =   $_SESSION['registratie_data'];

if(isset($_POST["edit_button"])) {
    foreach($registratie_data as $key => $value) {
        if($key == $_GET["focus"]) {
            $value = $_POST["edit_value"];
            echo $value;
        }
    }
}
?>
</code>```

As you see i am trying to change the value in the foreach loop. This actually works and when i echo the value, i see the result i want... But then to display this value in html, doesnt work.

Anyone who can tell me what i'm doing wrong here?

This is my html code, if anyone needs this in order to help me out.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        li {
            display: block;
        }
    </style>
</head>
<body>
    <a href="?session=destroy">Vernietig sessie</a>
    <h1>Registratiegegevens</h1>
    <?php if(isset($_POST["submit"]) || isset($_POST["edit_button"]) ): ?>
    <ul>
    <?php foreach($registratie_data as $key => $value): ?>
        <li>
            <?php echo $value . " | "  ?>
            <a href="?focus=<?php echo $key ?>">wijzig</a>
        </li>
    <?php endforeach ?>
    </ul>
    <?php elseif(isset($_GET["focus"])): ?>

            <form action="#" method=POST>
              <ul>
               <li>
                <?php echo $_GET["focus"] ?>
                <input type="text" name="edit_value" ?>
                <input type="submit" name="edit_button" value="Opslaan">
                </li>
              </ul>
            </form>

    <?php else: ?>
    <form action="#" method=POST>
        <ul>
            <li>
                <label for="straat">Straat</label>
                <input type="text" name="straat">
            </li>
            <li>
                <label for="nummer">Nummer</label>
                <input type="text" name="nummer">
            </li>
            <li>
                <label for="gemeente">Gemeente</label>
                <input type="text" name="gemeente">
            </li>
            <li>
                <label for="postcode">postcode</label>
                <input type="text" name="postcode">
            </li>
            <input class="el" type="submit" name="submit" value="Volgende">
        </ul>
    </form>
    <?php endif ?>
</body>
</html>
</code>```

答:
You dont change the value of registration_data in the foreach loop. I think it should look like this:</p>

```<code>foreach($registratie_data as $key => $value) {
    if($key == $_GET["focus"]) {
        $registratie_data[$key] = $_POST["edit_value"];
    }
}
</code>```

Title: How to change session values in php

Body:
i am trying to change the value of a session var in php.

<?php
session_start();

if(isset($_POST["submit"])) {
    $_SESSION["registratie_data"]["straat"] = $_POST["straat"];
    $_SESSION["registratie_data"]["nummer"] = $_POST["nummer"];
    $_SESSION["registratie_data"]["gemeente"] = $_POST["gemeente"];
    $_SESSION["registratie_data"]["postcode"] = $_POST["postcode"];
}
$registratie_data    =   $_SESSION['registratie_data'];

if(isset($_POST["edit_button"])) {
    foreach($registratie_data as $key => $value) {
        if($key == $_GET["focus"]) {
            $value = $_POST["edit_value"];
            echo $value;
        }
    }
}
?>

As you see i am trying to change the value in the foreach loop. This actually works and when i echo the value, i see the result i want... But then to display this value in html, doesnt work.

Anyone who can tell me what i'm doing wrong here?

This is my html code, if anyone needs this in order to help me out.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>test</title>

    Vernietig sessie

Registratiegegevens

    <?php if(isset($_POST["submit"]) || isset($_POST["edit_button"]) ): ?>

    <?php foreach($registratie_data as $key => $value): ?>

            <?php echo $value . " | "  ?>
            <a href="?focus=<?php echo $key ?>">wijzig

    <?php endforeach ?>

    <?php elseif(isset($_GET["focus"])): ?>

            <form action="#" method=POST>

                <?php echo $_GET["focus"] ?>
                <input type="text" name="edit_value" ?>
                <input type="submit" name="edit_button" value="Opslaan">

            </form>

    <?php else: ?>
    <form action="#" method=POST>

                Straat
                <input type="text" name="straat">

                Nummer
                <input type="text" name="nummer">

                Gemeente
                <input type="text" name="gemeente">

                postcode
                <input type="text" name="postcode">

            <input class="el" type="submit" name="submit" value="Volgende">

    </form>
    <?php endif ?>

Body:
You dont change the value of registration_data in the foreach loop. I think it should look like this:

foreach($registratie_data as $key => $value) {
    if($key == $_GET["focus"]) {
        $registratie_data[$key] = $_POST["edit_value"];
    }
}


问:
Find hashed (bcyrpt) code in database and validate it with input (Laravel)
I have a simple form with a single input field where you can submit a code (respectively a key). In my database are a bunch of codes stored (in clear text) and if the form input matches with one of those codes you get access to some Stuff.

This is the way I am finding out which code has been used to fetch the data

```<code>$usedCode = Stuff::where('code', $request->code)->get();
</code>```

Now while this works perfect I wanted to add some security to it. Because if somebody has access to my database he can just read the codes.

I tried to bcrypt all the codes but then of course the method above does not work anymore.

I know it is not possible to "decrypt" the hashed codes but how can I solve this?
Or is there no security breach I need to worry about and I should just use the clear text?

答:
you can use many ways. i recommend this:

first: bcrypt all your codes and then store them in database. never save a non encrypted data in database!

now you can use Laravel's Hash Facade for matching the input code:

```<code>// use Hash namesapce: Illuminate\Support\Facades\Hash

foreach(Stuff::all() as $stuff){
   if (Hash::check($request->code, $stuff->code))
       // The codes match...
}
//the codes doesn't match
</code>```

Body:
I have a simple form with a single input field where you can submit a code (respectively a key). In my database are a bunch of codes stored (in clear text) and if the form input matches with one of those codes you get access to some Stuff.

This is the way I am finding out which code has been used to fetch the data

$usedCode = Stuff::where('code', $request->code)->get();

Now while this works perfect I wanted to add some security to it. Because if somebody has access to my database he can just read the codes.

I tried to bcrypt all the codes but then of course the method above does not work anymore.

I know it is not possible to "decrypt" the hashed codes but how can I solve this?
Or is there no security breach I need to worry about and I should just use the clear text?

Body:
you can use many ways. i recommend this:

first: bcrypt all your codes and then store them in database. never save a non encrypted data in database!

now you can use Laravel's Hash Facade for matching the input code:

// use Hash namesapce: Illuminate\Support\Facades\Hash

foreach(Stuff::all() as $stuff){
   if (Hash::check($request->code, $stuff->code))
       // The codes match...
}
//the codes doesn't match


问:
knockout data-bind on dynamically generated elements
How is it possible to make knockout data-bind work on dynamically generated elements? For example, I insert a simple html select menu inside a div and want to populate options using the knockout options binding. This is what my code looks like:

```<code>$('#menu').html('<select name="list" data-bind="options: listItems"></select>');
</code>```

but this method doesn't work. Any ideas?

答:
Checkout this answer: How do define a custom knockout 'options binding' with predefined Text and Value options

ko.applyBindingsToNode is particularly useful.

Body:
How is it possible to make knockout data-bind work on dynamically generated elements? For example, I insert a simple html select menu inside a div and want to populate options using the knockout options binding. This is what my code looks like:

$('#menu').html('<select name="list" data-bind="options: listItems"></select>');

but this method doesn't work. Any ideas?


问:
Provide default arguments for subscript operator and function call operator
In the following code, I have provided default arguments for array subscript operator.

```<code>struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};
</code>```

But, compiler generated an error :

```<code>error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)
</code>```

But, If I provide default arguments for function call operator.

```<code>struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};
</code>```

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?

答:
Why doesn't allowed default argument for array subscript operator?

Why does allowed default argument for function call operator?

Mainly because the C++ grammar says so. According to A.4 [gram.expr]:

```<code>postfix-expression --> postfix-expression [ expr-or-braced-init-list ]
                   --> postfix-expression ( expression-list opt )
                   --> simple-type-specifier (expression-list opt)
                   --> typename-specifier ( expression-list opt )
</code>```

The parameters for braces are optional, the ones for brackets not.
As suggested in the comment, note that brackets are required to take exactly one parameter whereas the braces can take an arbitrary number of parameters.

Also consider songyuanyao's answer for an explicit statement from the standard.

Body:
In the following code, I have provided default arguments for array subscript operator.

struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};

But, compiler generated an error :

error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)

But, If I provide default arguments for function call operator.

struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?

Body:
Why doesn't allowed default argument for array subscript operator?

Why does allowed default argument for function call operator?

Mainly because the C++ grammar says so. According to A.4 [gram.expr]:

postfix-expression --> postfix-expression [ expr-or-braced-init-list ]
                   --> postfix-expression ( expression-list opt )
                   --> simple-type-specifier (expression-list opt)
                   --> typename-specifier ( expression-list opt )

The parameters for braces are optional, the ones for brackets not.
As suggested in the comment, note that brackets are required to take exactly one parameter whereas the braces can take an arbitrary number of parameters.

Also consider songyuanyao's answer for an explicit statement from the standard.


问:
Detect user change clock time after Force Stop app
I can detect change clock time when app in foreground, background, or kill from Recent App by using android.intent.action.TIME_SET follow here.

However, if I Force Stop app in Setting->Apps I can not receive this broadcast anymore.

Currently, I want to detect user change clock time come back to my app after ForceStop so I do

```<code>long deltaTimeBeetweenCurrentTimeAndTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime();
long oldDelta = mSharedPreference.getDeltaTimeBeetweenCurrentTimeAndTimeSinceReboot();
if(deltaTimeBeetweenCurrentTimeAndRebootTime - oldDelta > 5000){
    // clock time change
}
</code>```

Idea is I saved a delta between currently time (System.currentTimeMillis()) and time since reboot (SystemClock.elapsedRealtime()). Every time I open app, I will compare oldDelta and newDelta (except the first time install). It work well in case: User Fore Stop app->Change time->come back to app.

However, there is still have 1 case that is: User Fore Stop app -> Change the clock time -> Reboot device -> Open my app. At this time I can not use the above method to check the clock time have changed because after reboot the SystemClock.elapsedRealtime() will reset. How can I detect clock time have changed in that case?

Any help or suggestion would be great appreciate.

答:
Few months ago I was in pretty the same situation. I didn't find any answer to directly solve the case, so I won't help you with it. But I can give you kind of advice:

Look at it with a different point of view.

What I did in my case, I answered myself to questions:

"Do I really want to know that user has changed the time - because I implicitly inform/present the fact to user?"

OR

"Do I want to know that user has changed the time - because I need it to invoke some actions or calculations in the application background?"

In my case I had NO-YES answers. So, for problematic case of Force-Stop + reboot I assumed that the time could had been changed and I reset my application's time configuration likewise the first app launch.

Let me know if it helps you anyway.

Body:
I can detect change clock time when app in foreground, background, or kill from Recent App by using android.intent.action.TIME_SET follow here.

However, if I Force Stop app in Setting->Apps I can not receive this broadcast anymore.

Currently, I want to detect user change clock time come back to my app after ForceStop so I do

long deltaTimeBeetweenCurrentTimeAndTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime();
long oldDelta = mSharedPreference.getDeltaTimeBeetweenCurrentTimeAndTimeSinceReboot();
if(deltaTimeBeetweenCurrentTimeAndRebootTime - oldDelta > 5000){
    // clock time change
}

Idea is I saved a delta between currently time (System.currentTimeMillis()) and time since reboot (SystemClock.elapsedRealtime()). Every time I open app, I will compare oldDelta and newDelta (except the first time install). It work well in case: User Fore Stop app->Change time->come back to app.

However, there is still have 1 case that is: User Fore Stop app -> Change the clock time -> Reboot device -> Open my app. At this time I can not use the above method to check the clock time have changed because after reboot the SystemClock.elapsedRealtime() will reset. How can I detect clock time have changed in that case?

Any help or suggestion would be great appreciate.


问:
How to prevent user from navigating away?
In my SAPUI5 application I'm using a sap.tnt.Toolpage as the main layout container. The SideNavigation shows a list of application links and the mainContents is dynamically loaded using the sap.ui.core.routing.Router.

To navigate to a detail page I'm using

```<code>var router = sap.ui.core.UIComponent.getRouterFor(this);
router.navTo("MyDetailRoute", {
    detailItemId: oItem.getBindingContext("oDataSourceName").getProperty("DETAILID")
});
</code>```

This loads a detail view which then binds it's controls to the data from my data source.

The problem arises when I try to remember the user to save his changes back to the server. I basically want to interrup the navigation to aks the user if he'd like to a) Cancel his changes, b) Save his changes or c) Stay on the detail page. While a) and b) are easy to implement, I don't know how to prevent the navigation from happening.

I've tried so far by subscribing to onBeforeHide of my view:

```<code>var view = this.getView();
var that = this;
view.addEventDelegate({
    onBeforeHide: function (evt) {
        var oModel = that.getModel("oDataSourceName");
        if (oModel.hasPendingChanges()) {
            // How to prevent leaving the page?
        }
    }
});
</code>```

Things I've tried that are not working:

evt.preventDefault();

evt.stopPropagation();

throw 'something';

Option 3) actually prevents the navigation but leads to later problems because the URL will change nevertheless...

Does anyone have an idea?

Edit: Thanks to the answer from cschuff I was able to get it working. For anyone who has the same problem in the future:

```<code>// In onInit: Subscribe to onBeforeHide in order to un-register event handler for hashchange

onInit: function () {
    this.getRouter().getRoute("MyDetailRoute").attachPatternMatched(this.onNavigated, this);

    var view = this.getView();
    var that = this;

    view.addEventDelegate({
        onBeforeHide: function (evt) {
            $(window).off('hashchange');
        }
    });
}

// Then in onNavigate stoppen the router, saving the current window location and subscribing to hashchange (only once)
// In hashchange use helper variable m_bSelfURLSetting to prevent the function from running when triggered by URL restore (above)
// In the handler checking for pending changes and either resore the old URL or starting the router again if the user wants to quit or if there are no changes

onNavigated: function (oEvent) {

    this.getRouter().stop();
    this.m_strHref = window.location.href;
    var that = this;

    $(window).off('hashchange').on('hashchange', function (e) {
        if (that.m_bSelfURLSetting) {
            that.m_bSelfURLSetting = false;
            return;
        }

        var oModel = that.getModel("oDataSourceName");
        if (oModel.hasPendingChanges()) {
            var leave = confirm('There are unsaved changes.\r\n\r\nDo you really want to leave the page?');
            if (!leave) {
                // re-set the URL
                that.m_bSelfURLSetting = true;
                window.location.href = that.m_strHref;
            }
            else {
                that.getRouter().initialize(false);
                oModel.resetChanges();
            }
        } else {
            that.getRouter().initialize(false);
        }
    });
}
</code>```

This is definitively not the kind of code one is proud of...

答:
Solution #1: You could temporarily deactivate routing completely by using the Router methods stop and initialize. This will stop listening to changes in the url hash and thereby ignore all routing triggers.

From your controller:

```<code>var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.stop();

// later
// passing true will interpret and navigate to the current hash (since 1.48.0)
oRouter.initialize(true);
</code>```

Solution #2: Interrupt routing itself using sap.ui.core.routing.HashChanger events. hashChanged and hashReplaced are internally used by Router. You could also try if sap.ui.core.routing.Router routeMatched or beforeRouteMatched are cancelable (Docs are not giving any hint).

Solution #3: A less restrictive solution would be to just interrupt all actions that trigger routing from that particular view. Be aware that browser-back or changing the url-hash manually will still work here (the native JS events beforeunload and hashchange might help here).

BR Chris

Body:
In my SAPUI5 application I'm using a sap.tnt.Toolpage as the main layout container. The SideNavigation shows a list of application links and the mainContents is dynamically loaded using the sap.ui.core.routing.Router.

To navigate to a detail page I'm using

var router = sap.ui.core.UIComponent.getRouterFor(this);
router.navTo("MyDetailRoute", {
    detailItemId: oItem.getBindingContext("oDataSourceName").getProperty("DETAILID")
});

This loads a detail view which then binds it's controls to the data from my data source.

The problem arises when I try to remember the user to save his changes back to the server. I basically want to interrup the navigation to aks the user if he'd like to a) Cancel his changes, b) Save his changes or c) Stay on the detail page. While a) and b) are easy to implement, I don't know how to prevent the navigation from happening.

I've tried so far by subscribing to onBeforeHide of my view:

var view = this.getView();
var that = this;
view.addEventDelegate({
    onBeforeHide: function (evt) {
        var oModel = that.getModel("oDataSourceName");
        if (oModel.hasPendingChanges()) {
            // How to prevent leaving the page?
        }
    }
});

Things I've tried that are not working:

evt.preventDefault();

evt.stopPropagation();

throw 'something';

Option 3) actually prevents the navigation but leads to later problems because the URL will change nevertheless...

Does anyone have an idea?

Edit: Thanks to the answer from cschuff I was able to get it working. For anyone who has the same problem in the future:

// In onInit: Subscribe to onBeforeHide in order to un-register event handler for hashchange

onInit: function () {
    this.getRouter().getRoute("MyDetailRoute").attachPatternMatched(this.onNavigated, this);

    var view = this.getView();
    var that = this;

    view.addEventDelegate({
        onBeforeHide: function (evt) {
            $(window).off('hashchange');
        }
    });
}

// Then in onNavigate stoppen the router, saving the current window location and subscribing to hashchange (only once)
// In hashchange use helper variable m_bSelfURLSetting to prevent the function from running when triggered by URL restore (above)
// In the handler checking for pending changes and either resore the old URL or starting the router again if the user wants to quit or if there are no changes

onNavigated: function (oEvent) {

    this.getRouter().stop();
    this.m_strHref = window.location.href;
    var that = this;

    $(window).off('hashchange').on('hashchange', function (e) {
        if (that.m_bSelfURLSetting) {
            that.m_bSelfURLSetting = false;
            return;
        }

        var oModel = that.getModel("oDataSourceName");
        if (oModel.hasPendingChanges()) {
            var leave = confirm('There are unsaved changes.\r\n\r\nDo you really want to leave the page?');
            if (!leave) {
                // re-set the URL
                that.m_bSelfURLSetting = true;
                window.location.href = that.m_strHref;
            }
            else {
                that.getRouter().initialize(false);
                oModel.resetChanges();
            }
        } else {
            that.getRouter().initialize(false);
        }
    });
}

This is definitively not the kind of code one is proud of...

Body:
Solution #1: You could temporarily deactivate routing completely by using the Router methods stop and initialize. This will stop listening to changes in the url hash and thereby ignore all routing triggers.

From your controller:

var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.stop();

// later
// passing true will interpret and navigate to the current hash (since 1.48.0)
oRouter.initialize(true);

Solution #2: Interrupt routing itself using sap.ui.core.routing.HashChanger events. hashChanged and hashReplaced are internally used by Router. You could also try if sap.ui.core.routing.Router routeMatched or beforeRouteMatched are cancelable (Docs are not giving any hint).

Solution #3: A less restrictive solution would be to just interrupt all actions that trigger routing from that particular view. Be aware that browser-back or changing the url-hash manually will still work here (the native JS events beforeunload and hashchange might help here).

BR Chris


问:
Issue to resize element content properly
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>

<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1 With more text</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section></code>```

答:
As the h5 has a fixed height, that is the expected behavior.

Change to min-height: 44px; in the .card .front h5 rule

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    min-height: 44px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>

<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1 With more text</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section></code>```

Body:
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

Image 1

Abc

Image 1 With more text

Abc

Body:
As the h5 has a fixed height, that is the expected behavior.

Change to min-height: 44px; in the .card .front h5 rule

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    min-height: 44px;
}

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>

<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1 With more text</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>


问:
How to change views in android
Consider we have two Activies: Activity A and Activity B, both have an ImageView. If we click on ImageView in Activity A, ImageView in Activity B should change to another image. Please tell us, how to achieve this by using interface

Your timely suggestions will help us a lot

答: Send some info about the clicked image in Activity A to Activity B using Intent. Then based on that info show the corresponding image in Activity B

Title: How to change views in android


问:
Wordpress post page get 404 but Homepage works
I already red a lot about this problem, but non of the solutions helped me out. I installed a fresh Wordpress on my Apache. After changing the permalink structure from default (www.domain.com/?p=id) to another one, wordpress delivers me an 404 error for each page except the homepage.

I already checked the following:

mod_rewrite is installed and enabled (checked through phpinfo)

.htaccess is read- and writable

Here is my default .htaccess

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

Using the plugin "Debug this", I could also find out, that the rewrite rule always deliveres additional index.php? at the beginning. E.g. sitemap_index\.xml$ is rewrited as index.php?sitemap=1

What can I do so solve the problem? Default links like www.domain.com/?p=1 but that kills all my SEO.

Edit: After the installation, there was also /index.php/%postname% written in the custom permalink. But this setting is also returning a 404.

答: go to your permalink settings and change the permalink structure to "post name" and update your permalink structure. hope it will help.</p>

Body:
I already red a lot about this problem, but non of the solutions helped me out. I installed a fresh Wordpress on my Apache. After changing the permalink structure from default (www.domain.com/?p=id) to another one, wordpress delivers me an 404 error for each page except the homepage.

I already checked the following:

mod_rewrite is installed and enabled (checked through phpinfo)

.htaccess is read- and writable

Here is my default .htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Using the plugin "Debug this", I could also find out, that the rewrite rule always deliveres additional index.php? at the beginning. E.g. sitemap_index\.xml$ is rewrited as index.php?sitemap=1

What can I do so solve the problem? Default links like www.domain.com/?p=1 but that kills all my SEO.

Edit: After the installation, there was also /index.php/%postname% written in the custom permalink. But this setting is also returning a 404.


问:
Create django models from a CSV source
AdWords for some reason doesn't have a normal REST api, it uses instead a SOAP api which either returns a .csv file or recently a string.

I'm using django and I need to save results in my database. Currently I use Pandas to transfor the string to a dataframe, and then I iterate through it and save it in my database. However this process is slow and inefficient. I don't want to use pandas just for this. Would AST work in my situation?

What's the fastest way to do this?

My code with pandas looks like this:

```<code>abc = report_downloader.DownloadReportAsString(report, skip_report_header=True, skip_column_header=False,skip_report_summary=True)
print(abc)
print(type(abc))
df = pd.read_csv(StringIO(abc), sep=",",)
#print (df.to_string())

for index, row in df.iterrows():

    ctr = float(float(row['CTR'].strip('%')) / 100)
    conv_rate = float(float(row['Conv. rate'].strip('%')) / 100)
    cost = row['Cost']/1000000
    cpm = row['Avg. CPM']/1000000
    avg_cpc = row['Avg. CPC']/1000000
    def_data = {
                'impressions':row['Impressions'],
                'ctr':ctr,
                'avg_cpc':avg_cpc,
                'conversion_rate':conv_rate,
                'clicks':row['Clicks'],
                'cost':cost,
                'cpm':cpm,
                'conversions':row['Conversions'],
                }

    obj, created = AdWordsData.objects.get_or_create(
                                                    user=user,
                                                    date=row['Day'],
                                                    campaign=row['Campaign'],
                                                    ad_group=row['Ad group'],
                                                    final_url=row['Final URL'],
                                                    tracking_template=row['Tracking template'],
                                                    defaults=def_data,
                                                    )

    if not created:
        obj.__dict__.update(**def_data)
        obj.save()

else:
    print ('No campaigns were found.')
</code>```

ABC (the data return by adwords is a string and looks like this:

```<code>Day,Campaign,Ad group,Final URL,Tracking template,Impressions,CTR,Avg. CPC,Conv. rate,Clicks,Cost,Avg. CPM,Conversions
2017-09-08,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,364,0.82%,73333,0.00%,3,220000,604396,0.00
2017-09-10,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,1562,3.46%,435926,0.00%,54,23540000,15070423,0.00
2017-09-11,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,1806,3.49%,387619,0.00%,63,24420000,13521595,0.00
</code>```

答:
Using pandas to load a csv is indeed overkill I guess.
You could iterate over you csv lines using basic python.

Or better, you could use an existing django library that allow you to create a list of django model from a csv file / input. Ex: django import-export

```<code>>>> import tablib
>>> from import_export import resources
>>> from core.models import Book
>>> book_resource = resources.modelresource_factory(model=Book)()
>>> dataset = tablib.Dataset(['', 'New book'], headers=['id', 'name'])
>>> result = book_resource.import_data(dataset, dry_run=True)
>>> print result.has_errors()
False
>>> result = book_resource.import_data(dataset, dry_run=False)
</code>```

Title: Create django models from a CSV source

Body:
AdWords for some reason doesn't have a normal REST api, it uses instead a SOAP api which either returns a .csv file or recently a string.

I'm using django and I need to save results in my database. Currently I use Pandas to transfor the string to a dataframe, and then I iterate through it and save it in my database. However this process is slow and inefficient. I don't want to use pandas just for this. Would AST work in my situation?

What's the fastest way to do this?

My code with pandas looks like this:

abc = report_downloader.DownloadReportAsString(report, skip_report_header=True, skip_column_header=False,skip_report_summary=True)
print(abc)
print(type(abc))
df = pd.read_csv(StringIO(abc), sep=",",)
#print (df.to_string())

for index, row in df.iterrows():

    ctr = float(float(row['CTR'].strip('%')) / 100)
    conv_rate = float(float(row['Conv. rate'].strip('%')) / 100)
    cost = row['Cost']/1000000
    cpm = row['Avg. CPM']/1000000
    avg_cpc = row['Avg. CPC']/1000000
    def_data = {
                'impressions':row['Impressions'],
                'ctr':ctr,
                'avg_cpc':avg_cpc,
                'conversion_rate':conv_rate,
                'clicks':row['Clicks'],
                'cost':cost,
                'cpm':cpm,
                'conversions':row['Conversions'],
                }

    obj, created = AdWordsData.objects.get_or_create(
                                                    user=user,
                                                    date=row['Day'],
                                                    campaign=row['Campaign'],
                                                    ad_group=row['Ad group'],
                                                    final_url=row['Final URL'],
                                                    tracking_template=row['Tracking template'],
                                                    defaults=def_data,
                                                    )

    if not created:
        obj.__dict__.update(**def_data)
        obj.save()

else:
    print ('No campaigns were found.')

ABC (the data return by adwords is a string and looks like this:

Day,Campaign,Ad group,Final URL,Tracking template,Impressions,CTR,Avg. CPC,Conv. rate,Clicks,Cost,Avg. CPM,Conversions
2017-09-08,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,364,0.82%,73333,0.00%,3,220000,604396,0.00
2017-09-10,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,1562,3.46%,435926,0.00%,54,23540000,15070423,0.00
2017-09-11,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,1806,3.49%,387619,0.00%,63,24420000,13521595,0.00

Body:
Using pandas to load a csv is indeed overkill I guess.
You could iterate over you csv lines using basic python.

Or better, you could use an existing django library that allow you to create a list of django model from a csv file / input. Ex: django import-export

>>> import tablib
>>> from import_export import resources
>>> from core.models import Book
>>> book_resource = resources.modelresource_factory(model=Book)()
>>> dataset = tablib.Dataset(['', 'New book'], headers=['id', 'name'])
>>> result = book_resource.import_data(dataset, dry_run=True)
>>> print result.has_errors()
False
>>> result = book_resource.import_data(dataset, dry_run=False)


问:
How to use FIND() for a MongoDB query on a MVC .net C# project
I'm connecting a MongoDB (Azure) with a MVC .NET C# project. The connection and object definition are working very good so far. My problem is when I try to add the method FIND() to return all the data in the object USER.

My Model:

```<code>using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace backendnet.Models
{
    public class MongoCore
    {
        public class DB
        {
            static MongoClient Client = new MongoClient("mongodb://mydbconnect");
            static public IMongoDatabase Database = Client.GetDatabase("mydb");
            static public IMongoCollection<User> Users = Database.GetCollection<User>("users");
        }

        public class User
        {
            [BsonId]
            public ObjectId Id { get; set; }
            [BsonElement("email")]
            public string Email { get; set; }
            [BsonElement("password")]
            public string Password { get; set; }
            [BsonElement("name")]
            public List<DimensionName> Name { get; set; }
            [BsonElement("address")]
            public List<DimensionAddress> Address { get; set; }
            [BsonElement("permissions")]
            public List<DimensionPermissions> Permissions { get; set; }
            [BsonElement("status")]
            public string Status { get; set; }
            [BsonElement("created")]
            public string Created { get; set; }
            [BsonElement("updated")]
            public string Updated { get; set; }
        }

        public class DimensionName
        {
            [BsonElement("first")]
            public string First { get; set; }
            [BsonElement("last")]
            public string Last { get; set; }
        }

        public class DimensionAddress
        {
            [BsonElement("stree")]
            public string Stree { get; set; }
            [BsonElement("number")]
            public string Number { get; set; }
            [BsonElement("city")]
            public string City { get; set; }
            [BsonElement("state")]
            public string State { get; set; }
            [BsonElement("zipcode")]
            public string Zipcode { get; set; }
            [BsonElement("type")]
            public string Type { get; set; }
        }

        public class DimensionPermissions
        {
            [BsonElement("list")]
            public string List { get; set; }
            [BsonElement("create")]
            public string Create { get; set; }
            [BsonElement("edit")]
            public string Edit { get; set; }
            [BsonElement("delete")]
            public string Delete { get; set; }
        }
    }
}
</code>```

My Controller:

```<code>using System;
using System.Collections.Generic;
using System.Web.Mvc;
using backendnet.Models;
using MongoDB.Bson;

namespace backendnet.Controllers
{
    public class DashboardController : Controller
    {
        private string _viewFolder = "../Admin/Dashboard";

        public ActionResult Index()
        {
            var results = new MongoCore.DB();
            ViewData["ListPost"] = results.ToJson();

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

My View partial:

```<code><p>HERE: @ViewData["ListPost"]</p>
</code>```

I get this:

HERE: { }

So I tried adding in the Model -> DB the method Find:

```<code>MongoCursor<User> cursor = Users.Find("Email" != "");
</code>```

But always show an error:

Expression is always 'true' ["Email" != ""]

May anyone show me what I'm missing here?

答:
```<code>public ActionResult GetUsers()
{
 MongoServer objServer = MongoServer.Create("Server=localhost:27017");
 MongoDatabase objDatabse = objServer.GetDatabase("DBName");
 List UserDetails = objDatabse.GetCollection("Colletion_Name").FindAll().ToList();
 return View(UserDetails);
}
</code>```

Body:
I'm connecting a MongoDB (Azure) with a MVC .NET C# project. The connection and object definition are working very good so far. My problem is when I try to add the method FIND() to return all the data in the object USER.

My Model:

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace backendnet.Models
{
    public class MongoCore
    {
        public class DB
        {
            static MongoClient Client = new MongoClient("mongodb://mydbconnect");
            static public IMongoDatabase Database = Client.GetDatabase("mydb");
            static public IMongoCollection<User> Users = Database.GetCollection<User>("users");
        }

        public class User
        {
            [BsonId]
            public ObjectId Id { get; set; }
            [BsonElement("email")]
            public string Email { get; set; }
            [BsonElement("password")]
            public string Password { get; set; }
            [BsonElement("name")]
            public List<DimensionName> Name { get; set; }
            [BsonElement("address")]
            public List<DimensionAddress> Address { get; set; }
            [BsonElement("permissions")]
            public List<DimensionPermissions> Permissions { get; set; }
            [BsonElement("status")]
            public string Status { get; set; }
            [BsonElement("created")]
            public string Created { get; set; }
            [BsonElement("updated")]
            public string Updated { get; set; }
        }

        public class DimensionName
        {
            [BsonElement("first")]
            public string First { get; set; }
            [BsonElement("last")]
            public string Last { get; set; }
        }

        public class DimensionAddress
        {
            [BsonElement("stree")]
            public string Stree { get; set; }
            [BsonElement("number")]
            public string Number { get; set; }
            [BsonElement("city")]
            public string City { get; set; }
            [BsonElement("state")]
            public string State { get; set; }
            [BsonElement("zipcode")]
            public string Zipcode { get; set; }
            [BsonElement("type")]
            public string Type { get; set; }
        }

        public class DimensionPermissions
        {
            [BsonElement("list")]
            public string List { get; set; }
            [BsonElement("create")]
            public string Create { get; set; }
            [BsonElement("edit")]
            public string Edit { get; set; }
            [BsonElement("delete")]
            public string Delete { get; set; }
        }
    }
}

My Controller:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using backendnet.Models;
using MongoDB.Bson;

namespace backendnet.Controllers
{
    public class DashboardController : Controller
    {
        private string _viewFolder = "../Admin/Dashboard";

        public ActionResult Index()
        {
            var results = new MongoCore.DB();
            ViewData["ListPost"] = results.ToJson();

            return View (_viewFolder);
        }
    }
}

My View partial:

HERE: @ViewData["ListPost"]

I get this:

HERE: { }

So I tried adding in the Model -> DB the method Find:

MongoCursor<User> cursor = Users.Find("Email" != "");

But always show an error:

Expression is always 'true' ["Email" != ""]

May anyone show me what I'm missing here?


问:
R regular expression for p#q#c#
What would the regular expression be to encompass variable names such as p3q10000c150 and p29q2990c98? I want to add all variables in the format of p-any number-q-any number-c-any number to a list in R.

Thanks!

Title: R regular expression for p#q#c#

Body:
Try:

x <- c("p3q10000c150", "p29q2990c98")

sapply(strsplit(x, "[pqc]"), function(i){
  setNames(as.numeric(i[-1]), c("p", "q", "c"))
  })

#    [,1] [,2]
# p     3   29
# q 10000 2990
# c   150   98


问:
Could not set proper JBOSS_HOME directory in Jenkins
I'm just starting with Jenkins. I'm trying to set JBoss Management Builder (unless I do not need this plugin to control deployment on WildFly?) and Jenkins do not want to accept my JBOSS_HOME dir.
My home dir is:

```<code>/home/opt/wildfly-10.1.0.Final/
</code>```

I have also tried:

```<code>/home/opt/wildfly-10.1.0.Final/bin/
/home/opt/wildfly-10.1.0.Final/standalone/
/home/opt/wildfly-10.1.0.Final/standalone/configuration/
/home/opt/wildfly-10.1.0.Final/standalone/configuration/standalone.xml
</code>```

All of this tries have ended with an error:
"It's not look like correct JBoss home directory"

答:
I think it's unlikely that the JBoss Management Builder plugin will work with Wildfly.

Its latest release is from 2011 as written on the plugin page. Plus the source code where the error is coming from is looking for two folders explicitly in your JBOSS_HOME: "bin" and "server". And "server" is just not there in Wildfly.

I think you have to find other ways to interact with Wildfly.

Body:
I'm just starting with Jenkins. I'm trying to set JBoss Management Builder (unless I do not need this plugin to control deployment on WildFly?) and Jenkins do not want to accept my JBOSS_HOME dir.
My home dir is:

/home/opt/wildfly-10.1.0.Final/

I have also tried:

/home/opt/wildfly-10.1.0.Final/bin/
/home/opt/wildfly-10.1.0.Final/standalone/
/home/opt/wildfly-10.1.0.Final/standalone/configuration/
/home/opt/wildfly-10.1.0.Final/standalone/configuration/standalone.xml

All of this tries have ended with an error:
"It's not look like correct JBoss home directory"


问:
Apply different style to last x characters of input field
I am faced with a task as of current I am not sure on how to complete. Essentially, is there any way I could go about getting the last x characters of an  field to display differently from the rest of the field?

Something to the effect of this, assuming this was a typed input into an <input> field:
"TheLast6LettersOfThisShouldBeBigger"

That would be the intended effect. The only potential approach I could think of for completing this is to use two separate input fields and always have the last x characters in the second input styled differently. This would, however, provide problems with user interaction (backspacing at the front of the second input field would result in no previous character being deleted).

Any ideas or thoughts?

Update: I forget to mention before, this is intended to be a dynamic thing as the user is typing.

答:
I asked you in a comment to your question, when do you want the last 5 letters to get bold . You gave me no answer so i made an example where when you hover out of the input, the last 5 letters get bold.

You can change the mouseout event

Basically i made a contentEditable div and styled like an input ( you can change the styles ) and edit that div's contents. The input ( for you to be able to submit the values ) is hidden and  will have the value the same as the contentEditable div's text.

$("div").mouseout(function() {
  var inputText = $(this).text()
  $("input").val(inputText)
  var lastFive = inputText.substr(inputText.length - 5)
  var firstLetters = inputText.substr(0, inputText.length - 5)

    $(this).html(firstLetters + "" + lastFive + "");

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 1px solid grey;
  width: 200px;
  height: 20px;
  padding: 2px 3px;
  overflow: hidden;
}</code>```

<input type="hidden">```

Body:
I asked you in a comment to your question, when do you want the last 5 letters to get bold . You gave me no answer so i made an example where when you hover out of the input, the last 5 letters get bold.

You can change the mouseout event

Basically i made a contentEditable div and styled like an input ( you can change the styles ) and edit that div's contents. The input ( for you to be able to submit the values ) is hidden and  will have the value the same as the contentEditable div's text.

$("div").mouseout(function() {
  var inputText = $(this).text()
  $("input").val(inputText)
  var lastFive = inputText.substr(inputText.length - 5)
  var firstLetters = inputText.substr(0, inputText.length - 5)

    $(this).html(firstLetters + "<strong>" + lastFive + "</strong>");

})

div {
  border: 1px solid grey;
  width: 200px;
  height: 20px;
  padding: 2px 3px;
  overflow: hidden;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable>

</div>
<input type="hidden">


问:
C# - How to Italicise a words within a string resource
I'm writing a WPF application and I need to italicise words within descriptions on my view while still having them within resources to provide multi-lingual support later on. These descriptions are resourced and pass through a director that matches the descriptions in the view model by their code to their appropriate placement.

What I have tried:

I've begun resourcing the words of importance separately and added placeholder codes within the description resources. I then wanted to insert the words of importance into the description strings as they pass through the director but I can't italicise them at this stage either as they're just strings! How can i do achieve this?

答:
If your resources will be consumed by a TextBlock you have to separate the text into separate inlines.

E.g.:
The text you want to show is This is an italic, bold and underlinded text.
This string need to be split up into separate parts for your resource file like the following:

Res1: This is an

Res2: italic

Res3: ,

Res4: bold

Res5: and

Res6: underlined

Res7: text

Your XAML then should look like the following:

```<code><TextBlock FontSize="14">
    <Run Text="{x:Static p:Resources.Res1}" />
    <Run Text="{x:Static p:Resources.Res2}" FontStyle="Italic" />
    <Run Text="{x:Static p:Resources.Res3}" />
    <Run Text="{x:Static p:Resources.Res4}" FontWeight="Bold" />
    <Run Text="{x:Static p:Resources.Res5}" />
    <Run Text="{x:Static p:Resources.Res6}" TextDecorations="Underline" />
    <Run Text="{x:Static p:Resources.Res7}" />
</TextBlock>
</code>```

This results in the following format:

Body:
If your resources will be consumed by a TextBlock you have to separate the text into separate inlines.

E.g.:
The text you want to show is This is an italic, bold and underlinded text.
This string need to be split up into separate parts for your resource file like the following:

Res1: This is an

Res2: italic

Res3: ,

Res4: bold

Res5: and

Res6: underlined

Res7: text

Your XAML then should look like the following:

<TextBlock FontSize="14">
    <Run Text="{x:Static p:Resources.Res1}" />
    <Run Text="{x:Static p:Resources.Res2}" FontStyle="Italic" />
    <Run Text="{x:Static p:Resources.Res3}" />
    <Run Text="{x:Static p:Resources.Res4}" FontWeight="Bold" />
    <Run Text="{x:Static p:Resources.Res5}" />
    <Run Text="{x:Static p:Resources.Res6}" TextDecorations="Underline" />
    <Run Text="{x:Static p:Resources.Res7}" />
</TextBlock>

This results in the following format:


问:
IPFS: How to add a file to an existing folder?
Given a rather large folder, that has already been pushed to the network, and deleted locally. How would a file be added to that folder, without re-downloading the entire folder it?</p>

答:
This should be easy with the files API. Assuming you have already added the new file to ipfs and obtained its hash, try:

```<code>ipfs files cp /ipfs/QmExistingLargeFolderHash /folder-to-modify
ipfs files cp /ipfs/QmNewFileHash /folder-to-modify/new-file
</code>```

This of course does not add a file to an existing folder (because folders and files are immutable), it just creates a copy/new version of the folder with a new file added. Hence, it will have a new hash:

```<code>ipfs files stat /folder-to-modify
</code>```

The files API does not pin the files that are referenced or retrieve any subfolders unless necessary, so this can be done on any node in the network without incurring lots of traffic.

[Edit]
A while later, I learn that there are a few more things you can do:

Instead of

```<code>ipfs files cp /ipfs/QmNewFileHash /folder-to-modify/new-file
</code>```

you can use ipfs files write -te if you haven't added the file to ipfs yet.

You can enable write features of the HTTP API to use PUT requests to obtain hashes of new versions of a folder. See this blogpost.

You can mount ipns via fuse and write to …/ipns/local.

And probably best: you can use ipfs object patch add-link /ipfs/QmExistingLargeFolderHash new-file /ipfs/QmNewFileHash to do it in one step

Body:
This should be easy with the files API. Assuming you have already added the new file to ipfs and obtained its hash, try:

ipfs files cp /ipfs/QmExistingLargeFolderHash /folder-to-modify
ipfs files cp /ipfs/QmNewFileHash /folder-to-modify/new-file

This of course does not add a file to an existing folder (because folders and files are immutable), it just creates a copy/new version of the folder with a new file added. Hence, it will have a new hash:

ipfs files stat /folder-to-modify

The files API does not pin the files that are referenced or retrieve any subfolders unless necessary, so this can be done on any node in the network without incurring lots of traffic.

[Edit]
A while later, I learn that there are a few more things you can do:

Instead of

ipfs files cp /ipfs/QmNewFileHash /folder-to-modify/new-file

you can use ipfs files write -te if you haven't added the file to ipfs yet.

You can enable write features of the HTTP API to use PUT requests to obtain hashes of new versions of a folder. See this blogpost.

You can mount ipns via fuse and write to …/ipns/local.

And probably best: you can use ipfs object patch add-link /ipfs/QmExistingLargeFolderHash new-file /ipfs/QmNewFileHash to do it in one step

ContentLicense: CC BY-SA 4.0


问:
Video training program
I am looking to create a video training program which records videos - via webcam, user screen capture and captures sound. Now the main problem is that I need a cross-platform (mac and windows) solutions.

I know its possible to use flash to record webcam + audio. But its not possible to record the user's screen via flash.

So am wonder if I should use Java (which i believe will work on mac & windows). I do not want to develop to separate versions because of the cost involved in developing two versions.

Please guide me as I am new to this.

Thank you.

UPDATE

Hello again,

I had a look at the following site: www.screencast-o-matic.com or www.screentoaster.com. I see that they have developed a java applet which helps interact with Windows/Mac to record the screen.

I am wondering how to go about developing something like that and integrating it with Flash (for webcam and audio recording).

Is this a better idea?

答:
This is by no means a simple project. Lets get that said and out the way. There are open source (and cross-platform) options for each element, but nothing (I know of) that will do everything for you.

I think the "cleanest" option would be to use Flash for webcam and audio, as you said, and run a VNC server to send the screen video... The only closed-platform code will be the VNC launching code. That should be pretty simple to maintain!

That raises a problem because most people are behind NAT firewalls these days. Setting up port forwarding is a pain in the behind. I've used an app called Gitso before which allows people to connect to me and send their desktop to my screen (for tech support). Its VNC-based and all it really does is add another layer on top of the VNC connection so rather than me connecting to them, they connect to me. That makes the whole business of port forwarding a non-issue.

And once you've recorded everything, there's the final issue of syncing it all back together... Might not be so hard.

OwnerDisplayName: Alec Smart

Title: Video training program

LastEditorDisplayName: Alec Smart

OwnerDisplayName: Oli


问:
Actionscript 3 'this' question
Could someone point out why does the following code fail in the first case:

CASE 1

```<code>// In a constructor
this.gallery = new Gallery();
addChild(this.gallery);

this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // When this callback fires, there is a fail:
    // because there is no 'this.gallery'.
    this.gallery.someAction();
});
</code>```

CASE 2

```<code>this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // This works fine
    gallery.someAction();
})
</code>```

Are there any rules regarding this usage in such cases?

答:
This is because of the "scope chain".  In ActionScript 3 (which is ECMAScript compliant -- JavaScript has the same behavior described below), there is a built-in list of "places" that is used to resolve any named variable, called the scope chain.  E.g. when in a "normal" method of a class, the scope chain looks like this:

The current instance object (the same as this)

The class object (used for accessing static variables)

The global scope (used for accessing globals, e.g. Math)

But when you are in an anonymous inner function, the scope chain has one more entry at the top, representing the method that was in scope at the point in the time when the anonymous function was created.  So for example, suppose you have this code:

```<code>class C {
    var membervar:int;

    function f() {
        var localvar:int;

        var innerfunc:Function = function() {
            // what is on the scopechain here?
        };

        innerfunc();
    }
}
</code>```

In this case, when you are the the line that says "what is on the scopechain here", the scopechain looks like this (with the first scope below being the first place that will be checked):

One instance of the function f(), with variables localvar and innerfunc

The current instance of class C

The class C

The global scope

It's important to realize that that when the line of code var innerfunc:Function = function()... executes, it is creating the Function object on the fly, and setting its scope chain on the fly.  So for example, suppose you had this (confusing) code, which, given an argument an_arg, returns a Function which, when invoked, will print the value of an_arg:

```<code>function f(an_arg:int):Function {
    return function():void {
        trace(an_arg);
    }
}
</code>```

Each function returned by calls to f() has its own scope chain, pointing to different instances of f().  So:

```<code>var func1:Function = f(3);
var func2:Function = f(4);

func1(); // prints 3
func2(); // prints 4
</code>```

The common way to avoid this problem, if you really want to refer to this in the inner function rather than relying on the magic of the scope chain, is to create a temporary variable called self in the outer function -- in the case of your sample code, it would look like this:

```<code>var self = this;
this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // This works fine
    self.gallery.someAction();
})
</code>```

I could go on forever on this subject -- I find it fascinating :-)

Title: Actionscript 3 'this' question

Body:
Could someone point out why does the following code fail in the first case:

CASE 1

// In a constructor
this.gallery = new Gallery();
addChild(this.gallery);

this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // When this callback fires, there is a fail:
    // because there is no 'this.gallery'.
    this.gallery.someAction();
});

CASE 2

this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // This works fine
    gallery.someAction();
})

Are there any rules regarding this usage in such cases?

Body:
This is because of the "scope chain".  In ActionScript 3 (which is ECMAScript compliant -- JavaScript has the same behavior described below), there is a built-in list of "places" that is used to resolve any named variable, called the scope chain.  E.g. when in a "normal" method of a class, the scope chain looks like this:

The current instance object (the same as this)

The class object (used for accessing static variables)

The global scope (used for accessing globals, e.g. Math)

But when you are in an anonymous inner function, the scope chain has one more entry at the top, representing the method that was in scope at the point in the time when the anonymous function was created.  So for example, suppose you have this code:

class C {
    var membervar:int;

    function f() {
        var localvar:int;

        var innerfunc:Function = function() {
            // what is on the scopechain here?
        };

        innerfunc();
    }
}

In this case, when you are the the line that says "what is on the scopechain here", the scopechain looks like this (with the first scope below being the first place that will be checked):

One instance of the function f(), with variables localvar and innerfunc

The current instance of class C

The class C

The global scope

It's important to realize that that when the line of code var innerfunc:Function = function()... executes, it is creating the Function object on the fly, and setting its scope chain on the fly.  So for example, suppose you had this (confusing) code, which, given an argument an_arg, returns a Function which, when invoked, will print the value of an_arg:

function f(an_arg:int):Function {
    return function():void {
        trace(an_arg);
    }
}

Each function returned by calls to f() has its own scope chain, pointing to different instances of f().  So:

var func1:Function = f(3);
var func2:Function = f(4);

func1(); // prints 3
func2(); // prints 4

The common way to avoid this problem, if you really want to refer to this in the inner function rather than relying on the magic of the scope chain, is to create a temporary variable called self in the outer function -- in the case of your sample code, it would look like this:

var self = this;
this.gallery.addEventListener(GalleryEvent.WHATEVER, function(event:*) {
    // This works fine
    self.gallery.someAction();
})

I could go on forever on this subject -- I find it fascinating :-)