问:
Oracle 18c Listener unable to start
So I installed Oracle 18C XE and was able to connect to it. Comming back to it a few days later I can connect to it with SQLPlus using sys as Sysdba but am unable to connect with SQL Developer.

Starting the listener through services results in an error saying the
  OracleOraDB18Home1TNSListener service on local computer started then
  stopped.

lstnrctl start from an admin cmd line gives the following errors:

TNS-12545: Connect failed because target host or object does not exist

TNS-12560: TNS:protocol adapter error

TNS-00515: Connect failed
  because target host or object does not exist    64-bit Windows Error:
  49: Unknown error

Ok sure - so i can ping the IP listed in tnsnames.ora but I can't telnet to 1521 on that ip
generated xe entry from tnsnames.ora

```<code>XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.82)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )
</code>```

for good measure lstnrctl status is:

C:\WINDOWS\system32>lsnrctl status

LSNRCTL for 64-bit Windows: Version 18.0.0.0.0 - Production on 02-JUN-2020 08:25:17

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

```<code>Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.82)(PORT=1521)))
TNS-12535: TNS:operation timed out
 TNS-12560: TNS:protocol adapter error
  TNS-00505: Operation timed out
   64-bit Windows Error: 60: Unknown error
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   64-bit Windows Error: 2: No such file or directory
</code>```

How can I resolve this? I just need to test an entity framework application on oracle.

I can kinda see that the IP address is wrong but this is a local installation for local app development only. Can I use Localhost?

I have updated tnsnames and listener as follows:

```<code>listener
    DEFAULT_SERVICE_LISTENER = XE

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\Fraser\product\18.0.0\dbhomeXE)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\Fraser\product\18.0.0\dbhomeXE\bin\oraclr18.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

tnsnames
XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

LISTENER_XE =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )
</code>```

but SQL Developer now tells returns 'ora-12514, tns:listener does not currently know of service requested in connect descriptor'

connection properties are

```<code>username: sys as sysdba
PASSWORD: (confirmed with sql plus login)
hostname:localhost
port:1521
SID XE
Service name: XE
</code>```

I get the same result using sid or service name radio button (sid is ora 12505 but it still references listener not knowing the SID in the connect descriptor)

lsnrctl is now:

```<code>    C:\WINDOWS\system32>lsnrctl status

LSNRCTL for 64-bit Windows: Version 18.0.0.0.0 - Production on 02-JUN-2020 09:52:58

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 18.0.0.0.0 - Production
Start Date                02-JUN-2020 08:44:30
Uptime                    0 days 1 hr. 8 min. 32 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Default Service           XE
Listener Parameter File   C:\app\Fraser\product\18.0.0\dbhomeXE\network\admin\listener.ora
Listener Log File         C:\app\Fraser\product\18.0.0\diag\tnslsnr\SPR\listener\alert\log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
  Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
</code>```

Is tnsnames malformed?

答: Yes you can use localhost if you only intend to connect to XE database instance from your local machine ... but it requires reconfiguring Oracle Net (listener) and Oracle XE database which is not so easy.

Title: Oracle 18c Listener unable to start

Body:
So I installed Oracle 18C XE and was able to connect to it. Comming back to it a few days later I can connect to it with SQLPlus using sys as Sysdba but am unable to connect with SQL Developer.

Starting the listener through services results in an error saying the
  OracleOraDB18Home1TNSListener service on local computer started then
  stopped.

lstnrctl start from an admin cmd line gives the following errors:

TNS-12545: Connect failed because target host or object does not exist

TNS-12560: TNS:protocol adapter error

TNS-00515: Connect failed
  because target host or object does not exist    64-bit Windows Error:
  49: Unknown error

Ok sure - so i can ping the IP listed in tnsnames.ora but I can't telnet to 1521 on that ip
generated xe entry from tnsnames.ora

XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.82)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

for good measure lstnrctl status is:

C:\WINDOWS\system32>lsnrctl status

LSNRCTL for 64-bit Windows: Version 18.0.0.0.0 - Production on 02-JUN-2020 08:25:17

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.82)(PORT=1521)))
TNS-12535: TNS:operation timed out
 TNS-12560: TNS:protocol adapter error
  TNS-00505: Operation timed out
   64-bit Windows Error: 60: Unknown error
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   64-bit Windows Error: 2: No such file or directory

How can I resolve this? I just need to test an entity framework application on oracle.

I can kinda see that the IP address is wrong but this is a local installation for local app development only. Can I use Localhost?

I have updated tnsnames and listener as follows:

listener
    DEFAULT_SERVICE_LISTENER = XE

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\Fraser\product\18.0.0\dbhomeXE)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\Fraser\product\18.0.0\dbhomeXE\bin\oraclr18.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

tnsnames
XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

LISTENER_XE =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )

but SQL Developer now tells returns 'ora-12514, tns:listener does not currently know of service requested in connect descriptor'

connection properties are

username: sys as sysdba
PASSWORD: (confirmed with sql plus login)
hostname:localhost
port:1521
SID XE
Service name: XE

I get the same result using sid or service name radio button (sid is ora 12505 but it still references listener not knowing the SID in the connect descriptor)

lsnrctl is now:

    C:\WINDOWS\system32>lsnrctl status

LSNRCTL for 64-bit Windows: Version 18.0.0.0.0 - Production on 02-JUN-2020 09:52:58

Copyright (c) 1991, 2018, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 18.0.0.0.0 - Production
Start Date                02-JUN-2020 08:44:30
Uptime                    0 days 1 hr. 8 min. 32 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Default Service           XE
Listener Parameter File   C:\app\Fraser\product\18.0.0\dbhomeXE\network\admin\listener.ora
Listener Log File         C:\app\Fraser\product\18.0.0\diag\tnslsnr\SPR\listener\alert\log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
  Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully

Is tnsnames malformed?


来源: stackexchange

问:
How to remove previous merges and commits from the pull request on a feature branch?
Somewhere a month ago, I've started to have extra commits and merges with every pull request I make. The git log command shows all those commits as well.

Most of the answers I've seen here was related to the develop branch cleanup, but it seems like something happened to my local git history.

What can I do to see only those commits that are related to the feature I'm working on?

Example of commits and merges unrelated to the branch, I'm working on:

答:
It appears that you are having difficulty with the problem of a long-lived branch.

Let's say your team merges to develop and you always work on a feature branch. Let's call it feature. If you create feature and start working and keep working, meanwhile develop may advance, and you will miss those advances. Conflicts with develop may be created, which can be annoying when the time comes to merge later, and even worse, you're not using the "latest and greatest" code in your own branch.

What's the solution? It appears that your solution is, occasionally, to get onto develop, pull, then get onto feature and merge develop onto it.

That's not wrong per se, but there's a problem: it leaves a merge commit every time you do that. And that, it seems, is what you are complaining about.

Instead, from time to time, get onto develop, pull, then get onto feature and rebase onto develop. This will cause it to appear that feature started right at the end of where develop is now.

Do that one from time to time as you work, and do it one last time just before you push. Then quickly clean up feature (I usually completely rewrite all the commits to be more compact and informative), push, and create the pull request.

ContentLicense: CC BY-SA 4.0


问:
How to save to web local storage in flutter web
I have a web site built with flutter for web and currently, am trying to save to web local storage or cookie but can't seem to find any plugin or way to archive that.

答:
I am using shared_preferences package to store data on local storage

```<code>class SessionManager {
  static SessionManager manager;
  static SharedPreferences _prefs;

  static Future<SessionManager> getInstance() async {
    if (manager == null || _prefs == null) {
      manager = SessionManager();
      _prefs = await SharedPreferences.getInstance();
    }
    return manager;
  }

  void putCityId(String cityId) {
    _prefs.setString("KEY_CITY_ID", cityId);
  }

  String getCityId() {
    return _prefs.getString("KEY_CITY_ID") ?? "";
  }
}
</code>```

shared_preferences store data for the current session only.

If you want to store data permanently then you should use cookie to store data.

```<code>   import 'dart:html';

   class CookieManager {
      static CookieManager _manager;

      static getInstance() {
        if (_manager == null) {
          _manager = CookieManager();
        }
        return _manager;
      }

      void _addToCookie(String key, String value) {
        // 2592000 sec = 30 days.
        document.cookie = "$key=$value; max-age=2592000; path=/;";
      }

      String _getCookie(String key) {
        String cookies = document.cookie;
        List<String> listValues = cookies.isNotEmpty ? cookies.split(";") : List();
        String matchVal = "";
        for (int i = 0; i < listValues.length; i++) {
          List<String> map = listValues[i].split("=");
          String _key = map[0].trim();
          String _val = map[1].trim();
          if (key == _key) {
            matchVal = _val;
            break;
          }
        }
        return matchVal;
      }
    }
</code>```

Body:
I am using shared_preferences package to store data on local storage

class SessionManager {
  static SessionManager manager;
  static SharedPreferences _prefs;

  static Future<SessionManager> getInstance() async {
    if (manager == null || _prefs == null) {
      manager = SessionManager();
      _prefs = await SharedPreferences.getInstance();
    }
    return manager;
  }

