问:
What is the minimum functionality needed to create Shell Replacement for Windows?
As you know we can change Windows Shell by changing Shell key in
    HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon

I create simple AutoHotKey script, compile it to cgywin.exe, and implement the basic WIN+R, WIN+E etc. What I targeted is  a windows environment where there is no taskbar, a fullscreen Cygwin Console and emacs inside it. I found that simple AutoHotkey suffice me

Here is the AutoHotKey script (compiled to cygwin.exe)

```<code>
Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
Run C:\Development\Tools\Fun\xeyes.exe
run c:\Program Files\Digsby\digsby.exe
#h::
    run rundll32.exe powrprof.dll,SetSuspendState Hibernate
    return
#w::
    ifWinExist "@Gameloft:)"
    {
        WinActivate
    }else{
        run e:\Data\vs.net\At Gameloft\At Gameloft\At Gameloft\bin\Release\At Gameloft.exe
        WinWait "@Gameloft:)"
        WinActivate
    }
    return
#y::
    run c:\Program Files\Digsby\digsby.exe
    return
#f::
    run firefox
    return
#t::
        run thunderbird
        return
#c::
        Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
    return
#r::
    DllCall(DllCall("GetProcAddress", "Uint", DllCall("GetModuleHandle", "str", "shell32"), "Uint", 61), "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0)
    return
#g::
    run chrome
    return
#e::
    run c:\Program Files\zabkat\xplorer2_lite\xplorer2_lite.exe
    return
#^e::
    run explorer
    return
#d::
    WinSet, Style, -0xC00000, A
    WinMaximize, A
    return
</code>
```

But I realize that certain shell function is missing. Such as when I download using Chrome, I can' use "Open Folder" menu for the downloaded file. It seems like somehow the shell provide those functionality.

What is the most basic stuff that must be implemented to create a suffice Shell Replacement??

Thank you!

答:
What you describe is the phenomenon that no process is associated to the default protocol of a simple filename or path. For example, Chrome probably tries to start C:\Users\You\Downloads as a process. However, since you replaced the default shell, no executable is associated with that behavior.

I am unaware whether AutoHotKey can handle plain arguments passed it, however.

Body:
As you know we can change Windows Shell by changing Shell key in
    HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon

I create simple AutoHotKey script, compile it to cgywin.exe, and implement the basic WIN+R, WIN+E etc. What I targeted is  a windows environment where there is no taskbar, a fullscreen Cygwin Console and emacs inside it. I found that simple AutoHotkey suffice me

Here is the AutoHotKey script (compiled to cygwin.exe)

Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
Run C:\Development\Tools\Fun\xeyes.exe
run c:\Program Files\Digsby\digsby.exe
#h::
    run rundll32.exe powrprof.dll,SetSuspendState Hibernate
    return
#w::
    ifWinExist "@Gameloft:)"
    {
        WinActivate
    }else{
        run e:\Data\vs.net\At Gameloft\At Gameloft\At Gameloft\bin\Release\At Gameloft.exe
        WinWait "@Gameloft:)"
        WinActivate
    }
    return
#y::
    run c:\Program Files\Digsby\digsby.exe
    return
#f::
    run firefox
    return
#t::
        run thunderbird
        return
#c::
        Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
    return
#r::
    DllCall(DllCall("GetProcAddress", "Uint", DllCall("GetModuleHandle", "str", "shell32"), "Uint", 61), "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0)
    return
#g::
    run chrome
    return
#e::
    run c:\Program Files\zabkat\xplorer2_lite\xplorer2_lite.exe
    return
#^e::
    run explorer
    return
#d::
    WinSet, Style, -0xC00000, A
    WinMaximize, A
    return

But I realize that certain shell function is missing. Such as when I download using Chrome, I can' use "Open Folder" menu for the downloaded file. It seems like somehow the shell provide those functionality.

What is the most basic stuff that must be implemented to create a suffice Shell Replacement??

Thank you!


来源: stackexchange

问:
redux-persist: How to save state on browser's local storage?
I am learning redux and wanted to know how can I save the state locally so when I refresh after making some changes to state it remains. I came to know about redux-persist and saw the github doc describing how to use it but its not very clear to me.

Here is the index.js code of my app -

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('#container'));
</code>```

How can I achieve it ?

答:
```<code>//In your createStore have this code
import { applyMiddleware, compose, createStore } from 'redux'
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer from '../reducers';
import { persistReducer } from 'redux-persist'
import localForage from 'localforage';
const loggerMiddleware = createLogger();

export default (initialState = {}) => {
  // ======================================================
  // Middleware Configuration
  // ======================================================
  const middleware = [thunkMiddleware, loggerMiddleware]

  // ======================================================
  // Store Enhancers
  // ======================================================

  const enhancers = []
  const __DEV__ = process.env.NODE_ENV !== 'production';
  if (__DEV__) {
    const devToolsExtension = window.devToolsExtension
    if (typeof devToolsExtension === 'function') {
      enhancers.push(devToolsExtension())
    }
  }

  // ======================================================
  // Store Instantiation and HMR Setup
  // ======================================================
  let config = {
    key: 'root',
    storage: localForage,
    whitelist: ['user'],
    debug: __DEV__
  }
  let configureReducer = persistReducer(config, rootReducer)
  const store = createStore(
    configureReducer,
    initialState,
    compose(
      applyMiddleware(...middleware),
      ...enhancers
    ),
  )

  return store
}

// In your App.js or root app, do this in your componentDidMount

persistStore(
      store,
      undefined,
      () => {
        console.log('callback::')
      }
    )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am learning redux and wanted to know how can I save the state locally so when I refresh after making some changes to state it remains. I came to know about redux-persist and saw the github doc describing how to use it but its not very clear to me.

Here is the index.js code of my app -

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('#container'));

How can I achieve it ?


问:
mysql order by custom field with and list also these fields which are missing in custom list
I would like to make a query for mysql:

```<code>select field1, count(*) as c
from temporary table
group by field1
order by field(field1, 'XXX', 'YYY', 'ZZZ')
</code>```

so this makes a nice group i.e.:

```<code>XXX  ZZZ

454  321
</code>```

But, if there isn't any YYY values, because count(*) for YYY "returns 0", this is not listed like the XXX and ZZZ and should not be skipped because empty (or null) fields.

but I would like this output:

```<code>XXX  YYY  ZZZ

454    0  321
</code>```

is that possible only in mysql?

Thanks a lot in advance!

答:
Don't use SELECT * but the list of your fields SELECT fields, fields1, fields2
If your result is NULL or 0 you will have your column</p>

Body:
I would like to make a query for mysql:

select field1, count(*) as c
from temporary table
group by field1
order by field(field1, 'XXX', 'YYY', 'ZZZ')

so this makes a nice group i.e.:

XXX  ZZZ

454  321

But, if there isn't any YYY values, because count(*) for YYY "returns 0", this is not listed like the XXX and ZZZ and should not be skipped because empty (or null) fields.

but I would like this output:

XXX  YYY  ZZZ

454    0  321

is that possible only in mysql?

Thanks a lot in advance!


问:
from table database to gridview and opposite
```<code>private void BindPrimaryGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    string query = "select * from Land";
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter(query, con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gridview2.DataSource = dt;
    gridview2.DataBind();
}
</code>```

which gets the values from Land and transfer them to the gridview2. I would like to do the opposite. From the gridview2.DataSource i want to insert the values in Land. How can i do that? Thank you

答:
http://www.vbforums.com/showthread.php?t=474895

//If DataSource of GridView1 is a DataTable

DataTable dt = (DataTable)GridView1.DataSource;

//If DataSource of GridView1 is a DataView

DataView dv = (DataView)GridView1.DataSource;

ContentLicense: CC BY-SA 2.5

Body:
private void BindPrimaryGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    string query = "select * from Land";
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter(query, con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gridview2.DataSource = dt;
    gridview2.DataBind();
}

which gets the values from Land and transfer them to the gridview2. I would like to do the opposite. From the gridview2.DataSource i want to insert the values in Land. How can i do that? Thank you


问:
javascript: left-merge two objects using EcmaScript 6 / immutable js
I work in javascript Project.

I'm now about search after option to merge two objects, as the second object will only ovveride fields of the first object and not add new fields which the second not has.

Something like:

```<code>const firstObj = {name:'jon', age:'6}
const secondObj = {name:'nir', mark:'100%'}

const mergedObj = leftMerge(firstObj, secondObj);
</code>```

So I like mergedObj to be:

```<code>{name:'nir', age:'6'}
</code>```

Is I have any way to do that with javascript (I worl with EcmaScript 6), or with immutable.js library?

答:
Iterate firstObj keys, and take the values from secondObj if it has those properties, if not take the values from firstObj:

const firstObj = {name:'jon', age:'6'}
const secondObj = {name:'nir', mark:'100%'}

const leftMerge = (a, b) => Object.keys(a).reduce((r, key) => (r[key] = (key in b ? b : a)[key], r), {});

const mergedObj = leftMerge(firstObj, secondObj);

console.log(mergedObj);```

Body:
I work in javascript Project.

I'm now about search after option to merge two objects, as the second object will only ovveride fields of the first object and not add new fields which the second not has.

Something like:

const firstObj = {name:'jon', age:'6}
const secondObj = {name:'nir', mark:'100%'}

const mergedObj = leftMerge(firstObj, secondObj);

So I like mergedObj to be:

{name:'nir', age:'6'}

Is I have any way to do that with javascript (I worl with EcmaScript 6), or with immutable.js library?


问:
Bootstrap navbar-right not working on fix-top
I want the nav links aligned right of the nav bar. However my nav links are showing up next to the logo on the left. Any ideas?

Here is my code:

```<code><nav class="navbar navbar-expand-md navbar-light fixed-top bg-light white-bg purple-top-strip">
    <div class="container">
      <a class="navbar-brand" href="#"><img src="images/presitskillsbank-logo.png" width="102" height="40" alt=""/></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse navbar-right" id="navbarCollapse">
        <ul class="nav navbar-nav navbar-right">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled" href="#">Disabled</a>
          </li>
        </ul>

      </div>
    </div>
    </nav>
</code>```

答:
You made some mistakes the way you structured HTML, this would work in bootstrap 3, but in bootstrap 4 it will not.

Here is example of code that would work in bootstrap 4:

```<code><nav class="navbar navbar-light navbar-expand-md bg-faded justify-content-center">
    <a href="/" class="navbar-brand d-flex w-50 mr-auto">Brand</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar3">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse" id="collapsingNavbar3">
        <ul class="nav navbar-nav ml-auto w-100 justify-content-end">
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
        </ul>
    </div>
</nav>
</code>```

Here is JSBin with example http://jsbin.com/pagigugelo/edit?output

Body:
I want the nav links aligned right of the nav bar. However my nav links are showing up next to the logo on the left. Any ideas?

Here is my code:

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home (current)

            Link

            Disabled

Body:
You made some mistakes the way you structured HTML, this would work in bootstrap 3, but in bootstrap 4 it will not.

Here is example of code that would work in bootstrap 4:

<nav class="navbar navbar-light navbar-expand-md bg-faded justify-content-center">
    <a href="/" class="navbar-brand d-flex w-50 mr-auto">Brand</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar3">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse" id="collapsingNavbar3">
        <ul class="nav navbar-nav ml-auto w-100 justify-content-end">
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
        </ul>
    </div>
</nav>

Here is JSBin with example http://jsbin.com/pagigugelo/edit?output


问:
How to create json array in json array codeigniter
I have been searching for the solution on how to create JSON array in JSON object from Mysql query. Need help from any of you.

My source data in mysql:

```<code>Table: parent
--------------------------------------
| id | firstname | lastname | rating |
--------------------------------------
|  1 | John      | Doe      | 9.3    |
|  2 | Marry     | Jane     | 8.5    |
|  3 | Paijo     | Masni    | 9.8    |
--------------------------------------

Table: children
------------------------------
| id |  idparent  | name     |
------------------------------
|  1 |  1         | John A   |
|  2 |  1         | John B   |
|  3 |  1         | John C   |
|  4 |  2         | Jane A   |
|  5 |  2         | Jane B   |
|  6 |  3         | Bang Jo  |
|  7 |  3         | Kak Jo   |
------------------------------
</code>```

My MySQL Query:

Select p.firstname, p.lastname, p.rating, c.name as children

from parent p join children c on p.id = c.idparent

```<code>Output:
-------------------------------------------------
| id | firstname | lastname | rating | children |
-------------------------------------------------
|  1 | John      | Doe      | 9.3    | John A   |
|  1 | John      | Doe      | 9.3    | John B   |
|  1 | John      | Doe      | 9.3    | John C   |
|  2 | Marry     | Jane     | 8.5    | Jane A   |
|  2 | Marry     | Jane     | 8.5    | Jane B   |
|  3 | Paijo     | Masni    | 9.8    | Bang Jo  |
|  3 | Paijo     | Masni    | 9.8    | Kak Jo   |
-------------------------------------------------
</code>```

Here is my output of JSON format that I wanted:

```<code>var profile = [
    {
        "firstname": "John",
        "lastname": "Doe",
        "rating": 9.3,
        "children": [
            "John A",
            "John B",
            "John C"
        ],
        "id": 1
    },
    {
        "firstname": "Marry",
        "lastname": "Jane",
        "rating": 8.5,
        "children": [
            "Jane A",
            "Jane B"
        ],
        "id": 2
    },
    {
        "firstname": "Paijo",
        "lastname": "Masni",
        "rating": 9.8,
        "children": [
            "Bang Jo",
            "Kak Jo"
        ],
        "id": 3
    }
];
</code>```

The one I got stuck from generating the JSON is on the children: [], I want to have an array with double-quote "" separated by comma ',' inside the [].

Thank you.

NB:
Currenty I am using codeigniter for my coding. If you have faced this kind of problem on codeigniter before, I'm looking forward to getting the sharing from you.

答:
```<code>$people = array();
$person = array();

$person['firstname'] = "John";
$person['lastname'] = "Doe";
$person['rating'] = 9.3;
$person['children'] = array('John A', 'John B', 'John C');
$person['id'] = 1;

$people[] = $person;
$person = array();

$person['firstname'] = "Marry";
$person['lastname'] = "Jane";
$person['rating'] = 8.5;
$person['children'] = array('JaneA', 'JaneB');
$person['id'] = 2;

$people[] = $person;

$profile = json_encode($people);

echo $profile;
</code>```

Gives the following output:

```<code>[{"firstname":"John","lastname":"Doe","rating":9.3,"children":["John A","John B","John C"],"id":1},
{"firstname":"Marry","lastname":"Jane","rating":8.5,"children":["JaneA","JaneB"],"id":2}]
</code>```

Body:
I have been searching for the solution on how to create JSON array in JSON object from Mysql query. Need help from any of you.

My source data in mysql:

Table: parent
--------------------------------------
| id | firstname | lastname | rating |
--------------------------------------
|  1 | John      | Doe      | 9.3    |
|  2 | Marry     | Jane     | 8.5    |
|  3 | Paijo     | Masni    | 9.8    |
--------------------------------------

Table: children
------------------------------
| id |  idparent  | name     |
------------------------------
|  1 |  1         | John A   |
|  2 |  1         | John B   |
|  3 |  1         | John C   |
|  4 |  2         | Jane A   |
|  5 |  2         | Jane B   |
|  6 |  3         | Bang Jo  |
|  7 |  3         | Kak Jo   |
------------------------------

My MySQL Query:

Select p.firstname, p.lastname, p.rating, c.name as children

from parent p join children c on p.id = c.idparent

Output:
-------------------------------------------------
| id | firstname | lastname | rating | children |
-------------------------------------------------
|  1 | John      | Doe      | 9.3    | John A   |
|  1 | John      | Doe      | 9.3    | John B   |
|  1 | John      | Doe      | 9.3    | John C   |
|  2 | Marry     | Jane     | 8.5    | Jane A   |
|  2 | Marry     | Jane     | 8.5    | Jane B   |
|  3 | Paijo     | Masni    | 9.8    | Bang Jo  |
|  3 | Paijo     | Masni    | 9.8    | Kak Jo   |
-------------------------------------------------

Here is my output of JSON format that I wanted:

var profile = [
    {
        "firstname": "John",
        "lastname": "Doe",
        "rating": 9.3,
        "children": [
            "John A",
            "John B",
            "John C"
        ],
        "id": 1
    },
    {
        "firstname": "Marry",
        "lastname": "Jane",
        "rating": 8.5,
        "children": [
            "Jane A",
            "Jane B"
        ],
        "id": 2
    },
    {
        "firstname": "Paijo",
        "lastname": "Masni",
        "rating": 9.8,
        "children": [
            "Bang Jo",
            "Kak Jo"
        ],
        "id": 3
    }
];

The one I got stuck from generating the JSON is on the children: [], I want to have an array with double-quote "" separated by comma ',' inside the [].

Thank you.

NB:
Currenty I am using codeigniter for my coding. If you have faced this kind of problem on codeigniter before, I'm looking forward to getting the sharing from you.

Body:
$people = array();
$person = array();

$person['firstname'] = "John";
$person['lastname'] = "Doe";
$person['rating'] = 9.3;
$person['children'] = array('John A', 'John B', 'John C');
$person['id'] = 1;

$people[] = $person;
$person = array();

$person['firstname'] = "Marry";
$person['lastname'] = "Jane";
$person['rating'] = 8.5;
$person['children'] = array('JaneA', 'JaneB');
$person['id'] = 2;

$people[] = $person;

$profile = json_encode($people);

echo $profile;

Gives the following output:

[{"firstname":"John","lastname":"Doe","rating":9.3,"children":["John A","John B","John C"],"id":1},
{"firstname":"Marry","lastname":"Jane","rating":8.5,"children":["JaneA","JaneB"],"id":2}]


问:
Remove a FileList item from a multiple "input:file"
I have this DOM:

```<code>var id = 0;