  void putCityId(String cityId) {
    _prefs.setString("KEY_CITY_ID", cityId);
  }

  String getCityId() {
    return _prefs.getString("KEY_CITY_ID") ?? "";
  }
}

shared_preferences store data for the current session only.

If you want to store data permanently then you should use cookie to store data.

   import 'dart:html';

   class CookieManager {
      static CookieManager _manager;

      static getInstance() {
        if (_manager == null) {
          _manager = CookieManager();
        }
        return _manager;
      }

      void _addToCookie(String key, String value) {
        // 2592000 sec = 30 days.
        document.cookie = "$key=$value; max-age=2592000; path=/;";
      }

      String _getCookie(String key) {
        String cookies = document.cookie;
        List<String> listValues = cookies.isNotEmpty ? cookies.split(";") : List();
        String matchVal = "";
        for (int i = 0; i < listValues.length; i++) {
          List<String> map = listValues[i].split("=");
          String _key = map[0].trim();
          String _val = map[1].trim();
          if (key == _key) {
            matchVal = _val;
            break;
          }
        }
        return matchVal;
      }
    }


问:
Equivalent of windows gdi regions in linux
I sometimes use windows gdi regions for graphics drawing and invalidation/validation. For example the program http://www.maxerist.net/main/soft-for-win/tubicus (oss) was made using only regions (no bitmaps or off-screen buffer). The drawing was made with FillRgn and FrameRgn, invalidation and painting with  InvalidateRgn and CombineRgn,  every cell (see screenshot) is a simple region created with CreateEllipticRgn, CreatePolygonRgn and CombineRgn.

I have plans to port it to Linux. As I understood, there are many graphics libraries in Linux. Are there ones that support windows-like regions?

Thanks

答:
You want to use The X Window System, a.k.a. X11, as your graphic platform. Its client library is called Xlib. The platform supports polygonal regions.

There are many libraries written on top of Xlib (Gtk, Qt, wxWindows and more) but you always can use the low-level Xlib API directly with any of them. Qt even supports elliptic regions. I don't know the details but I guess it's implemented on top of X11 polygonal regions.

ContentLicense: CC BY-SA 3.0


问:
Wordpress Elementor Header issue
I am new to elementor, and by watching youtube created first website http://itz4u.in/itz4u/ in wordpress in mochahost.com. It is working fine but I can not remove header from this page.</p>

答:
To remove the header in a page, open the page with Elementor Editor.

Click on page settings (little gear icon) on the left bottom of screen.

In page layout, select CANVAS.

This will eliminate header and footer on the page.

If you need to remove only the header, you can create a empty Header template and define that as header. This way the footer will be visible and header invisible. In this case remember to leave the page layout as DEFAULT

Title: Wordpress Elementor Header issue


问:
Find neighbours in a pandas data frame
I have a dataset of bicycles where I have columns for the store, where they are sold, and some information on the bicycle model. I need to compare the sales numbers of models in each store. For that reason I need to do the following:

Group bicycles by store:

groups = df.groupby('store_id')

Then, for each model in that store, I need to find models that have similar characteristics. That is similar height, length, weight, etc. For that, I have set a 10% difference bound, meaning if the difference in weight between the two models is less than 10%, the other model is a comparable neighbor.

Finally, for each model, I want to see where it ranks among its competitors, giving it a "top seller" label if it performs better than 50% of them.

The problem is, I don't know how to do steps 2 and 3. Does anybody have an idea? I've taken a look at Groupby.Transform in the pandas documentation, but I don't know how it fits in the whole picture.

Your help would be really appreciated!

答:
Try this out:

import pandas as pd
import numpy as np

def sales_rank(x, df):
    df_ns = df.set_index('id')
    df_ns = df_ns.loc[x.neighbors, 'sales']
    df_ns.sort_values(ascending=False, inplace=True)
    df_ns = df_ns.reset_index()
    return df_ns[df_ns.id == x.id].index[0]