$('input:file#upload')[0].files[ id ]
</code>```

That get's the first file on the 0th index. File properties are listed and all works, but...

How do we remove items from the DOM's [object FileList] with JavaScript?

答:
I have found very quick & short workaround for this. Tested in many popular browsers (Chrome, Firefox, Safari);

First, you have to convert FileList to an Array

```<code>var newFileList = Array.from(event.target.files);
</code>```

to delete the particular element use this

```<code>newFileList.splice(index,1);
</code>```

Body:
I have this DOM:

var id = 0;

$('input:file#upload')[0].files[ id ]

That get's the first file on the 0th index. File properties are listed and all works, but...

How do we remove items from the DOM's [object FileList] with JavaScript?

Body:
I have found very quick & short workaround for this. Tested in many popular browsers (Chrome, Firefox, Safari);

First, you have to convert FileList to an Array

var newFileList = Array.from(event.target.files);

to delete the particular element use this

newFileList.splice(index,1);


问:
Can you avoid unboxing in a memoizing generic method?
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

```<code>public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}
</code>```

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

答:
If T and the result of Convert.ChangeType are reference types then there will be no unboxing.

If Convert.ChangeType returns a boxed value type and T is a value type then there isn't anything you can do to avoid unboxing if you want GetValue to return T.

Body:
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)


问:
c# list Group By
I am getting domain related information as a simple list from database and now i need to group the information before binding to the view. Here is my Class details. I tried various group logic but could not get achieve the result

```<code>public class CapabilitySelectionModel
    {
        public string Domain { get; set; }
        public string Category { get; set; }
        public string Capability { get; set; }
    }

List<CapabilitySelectionModel> list1 = new List<CapabilitySelectionModel>();
            list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category1", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category1", Capability = "Capability2" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category2", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category1", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category2", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category2", Capability = "Capability2" });
</code>```

It will look something like this

```<code>Domain1
    Category1
       Capability1
       Capability2
   Category2
       Capability1
Domain2
   Category1
     Capability1
   Category2
     Capability1
     Capability2
</code>```

Now, i want this list to be converted to the below list format

```<code>public class DomainModel
    {
        public string DomainName { get; set; }
        public List<CategoryModel> CategoryModel { get; set; }
    }

 public class CategoryModel
    {
        public string CategoryName  {  get;  set;  }
        public List<CapablityModel> CapablityModel   { get; set;}
    }

public class CapablityModel
    {
        public string CapablityName {  get;  set; }
    }
</code>```

Can someone advise?

答:
Not tested, but you just need some nested Grouping:</p>

```<code>var results = list1
  .GroupBy(a => a.Domain)
  .Select(g => new DomainModel {
           DomainName = g.Key,
           CategoryModel = g.GroubY(b => b.Category)
              .Select(h => new CategoryModel {
                 CategoryName  = h.Key,
                 CapablityModel = h.Select( c => new CapablityModel {
                     c.CapablityName }).ToList()
           }).ToList()
   }).ToList();
</code>```

Title: c# list Group By

Body:
I am getting domain related information as a simple list from database and now i need to group the information before binding to the view. Here is my Class details. I tried various group logic but could not get achieve the result

public class CapabilitySelectionModel
    {
        public string Domain { get; set; }
        public string Category { get; set; }
        public string Capability { get; set; }
    }

List<CapabilitySelectionModel> list1 = new List<CapabilitySelectionModel>();
            list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category1", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category1", Capability = "Capability2" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category2", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category1", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category2", Capability = "Capability1" });
            list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category2", Capability = "Capability2" });

It will look something like this

Domain1
    Category1
       Capability1
       Capability2
   Category2
       Capability1
Domain2
   Category1
     Capability1
   Category2
     Capability1
     Capability2

Now, i want this list to be converted to the below list format

public class DomainModel
    {
        public string DomainName { get; set; }
        public List<CategoryModel> CategoryModel { get; set; }
    }

 public class CategoryModel
    {
        public string CategoryName  {  get;  set;  }
        public List<CapablityModel> CapablityModel   { get; set;}
    }

public class CapablityModel
    {
        public string CapablityName {  get;  set; }
    }

Can someone advise?

Body:
Not tested, but you just need some nested Grouping:

var results = list1
  .GroupBy(a => a.Domain)
  .Select(g => new DomainModel {
           DomainName = g.Key,
           CategoryModel = g.GroubY(b => b.Category)
              .Select(h => new CategoryModel {
                 CategoryName  = h.Key,
                 CapablityModel = h.Select( c => new CapablityModel {
                     c.CapablityName }).ToList()
           }).ToList()
   }).ToList();


问:
res.end(result) doesn't display the result on my web page
Calling res.end(result) doesn't display the result on my web page, it is just displayed on the console when I call console.log('result ' + result).

this is my nodejs code:

```<code> const express = require('express')
    const app = express()
    var url = require('url');
    var Web3 = require('web3');

app.get('/', function(req, res) {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            });

            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://54.00.00.00:3010"));
            }

            if (web3.isConnected()) {

                var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getData","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"},{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Achats","outputs":[{"name":"aName","type":"bytes32"},{"name":"aId","type":"uint256"},{"name":"aDate","type":"bytes32"},{"name":"aValue","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"name","type":"bytes32"},{"name":"iid","type":"uint256"},{"name":"date","type":"bytes32"},{"name":"value","type":"uint256"}],"name":"setData","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]');
                TestContract = web3.eth.contract(abi);
                contractInstance = TestContract.at('0xc08f46fff9fcf082a0d1cebbcc464ca141d2b7d7');

                if (q.opt == 'get' && typeof q.index != "undefined") {
                    contractInstance.getData.call(parseInt(q.index), {
                        from: '0x3e10889Ef5066C1428ECaf8580aD4EFd50F8Cf7B'
                    }, function(error, result) {
                        console.log('error ' + error);
                        console.log('result ' + result);
                        res.end(result);
                    });
                }
            }
        }
        app.listen(3000, function() {
            console.log('Yep... on 3000 !')
        })
</code>```

i have been trying "res.end(result)" inside and outside of the function 'getData' but the same problem, nothing displayed on the web page

答: Well, you only send a response back if web3.isConnected() and q.opt == 'get' && typeof q.index != "undefined". Could be that one of those conditions do not hold.

Body:
Calling res.end(result) doesn't display the result on my web page, it is just displayed on the console when I call console.log('result ' + result).

this is my nodejs code:

 const express = require('express')
    const app = express()
    var url = require('url');
    var Web3 = require('web3');

app.get('/', function(req, res) {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            });

            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://54.00.00.00:3010"));
            }

            if (web3.isConnected()) {

                var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getData","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"},{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Achats","outputs":[{"name":"aName","type":"bytes32"},{"name":"aId","type":"uint256"},{"name":"aDate","type":"bytes32"},{"name":"aValue","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"name","type":"bytes32"},{"name":"iid","type":"uint256"},{"name":"date","type":"bytes32"},{"name":"value","type":"uint256"}],"name":"setData","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]');
                TestContract = web3.eth.contract(abi);
                contractInstance = TestContract.at('0xc08f46fff9fcf082a0d1cebbcc464ca141d2b7d7');

                if (q.opt == 'get' && typeof q.index != "undefined") {
                    contractInstance.getData.call(parseInt(q.index), {
                        from: '0x3e10889Ef5066C1428ECaf8580aD4EFd50F8Cf7B'
                    }, function(error, result) {
                        console.log('error ' + error);
                        console.log('result ' + result);
                        res.end(result);
                    });
                }
            }
        }
        app.listen(3000, function() {
            console.log('Yep... on 3000 !')
        })

i have been trying "res.end(result)" inside and outside of the function 'getData' but the same problem, nothing displayed on the web page


问:
Footer doesn't extend to the edge of the screen - not a duplicate
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.

I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.

The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.

I'm being left with a footer which begins about an inch in from the left of the screen and seems to be in line with the blog title. Does anyone know what might be causing this?

I've checked this in Chrome and Edge so far, both come up with the indent.

Here's the HTML:

```<code>{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <!-- MyBlog custom styles -->
    <link href="{% static "myblog.css" %}" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src=https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    {% render_block "css" %}
</head>
<body>
    {% cms_toolbar %}
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a href=""><img src="{% static "" %}"/></a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    {% show_menu 0 1 0 100 "menu.html" %}
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="blog-header">
            <h1 class="blog-title">Patch's Soapbox</h1>
            <p class="lead blog-description">The political system is broken; it could do with a Patch</p>
        </div>
        {% block content %}{% endblock content %}
    </div>

    <footer class="footer">
     <div class="container">
      <p class="text-muted">{% block footer %}My Blog©2015{%endblock footer%}</p>
     </div>
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bu -->
    <script src="{% static "ie10-viewport-bug-workaround.js" %}"></script>

    {% render_block "js" %}
</body>
</code>```

And the CSS:

```<code>html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}
</code>```

答:
I found the issue. I needed to use the "container-fluid" class, rather than the "container" class.

This increased the width of the container in-line with the device.

I then had to remove bootstrap's default padding using:

```<code>.container-fluid{margin:0 auto}
</code>```

Body:
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.

I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.

The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.

I'm being left with a footer which begins about an inch in from the left of the screen and seems to be in line with the blog title. Does anyone know what might be causing this?

I've checked this in Chrome and Edge so far, both come up with the indent.

Here's the HTML:

{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <link href="{% static "myblog.css" %}" rel="stylesheet">

    {% render_block "css" %}

    {% cms_toolbar %}

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

                    {% show_menu 0 1 0 100 "menu.html" %}

Patch's Soapbox

The political system is broken; it could do with a Patch

        {% block content %}{% endblock content %}

{% block footer %}My Blog©2015{%endblock footer%}

    {% render_block "js" %}

And the CSS:

html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}

Body:
I found the issue. I needed to use the "container-fluid" class, rather than the "container" class.

This increased the width of the container in-line with the device.

I then had to remove bootstrap's default padding using:

.container-fluid{margin:0 auto}


问:
How to Create Circle on corner of line in css

.line-8 {
  width: 100px;
  height: 1px;
  background-color: orange;
  position: relative;
  left: 240px;
  top: 15px;
  margin-bottom: 35px;
}```