df = pd.DataFrame(data={'id': range(5), 'weight': [20, 21, 23, 43, 22], 'sales':[200, 100, 140, 100, 100]})
df['neighbors'] = df.weight.apply(lambda x: df.id[np.isclose(df.weight.values, x, rtol=0.10)].values)
df['sales_rank_in_neighborhood'] = df.apply(lambda x: sales_rank(x, df) , axis=1)
df['top_seller'] = df.apply(lambda x: x.sales_rank_in_neighborhood < len(x.neighbors)//2, axis=1)
print(df)
```

<h3>Output</h3>

```   id  weight  sales     neighbors  sales_rank_in_neighborhood  top_seller
0   0      20    200     [0, 1, 4]                           0        True
1   1      21    100  [0, 1, 2, 4]                           3       False
2   2      23    140     [1, 2, 4]                           0        True
3   3      43    100           [3]                           0       False
4   4      22    100  [0, 1, 2, 4]                           2       False
```

<p>Note that there are no top sellers in single-element neighborhoods. Tweak the rule to suit your purposes.</p>

<p>I hope this helps!</p>

<h2>Edits</h2>

<p>I added a solution for groups, multiple rules for defining neighborhood and fixed sales rank implementation:</p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np

def ns(x, df):
    weight_rule = np.isclose(df.weight.values, x.weight, rtol=0.10)
    gear_rule = df.gear == x.gear
    type_rule = df.type == x.type
    return df.id[np.logical_and.reduce((weight_rule, gear_rule, type_rule))].values

def sales_rank(x, df):
    df_ns = df.set_index('id')
    df_ns = df_ns.loc[x.neighbors, 'sales']
    df_ns.sort_values(ascending=False, inplace=True)
    df_ns = df_ns.reset_index()
    return df_ns[df_ns.id == x.id].index[0]

df = pd.DataFrame(data={'store_id': [0, 1, 0, 1, 0], 'id': range(5), 'weight': [20, 21, 23, 43, 22], 'gear': [3, 3, 3, 7, 3], 'type':['mountain', 'mountain', 'mountain', 'bmx', 'mountain'], 'sales':[200, 100, 140, 100, 100]})
# Columns for results
df['neighbors'] = ''
df['sales_rank_in_neighborhood'] = ''
df['top_seller'] = ''
groups = df.groupby('store_id')

for _, g in groups:
    df_temp = df.loc[g.index, :]
    df_temp.neighbors = df_temp.apply(lambda x: ns(x, df_temp), axis=1)
    df_temp.sales_rank_in_neighborhood = df_temp.apply(lambda x: sales_rank(x, df_temp), axis=1)
    df_temp.top_seller = df_temp.apply(lambda x: x.sales_rank_in_neighborhood < len(x.neighbors)//2, axis=1)
    df.loc[g.index, :] = df_temp

print(df)
</code>```

Output

```<code>   store_id  id  weight  gear      type  sales  neighbors sales_rank_in_neighborhood top_seller
0         0   0      20     3  mountain    200     [0, 4]                          0       True
1         1   1      21     3  mountain    100        [1]                          0      False
2         0   2      23     3  mountain    140     [2, 4]                          0       True
3         1   3      43     7       bmx    100        [3]                          0      False
4         0   4      22     3  mountain    100  [0, 2, 4]                          2      False
</code>```

I guess there would be a way for avoiding looping over groups but this seems to do the trick.

Title: Find neighbours in a pandas data frame

Body:
Try this out:

import pandas as pd
import numpy as np

def sales_rank(x, df):
    df_ns = df.set_index('id')
    df_ns = df_ns.loc[x.neighbors, 'sales']
    df_ns.sort_values(ascending=False, inplace=True)
    df_ns = df_ns.reset_index()
    return df_ns[df_ns.id == x.id].index[0]

df = pd.DataFrame(data={'id': range(5), 'weight': [20, 21, 23, 43, 22], 'sales':[200, 100, 140, 100, 100]})
df['neighbors'] = df.weight.apply(lambda x: df.id[np.isclose(df.weight.values, x, rtol=0.10)].values)
df['sales_rank_in_neighborhood'] = df.apply(lambda x: sales_rank(x, df) , axis=1)
df['top_seller'] = df.apply(lambda x: x.sales_rank_in_neighborhood < len(x.neighbors)//2, axis=1)
print(df)

Output

   id  weight  sales     neighbors  sales_rank_in_neighborhood  top_seller
0   0      20    200     [0, 1, 4]                           0        True
1   1      21    100  [0, 1, 2, 4]                           3       False
2   2      23    140     [1, 2, 4]                           0        True
3   3      43    100           [3]                           0       False
4   4      22    100  [0, 1, 2, 4]                           2       False

Note that there are no top sellers in single-element neighborhoods. Tweak the rule to suit your purposes.

I hope this helps!

Edits

I added a solution for groups, multiple rules for defining neighborhood and fixed sales rank implementation:

import pandas as pd
import numpy as np

def ns(x, df):
    weight_rule = np.isclose(df.weight.values, x.weight, rtol=0.10)
    gear_rule = df.gear == x.gear
    type_rule = df.type == x.type
    return df.id[np.logical_and.reduce((weight_rule, gear_rule, type_rule))].values

def sales_rank(x, df):
    df_ns = df.set_index('id')
    df_ns = df_ns.loc[x.neighbors, 'sales']
    df_ns.sort_values(ascending=False, inplace=True)
    df_ns = df_ns.reset_index()
    return df_ns[df_ns.id == x.id].index[0]

df = pd.DataFrame(data={'store_id': [0, 1, 0, 1, 0], 'id': range(5), 'weight': [20, 21, 23, 43, 22], 'gear': [3, 3, 3, 7, 3], 'type':['mountain', 'mountain', 'mountain', 'bmx', 'mountain'], 'sales':[200, 100, 140, 100, 100]})
# Columns for results
df['neighbors'] = ''
df['sales_rank_in_neighborhood'] = ''
df['top_seller'] = ''
groups = df.groupby('store_id')

for _, g in groups:
    df_temp = df.loc[g.index, :]
    df_temp.neighbors = df_temp.apply(lambda x: ns(x, df_temp), axis=1)
    df_temp.sales_rank_in_neighborhood = df_temp.apply(lambda x: sales_rank(x, df_temp), axis=1)
    df_temp.top_seller = df_temp.apply(lambda x: x.sales_rank_in_neighborhood < len(x.neighbors)//2, axis=1)
    df.loc[g.index, :] = df_temp

print(df)

Output

   store_id  id  weight  gear      type  sales  neighbors sales_rank_in_neighborhood top_seller
0         0   0      20     3  mountain    200     [0, 4]                          0       True
1         1   1      21     3  mountain    100        [1]                          0      False
2         0   2      23     3  mountain    140     [2, 4]                          0       True
3         1   3      43     7       bmx    100        [3]                          0      False
4         0   4      22     3  mountain    100  [0, 2, 4]                          2      False

I guess there would be a way for avoiding looping over groups but this seems to do the trick.


问:
Angular Ngrx: Getting & displaying list of options from Java API
Java API would be - localhost://company/products/123/fetchOptions
Its response would be like same below :

```<code>{
 "Increase": true,
 "Decrease" : true,
 "Like" : true,
 "Dislike" : true,
 "Old" : false,
 "Others" : true
}
</code>```

Now on UI using Angular & ngrx i need to include changes to fetch data from above API and display all 6 values above as dropdown Options.

The value with boolean false will be shown in dropdown but would be disabled.

How to do that using Ngrx ?

i know a bit about it, that first i need to define Interface, then Any Action followed by its dispatcher so that i can subscribe to it in my UI component (productAttributes.component.ts).

How would be my interface like and other things ?
Currently using JSON to make everything ready, later will replace JSON url with API

Thanks in advance for help...

答:
You need to:

create a store feature for it

define a reducer

define a selector

create a load action

create a success action

create a failure action

create an effect

reducer

export const optionsFeatureKey = 'options';

export const optionsLoad = createAction(
    'options:load',
);

export const optionsSuccess = createAction(
    'options:success',
    props<{data: OptionsState}>(),
);

export const optionsFailure = createAction(
    'options:failure',
);

export interface OptionsState {
    Increase: boolean;
    Decrease: boolean;
    Like: boolean;
    Dislike: boolean;
    Old: boolean;
    Others: boolean;
}

export const initialState: OptionsState = {
    Increase: false,
    Decrease: false,
    Like: false,
    Dislike: false,
    Old: false,
    Others: false,
};

const reducer = createReducer(
    initialState,

    on(optionsSuccess, (state, {data}) => ({
        ...state,
        ...data,
    })),

);

export function optionsReducer(state: OptionsState | undefined, action: Action): OptionsState {
    return reducer(state, action);
}

export const optionsFeature = createFeatureSelector<OptionsState>(optionsFeatureKey);

export const getOptions = createSelector(
    optionsFeature,
    v => v,
);
```

<p>effect</p>

<pre class="lang-js prettyprint-override"><code>
@Injectable()
export class OptionsEffects {
    public readonly load$: Observable<Action> = createEffect(() =>
        this.actions$.pipe(
            ofType(optionsLoad),
            switchMap(() => this.http.get<OptionsState>(`url.com`).pipe(
                map(data => optionsSuccess({data: data})),
                catchError(() => of(optionsFailure())),
            ),
        ),
    );

    constructor(
        protected readonly actions$: Actions,
        protected readonly http: HttpClient,
    ) {}
}
</code>```

and somewhere in your app

store.dispatch(optionsLoad());

store.select(getOptions).subscribe(options => {
  // logic.
});
```

Body:
Java API would be - localhost://company/products/123/fetchOptions
Its response would be like same below :

{
 "Increase": true,
 "Decrease" : true,
 "Like" : true,
 "Dislike" : true,
 "Old" : false,
 "Others" : true
}

Now on UI using Angular & ngrx i need to include changes to fetch data from above API and display all 6 values above as dropdown Options.

The value with boolean false will be shown in dropdown but would be disabled.

How to do that using Ngrx ?

i know a bit about it, that first i need to define Interface, then Any Action followed by its dispatcher so that i can subscribe to it in my UI component (productAttributes.component.ts).

How would be my interface like and other things ?
Currently using JSON to make everything ready, later will replace JSON url with API

Thanks in advance for help...

Body:
You need to:

create a store feature for it

define a reducer

define a selector

create a load action

create a success action

create a failure action

create an effect

reducer

export const optionsFeatureKey = 'options';

export const optionsLoad = createAction(
    'options:load',
);

export const optionsSuccess = createAction(
    'options:success',
    props<{data: OptionsState}>(),
);

export const optionsFailure = createAction(
    'options:failure',
);

export interface OptionsState {
    Increase: boolean;
    Decrease: boolean;
    Like: boolean;
    Dislike: boolean;
    Old: boolean;
    Others: boolean;
}

export const initialState: OptionsState = {
    Increase: false,
    Decrease: false,
    Like: false,
    Dislike: false,
    Old: false,
    Others: false,
};

const reducer = createReducer(
    initialState,

    on(optionsSuccess, (state, {data}) => ({
        ...state,
        ...data,
    })),

);

export function optionsReducer(state: OptionsState | undefined, action: Action): OptionsState {
    return reducer(state, action);
}

export const optionsFeature = createFeatureSelector<OptionsState>(optionsFeatureKey);

export const getOptions = createSelector(
    optionsFeature,
    v => v,
);

effect

@Injectable()
export class OptionsEffects {
    public readonly load$: Observable<Action> = createEffect(() =>
        this.actions$.pipe(
            ofType(optionsLoad),
            switchMap(() => this.http.get<OptionsState>(`url.com`).pipe(
                map(data => optionsSuccess({data: data})),
                catchError(() => of(optionsFailure())),
            ),
        ),
    );

    constructor(
        protected readonly actions$: Actions,
        protected readonly http: HttpClient,
    ) {}
}

and somewhere in your app

store.dispatch(optionsLoad());

store.select(getOptions).subscribe(options => {
  // logic.
});


问:
How to create a password reset method in Laravel when using the Database User Provider
I've been searching the internet and have yet to find a solution to the following problem...

We currently have a website developed using Laravel which the user table is a remote Microsoft SQL database. The driver in config/auth.php has been set to "database". All is working fine except for the password reset functionality, which we get the following error:

```<code>UnexpectedValueException in PasswordBroker.php line 238: User must implement CanResetPassword interface.
</code>```

From my limited understanding of Laravel (this is my first experiance with Laravel), the Eloquent driver has support for the CanResetPassword functionality, however, this has not been implemented in the Database User Provider by Laravel, hence the error.

So my question is thus, has anyone had a configuration where they have the driver to “Database” and implemented a reset password functionality? All the examples I have seen to date relate to using the Eloquent model, which from my understanding of Laravel is not an option since during the initial development we had to change the driver from Eloquent to database to get the remote Microsoft SQL server working in the first place. Moving the Microsoft SQL database to a local database is not an option I’m afraid.

Alternatively, if anyone has implemented another method of a user resetting their password using an email address I would be open to suggestions.

答:
Just to add to what @eddythedove said.

Instead of str_random(60) I used the Laravel way of creating a token:

```<code>private function generateToken()
{
    // This is set in the .env file
    $key = config('app.key');

    // Illuminate\Support\Str;
    if (Str::startsWith($key, 'base64:')) {
        $key = base64_decode(substr($key, 7));
    }
    return hash_hmac('sha256', Str::random(40), $key);
}
</code>```

Body:
I've been searching the internet and have yet to find a solution to the following problem...

We currently have a website developed using Laravel which the user table is a remote Microsoft SQL database. The driver in config/auth.php has been set to "database". All is working fine except for the password reset functionality, which we get the following error:

UnexpectedValueException in PasswordBroker.php line 238: User must implement CanResetPassword interface.

From my limited understanding of Laravel (this is my first experiance with Laravel), the Eloquent driver has support for the CanResetPassword functionality, however, this has not been implemented in the Database User Provider by Laravel, hence the error.

So my question is thus, has anyone had a configuration where they have the driver to “Database” and implemented a reset password functionality? All the examples I have seen to date relate to using the Eloquent model, which from my understanding of Laravel is not an option since during the initial development we had to change the driver from Eloquent to database to get the remote Microsoft SQL server working in the first place. Moving the Microsoft SQL database to a local database is not an option I’m afraid.

Alternatively, if anyone has implemented another method of a user resetting their password using an email address I would be open to suggestions.

Body:
Just to add to what @eddythedove said.

Instead of str_random(60) I used the Laravel way of creating a token:

private function generateToken()
{
    // This is set in the .env file
    $key = config('app.key');

    // Illuminate\Support\Str;
    if (Str::startsWith($key, 'base64:')) {
        $key = base64_decode(substr($key, 7));
    }
    return hash_hmac('sha256', Str::random(40), $key);
}


问:
Typescript:force method to accept given Class reference
If I have this:

export class JobFields implements EntityFields {} (it could also extends from EntityFields if it helps)

can I have my method accepting only references for classes that implements/extends EntityFields? Like:

private test(entity: EntityFields) {} //this does not work, it accept anything

I'm creating components that automatically reads from classes that contains information regarding back-end entities. I just want to force/induce the Developper to give it the right kind of class reference.

```<code>this.test(JobFields); //this should work
this.test(JobView);   //while this shouldn't
</code>```

答:
You can write custom guard functions in Typescript

Here is an example. Consider the following:

```<code>IEntityFields {
    prop1: string,
    fieldprop2: {prop: string},
    metaData: {azureFilePath: string}
}

export const instanceOfEntityFields = (_o: any): _o is EntityFields => {
  return 'prop1' in _o && 'fieldprop2' in _o.metaData && 'azureFilePath' in _o.metaData;
};
</code>```

then in your method calls, you could use the check...

```<code>private test(entity: EntityFields) {
    return instanceOfEntityFields(entity)
        ? //...do work here
        : false;
}
</code>```

this is a cool pattern, because you can stack the checks;
e.g.

```<code>export const instanceOfJobFields = (_o: any): _o is JobFields => {
      return 'jobprop1' in _o && instanceOfEntityFields(_o);
    };
</code>```

Body:
If I have this:

export class JobFields implements EntityFields {} (it could also extends from EntityFields if it helps)

can I have my method accepting only references for classes that implements/extends EntityFields? Like:

private test(entity: EntityFields) {} //this does not work, it accept anything

I'm creating components that automatically reads from classes that contains information regarding back-end entities. I just want to force/induce the Developper to give it the right kind of class reference.

this.test(JobFields); //this should work
this.test(JobView);   //while this shouldn't

Body:
You can write custom guard functions in Typescript

Here is an example. Consider the following:

IEntityFields {
    prop1: string,
    fieldprop2: {prop: string},
    metaData: {azureFilePath: string}
}

export const instanceOfEntityFields = (_o: any): _o is EntityFields => {
  return 'prop1' in _o && 'fieldprop2' in _o.metaData && 'azureFilePath' in _o.metaData;
};

then in your method calls, you could use the check...

private test(entity: EntityFields) {
    return instanceOfEntityFields(entity)
        ? //...do work here
        : false;
}

this is a cool pattern, because you can stack the checks;
e.g.

export const instanceOfJobFields = (_o: any): _o is JobFields => {
      return 'jobprop1' in _o && instanceOfEntityFields(_o);
    };


问:
NodeJS: Can't return a result from a function
I'm trying to return the result from this function :

var YouTube = require('youtube-node');
var youTube = new YouTube();

youTube.setKey('XXXXXXXXXXXX');

var result = youTube.search('World War z Trailer', 2,
    function(error, result) {
        if (error) {
            console.log(error);
        } else {
            return result
        }})

console.log(result)
```

But then I only get undefined as a result in console.

答:
Last function here is a callback function, it doesn't return value in way you want. Read how it works somewhere, for example here.
Your issue could be resolved with Promise in this way

var search = new Promise(
  (resolve, reject) => {
    youTube.search('World War z Trailer', 2, function(error, result) {
     if (error) { reject(error); }
     resolve(result);
    })
  }
);
(async () => {
  var result = await search;
  console.log(result);
})()
```

Body:
I'm trying to return the result from this function :

var YouTube = require('youtube-node');
var youTube = new YouTube();

youTube.setKey('XXXXXXXXXXXX');

var result = youTube.search('World War z Trailer', 2,
    function(error, result) {
        if (error) {
            console.log(error);
        } else {
            return result
        }})

console.log(result)

But then I only get undefined as a result in console.


问:
Java 8 stream filter local variable
```<code>Obj1 x = null;
String key = null;
while(it.hasNext()){
   x = it.next();
   key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}
</code>```

This is complaining with the following message: "Local variable key must be final or effective final..." I understand the the lambda context is created at runtime and it needs variables that do not change.

How can I use the functional style to find the object in the list?
I want to avoid the old fashion way of iterating over the list with while.

答:
I want to avoid the old fashion way to iterate over the list through a while

Here is a way to iterate without explicit while loop:

```<code>StreamSupport.stream(spliteratorUnknownSize(it, Spliterator.ORDERED), false)
             .map(...)
             ...
</code>```

Title: Java 8 stream filter local variable

Body:
Obj1 x = null;
String key = null;
while(it.hasNext()){
   x = it.next();
   key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}

This is complaining with the following message: "Local variable key must be final or effective final..." I understand the the lambda context is created at runtime and it needs variables that do not change.

How can I use the functional style to find the object in the list?
I want to avoid the old fashion way of iterating over the list with while.

Body:
I want to avoid the old fashion way to iterate over the list through a while

Here is a way to iterate without explicit while loop:

StreamSupport.stream(spliteratorUnknownSize(it, Spliterator.ORDERED), false)
             .map(...)
             ...


问:
Method not supported using Auth::login()
I want to login from a parent account to a son account
I tried this
Route:

```<code> Route::middleware('can:isTutor')->group(function() {

       Route::POST('/redirect','TuteurEtudiantController@loginkid')->name('loginkid');

    });
</code>```

Function:

```<code>public function loginkid(Request $request){
    $id= $request->input('id');
    $user = User::find($id);
    Auth::login($user);

}
</code>```

The data come in the $etudiants variable in my view

```<code> @foreach($etudiants as $etudiant)
       <tr>
           <td>{{$etudiant->name }}</td>
           <td>{{$etudiant->id }}</td>
           <td>
           <form action="{{route('loginkid')}}" method="GET" >
                           {{csrf_field()}}
                      <input hidden name="id" value="{{ $etudiant->id }}">
             <button type="submit" class="btn btn-info"><i class="fas fa-user"></i>&nbspSe connecter</button>
           </form>

           </td>

       </tr>
       @endforeach
</code>```

When I try to log using the button "Se connecter"
I get the error

```<code>The POST method is not supported for this route. Supported methods: GET, HEAD.
</code>```

My controller, in case something can help by knowing what are the functions that I have on it

```<code>   <?php

namespace App\Http\Controllers;
use App\User;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\TuteurEtudiant;

class TuteurEtudiantController extends Controller

{

    public function createlink(){
        $etudiants = User::where('type','=','etudiant')->get();
        $tuteurs = User::where('type','=','tuteur')->get();

        return view('manageMe.createlink',['tuteurs'=>$tuteurs,'etudiants'=>$etudiants]);
    }
    public function storelink(Request $request){

        $lien = new TuteurEtudiant();
        $lien->tuteur_id=$request->input('tuteur');
        $lien->etudiant_id=$request->input('etudiant');
        $lien->save();
        return redirect()->back()->withMessage('Lien de parenté créé avec succées!');

    }

    public function loginkid(Request $request){
        $id= $request->input('id');
        $user = User::find($id);
        Auth::login($user);

    }

}
</code>```

答:
Actually the parent log to /home and do this in the view where with the route /home
So when you have to post the data you have to post it to the same route /home

```<code>Route::middleware('can:isTutor')->group(function() {

   Route::post('/home','TuteurEtudiantController@loginkid')->name('loginkid');

});
</code>```

Body:
I want to login from a parent account to a son account
I tried this
Route:

 Route::middleware('can:isTutor')->group(function() {

       Route::POST('/redirect','TuteurEtudiantController@loginkid')->name('loginkid');

    });

Function:

public function loginkid(Request $request){
    $id= $request->input('id');
    $user = User::find($id);
    Auth::login($user);

}

The data come in the $etudiants variable in my view

 @foreach($etudiants as $etudiant)

           {{$etudiant->name }}
           {{$etudiant->id }}

           <form action="{{route('loginkid')}}" method="GET" >
                           {{csrf_field()}}
                      <input hidden name="id" value="{{ $etudiant->id }}">
             <button type="submit" class="btn btn-info">&nbspSe connecter</button>
           </form>

       @endforeach

When I try to log using the button "Se connecter"
I get the error

The POST method is not supported for this route. Supported methods: GET, HEAD.

My controller, in case something can help by knowing what are the functions that I have on it

   <?php

namespace App\Http\Controllers;
use App\User;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\TuteurEtudiant;

class TuteurEtudiantController extends Controller

{

    public function createlink(){
        $etudiants = User::where('type','=','etudiant')->get();
        $tuteurs = User::where('type','=','tuteur')->get();

        return view('manageMe.createlink',['tuteurs'=>$tuteurs,'etudiants'=>$etudiants]);
    }
    public function storelink(Request $request){

        $lien = new TuteurEtudiant();
        $lien->tuteur_id=$request->input('tuteur');
        $lien->etudiant_id=$request->input('etudiant');
        $lien->save();
        return redirect()->back()->withMessage('Lien de parenté créé avec succées!');

    }

    public function loginkid(Request $request){
        $id= $request->input('id');
        $user = User::find($id);
        Auth::login($user);

    }

}

Body:
Actually the parent log to /home and do this in the view where with the route /home
So when you have to post the data you have to post it to the same route /home

Route::middleware('can:isTutor')->group(function() {

   Route::post('/home','TuteurEtudiantController@loginkid')->name('loginkid');

});


问:
Cannot use Using Statement
I am using Visual Studio 2005 and am unable to use the "Using" statement. I have just moved some code over from a .net 4 application, but that does not seem to be the problem as it is still not usable in a new app.

```<code>Using sw as StreamWriter = new StreamWriter(userFile2)
    For each blah as blahblah in blah()
        sw.WriteLine(blah)
    sw.Close()
End Using
</code>```

Error = Using is not declared
I am lead to believe that it should work the exact same as in VB 2010.

答:
Seems compile fine for me (VS 2005/.Net 2.0). You are missing Next for the For Each. Also you don't have to explicitly call Close() for sw, the Using block take care of it.

```<code>Using sw as StreamWriter = new StreamWriter(userFile2)
    For each blah as blahblah in blah()
        sw.WriteLine(blah)
    Next
End Using
</code>```

Title: Cannot use Using Statement

Body:
I am using Visual Studio 2005 and am unable to use the "Using" statement. I have just moved some code over from a .net 4 application, but that does not seem to be the problem as it is still not usable in a new app.

Using sw as StreamWriter = new StreamWriter(userFile2)
    For each blah as blahblah in blah()
        sw.WriteLine(blah)
    sw.Close()
End Using

Error = Using is not declared
I am lead to believe that it should work the exact same as in VB 2010.

Body:
Seems compile fine for me (VS 2005/.Net 2.0). You are missing Next for the For Each. Also you don't have to explicitly call Close() for sw, the Using block take care of it.

Using sw as StreamWriter = new StreamWriter(userFile2)
    For each blah as blahblah in blah()
        sw.WriteLine(blah)
    Next
End Using


问:
Firefox 32-bit does not fire ondevicechange event
I'm having trouble using the MediaDevices.ondevicechange event in Firefox (77.0) 32-Bit Version.
The event is not fired at all. In Firefox (77.0) 64-Bit the code works as expected. My machine is a 64-Bit Windows 10 desktop computer.

The example on the official mozilla site doesn't work either - it doesn't detect device changes in 32-Bit Firefox.

Anyone else experiencing this issue? Is this a bug or the expected behavior?

Is there a way to differentiate between Firefox 32- and 64-Bit with javascript? I don't see a way to do this with just feature detection, as they behave the same (code wise).
If yes i could at least implement some kind of fallback.

Any help would be appreciated.

答:
For extensive discussion of way to differentiate between 32 and 64-Bit question, see:

Detect 64-bit or 32-bit Windows from User Agent or Javascript?


问:
Docker apt-get update fails
Can somebody help me get apt-get working in my docker container? Whenever I try running any apt-get command in my docker container, the command fails. I'm running Docker version 1.1.1, build bd609d2 on ubuntu 12.04.

When I do

```<code>$ sudo docker run -i -t ubuntu:14.04 /bin/bash
# apt-get update
</code>```

I get errors saying

Could not resolve 'archive.ubuntu.com'

I tried uncommenting the line below in /etc/default/docker

DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"

but I still can't ping google.com

ping: unknown host

I confirmed that the container is using the dns servers 8.8.8.8 and 8.8.4.4

root@0baa87fc6322:/# cat /etc/resolv.conf

nameserver 8.8.8.8

nameserver 8.8.4.4

and I'm able to ping both servers so I'm pretty sure that a firewall isn't just dropping my packets.

Any help with this would be appreciated!

Thanks!

答:
I was using Jenkins base image and no matter what I do, apt-get update was always failing.
Eventually, this helped, removing /var/lib/apt/lists/
 and /etc/apt/sources.list.d/* *  did the trick.

```<code>USER root
RUN rm -rf /var/lib/apt/lists/*
RUN rm -rf /etc/apt/sources.list.d/*
RUN apt-get update
....Continue using apt-get for installing your stuff..
RUN apt-get install -y maven
</code>```

Title: Docker apt-get update fails

Body:
Can somebody help me get apt-get working in my docker container? Whenever I try running any apt-get command in my docker container, the command fails. I'm running Docker version 1.1.1, build bd609d2 on ubuntu 12.04.

When I do

$ sudo docker run -i -t ubuntu:14.04 /bin/bash
# apt-get update

I get errors saying

Could not resolve 'archive.ubuntu.com'

I tried uncommenting the line below in /etc/default/docker

DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"

but I still can't ping google.com

ping: unknown host

I confirmed that the container is using the dns servers 8.8.8.8 and 8.8.4.4

root@0baa87fc6322:/# cat /etc/resolv.conf

nameserver 8.8.8.8

nameserver 8.8.4.4

and I'm able to ping both servers so I'm pretty sure that a firewall isn't just dropping my packets.

Any help with this would be appreciated!

Thanks!

Body:
I was using Jenkins base image and no matter what I do, apt-get update was always failing.
Eventually, this helped, removing /var/lib/apt/lists/
 and /etc/apt/sources.list.d/* *  did the trick.

USER root
RUN rm -rf /var/lib/apt/lists/*
RUN rm -rf /etc/apt/sources.list.d/*
RUN apt-get update
....Continue using apt-get for installing your stuff..
RUN apt-get install -y maven


问:
What do i need to add and where to send the JWT token to the browser header?
I'm a new to backend and I was trying to create an authentication and authorization API. The app is working fine in Postman but I have to manually send the token. I want to send it to the header.

This is my auth.js middleware.

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {

  const token = req.header("token");
  console.log(token)
  if (!token) return res.status(401).json({
    message: "Auth Error"
  });

  try {
    const decoded = jwt.verify(token, "randomString");
    req.user = decoded.user;
    next();
  } catch (e) {
    console.error(e);
    res.status(500).send({
      message: "Invalid Token"
    });
  }
};
```

<p>And this is my authentication index.js file</p>

<pre class="lang-js prettyprint-override"><code>// Filename : user.js

const express = require("express");
const {
  check,
  validationResult
} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const auth = require('../middleware/auth')
const router = express.Router();

const User = require("../model/User");

//Signup
router.get('/signup', (req, res) => {
  res.render("signup.pug")
})

router.post(
  "/signup", [
    check("username", "Please Enter a Valid Username").isLength({
      min: 5
    }),
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 7
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    try {
      let user = await User.findOne({
        email
      });
      if (user) {
        return res.status(400).json({
          msg: "User Already Exists"
        });
      }

      user = new User({
        username,
        email,
        password
      });

      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);

      await user.save();

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 10000
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (err) {
      console.log(err.message);
      res.status(500).send("Error in Saving");
    }
  }
);

//Login

router.get('/login', (req, res) => {
  res.render("login.pug")
})

router.post(
  "/login", [
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 6
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const {
      email,
      password
    } = req.body;
    try {
      let user = await User.findOne({
        email
      });
      if (!user)
        return res.status(400).json({
          message: "User Not Exist"
        });

      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch)
        return res.status(400).json({
          message: "Incorrect Password !"
        });

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 3600
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (e) {
      console.error(e);
      res.status(500).json({
        message: "Server Error"
      });
    }
  }
);

router.get("/me", auth, async(req, res) => {

  try {
    // request.user is getting fetched from Middleware after token authentication
    const user = await User.findById(req.user.id);
    res.json(user);
  } catch (e) {
    res.send({
      message: "Error in Fetching user"
    });
  }
});

module.exports = router;
</code>```

Please also tell where to put in the code. Thanks in advance!!!

答:
Insert this after signing the token.</p>

```<code>res.render('/(Page Route)',{token: token});
</code>```

Body:
I'm a new to backend and I was trying to create an authentication and authorization API. The app is working fine in Postman but I have to manually send the token. I want to send it to the header.

This is my auth.js middleware.

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {

  const token = req.header("token");
  console.log(token)
  if (!token) return res.status(401).json({
    message: "Auth Error"
  });

  try {
    const decoded = jwt.verify(token, "randomString");
    req.user = decoded.user;
    next();
  } catch (e) {
    console.error(e);
    res.status(500).send({
      message: "Invalid Token"
    });
  }
};

And this is my authentication index.js file

// Filename : user.js

const express = require("express");
const {
  check,
  validationResult
} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const auth = require('../middleware/auth')
const router = express.Router();

const User = require("../model/User");

//Signup
router.get('/signup', (req, res) => {
  res.render("signup.pug")
})

router.post(
  "/signup", [
    check("username", "Please Enter a Valid Username").isLength({
      min: 5
    }),
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 7
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    try {
      let user = await User.findOne({
        email
      });
      if (user) {
        return res.status(400).json({
          msg: "User Already Exists"
        });
      }

      user = new User({
        username,
        email,
        password
      });

      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);

      await user.save();

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 10000
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (err) {
      console.log(err.message);
      res.status(500).send("Error in Saving");
    }
  }
);

//Login

router.get('/login', (req, res) => {
  res.render("login.pug")
})

router.post(
  "/login", [
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 6
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const {
      email,
      password
    } = req.body;
    try {
      let user = await User.findOne({
        email
      });
      if (!user)
        return res.status(400).json({
          message: "User Not Exist"
        });

      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch)
        return res.status(400).json({
          message: "Incorrect Password !"
        });

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 3600
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (e) {
      console.error(e);
      res.status(500).json({
        message: "Server Error"
      });
    }
  }
);

router.get("/me", auth, async(req, res) => {

  try {
    // request.user is getting fetched from Middleware after token authentication
    const user = await User.findById(req.user.id);
    res.json(user);
  } catch (e) {
    res.send({
      message: "Error in Fetching user"
    });
  }
});

module.exports = router;

Please also tell where to put in the code. Thanks in advance!!!

Body:
Insert this after signing the token.

res.render('/(Page Route)',{token: token});


问:
Why does my page work in IE9's IE7 mode, but not in IE7 itself?
I recently went live with our new home page, after heavily testing it in each of IE9's browser and document modes (not just compatibility mode, but actual IE7 and IE8 emulation). The site works in each mode, not to mention modern browsers. However, after it launched I got an email that said the site was very broken in IE7. I went to an abandoned machine and booted up Windows XP, started IE7, and loaded the page. To my horror, the layout was indeed broken! (NOT just the slideshow!)

Most importantly, why does my page not work in IE7, even though it works in IE7 mode in IE9? And as a secondary question, what might be "wrong" with it?

Edit: I have figured out that one of my problems may be the slideshow, but adding .ie7 #slideshow {display:none !important} won't even hide the slideshow. I can't access it via CSS.

Edit 2: There is another problem that only shows up in native IE7 -- the footer on that home page, and this page, is ultra-tiny text that can't be zoomed. It doesn't do this in IE9's IE7 mode (not compatibility), or in any other browser. Another example of the discrepancy.

答: Alrgiht, this maybe the answer ur looking for. Go to F12 developer tools and click IE9 browser mode and IE7 document mode It will be IE7 standards, but a IE9 useragent. If that doesn't work, try using IE7 browser mode and document mode.


问:
Download all Twilio Call logs?
I'm trying to download all my twilio call logs (as it's explained here https://support.twilio.com/hc/en-us/articles/223183588-Exporting-SMS-and-Call-Logs) but the problem is that this method is limited to 1000 logs.
Any idea how can I download them all (csv)?

Thanks in advance

答:
You can use the Twilio Helper Libraries or Twilio CLI to do so.</p>

```<code>TWILIO CLI USAGE
  $ twilio api:core:calls:list

OPTIONS
  -l=(debug|info|warn|error|none)                                                 [default: info] Level of logging messages.
  -o=(columns|json|tsv)                                                           [default: columns] Format of command output.
  -p, --profile=profile                                                           Shorthand identifier for your profile.
  --account-sid=account-sid                                                       The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to read.

  --end-time=end-time                                                             Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that ended on this date. You can also
                                                                                specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on
                                                                                or after midnight of this date.

  --end-time-after=end-time-after                                                 Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that ended on this date. You can also
                                                                                specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on
                                                                                or after midnight of this date.

  --end-time-before=end-time-before                                               Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that ended on this date. You can also
                                                                                specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on
                                                                                or after midnight of this date.

  --from=from                                                                     Only include calls from this phone number, SIP address, Client identifier or SIM SID.

  --limit=limit                                                                   [default: 50] The maximum number of resources to return. Use '--no-limit' to disable.

  --page-size=page-size                                                           How many resources to return in each list page. The default is 50, and the maximum is 1000.

  --parent-call-sid=parent-call-sid                                               Only include calls spawned by calls with this SID.

  --properties=properties                                                         [default: sid,from,to,status,startTime] The properties you would like to display (JSON output always shows all properties).

  --start-time=start-time                                                         Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that started on this date. You can
                                                                                also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls
                                                                                that started on or after midnight of this date.

  --start-time-after=start-time-after                                             Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that started on this date. You can
                                                                                also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls
                                                                                that started on or after midnight of this date.

  --start-time-before=start-time-before                                           Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that started on this date. You can
                                                                                also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls
                                                                                that started on or after midnight of this date.

  --status=(queued|ringing|in-progress|completed|busy|failed|no-answer|canceled)  The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`.

  --to=to                                                                         Only show calls made to this phone number, SIP address, Client identifier or SIM SID.
</code>```

Title: Download all Twilio Call logs?

Body:
You can use the Twilio Helper Libraries or Twilio CLI to do so.

TWILIO CLI USAGE
  $ twilio api:core:calls:list

OPTIONS
  -l=(debug|info|warn|error|none)                                                 [default: info] Level of logging messages.
  -o=(columns|json|tsv)                                                           [default: columns] Format of command output.
  -p, --profile=profile                                                           Shorthand identifier for your profile.
  --account-sid=account-sid                                                       The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to read.

  --end-time=end-time                                                             Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that ended on this date. You can also
                                                                                specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on
                                                                                or after midnight of this date.

  --end-time-after=end-time-after                                                 Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that ended on this date. You can also
                                                                                specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on
                                                                                or after midnight of this date.

  --end-time-before=end-time-before                                               Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that ended on this date. You can also
                                                                                specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on
                                                                                or after midnight of this date.

  --from=from                                                                     Only include calls from this phone number, SIP address, Client identifier or SIM SID.

  --limit=limit                                                                   [default: 50] The maximum number of resources to return. Use '--no-limit' to disable.

  --page-size=page-size                                                           How many resources to return in each list page. The default is 50, and the maximum is 1000.

  --parent-call-sid=parent-call-sid                                               Only include calls spawned by calls with this SID.

  --properties=properties                                                         [default: sid,from,to,status,startTime] The properties you would like to display (JSON output always shows all properties).

  --start-time=start-time                                                         Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that started on this date. You can
                                                                                also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls
                                                                                that started on or after midnight of this date.

  --start-time-after=start-time-after                                             Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that started on this date. You can
                                                                                also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls
                                                                                that started on or after midnight of this date.

  --start-time-before=start-time-before                                           Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read only calls that started on this date. You can
                                                                                also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls
                                                                                that started on or after midnight of this date.

  --status=(queued|ringing|in-progress|completed|busy|failed|no-answer|canceled)  The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`.

  --to=to                                                                         Only show calls made to this phone number, SIP address, Client identifier or SIM SID.


问:
Bootstrap Vue datepicker failed for prop max, expected String, Date, got Date
I am using Bootstrap Vue and more specifally the formdatepicker.
It's looking like this:

```<code><b-form-datepicker
  v-model="user.birthdate"
  class="mb-2"
  :max="maxBirthdate"
  :placeholder="$t('birthdate_field_placeholder')"
  :show-decade-nav="true"
/>
</code>```

I want to restrict the max date to be 16 years ago from today.
So I use this code:

```<code>created () {
    let now = new Date()
    let today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    let todayMinusSixteenYears = new Date(today)
    todayMinusSixteenYears.setFullYear(todayMinusSixteenYears.getFullYear() - 16)
    this.maxBirthdate = todayMinusSixteenYears
  },
</code>```

When I then start my Nuxt app, I am getting the following error:

```<code>[Vue warn]: Invalid prop: type check failed for prop "max". Expected String, Date, got Date

found in

---> <BCalendar>
       <BVFormBtnLabelControl>
         <BFormDatepicker>
           <Anonymous>
             <BFormGroup>
               <FormControlWrapper> at components/form/FormControlWrapper.vue
                 <ValidationObserver>
                   <Pages/register/volunteer.vue> at pages/register/volunteer.vue
                     <Nuxt>
                       <Layouts/default.vue> at layouts/default.vue
                         <Root>
</code>```

I'm not sure where or what the error is, since the variable is definitely a Javascript Date.
When trying to put .toString() at the end, it does not work at all anymore.

Please note, that even though the application is giving the error as shown, it does work perfectly with the Javascript Date object.

答:
Without the full script (especially the data object) I can't say what is the root of your issue here, but going off of the Bootstrap Vue demo, the code below works. What you're likely experiencing is a conflict between created function and whatever you have in data

```

Body:
I am using Bootstrap Vue and more specifally the formdatepicker.
It's looking like this:

I want to restrict the max date to be 16 years ago from today.
So I use this code:

created () {
    let now = new Date()
    let today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    let todayMinusSixteenYears = new Date(today)
    todayMinusSixteenYears.setFullYear(todayMinusSixteenYears.getFullYear() - 16)
    this.maxBirthdate = todayMinusSixteenYears
  },

When I then start my Nuxt app, I am getting the following error:

[Vue warn]: Invalid prop: type check failed for prop "max". Expected String, Date, got Date

found in

---> <BCalendar>
       <BVFormBtnLabelControl>
         <BFormDatepicker>
           <Anonymous>
             <BFormGroup>
               <FormControlWrapper> at components/form/FormControlWrapper.vue
                 <ValidationObserver>
                   <Pages/register/volunteer.vue> at pages/register/volunteer.vue
                     <Nuxt>
                       <Layouts/default.vue> at layouts/default.vue
                         <Root>

I'm not sure where or what the error is, since the variable is definitely a Javascript Date.
When trying to put .toString() at the end, it does not work at all anymore.

Please note, that even though the application is giving the error as shown, it does work perfectly with the Javascript Date object.

Body:
Without the full script (especially the data object) I can't say what is the root of your issue here, but going off of the Bootstrap Vue demo, the code below works. What you're likely experiencing is a conflict between created function and whatever you have in data

<script>
  export default {
    data() {
      let now = new Date()
      let today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      let todayMinusSixteenYears = new Date(today)
      todayMinusSixteenYears.setFullYear(todayMinusSixteenYears.getFullYear() - 16)

      return {
        value: '',
        maxBirthdate: todayMinusSixteenYears,
      }
    }
  }
</script>


问:
How to read character by character right to left?
I hope and you can help me please, I have a label that shows a value in binary.

Example: "1000010101", this data, I'm reading it with an inverted for. That is, starting from right to left, the binary number is dynamic, so it will not always be the same.

Until now this is my idea, but it does not give me any value

```<code>for (int i = lbl_conversion.Text.Length; i > 0; i--)
    {
        if (st[i] == 1)
        {
            MessageBox("1");
        }
        else
        {
            MessageBox("0");
        }

    }
</code>```

What I would like is to read character by character from left to right and know if it is "1" or "0" and then make a comparison, could someone support me to get that result?

Thank you.

答:
When you need read the string to right to left, typically you know the number of character to have to read.

I have this function.

```<code> private string GetValue(string strValor, int lenght)
    {
        if (strValor.Length > lenght)
            return strValor.Substring(strValor.Length - lenght, lenght);
        return strValor;
    }
</code>```

strValor: String to read.

lenght: Number of character to read.

Example: GetValue("R6C5736423792", 10); return "5736423792"

Body:
I hope and you can help me please, I have a label that shows a value in binary.

Example: "1000010101", this data, I'm reading it with an inverted for. That is, starting from right to left, the binary number is dynamic, so it will not always be the same.

Until now this is my idea, but it does not give me any value

for (int i = lbl_conversion.Text.Length; i > 0; i--)
    {
        if (st[i] == 1)
        {
            MessageBox("1");
        }
        else
        {
            MessageBox("0");
        }

    }

What I would like is to read character by character from left to right and know if it is "1" or "0" and then make a comparison, could someone support me to get that result?

Thank you.

Body:
When you need read the string to right to left, typically you know the number of character to have to read.

I have this function.

 private string GetValue(string strValor, int lenght)
    {
        if (strValor.Length > lenght)
            return strValor.Substring(strValor.Length - lenght, lenght);
        return strValor;
    }

strValor: String to read.

lenght: Number of character to read.

Example: GetValue("R6C5736423792", 10); return "5736423792"


问:
Firebase import export JSON not found
I create a collection in Firebase as shown in the picture:

In the old version, there was a three button in the top, where you can import and export data as JSON and other types, but now I can't find it.

Does the tool change this action (import/export) or I should to do some configuration to solve this?

答:
You'll need to export/import this on your own.

Documents for Exporting and importing data

Title: Firebase import export JSON not found


问:
What is a good solution to synchronize data between iOS apps?
I am developing an application, whose data management is realized through Core Data, and I am studying how to implement a feature to synchronize data between two different devices (even between iDevices and Mac's eventually).

Until now I haven't found nothing interesting or useful, so I am asking you for a good start point, a guide, or a model to follow. Did you ever realize something like this?

Update

I've started a bounty on this question. Synchronization could be a difficult task on iOS, but come on, there's plenty of apps out there that offer device-to-device sync functionalities. My question is: how they do this? What's the best approach? What are the different solutions?

Update 2

This question is surely outdated, right now, since iCloud has been released almost a year ago. I'd like to keep it alive since it can give interesting insights on mobile data synchronization between devices.

答:
If you want to do it yourself, this can be a very nice, yet challenging exercise. I don't know of any 3rd party frameworks that facilitate P2P connectivity between "iDevices", other than the ones below, from Apple. You can do some research along those lines if you don't want to re-invent the wheel. I am answering based on my (little) experience with implementing a syncing service via an app server - the principles must be more or less the same with a P2P approach.

The first step would be to design a protocol for syncing your data. Questions you might have to answer for yourself:

What do I need to understand about data synchronization?

Which part of my Core Data model do I want to sync? Should I make changes to my current model to facilitate syncing?

What serialization/deserialization mechanism will I use?

How will I be able to uniquely identify entities across multiple devices?

How will I version my data? How can I tell which entities need to be sync'ed?

Do I need to be able to revert a syncing operation?

How will I keep track of sync progress and how will I handle failures and exception cases? How will I notify the user of these?

Do I prefer to sync "incrementally" (parts of my model) or "globally" (the whole model at once)?

How often will the user need to sync between devices?

Are there any security considerations? Do I need encryption?

etc.

This is barely scratching the surface. You will definitely find more things to think about as you move forward.

Next, determine how you want to connect between devices. You seem to prefer an over-the-air solution, the P2P kind. For that, I would start by looking at these tools:

GameKit (this framework has APIs for establishing connectivity between devices over Bluetooth)

Bonjour (the Apple protocol for device discovery over a network - see the BonjourWeb sample application) + BSD sockets

Pick whichever tool(s) you feel most comfortable with and based on your design decisions discussed earlier. I can't help you there, as I don't have any experience with either of them. As Morpheus said:

I can only show you the door. You're
  the one that has to walk through it.

Sorry, little humor :)

Finally, decide on a solution to implement your syncing mechanism. You could e.g. choose a client-server model (one device will listen for a connection and another one will initiate it).

More relevant documentation:

Networking & Internet Starting Point

Document Transfer Strategies

I hope this gives you a starting path.


问:
Error Invalid option '6' for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default
I am trying to target .NET 4.6 and also take advantage of the latest C# version by changing the C# language version to 6.

However during compilation I got this error:

Error Invalid option '6' for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If I update the /langversion:6 in Web.Config setting to 5 it works,

```<code>  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701">
</code>```

But how do I resolve this without resorting to lower language version?

I am using Visual Studio 2015 Community Edition, and I have also installed .NET Framework 4.6 manually just in case it was not installed by default by Visual Studio 2015.

The project is a standard ASP.NET MVC template project created by Visual Studio 2015.

答: I had similar issue when I was loading application for the first time in visual studio 2019. Updating "Microsoft.CodeDom.Providers.DotNetCompilerPlatform" nuget to later version did the trick for me.</p>

Body:
I am trying to target .NET 4.6 and also take advantage of the latest C# version by changing the C# language version to 6.

However during compilation I got this error:

Error Invalid option '6' for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If I update the /langversion:6 in Web.Config setting to 5 it works,

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701">

But how do I resolve this without resorting to lower language version?

I am using Visual Studio 2015 Community Edition, and I have also installed .NET Framework 4.6 manually just in case it was not installed by default by Visual Studio 2015.

The project is a standard ASP.NET MVC template project created by Visual Studio 2015.


问:
How can i align (center) row data in Python PyQt5 QTableView?
I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

Re:I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

```<code>class App(Ui_MainWindow):
    def __init__(self, window):
        self.setupUi(window)
        # code...
        numbers = [["Thomas","17776661122",❌],["Parker","1777666331",❌],["Michael","17775553322",❌]]
        CreateTable()
    def CreateTable(self,fromlist):
        for i in range(0,len(fromlist)):
            self.model.addCustomer(Customer(fromlist[i][0],fromlist[i][1],fromlist[i][2]))
            ### align code
        # code...

</code>```

This is my QtTableView Model.

```<code>class Customer(object):
    def __init__(self,name,number,status):
        self.name = name
        self.number = number
        self.status = status

class CustomerTableModel(QtCore.QAbstractTableModel):

    ROW_BATCH_COUNT = 15

    def __init__(self):
        super(CustomerTableModel,self).__init__()
        self.headers = ['               İsim                     ','  Telefon No (Örn 9053xx..)   ','   Mesaj Durumu   ']
        self.customers  = []
        self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT

    def rowCount(self,index=QtCore.QModelIndex()):
        if not self.customers:
            return 0

        if len(self.customers) <= self.rowsLoaded:
            return len(self.customers)
        else:
            return self.rowsLoaded

    def canFetchMore(self,index=QtCore.QModelIndex()):
        if len(self.customers) > self.rowsLoaded:
            return True
        else:
            return False

    def fetchMore(self,index=QtCore.QModelIndex()):
        reminder = len(self.customers) - self.rowsLoaded
        itemsToFetch = min(reminder,CustomerTableModel.ROW_BATCH_COUNT)
        self.beginInsertRows(QtCore.QModelIndex(),self.rowsLoaded,self.rowsLoaded+itemsToFetch-1)
        self.rowsLoaded += itemsToFetch
        self.endInsertRows()

    def addCustomer(self,customer):
        self.beginResetModel()
        self.customers.append(customer)
        self.endResetModel()

    def columnCount(self,index=QtCore.QModelIndex()):
        return len(self.headers)

    def data(self,index,role=QtCore.Qt.DisplayRole):
        col = index.column()
        customer = self.customers[index.row()]
        if role == QtCore.Qt.DisplayRole:
            if col == 0:
                return QtCore.QVariant(customer.name)
            elif col == 1:
                return QtCore.QVariant(customer.number)
            elif col == 2:
                return QtCore.QVariant(customer.status)
            return QtCore.QVariant()

    def headerData(self,section,orientation,role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            return QtCore.QVariant(self.headers[section])
        return QtCore.QVariant(int(section + 1))
</code>```

P.S. : Sorry for my English :-)

答:
I found the solution. I added the this line to ...</p>

```<code>def data(self,index,role=QtCore.Qt.DisplayRole):
    col = index.column()
    customer = self.customers[index.row()]
    if role == QtCore.Qt.DisplayRole:
        if col == 0:
            return QtCore.QVariant(customer.name)
        elif col == 1:
            return QtCore.QVariant(customer.number)
        elif col == 2:
            return QtCore.QVariant(customer.status)
        return QtCore.QVariant()
    # ADDED LINES
    elif role == QtCore.Qt.TextAlignmentRole:
        return QtCore.Qt.AlignCenter
    ###
</code>```

Body:
I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

Re:I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?

class App(Ui_MainWindow):
    def __init__(self, window):
        self.setupUi(window)
        # code...
        numbers = [["Thomas","17776661122",❌],["Parker","1777666331",❌],["Michael","17775553322",❌]]
        CreateTable()
    def CreateTable(self,fromlist):
        for i in range(0,len(fromlist)):
            self.model.addCustomer(Customer(fromlist[i][0],fromlist[i][1],fromlist[i][2]))
            ### align code
        # code...

This is my QtTableView Model.

class Customer(object):
    def __init__(self,name,number,status):
        self.name = name
        self.number = number
        self.status = status

class CustomerTableModel(QtCore.QAbstractTableModel):

    ROW_BATCH_COUNT = 15

    def __init__(self):
        super(CustomerTableModel,self).__init__()
        self.headers = ['               İsim                     ','  Telefon No (Örn 9053xx..)   ','   Mesaj Durumu   ']
        self.customers  = []
        self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT

    def rowCount(self,index=QtCore.QModelIndex()):
        if not self.customers:
            return 0

        if len(self.customers) <= self.rowsLoaded:
            return len(self.customers)
        else:
            return self.rowsLoaded

    def canFetchMore(self,index=QtCore.QModelIndex()):
        if len(self.customers) > self.rowsLoaded:
            return True
        else:
            return False

    def fetchMore(self,index=QtCore.QModelIndex()):
        reminder = len(self.customers) - self.rowsLoaded
        itemsToFetch = min(reminder,CustomerTableModel.ROW_BATCH_COUNT)
        self.beginInsertRows(QtCore.QModelIndex(),self.rowsLoaded,self.rowsLoaded+itemsToFetch-1)
        self.rowsLoaded += itemsToFetch
        self.endInsertRows()

    def addCustomer(self,customer):
        self.beginResetModel()
        self.customers.append(customer)
        self.endResetModel()

    def columnCount(self,index=QtCore.QModelIndex()):
        return len(self.headers)

    def data(self,index,role=QtCore.Qt.DisplayRole):
        col = index.column()
        customer = self.customers[index.row()]
        if role == QtCore.Qt.DisplayRole:
            if col == 0:
                return QtCore.QVariant(customer.name)
            elif col == 1:
                return QtCore.QVariant(customer.number)
            elif col == 2:
                return QtCore.QVariant(customer.status)
            return QtCore.QVariant()

    def headerData(self,section,orientation,role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            return QtCore.QVariant(self.headers[section])
        return QtCore.QVariant(int(section + 1))

P.S. : Sorry for my English :-)

Body:
I found the solution. I added the this line to ...

def data(self,index,role=QtCore.Qt.DisplayRole):
    col = index.column()
    customer = self.customers[index.row()]
    if role == QtCore.Qt.DisplayRole:
        if col == 0:
            return QtCore.QVariant(customer.name)
        elif col == 1:
            return QtCore.QVariant(customer.number)
        elif col == 2:
            return QtCore.QVariant(customer.status)
        return QtCore.QVariant()
    # ADDED LINES
    elif role == QtCore.Qt.TextAlignmentRole:
        return QtCore.Qt.AlignCenter
    ###


问:
Is it possible to `continue` a foreach loop while in a for loop?
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

```<code>public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}
</code>```

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

答:
Regular Expressions are perfectly suited to handle this type of "problem" and is considerably more flexible...for one thing you would not be limited to consecutive characters. The following console app demonstrates how to use Regex to extract the desired information from the targeted string.

```<code>private static string TestSearchTextRegex(string textToSearch)
{
    var pattern = "[^a-m]";
    var ms = Regex.Matches(textToSearch, pattern);

    return $"{ms.Count}/{textToSearch.Length}";
}
</code>```

NOTE

The pattern "[^a-m]" basically says: find a match that is NOT (^) in the set of characters. This pattern could easily be defined as "[^a-mz]" which in addition to characters "a-m" would also consider "z" to also be a character that would not be counted in the error group.

Another advantage to the Regex solution, you are able to use the actual characters you are looking for as apposed to the number that represents that character.

Body:
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

Body:
Regular Expressions are perfectly suited to handle this type of "problem" and is considerably more flexible...for one thing you would not be limited to consecutive characters. The following console app demonstrates how to use Regex to extract the desired information from the targeted string.

private static string TestSearchTextRegex(string textToSearch)
{
    var pattern = "[^a-m]";
    var ms = Regex.Matches(textToSearch, pattern);

    return $"{ms.Count}/{textToSearch.Length}";
}

NOTE

The pattern "[^a-m]" basically says: find a match that is NOT (^) in the set of characters. This pattern could easily be defined as "[^a-mz]" which in addition to characters "a-m" would also consider "z" to also be a character that would not be counted in the error group.

Another advantage to the Regex solution, you are able to use the actual characters you are looking for as apposed to the number that represents that character.


问:
vuetify: Align Odd elements to left even elements to right in grid
I have a list of values where I need to place the even elements to the right, odd element to the left in a grid. But every element is getting aligned to the left itself.</p>

```<code>list = [1,2,3,4,5,6]

<v-row>
     <v-col cols="12" v-for="(l,index) in list">
        <v-col v-if="index%2==0" cols="6">{{l}}</v-col>
        <v-col v-else cols="6">{{l}}</v-col>
     </v-col>
</v-row>
</code>```

答:
```<code><v-col cols="6" v-for="(l,index) in list">
  {{l}}
</v-col>
</code>```

Here a demonstration of Mr. Hameeds reply working in a codepen

However, as you can see this approach puts both the odd and even cols in the same row, if you do wish to have them in seperate rows, all you have to do is in your case, put the margin-left style property of the odd columns to auto. Since you are in a flex container, margin-auto will fill up as much space as it can, pushing the component all the way to the left.

Your modified code will look like this:

```<code><v-row>
     <v-col cols="12" v-for="(l,index) in list">
        <v-col v-if="index%2==0" cols="6">{{l}}</v-col>
        <v-col v-else cols="6" class="ml-auto">{{l}}</v-col>
     </v-col>
</v-row>
</code>```

Here the codepen

Body:
I have a list of values where I need to place the even elements to the right, odd element to the left in a grid. But every element is getting aligned to the left itself.

list = [1,2,3,4,5,6]

<v-row>
     <v-col cols="12" v-for="(l,index) in list">
        <v-col v-if="index%2==0" cols="6">{{l}}</v-col>
        <v-col v-else cols="6">{{l}}</v-col>
     </v-col>
</v-row>

Body:
<v-col cols="6" v-for="(l,index) in list">
  {{l}}
</v-col>

Here a demonstration of Mr. Hameeds reply working in a codepen

However, as you can see this approach puts both the odd and even cols in the same row, if you do wish to have them in seperate rows, all you have to do is in your case, put the margin-left style property of the odd columns to auto. Since you are in a flex container, margin-auto will fill up as much space as it can, pushing the component all the way to the left.

Your modified code will look like this:

<v-row>
     <v-col cols="12" v-for="(l,index) in list">
        <v-col v-if="index%2==0" cols="6">{{l}}</v-col>
        <v-col v-else cols="6" class="ml-auto">{{l}}</v-col>
     </v-col>
</v-row>

Here the codepen