How to make look like this

答:
Try This:

.line-8 {
  width: 100px;
  height: 1px;
  background-color: orange;
  position:relative;
  left: 240px;
  top: 15px;
  margin-bottom:35px;
}

.line-8:after {
  position: absolute;
  content: '';
  width: 10px;
  height: 10px;
  border-radius: 100%;
  background-color: orange;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line-8"></div> </code>```

Body:
.line-8 {
  width: 100px;
  height: 1px;
  background-color: orange;
  position: relative;
  left: 240px;
  top: 15px;
  margin-bottom: 35px;
}

How to make look like this

Body:
Try This:

.line-8 {
  width: 100px;
  height: 1px;
  background-color: orange;
  position:relative;
  left: 240px;
  top: 15px;
  margin-bottom:35px;
}

.line-8:after {
  position: absolute;
  content: '';
  width: 10px;
  height: 10px;
  border-radius: 100%;
  background-color: orange;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

<div class="line-8"></div>


问:
Reduce durability to improve performace in db2
In db2 10.5, is it possible that  transaction commit  does not wait for log IO to finish and return control to the client, like SQL server's delayed durability?
Is there any way to reduce the number of log IOs when there are large number of serial small transactions?</p>

答:
Db2 on Linux/Unit/Windows, at version 11.1 does not currently support lazy commits as offered by some versions of Microsoft SQL-server.

For some kinds of processing, especially large batches, it is often very convenient to use unlogged global temporary tables for intermediate tables. That is the one convenient way to eliminate logging overhead, although the use case is limited to specific scenarios. Such tables (declared global temporary tables,  or created global temporary tables) let you do fast processing without incurring logging overhead, although you have to design your batches (typically your stored procedures) to work with these kinds of tables, including the ability to restart after failures and recover etc.

If you have high frequency discrete OLTP transactions that include both insert AND update (not batch) , you should concentrate on optimising your active-logging configuration. For example to ensure your active logs are on the fastest media, to ensure your Db2 is never waiting for log files, to ensure that the logbufsz is adequate, to ensure that the bufferpool cleaning is optimal etc, to ensure that the size of your transaction-log files is compatible with your RTO and RPO Service-levels.


问:
Core-plot graph rendered upside-down in a different context
I'm using core-plot library to draw graphs. For some animation I have to take the image snapshot of the entire screen in order to make it smooth. The problem is that when I try to get image from the graph. The graph is always upside down. If I took only the graph itself as the snapshot, then it wouldn't be a problem - i could easily apply a transform on it. The problem is, I'm animating the whole screen, so that I take the snapshot of the entire UIWindow which consists the graph in one of its subviews.
I tried it with the coreplot 0.2.2 sample available in coreplot project on code.google. I simply added one button to the window (so that it is visible on each tab), when the button is pressed, I take the image from the window content and save is as an image in the Album library using this code:

```<code>
UIView *window = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContext(window.frame.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(newImage, nil, NULL, NULL);
</code>```

The result is as described above. Graph in the generated image is rendered upside down compared to the one that is visible on the screen. Do I do sth wrong or that's core-plots bug?

答: Yup, this is a design decision made by the core plot people that's caused a ton of problems for me, when I try to do exactly what you're doing there. Best course of action is just to apply a transform to flip the core plot view upside down before you grab the image, then un-transform the view after you render the image.</p>

Body:
I'm using core-plot library to draw graphs. For some animation I have to take the image snapshot of the entire screen in order to make it smooth. The problem is that when I try to get image from the graph. The graph is always upside down. If I took only the graph itself as the snapshot, then it wouldn't be a problem - i could easily apply a transform on it. The problem is, I'm animating the whole screen, so that I take the snapshot of the entire UIWindow which consists the graph in one of its subviews.
I tried it with the coreplot 0.2.2 sample available in coreplot project on code.google. I simply added one button to the window (so that it is visible on each tab), when the button is pressed, I take the image from the window content and save is as an image in the Album library using this code:

UIView *window = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContext(window.frame.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(newImage, nil, NULL, NULL);

The result is as described above. Graph in the generated image is rendered upside down compared to the one that is visible on the screen. Do I do sth wrong or that's core-plots bug?


问:
Angular 4 - Router resolve not working with BehaviorSubject
Angular gurus your help is greatly appreciated in this regard.

Here is what I am trying to do, when I access main app page it calls getConfigs() from config.service.ts and get the data from backend then updates this.configStringSource.next(config).  Right after that I am trying to redirect it to this.router.navigate(['/clone/status']), but redirect is not happening.

app.routing.ts

```<code>import { Routes, RouterModule } from '@angular/router';

import { CloneComponent } from './clone/clone.component';
import { StatusComponent } from './status/status.component';
import { ConfigurationComponent } from './configuration/configuration.component';
import { LogsComponent } from './logs/logs.component';
import { ConfigResolver } from './_services/config-resolver.service';

const appRoutes: Routes = [
    { path: 'clone', component: CloneComponent, children: [
        {path: 'status', component: StatusComponent, resolve: {config: ConfigResolver} },
        ]
    },
    { path: 'logstream', component: LogstreamComponent },
];

export const AppRouting = RouterModule.forRoot(appRoutes);
</code>```

config.ts

```<code>export class Config {
    configID: string;
    sourceDbNodes: string;
    targetDbNodes: string;
}
</code>```

config.service.ts

```<code>import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
//import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Router } from '@angular/router';
import {Subject} from 'rxjs/Subject';

import { Config } from '../_models/config';

@Injectable()
export class ConfigService {

    // Observable string source
    private configsStringSource = new BehaviorSubject<Config>({ configID: "", sourceDbNodes: "", targetDbNodes: ""});

    // Observable string stream
    configsString$ = this.configsStringSource.asObservable();

    // Service message commands
    updateConfigs(configs: Config) {
      this.configsStringSource.next(configs)
    }

    constructor(private http: Http, private router:Router) { }

    getConfigs() {
      let headers = new Headers();
      headers.append('Content-Type','application/json');
      return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers })
        .map((response: Response) => response.json());
    }
}
</code>```

config-resolver.service.ts

```<code>import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';

import { ConfigService } from './config.service';
import { Config } from '../_models/config';

interface Server {
  id: number;
  name: string;
  status: string;
}

@Injectable()
export class ConfigResolver implements Resolve<Config> {

  config: Config;

  constructor(private configService: ConfigService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
    return this.configService.configsString$.map(
      data => data[1]);
    }
}
</code>```

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Config } from './_models/config';
import { ConfigService } from './_services/config.service';

@Component({
  moduleId: module.id.toString(),
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  configs: Config[];

  constructor(private router:Router, private configService:ConfigService ) { }

  title = 'Angular 4 Proeject';

  private getConfigs() {
    this.configService.getConfigs().subscribe(configs => {
        this.configs = configs;
                this.configService.updateConfigs(configs);
console.log('app.component.ts sourceDbNode = '+this.configs[0].sourceDbNodes);
    });
  }

  ngOnInit() {
    this.getConfigs();
    this.router.navigate(['/clone/status']);
  }

}
</code>```

status.component.ts

```<code>import { Component, Input, OnInit, AfterContentChecked } from '@angular/core';
import { ActivatedRoute, Params, Router, Data } from '@angular/router';

import { Config } from '../_models/config';
import { ConfigService } from '../_services/config.service';

@Component({
  selector: 'app-status',
  template: `
    <p>
      status Works! {{config}}
    </p>
  `,
  styleUrls: ['./status.component.scss']
})

export class StatusComponent implements OnInit {

  configs: string;
  config: Config;
  servers: Array<any>;
  server: { id: number; name: string; status: string; };

  constructor(private configService:ConfigService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.data.subscribe(
        (data: Data) => {
          this.config = data['config'];
console.log('status.component.ts data = ', data['config']);
console.log('status.component.ts this.config = ', this.config);
        }
    );
  }
}
</code>```

答:
It helped to me.
In config.service change

```<code>// Observable string stream
configsString$ = this.configsStringSource.asObservable();
</code>```

to stack.

Add .first() to .asObservable().

Body:
Angular gurus your help is greatly appreciated in this regard.

Here is what I am trying to do, when I access main app page it calls getConfigs() from config.service.ts and get the data from backend then updates this.configStringSource.next(config).  Right after that I am trying to redirect it to this.router.navigate(['/clone/status']), but redirect is not happening.

app.routing.ts

import { Routes, RouterModule } from '@angular/router';

import { CloneComponent } from './clone/clone.component';
import { StatusComponent } from './status/status.component';
import { ConfigurationComponent } from './configuration/configuration.component';
import { LogsComponent } from './logs/logs.component';
import { ConfigResolver } from './_services/config-resolver.service';

const appRoutes: Routes = [
    { path: 'clone', component: CloneComponent, children: [
        {path: 'status', component: StatusComponent, resolve: {config: ConfigResolver} },
        ]
    },
    { path: 'logstream', component: LogstreamComponent },
];

export const AppRouting = RouterModule.forRoot(appRoutes);

config.ts

export class Config {
    configID: string;
    sourceDbNodes: string;
    targetDbNodes: string;
}

config.service.ts

import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
//import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Router } from '@angular/router';
import {Subject} from 'rxjs/Subject';

import { Config } from '../_models/config';

@Injectable()
export class ConfigService {

    // Observable string source
    private configsStringSource = new BehaviorSubject<Config>({ configID: "", sourceDbNodes: "", targetDbNodes: ""});

    // Observable string stream
    configsString$ = this.configsStringSource.asObservable();

    // Service message commands
    updateConfigs(configs: Config) {
      this.configsStringSource.next(configs)
    }

    constructor(private http: Http, private router:Router) { }

    getConfigs() {
      let headers = new Headers();
      headers.append('Content-Type','application/json');
      return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers })
        .map((response: Response) => response.json());
    }
}

config-resolver.service.ts

import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';

import { ConfigService } from './config.service';
import { Config } from '../_models/config';

interface Server {
  id: number;
  name: string;
  status: string;
}

@Injectable()
export class ConfigResolver implements Resolve<Config> {

  config: Config;

  constructor(private configService: ConfigService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
    return this.configService.configsString$.map(
      data => data[1]);
    }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Config } from './_models/config';
import { ConfigService } from './_services/config.service';

@Component({
  moduleId: module.id.toString(),
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  configs: Config[];

  constructor(private router:Router, private configService:ConfigService ) { }

  title = 'Angular 4 Proeject';

  private getConfigs() {
    this.configService.getConfigs().subscribe(configs => {
        this.configs = configs;
                this.configService.updateConfigs(configs);
console.log('app.component.ts sourceDbNode = '+this.configs[0].sourceDbNodes);
    });
  }

  ngOnInit() {
    this.getConfigs();
    this.router.navigate(['/clone/status']);
  }

}

status.component.ts

import { Component, Input, OnInit, AfterContentChecked } from '@angular/core';
import { ActivatedRoute, Params, Router, Data } from '@angular/router';

import { Config } from '../_models/config';
import { ConfigService } from '../_services/config.service';

@Component({
  selector: 'app-status',
  template: `

      status Works! {{config}}

  `,
  styleUrls: ['./status.component.scss']
})

export class StatusComponent implements OnInit {

  configs: string;
  config: Config;
  servers: Array<any>;
  server: { id: number; name: string; status: string; };

  constructor(private configService:ConfigService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.data.subscribe(
        (data: Data) => {
          this.config = data['config'];
console.log('status.component.ts data = ', data['config']);
console.log('status.component.ts this.config = ', this.config);
        }
    );
  }
}

Body:
It helped to me.
In config.service change

// Observable string stream
configsString$ = this.configsStringSource.asObservable();

to stack.

Add .first() to .asObservable().


问:
Requirejs: Waiting for require function inside Module
I have a simple translate class (module) which handles the localization for my app. Inside the translate class I am loading the required language modules with a require function. </p>

```<code>define(['require', 'config', 'store'],
function(require, Config, Store) {
    // Using ECMAScript 5 strict mode during development. By default r.js will ignore that.
    'use strict';

    var translation = {
        locale: null,
        name: null,
        keys: null,
        timezones: null
    };

    var languageCode = Store.getInstance().get('LanguageCode') || Config.defaultLanguageCode;

    require(['translation/' + languageCode], function(trans) {
        translation = trans;
    });

    var get = function(key) {
        return (!!translation.keys && translation.keys[key]) ? translation.keys[key] : key;
    };

    var timezone = function(key) {
        return (translation.timezones[key]) ? translation.timezones[key] : key;
    };

    return {
        _: get,
        timezone: timezone,
        timezones: function() {
            return translation.timezones;
        }
    };
});
</code>```

<p>The problem is that the return statement is executed before the needed language has loaded.
I put the translate class in the require shim to load it before other modules but that didn't work either. </p>

答:
I found a solution to your exact problem without using promises. I use a function WaitFor to wait for the module require() dependency to load.

This is how my App module looks like:

```<code>define("App", ["Config"], function () {

    var queue = [];
    var fetchingId, cb;

    var App = {
        Dialog: null
    };

    require(["FloDialog"], function () {
        App.Dialog = new FloDialog();
    });

    return {
        WaitFor: function (id, callback) {
            if (!fetchingId) {
                fetchingId = id;
                cb = callback;
                require([id], function () {
                    cb(App);
                });
            } else {
                queue.push([id, callback]);
            }
        }
    };
});
</code>```

Notice the WaitFor function at the bottom. When I require the module App like you see below I use the WaitFor function to literally wait for the require() dependency to load in the module. When it is ready, in my case, I return a App variable that now contains the App.Dialog var (and is loaded with an instance of the FloDialog class).

On some-page.html:

```<code><script type="text/javascript">
  require(['App'], function (App) {

        App.WaitFor('FloDialog', function(App) {
            console.log(App.Dialog); // Yay! The instance is loaded and good to go!
        });

</script>
</code>```

Body:
I have a simple translate class (module) which handles the localization for my app. Inside the translate class I am loading the required language modules with a require function.

define(['require', 'config', 'store'],
function(require, Config, Store) {
    // Using ECMAScript 5 strict mode during development. By default r.js will ignore that.
    'use strict';

    var translation = {
        locale: null,
        name: null,
        keys: null,
        timezones: null
    };

    var languageCode = Store.getInstance().get('LanguageCode') || Config.defaultLanguageCode;

    require(['translation/' + languageCode], function(trans) {
        translation = trans;
    });

    var get = function(key) {
        return (!!translation.keys && translation.keys[key]) ? translation.keys[key] : key;
    };

    var timezone = function(key) {
        return (translation.timezones[key]) ? translation.timezones[key] : key;
    };

    return {
        _: get,
        timezone: timezone,
        timezones: function() {
            return translation.timezones;
        }
    };
});

The problem is that the return statement is executed before the needed language has loaded.
I put the translate class in the require shim to load it before other modules but that didn't work either.

Body:
I found a solution to your exact problem without using promises. I use a function WaitFor to wait for the module require() dependency to load.

This is how my App module looks like:

define("App", ["Config"], function () {

    var queue = [];
    var fetchingId, cb;

    var App = {
        Dialog: null
    };

    require(["FloDialog"], function () {
        App.Dialog = new FloDialog();
    });

    return {
        WaitFor: function (id, callback) {
            if (!fetchingId) {
                fetchingId = id;
                cb = callback;
                require([id], function () {
                    cb(App);
                });
            } else {
                queue.push([id, callback]);
            }
        }
    };
});

Notice the WaitFor function at the bottom. When I require the module App like you see below I use the WaitFor function to literally wait for the require() dependency to load in the module. When it is ready, in my case, I return a App variable that now contains the App.Dialog var (and is loaded with an instance of the FloDialog class).

On some-page.html:

<script type="text/javascript">
  require(['App'], function (App) {

        App.WaitFor('FloDialog', function(App) {
            console.log(App.Dialog); // Yay! The instance is loaded and good to go!
        });

</script>


问:
Progressively slower reloading time of .vimrc
My boot time for vim is about a half second (tested with "--startuptime"), but after I reload vimrc a couple times via source, it gets slower subsequently. I have not debugged .vimrc in a systematic way, so I am not sure how to proceed. Setting verbose helps to kind of see what is going on and I am almost certain that the .vimrc is being loaded more than once. (especially filetype.vim and ftplugin.vim) Whenever I press Ctrl-C to stop the hang, I get an error in filetype.vim, which I think is because vim spends most time trying to load filetype.vim. The most probable culprit I see is the auto reload of .vimrc:

```<code>if has("autocmd")
    autocmd bufwritepost .vimrc source $MYVIMRC "auto source vimrc
endif
</code>```

How could I stop this from happening?

答:
This is my solution that also clears previous mappings:</p>

```<code>augroup VimrcGroup
  autocmd!
  " Make changes effective after saving .vimrc. Beware that autocommands are
  " duplicated if .vimrc gets sourced again, unless they are wrapped in an
  " augroup and the autocommands are cleared first using 'autocmd!'
  autocmd bufwritepost $MYVIMRC call OnSavingVimrc()
augroup END

" Avoid infinite loops
if !exists("*OnSavingVimrc")
  function! OnSavingVimrc()
    " Clear previous mappings, they don't go away automatically when sourcing vimrc
    mapclear
    echo "Sourcing Vimrc after saving it"
    source $MYVIMRC
  endfunction
endif
</code>```

Body:
My boot time for vim is about a half second (tested with "--startuptime"), but after I reload vimrc a couple times via source, it gets slower subsequently. I have not debugged .vimrc in a systematic way, so I am not sure how to proceed. Setting verbose helps to kind of see what is going on and I am almost certain that the .vimrc is being loaded more than once. (especially filetype.vim and ftplugin.vim) Whenever I press Ctrl-C to stop the hang, I get an error in filetype.vim, which I think is because vim spends most time trying to load filetype.vim. The most probable culprit I see is the auto reload of .vimrc:

if has("autocmd")
    autocmd bufwritepost .vimrc source $MYVIMRC "auto source vimrc
endif

How could I stop this from happening?

Body:
This is my solution that also clears previous mappings:

augroup VimrcGroup
  autocmd!
  " Make changes effective after saving .vimrc. Beware that autocommands are
  " duplicated if .vimrc gets sourced again, unless they are wrapped in an
  " augroup and the autocommands are cleared first using 'autocmd!'
  autocmd bufwritepost $MYVIMRC call OnSavingVimrc()
augroup END

" Avoid infinite loops
if !exists("*OnSavingVimrc")
  function! OnSavingVimrc()
    " Clear previous mappings, they don't go away automatically when sourcing vimrc
    mapclear
    echo "Sourcing Vimrc after saving it"
    source $MYVIMRC
  endfunction
endif


问:
How to display first three characters in employee name in lower case and remaining characters in upper case in sql
I need an answer for the above question </p>

答:
You could use UPPER() & LOWER() function if you are working with Microsoft SQL Server

```<code>DECLARE @DATA NVARCHAR(MAX) = 'xxxyyy'

SELECT @DATA

SELECT CONCAT(UPPER(LEFT(@DATA, 3)), LOWER(SUBSTRING(@DATA, 4, LEN(@DATA))))
</code>```

Result :

```<code>XXXyyy
</code>```

Body: I need an answer for the above question

Body:
You could use UPPER() & LOWER() function if you are working with Microsoft SQL Server

DECLARE @DATA NVARCHAR(MAX) = 'xxxyyy'

SELECT @DATA

SELECT CONCAT(UPPER(LEFT(@DATA, 3)), LOWER(SUBSTRING(@DATA, 4, LEN(@DATA))))

Result :

XXXyyy


问:
HTML input pattern that consists of 4 numbers and 2 letters at the end
Ive looked around for different validation patterns but didnt find any good examples that would help me create something like that. For example "5676AB".
Needs to have 4 numbers at the beginning, followed by 2 characters (can be uppercase and also lowercase).

If anyone would help me I would be very thankful!

Body:
var str = '5676AB';
console.log(str.match(/^[0-9]{4}[a-zA-Z]{2}/));


问:
DataGridView row added event
I'm using a DataGridView and I bind a List to the DataSource.

I already have the right columns and I map exactly the fields. What I'm trying to do is handling a sort of RowAdded or RowDataBound (like in aspx GridView) event.

The only event that I found is RowsAdded but no matter how many items I have, it is fired only 4 times the first time i bound, and twice the other times, with values

e.RowCount:1 e.RowIndex:0
e.RowCount:[n-1] e.RowIndex:1 *where n is the number of my items

is there a way I can get to a handle for each item?

EDIT: without changing the DataSource = binding method

答:
The easiest way for me is using a System.Windows.Forms.BindingSource. Add the list to that and then use the BindingSource as the grid DataSource. This then acts as a go-between for the grid and data.

There are then several events that can then be used from the bindingsouce. One of those is AddingNew. You can also use it to capture rows being add or removed, as well as several other things.

Title: DataGridView row added event


问:
Using Thor, can I pass the CLI an argument only (not a task) and send it to a default method/task?
I am using Thor to create a CLI for a Ruby gem that I am making.  The executable would ideally take a command like myapp path/to/file, in the sense that I would rather the user not have to define a task, only an argument.

I've looked over the API but default_task only works when no task/argument is present.

How can I make Thor send this variable file argument to a default method/task, and not interpret it like a task that does not exist?

答:
myapp path/to/file

two part answer:

1) myapp ... to use an executable other than 'thor' you will need to utilize the 'thor/runner' library.

2) path/to/file can be accomplished in the initialize method, like so:

```<code>class Something < Thor
  def initialize(*args)
    super
    case @path
      when /something$/; self.class.new([@path],options).do_run
    end
  end

  desc 'do_run', "do something"
  argument :path, :banner=>"path/to/file", :optional=>true
  def do_run
    # something
  end
end
</code>```

Body:
myapp path/to/file

two part answer:

1) myapp ... to use an executable other than 'thor' you will need to utilize the 'thor/runner' library.

2) path/to/file can be accomplished in the initialize method, like so:

class Something < Thor
  def initialize(*args)
    super
    case @path
      when /something$/; self.class.new([@path],options).do_run
    end
  end

  desc 'do_run', "do something"
  argument :path, :banner=>"path/to/file", :optional=>true
  def do_run
    # something
  end
end


问:
Element position from nested DataFrame array (Spark 2.2)
I'm trying to explode a nested DataFrame in Spark Scala. I have a DataFrame df which contains the following information:

```<code>root
|-- id: integer (nullable = false)
|-- features: array (nullable = true)
|   |-- element: float (containsNull = false)
</code>```

I've exploded the array information into to a flat DataFrame with:

```<code>df.selectExpr("id","explode(features) as features")
</code>```

and got the following DataFrame:

```<code>id  features
0   0.0629885
0   0.15931357
0   0.08922347
</code>```

My end goal is to pivot the data and calculate some similarities with that information. To do that, it would be very cool to get the actual position of the feature for every ID into the DataFrame, like this:

```<code>  id  features    feature_pos
  0   0.0629885   0
  0   0.15931357  1
  0   0.08922347  2
</code>```

Body:
I'm trying to explode a nested DataFrame in Spark Scala. I have a DataFrame df which contains the following information:

root
|-- id: integer (nullable = false)
|-- features: array (nullable = true)
|   |-- element: float (containsNull = false)

I've exploded the array information into to a flat DataFrame with:

df.selectExpr("id","explode(features) as features")

and got the following DataFrame:

id  features
0   0.0629885
0   0.15931357
0   0.08922347

My end goal is to pivot the data and calculate some similarities with that information. To do that, it would be very cool to get the actual position of the feature for every ID into the DataFrame, like this:

  id  features    feature_pos
  0   0.0629885   0
  0   0.15931357  1
  0   0.08922347  2

Body:
You can also apply Scala's zipWithIndex via a UDF as follows:

val df = Seq(
  (0, Seq(0.1f, 0.2f, 0.3f)),
  (1, Seq(0.4f, 0.5f, 0.6f))
).toDF("id", "features")

def addIndex = udf(
  (s: Seq[Float]) => s.zipWithIndex
)

val df2 = df.withColumn( "features_idx", explode(addIndex($"features")) )

df2.select( $"id", $"features_idx._1".as("features"), $"features_idx._2".as("features_pos") ).show
+---+--------+------------+
| id|features|features_pos|
+---+--------+------------+
|  0|     0.1|           0|
|  0|     0.2|           1|
|  0|     0.3|           2|
|  1|     0.4|           0|
|  1|     0.5|           1|
|  1|     0.6|           2|
+---+--------+------------+


问:
Add legend in igraph to annotate difference vertices size
I have a graph in igraph with a vertex size that is coded for a value.

I wish to add a legend with symbols (points in my case) with different sizes.
I tried the following code

```<code>require(igraph)
er_graph <- erdos.renyi.game(100, 5/100)
value<-runif(100)
n<-6
size_vec<-seq_len(n)
sizeCut<-cut(value,n)
vertex.size<-size_vec[sizeCut]
plot(er_graph, vertex.label=NA, vertex.size=vertex.size)
legend('topleft',legend=levels(sizeCut),pt.cex=size_vec,col='black')
</code>```

but end with legend without symbols
see example

Any sugestions how I go about this?

答:
Anyone looking at this who wants a continuous scale for node sizes instead of a discrete scale then this is the code you need to do it:

```<code>require(igraph)
er_graph <- erdos.renyi.game(100, 5/100)
value<-runif(100)
sizeCut<- c(0.2,0.4,0.6,0.8,1.0)
sizeCutScale <- sizeCut*10
vertex.size<-value*10
plot(er_graph, vertex.label=NA, vertex.size=vertex.size)
legend('topleft',legend=unique(sizeCut),pt.cex= sizeCutScale,col='black')
a <- legend('topleft',legend=unique(sizeCut),pt.cex=sizeCutScale/200,col='white',
            pch=21, pt.bg='white')
x <- (a$text$x + a$rect$left) / 2
y <- a$text$y
symbols(x,y,circles=sizeCutScale/200,inches=FALSE,add=TRUE,bg='orange')
</code>```

Body:
I have a graph in igraph with a vertex size that is coded for a value.

I wish to add a legend with symbols (points in my case) with different sizes.
I tried the following code

require(igraph)
er_graph <- erdos.renyi.game(100, 5/100)
value<-runif(100)
n<-6
size_vec<-seq_len(n)
sizeCut<-cut(value,n)
vertex.size<-size_vec[sizeCut]
plot(er_graph, vertex.label=NA, vertex.size=vertex.size)
legend('topleft',legend=levels(sizeCut),pt.cex=size_vec,col='black')

but end with legend without symbols
see example

Any sugestions how I go about this?

Body:
Anyone looking at this who wants a continuous scale for node sizes instead of a discrete scale then this is the code you need to do it:

require(igraph)
er_graph <- erdos.renyi.game(100, 5/100)
value<-runif(100)
sizeCut<- c(0.2,0.4,0.6,0.8,1.0)
sizeCutScale <- sizeCut*10
vertex.size<-value*10
plot(er_graph, vertex.label=NA, vertex.size=vertex.size)
legend('topleft',legend=unique(sizeCut),pt.cex= sizeCutScale,col='black')
a <- legend('topleft',legend=unique(sizeCut),pt.cex=sizeCutScale/200,col='white',
            pch=21, pt.bg='white')
x <- (a$text$x + a$rect$left) / 2
y <- a$text$y
symbols(x,y,circles=sizeCutScale/200,inches=FALSE,add=TRUE,bg='orange')


问:
How to add flag icons in admin-theme in Liferay DXP
I am working with Liferay DXP. I would like to add some flag icons to some languages.

In Liferay 6.2 I can do it with a hook which adds the flags icons in the control-panel (now for Liferay DXP is admin-theme) theme and/or classic-theme. For instance, I would like using the flag icon in web content localization.

Someone know how to do it in Liferay DXP?

答: You can add svg icon & language icon in liferay admin theme as described in this answer. This works for me, you can try this solution.</p>


问:
Does creating new object reseting properties of class
I am new to OO programming. Suppose I have class and 2d array inside full of values.
If I create object of a class in another class, is that 2d array going to be empty?
If yes, what is the way to preserve values, while making new instance of a class?</p>

答:
Create a constructor that takes in the array as a parameter.</p>

```<code>public static void main(String[] args) {
        int[][] array = new int[5][10];
        otherClass oc = new otherClass(array);
    }

public class otherClass {

    public otherClass(int[][] a){
        //do stuff with full array
    }
}
</code>```

Body:
Create a constructor that takes in the array as a parameter.

public static void main(String[] args) {
        int[][] array = new int[5][10];
        otherClass oc = new otherClass(array);
    }

public class otherClass {

    public otherClass(int[][] a){
        //do stuff with full array
    }
}


答: You can use the static keyword to make the member variable common across all instances of the class. That way, every instance will hold the same values in the array.

Title: Does creating new object reseting properties of class

Body:
I am new to OO programming. Suppose I have class and 2d array inside full of values.
If I create object of a class in another class, is that 2d array going to be empty?
If yes, what is the way to preserve values, while making new instance of a class?


问:
Inconsistent representation of tuples?
Assume we've made the following assignment:

```<code>x = (1, 2, (3, 'John', 4), 'Hi')
</code>```

Why does x[0:1] gives me (1,) but x[0:-1] gives (1, 2, (3, 'John', 4))? Why is there no comma after (3, 'John', 4)?

答:
Parentheses don't define a tuple; commas do. Normally, the commas occur between elements, but a 1-tuple needs to be special-cased somewhat because there is no second element to provide a medial position for the comma.

Parentheses are only needed when working with tuples where necessary to distinguish different uses of commas, and in the special case of the empty tuple.

```<code># empty tuple
# There's no such thing syntactically as an empty expression, so
# parentheses can be used.
x = ()

# 1-tuple - the comma signals a tuple is being created; no need for parentheses here, but they can be optionally used.
x = 1,
y = (1,)  # x == y

# n-tuples. A trailing comma is allowed but has no affect.
x = 1,2
y = 1,2,  # x == y
</code>```

Title: Inconsistent representation of tuples?

Body:
Assume we've made the following assignment:

x = (1, 2, (3, 'John', 4), 'Hi')

Why does x[0:1] gives me (1,) but x[0:-1] gives (1, 2, (3, 'John', 4))? Why is there no comma after (3, 'John', 4)?

Body:
Parentheses don't define a tuple; commas do. Normally, the commas occur between elements, but a 1-tuple needs to be special-cased somewhat because there is no second element to provide a medial position for the comma.

Parentheses are only needed when working with tuples where necessary to distinguish different uses of commas, and in the special case of the empty tuple.

# empty tuple
# There's no such thing syntactically as an empty expression, so
# parentheses can be used.
x = ()

# 1-tuple - the comma signals a tuple is being created; no need for parentheses here, but they can be optionally used.
x = 1,
y = (1,)  # x == y

# n-tuples. A trailing comma is allowed but has no affect.
x = 1,2
y = 1,2,  # x == y


问:
Mongodb .net updating one of the embedded documents
I have an orders and each has transactions embedded.

```<code>{
    _id: orderId1,
    other_fields: something else,
    transactions: [
       {
           _id: someId,
           price: 25,
           status: 1
       },
       {
           _id: someId2,
           price: 30,
           status: 0
       }
    ]
}
</code>```

Now i want to change the status of one of the transactions(lets say: someId2). How can i do that?

Both orders and transactions are models with transaction as ICollection<Transaction>

Also, is it possible without using any magic string?

答:
Here's an example of one way this can be done using the C# driver:

```<code>await mongoCollection.UpdateOneAsync(
    o => o.Id == orderId1 && x.Transactions.Any(t => t.Id == someId2),
    Builders<Order>.Update.Set(x => x.Transactions[-1].Status, someStatus));
</code>```

The use of -1 as an indexer is the key to all of this - it's essentially the translation from C# to the Positional Operator. This instructs the driver to use the index that was matched in the call to x.Transactions.Any in my example. I'm sure there are alternatives to using Any, but given that you're searching by a unique ID, this should work for your setup.

Body:
I have an orders and each has transactions embedded.

{
    _id: orderId1,
    other_fields: something else,
    transactions: [
       {
           _id: someId,
           price: 25,
           status: 1
       },
       {
           _id: someId2,
           price: 30,
           status: 0
       }
    ]
}

Now i want to change the status of one of the transactions(lets say: someId2). How can i do that?

Both orders and transactions are models with transaction as ICollection<Transaction>

Also, is it possible without using any magic string?

Body:
Here's an example of one way this can be done using the C# driver:

await mongoCollection.UpdateOneAsync(
    o => o.Id == orderId1 && x.Transactions.Any(t => t.Id == someId2),
    Builders<Order>.Update.Set(x => x.Transactions[-1].Status, someStatus));

The use of -1 as an indexer is the key to all of this - it's essentially the translation from C# to the Positional Operator. This instructs the driver to use the index that was matched in the call to x.Transactions.Any in my example. I'm sure there are alternatives to using Any, but given that you're searching by a unique ID, this should work for your setup.


问:
Page breaks for images in Python fpdf
I want to insert some lengthy images (each image can extend to 2 pages) using python fpdf. But the images don't continue to next page once a page break is triggered. How can I print the rest of the images into the next page starting from a given set_y value (header included)?</p>

答:
Just an example of my above comment,</p>

```<code>from fpdf import FPDF
from PIL import Image

pdf = FPDF()
pdf.add_page()

im = Image.open('1.jpg')
width_img, height_img = im.size

#mm = (pixels * 25.4) / dpi
# - 25.4 millimeters in an inch
w = (width_img*25.4)/300
h = (height_img*25.4)/300

pdf.image('1.jpg',0,0,w,h)
pdf.output("yourfile.pdf", "F")
</code>```

Title: Page breaks for images in Python fpdf

Body:
Just an example of my above comment,

from fpdf import FPDF
from PIL import Image

pdf = FPDF()
pdf.add_page()

im = Image.open('1.jpg')
width_img, height_img = im.size

#mm = (pixels * 25.4) / dpi
# - 25.4 millimeters in an inch
w = (width_img*25.4)/300
h = (height_img*25.4)/300

pdf.image('1.jpg',0,0,w,h)
pdf.output("yourfile.pdf", "F")


问:
java.sql.SQLException : Operation not allowed after ResultSet closed
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed

Here is the code i believe the error occurs in

```<code>Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";

int candidateNo = 42;

query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
    query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
    ResultSet ts = stmt.executeQuery(query2);
}
</code>```

I have tried using resultset rs = null; to create the variable but the error still occurs

答: In your code you used 2 ResultSet executing the same Statement object (stmt)concurrently. Use different Statement Objects for both queries.</p>

Body:
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed

Here is the code i believe the error occurs in

Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";

int candidateNo = 42;

query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
    query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
    ResultSet ts = stmt.executeQuery(query2);
}

I have tried using resultset rs = null; to create the variable but the error still occurs


问:
How to transform Scala collection of Option[X] to collection of X
I'm starting to explore Scala, and one of the things I'm intrigued by is the Option type and the promise of being able to eliminate null related errors.

However I haven't been able to work out how to transform a list (or other collection) of, say, Option[String], to a collection of String (obviously filtering out any values that are None).

In other words, how do I get from this:

```<code>List[Option[Int]] = List(Some(1))
</code>```

... to this:

```<code>List[Int] = List(1)
</code>```

I'm using Scala 2.8 if that has any impact on the answer.

答:
```<code>val list1 = List(Some(1), None, Some(2))
val list2 = list1.flatten // will be: List(1,2)
</code>```

Body:
I'm starting to explore Scala, and one of the things I'm intrigued by is the Option type and the promise of being able to eliminate null related errors.

However I haven't been able to work out how to transform a list (or other collection) of, say, Option[String], to a collection of String (obviously filtering out any values that are None).

In other words, how do I get from this:

List[Option[Int]] = List(Some(1))

... to this:

List[Int] = List(1)

I'm using Scala 2.8 if that has any impact on the answer.


问:
Regex to allow max 10 digits followed by only one comma and 3 more digits
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.

So far i have come up with this:

```<code>^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.
</code>```

I am going to validate input in javascript.

I am using sap.m.input control, and user's keystroke is captured on live change event.

Following examples are accepted as user input:

1234567890,123

  4,1

   234,45

  56457

Input must always begin with a natural number and only comma should be appear.

Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23.

I have added the following code in the application:

```<code>var input = oEvent.getSource().getValue();
        var isValid = false;
        var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
        isValid = regex.test(input);
        if (isValid == false) {
            //  oEvent.getSource().setValueState("Error");
            input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
            oEvent.getSource().setValue(input);
            return;
        }
</code>```

I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.

Please suggest ways to form perfect regex to handle this scenario.

Thanks.

答:
Since you're using SAPUI5 / OpenUI5, take a look at what the framework already offers. E.g.: It is recommended to use the control StepInput instead of a plain Input for your scenario:

It allows only numbers with support of decimal values.

It supports min and max values.

It removes unwanted characters such as whitespaces.

It replaces blank entry (with min value).

Additionally, it supports easy stepping with keyboard and scroll wheel as well.

Here is an example showcasing the above mentioned criteria. Optionally, we can also set a model on the control and bind the data to the value so that UI5 handles saving the value only when certain conditions are met. For this, we're using the type Float with the respective constraints:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/ui/core/mvc/XMLView",
  "sap/ui/model/json/JSONModel",
  "sap/ui/core/Core",
], async (XMLView, JSONModel, Core) => {
  "use strict";

  const control = await XMLView.create({
    definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
      height="100%"
      displayBlock="true">
      <App>
        <Page class="sapUiResponsiveContentPadding" showHeader="false">
          <StepInput xmlns:core="sap.ui.core"
            core:require="{ 'FloatType': 'sap/ui/model/type/Float' }"
            textAlign="Center"
            width="14rem"
            displayValuePrecision="3"
            step="0.1"
            min="1"
            max="9999999999.999"
            value="{
              path: '/data',
              type: 'FloatType',
              constraints: {
                minimum: 1,
                maximum: 9999999999.999
              }
            }"/>
          <ObjectAttribute title="Model data" text="{/data}" />
        </Page>
      </App>
    </mvc:View>`,
    models: new JSONModel({
      "data": 1.0,
    }),
  });

  Core.getMessageManager().registerObject(control, true);
  control.placeAt("content");
}));

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script id="sap-ui-bootstrap"
  src="https://openui5nightly.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core,sap.m"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body></code>```

We can see that the model doesn't save the value if the value was invalid (e.g. "-1.000").

Body:
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.

So far i have come up with this:

^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.

I am going to validate input in javascript.

I am using sap.m.input control, and user's keystroke is captured on live change event.

Following examples are accepted as user input:

1234567890,123

  4,1

   234,45

  56457

Input must always begin with a natural number and only comma should be appear.

Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23.

I have added the following code in the application:

var input = oEvent.getSource().getValue();
        var isValid = false;
        var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
        isValid = regex.test(input);
        if (isValid == false) {
            //  oEvent.getSource().setValueState("Error");
            input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
            oEvent.getSource().setValue(input);
            return;
        }

I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.

Please suggest ways to form perfect regex to handle this scenario.

Thanks.

Body:
Since you're using SAPUI5 / OpenUI5, take a look at what the framework already offers. E.g.: It is recommended to use the control StepInput instead of a plain Input for your scenario:

It allows only numbers with support of decimal values.

It supports min and max values.

It removes unwanted characters such as whitespaces.

It replaces blank entry (with min value).

Additionally, it supports easy stepping with keyboard and scroll wheel as well.

Here is an example showcasing the above mentioned criteria. Optionally, we can also set a model on the control and bind the data to the value so that UI5 handles saving the value only when certain conditions are met. For this, we're using the type Float with the respective constraints:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/ui/core/mvc/XMLView",
  "sap/ui/model/json/JSONModel",
  "sap/ui/core/Core",
], async (XMLView, JSONModel, Core) => {
  "use strict";

  const control = await XMLView.create({
    definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
      height="100%"
      displayBlock="true">
      <App>
        <Page class="sapUiResponsiveContentPadding" showHeader="false">
          <StepInput xmlns:core="sap.ui.core"
            core:require="{ 'FloatType': 'sap/ui/model/type/Float' }"
            textAlign="Center"
            width="14rem"
            displayValuePrecision="3"
            step="0.1"
            min="1"
            max="9999999999.999"
            value="{
              path: '/data',
              type: 'FloatType',
              constraints: {
                minimum: 1,
                maximum: 9999999999.999
              }
            }"/>
          <ObjectAttribute title="Model data" text="{/data}" />
        </Page>
      </App>
    </mvc:View>`,
    models: new JSONModel({
      "data": 1.0,
    }),
  });

  Core.getMessageManager().registerObject(control, true);
  control.placeAt("content");
}));

<script id="sap-ui-bootstrap"
  src="https://openui5nightly.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core,sap.m"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>

We can see that the model doesn't save the value if the value was invalid (e.g. "-1.000").

ContentLicense: CC BY-SA 4.0


问:
Is it possible to make this image in CSS?
I was working on something in photoshop. You can see the picture here:

The three triangles in the background refer to 3 different pages on my website. I was wondering if it was possible to put the images like this in CSS because I want them to work like links and put some simple zoom animation on it when you hover on it. I'm actually pretty noob and new to CSS in overall so this will be hard to make without doing a lot of research but I hope you guys can help me out and give me a way to start. Any help is appreciated, thanks a lot!

just to be clear, the 3 triangles should become 3 individual pictures. I'm forced to work with flexbox on school if that matters. Thanks again.

答:
You can convert the image (or single elements) in base64 with a tool like this: https://www.base64-image.de/

It is one of the oldest ways to encode things into html (first proposed in 1987!). It is a way of turning different types of data into a series of letters and numbers that is safe for HTML. One of those data types is images.

I can't paste a sample code here because it's too long.