问:
Why can't I pass a const object in a const argument function/method?
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

```<code>int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}
</code>```

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

答:
I presume you mean the line

```<code>parentItem->childItems.indexOf(item);
</code>```

doesn't compile.
I also presume you wrote

```<code>QList< ProjTreeItem* > childItems;
</code>```

in parentItem's type(class) definition.

If I understand correctly, in the line

```<code>parentItem->childItems.indexOf(item)
</code>```

you are going to convert ProjTreeItem const* into ProjTreeItem*, and
this requires const_cast.

JaredC has already answered kindly about constness.
I suggest reading his answer again carefully.

Edit:

I think Jon's answer applies to your question.

The 1st parameter of QList::indexOf is T const&, where T is ProjTreeItem*
in your case.

So, the concrete parameter type is ProjTreeItem*const&.

Please note it differs from ProjTreeItem const*const&.

ProjTreeItem* and ProjTreeItem const* are different types.

const_cast is needed to convert from the latter to the former.

ProjTreeItem const* means that ProjTreeItem is const.

However, ProjTreeItem*const& means pointer is const, ProjTreeItem is not const.

Edit2:

You seem to misunderstand.

```<code>#include <typeinfo>
#include <iostream>
using namespace std;

struct ProjTreeItem;

template< class T >
struct Test {
  typedef T const type;
};

int main()
{
  cout<< boolalpha;
  cout<<
    (typeid( Test< ProjTreeItem* >::type ) == typeid( ProjTreeItem const* ))
  <<endl;
  cout<<
    (typeid( Test< ProjTreeItem* >::type ) == typeid( ProjTreeItem*const ))
  <<endl;
}
</code>```

If your interpretation is right, the above code will print true,
and then false.

However, the code prints false, and then true.

Body:
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

Body:
I presume you mean the line

parentItem->childItems.indexOf(item);

doesn't compile.
I also presume you wrote

QList< ProjTreeItem* > childItems;

in parentItem's type(class) definition.

If I understand correctly, in the line

parentItem->childItems.indexOf(item)

you are going to convert ProjTreeItem const* into ProjTreeItem*, and
this requires const_cast.

JaredC has already answered kindly about constness.
I suggest reading his answer again carefully.

Edit:

I think Jon's answer applies to your question.

The 1st parameter of QList::indexOf is T const&, where T is ProjTreeItem*
in your case.

So, the concrete parameter type is ProjTreeItem*const&.

Please note it differs from ProjTreeItem const*const&.

ProjTreeItem* and ProjTreeItem const* are different types.

const_cast is needed to convert from the latter to the former.

ProjTreeItem const* means that ProjTreeItem is const.

However, ProjTreeItem*const& means pointer is const, ProjTreeItem is not const.

Edit2:

You seem to misunderstand.

#include <typeinfo>
#include <iostream>
using namespace std;

struct ProjTreeItem;

template< class T >
struct Test {
  typedef T const type;
};

int main()
{
  cout<< boolalpha;
  cout<<
    (typeid( Test< ProjTreeItem* >::type ) == typeid( ProjTreeItem const* ))
  <<endl;
  cout<<
    (typeid( Test< ProjTreeItem* >::type ) == typeid( ProjTreeItem*const ))
  <<endl;
}

If your interpretation is right, the above code will print true,
and then false.

However, the code prints false, and then true.


来源: stackexchange

问:
How to change Angular 5 Material input placeholder?
How do you change the placeholder colour on a angular/material input placeholder?</p>

```<code><mat-form-field>
    <input matInput placeholder="Name">
  </mat-form-field>
</code>```

答:
To change the color of placeholder, override the color property of .mat-form-field-placeholder like:

```<code>::ng-deep .mat-form-field-placeholder{

  color:red;
}

::ng-deep .mat-focused .mat-form-field-placeholder{

  color:red;
}
</code>```

To change the color of underline:

```<code>::ng-deep .mat-form-field-underline .mat-form-field-ripple{

  background-color:red;
}

::ng-deep .mat-form-field-underline{

  background-color:red;
}
</code>```

This works perfect.
Demo: https://plnkr.co/edit/yF4kXJ500YzefLOnLKNe?p=preview

ContentLicense: CC BY-SA 3.0

Body:
How do you change the placeholder colour on a angular/material input placeholder?

<mat-form-field>
    <input matInput placeholder="Name">
  </mat-form-field>

Body:
To change the color of placeholder, override the color property of .mat-form-field-placeholder like:

::ng-deep .mat-form-field-placeholder{

  color:red;
}

::ng-deep .mat-focused .mat-form-field-placeholder{

  color:red;
}

To change the color of underline:

::ng-deep .mat-form-field-underline .mat-form-field-ripple{

  background-color:red;
}

::ng-deep .mat-form-field-underline{

  background-color:red;
}

This works perfect.
Demo: https://plnkr.co/edit/yF4kXJ500YzefLOnLKNe?p=preview


问:
Error: "Property 'setIn' does not exist on type 'Map<any, any>'"
I'm (fairly) new to Immutable.js and Redux (and Angular2) and getting the error in the title (I get an error both for setIn and getIn). The error comes from my store.ts. Here's the short version:

import { Action as reduxAction, Reducer, combineReducers } from 'redux';
import { ActionActions } from './actions/action.actions';
import { UserActions } from './actions/user.actions';
import { MetaActions } from './actions/meta.actions';
import { Action } from './app/library/action/class.action';
import * as Immutable from 'immutable';
import 'rxjs/add/operator/map';

export interface IAppState {
    action: IActionState
}

export interface IActionState {
    action?: Map<any, any>
}

export const INITIAL_STATE: IAppState = {
    action: {
        action: null
    }
}

export function actionReducer(lastState: IActionState, action)
{
    // Initial action state
    if (undefined === lastState) {
        lastState = {
            action: null
        }
    }

    // Switching
    switch(action.type)
    {
        case ActionActions.REMOVE_EMPLOYEE:
        {
            return { action: lastState.action.setIn(['employees', action.value.role],
                lastState.action.getIn(['employees', action.value.role])
                .filter(o => o.getIn(['employee','employeeId']) !== action.value.employeeId)) };
        }
    }

    return { action: lastState.action }
}```

(Please don't be confused that the object I'm working on also happens to be named "action". It's a bit unlucky in the context of Redux but it does make sense in the context of the application as such.)

When the compiler (transpiler?) runs in the terminal I get the error in the title but the script works just fine when I run the website. No problem at all. Just the error in the terminal.

If I try running Immutable.map.isMap() on the action-object it returns true. Also methods get() and set() seems to exist on the object.

So if it in fact is a Map and set() and get() works - why not setIn() and getIn()? To be clear - they do work - perfectly. I just get an error in the terminal.

I can use setIn() and getIn() elsewhere in the application. Even on the same object. So why not in the store.ts? Is it a problem in my imports?

答:
Okay - after many intensive meetings between forehead and wall it seems I have solved the issue myself.

I imported the Immutable.js library as such:

```<code>import * as Immutable from 'immutable';
</code>```

And then I instantiated the (interface for the) object like so:

```<code>action?: Map<any, any>
</code>```

When it should have been

```<code>action?: Immutable.Map<any, any>
</code>```

Apparently this works.

This maybe seems obvious for some, but I was thrown off because Immutable.map.isMap() evaluated true.

Body:
I'm (fairly) new to Immutable.js and Redux (and Angular2) and getting the error in the title (I get an error both for setIn and getIn). The error comes from my store.ts. Here's the short version:

import { Action as reduxAction, Reducer, combineReducers } from 'redux';
import { ActionActions } from './actions/action.actions';
import { UserActions } from './actions/user.actions';
import { MetaActions } from './actions/meta.actions';
import { Action } from './app/library/action/class.action';
import * as Immutable from 'immutable';
import 'rxjs/add/operator/map';

export interface IAppState {
    action: IActionState
}

export interface IActionState {
    action?: Map<any, any>
}

export const INITIAL_STATE: IAppState = {
    action: {
        action: null
    }
}

export function actionReducer(lastState: IActionState, action)
{
    // Initial action state
    if (undefined === lastState) {
        lastState = {
            action: null
        }
    }

    // Switching
    switch(action.type)
    {
        case ActionActions.REMOVE_EMPLOYEE:
        {
            return { action: lastState.action.setIn(['employees', action.value.role],
                lastState.action.getIn(['employees', action.value.role])
                .filter(o => o.getIn(['employee','employeeId']) !== action.value.employeeId)) };
        }
    }

    return { action: lastState.action }
}

(Please don't be confused that the object I'm working on also happens to be named "action". It's a bit unlucky in the context of Redux but it does make sense in the context of the application as such.)

When the compiler (transpiler?) runs in the terminal I get the error in the title but the script works just fine when I run the website. No problem at all. Just the error in the terminal.

If I try running Immutable.map.isMap() on the action-object it returns true. Also methods get() and set() seems to exist on the object.

So if it in fact is a Map and set() and get() works - why not setIn() and getIn()? To be clear - they do work - perfectly. I just get an error in the terminal.

I can use setIn() and getIn() elsewhere in the application. Even on the same object. So why not in the store.ts? Is it a problem in my imports?

Body:
Okay - after many intensive meetings between forehead and wall it seems I have solved the issue myself.

I imported the Immutable.js library as such:

import * as Immutable from 'immutable';

And then I instantiated the (interface for the) object like so:

action?: Map<any, any>

When it should have been

action?: Immutable.Map<any, any>

Apparently this works.

This maybe seems obvious for some, but I was thrown off because Immutable.map.isMap() evaluated true.


问:
Unity - using enum properties to detect objects colliding
Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other.  I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).

For detecting the collisions on the GateManager I was using tags for each gate. So for example:

```<code>    void OnTriggerEnter(Collider collider) {
       switch (gameObject.tag) {
         case "WoodenGate":
             ...
         case "StoneGate":
             ...
</code>```

The above code isn't exact but should give an idea.  It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).

So I came up with an alternative.  I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate).  I then attached a public GateType property to the GateManager class.  This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity.  It was very neat and I was really happy.

Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate.  This meant the metal gate prefab suddenly had a GateType of stonegate.  Which broke my game.

Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items?  I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.

I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?

答: You could set it up as per the spawn/init event.  If you're going to use the enum method you could just define it when the object is spawned.  This obviously depends on your game mechanic.  However I would probably outsource this to a monobehaviour specifically for the material behaviour you want.  That way if you want to change how the wood arches behaves you just have to update the one script and it's self contained.  this will help as your codebase gets bigger and will improve the compile and load times if you use the features of 2017.3 that allow you to define which files go into which assemblies</p>

Body:
Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other.  I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).

For detecting the collisions on the GateManager I was using tags for each gate. So for example:

    void OnTriggerEnter(Collider collider) {
       switch (gameObject.tag) {
         case "WoodenGate":
             ...
         case "StoneGate":
             ...

The above code isn't exact but should give an idea.  It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).

So I came up with an alternative.  I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate).  I then attached a public GateType property to the GateManager class.  This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity.  It was very neat and I was really happy.

Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate.  This meant the metal gate prefab suddenly had a GateType of stonegate.  Which broke my game.

Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items?  I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.

I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?


问:
C# jQuery Ajax Post Getting Blocked by IIS Rewrite Rule
Our domain on the product server has a couple of url rewrites which I think are preventing the jQuery from posting.

I have tried the same script on a domain same server which has no rewrite rules and the script works.

The full script I'm testing is this
https://www.aspsnippets.com/Articles/Load-data-while-Scrolling-Page-down-with-jQuery-AJAX-and-ASPNet.aspx

I just can't get my head around how to solve it. I think the rewrite rule causing the issues is the one which creates endless urls which removes the ".aspx" extension from the page name

this is the function

```<code>    function GetRecords() {
    pageIndex++;
    if (pageIndex == 2 || pageIndex <= pageCount) {
        $("#loader").show();
        $.ajax({
            type: "POST",
            url: "CS.aspx/GetCustomers",
            data: '{pageIndex: ' + pageIndex + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }
}
</code>```

I have tried removing the .aspx in the code above but didn't make any change

The rewrite rules to remove the ".aspx" is this

```<code>    <rule name="extensionless" stopProcessing="true">
      <match url="(.*)\.aspx$" />
      <action type="Redirect" url="{R:1}" redirectType="Permanent" />
</rule>
<rule name="removeextension" enabled="true">
    <match url=".*" negate="false" />
         <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{URL}" pattern="(.*)\.(.*)" negate="true" />
        </conditions>
        <action type="Rewrite" url="{R:0}.aspx" />
</rule>
</code>```

The rewrite rules to remove the "&"

```<code>    <rule name="Rewrite URL to remove & from path." stopProcessing="true">
    <match url="^(.*)\:\[20\](.*)$" />
    <conditions logicalGrouping="MatchAny" />
    <action type="Redirect" url="{R:1}" appendQueryString="false" redirectType="Permanent" />
  </rule>
</code>```

The rewrite rules to remove the "80"

```<code>    <rule name="Rewrite URL to remove [80] from path." stopProcessing="true">
    <match url="^(.*)\:\[80\](.*)$" />
    <conditions logicalGrouping="MatchAny" />
    <action type="Redirect" url="{R:1}" appendQueryString="false" redirectType="Permanent" />
  </rule>
</code>```

I'm not 100% on why the last 2 rules are in place it must be historic as this is a very old site.

The web config rewrite rules are the only differences between the 2 domains I've tested. Obviously I need to keep the rewrite rules in place and hope someone can help me solve this.

Also if I load the following in the browser

domain.com/CS.aspx/GetCustomers

the page does load

if I load

domain.com/CS/GetCustomers

I get a 404 error

Thanks

答:
I could kick myself

I was calling http instead of https for

http://ajax.googleapis.com

and it was getting blocked

Body:
Our domain on the product server has a couple of url rewrites which I think are preventing the jQuery from posting.

I have tried the same script on a domain same server which has no rewrite rules and the script works.

The full script I'm testing is this
https://www.aspsnippets.com/Articles/Load-data-while-Scrolling-Page-down-with-jQuery-AJAX-and-ASPNet.aspx

I just can't get my head around how to solve it. I think the rewrite rule causing the issues is the one which creates endless urls which removes the ".aspx" extension from the page name

this is the function

    function GetRecords() {
    pageIndex++;
    if (pageIndex == 2 || pageIndex <= pageCount) {
        $("#loader").show();
        $.ajax({
            type: "POST",
            url: "CS.aspx/GetCustomers",
            data: '{pageIndex: ' + pageIndex + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }
}

I have tried removing the .aspx in the code above but didn't make any change

The rewrite rules to remove the ".aspx" is this

    <rule name="extensionless" stopProcessing="true">
      <match url="(.*)\.aspx$" />
      <action type="Redirect" url="{R:1}" redirectType="Permanent" />
</rule>
<rule name="removeextension" enabled="true">
    <match url=".*" negate="false" />
         <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{URL}" pattern="(.*)\.(.*)" negate="true" />
        </conditions>
        <action type="Rewrite" url="{R:0}.aspx" />
</rule>

The rewrite rules to remove the "&"

    <rule name="Rewrite URL to remove & from path." stopProcessing="true">
    <match url="^(.*)\:\[20\](.*)$" />
    <conditions logicalGrouping="MatchAny" />
    <action type="Redirect" url="{R:1}" appendQueryString="false" redirectType="Permanent" />
  </rule>

The rewrite rules to remove the "80"

    <rule name="Rewrite URL to remove [80] from path." stopProcessing="true">
    <match url="^(.*)\:\[80\](.*)$" />
    <conditions logicalGrouping="MatchAny" />
    <action type="Redirect" url="{R:1}" appendQueryString="false" redirectType="Permanent" />
  </rule>

I'm not 100% on why the last 2 rules are in place it must be historic as this is a very old site.

The web config rewrite rules are the only differences between the 2 domains I've tested. Obviously I need to keep the rewrite rules in place and hope someone can help me solve this.

Also if I load the following in the browser

domain.com/CS.aspx/GetCustomers

the page does load

if I load

domain.com/CS/GetCustomers

I get a 404 error

Thanks


问:
Python click button on alert
I am new to python, but need to modify code created by someone else. I am not able to post the full code, but I posted most of it below:

```<code>from bs4 import BeautifulSoup
import datetime
import getpass
from gmail import Gmail
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementNotVisibleException
from time import sleep
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.support import expected_conditions as EC

def soupify(session, url):
    """
    Makes parse-able HTML from any given URL.
    :param session: requests.Session()
    :param url: str
    :return: BeautifulSoup object
    """
    while True:
        try:
            r = session.get(url)
            break
        except Exception as e:
            print(e)
    return BeautifulSoup(r.content, 'html.parser')

def create_http_session():
    """
    Quick little function for returning a requests.Session() instance
    with a properly set User-Agent header.
    :return: requests.Session()
    """
    session = requests.Session()
    session.headers.update({'User-Agent':
                            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
                        })
    return session

def retrieve_hidden_input(soup, name):
    return soup.find('input', attrs={
        'type': 'hidden',
        'name': name
    }).get('value')

class AmericanHomesScraper:
    def __init__(self, username, password, testing):
        self.username = username
        self.password = password
        self.testing = testing
        self.chrome_session = webdriver.PhantomJS()
        self.chrome_session.maximize_window()
        self.g = Gmail()
        self.g.login(username, password)
        self.index = 0

    def check_for_new_emails_from_sender(self,
                                     sender='info@mailer.netflix.com'):
        self.index += 1
        if self.index % 1000 == 0:
            print('Checking emails - {0}.'.format(datetime.datetime.now()))
        elif self.index == 1:
            print('Checking emails - {0}.'.format(datetime.datetime.now()))
        else:
            pass
        for s in sender:
            messages = self.g.inbox().mail(sender=s,
                                       unread=True)
            for message in messages:
                message.read()
                print(
                'Email from {0}: {1}.'.format(s, datetime.datetime.now()))
                self.check_for_listings()
            self.g.logout()
            self.g = Gmail()
            self.g.login(self.username, self.password)

 def login(self, username, ahsPassword):
    self.ahsPassword = ahsPassword
    self.chrome_session.get('https://www.aaa.com/Login.aspx')
    self.chrome_session.find_element_by_xpath(
        '//*[@id="txtUsername"]'
    ).send_keys(username)
    self.chrome_session.find_element_by_xpath(
        '//*[@id="txtPassword"]'
    ).send_keys(ahsPassword)
    self.chrome_session.find_element_by_xpath(
        '//*[@id="btnSubmit"]'
    ).click()

 def check_for_listings(self):
    #code block
    links = self.chrome_session.find_elements_by_class_name('link-record')
    links = [(link.text, link.get_attribute('href').decode('utf-8'))
             for link in links]
    if len(links) == 0:
        print("No work orders available at {0}".format(
            datetime.datetime.now())
        )
    else:
        for link_text, link_url in links:
            print("Clicking work order {0} at {1}".format(link_text,datetime.datetime.now()))
            self.chrome_session.get(link_url)
            print("Attempting to accept at {0}".format(datetime.datetime.now()))
            try:
                self.chrome_session.find_element_by_xpath("//input[@value='Accept']").click()
                try:
                    WebDriverWait(self.chrome_session, 1).until(EC.alert_is_present)
                    self.chrome_session.switch_to().alert().accept()
                    print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now()))
                except:
                    print "no alert"
            except ElementNotVisibleException:
                print("Accept input not found at {0}".format(datetime.datetime.now()))
            self.chrome_session.back()

def main():
    username = raw_input(
        'Please enter the username of the GMail account you want to monitor.\n>')
    password = getpass.getpass(
        'Please enter the password of the GMail account you want to monitor.\n>')
    ahsPassword = getpass.getpass('Please enter the password for ahs. \n>')
    ahs = AmericanHomesScraper(username, password, testing)
    ahs.login(username,ahsPassword)
    print("Starting script")
    while True:
        ahs.check_for_new_emails_from_sender([
            'crm@aaa.com',
            'ds@aaa.com',
        ])

if __name__ == '__main__':
    main()
</code>```

This correctly finds and clicks the "Accept" input button. After clicking accept, a javascript alert (Ok/Cancel) opens to confirm the acceptance. However, the script does not find the resulting alert. Or, at least it is not able to accept it because the exception is called.

As you can see, I have attempted to switch_to().alert(), but that isn't working.

What am I doing wrong? Thank you so much for your help, I have been working on this for hours.

UPDATE

This code is running on a virtual server and does not use a UI. I just realized that the driver is PhantomJS, not Chrome. So, this is probably why it is failing. I have updated the question to reflect this.

I have tried the suggestions from similar questions, but it isn't working. The 3rd party site requires the alert confirmation to finish the process, but my script cannot see it because it is headless.

答:
I dont know if the below code will help you, at one point I faced the same problem and ended up waiting for an alert and then accepting the alert, worked for me.  </p>

```<code>from selenium.common.exceptions import NoAlertPresentException,

   def wait_for_alert(self):

        for i in range(50):
            try:
                alert = chrome_session.switch_to.alert
                if alert.text:
                   break
            except NoAlertPresentException:
              pass
            time.sleep(.25)
        else:
            raise NoAlertPresentException("Alert visibility timed out")
    return alert

wait_for_alert().accept()
</code>```

Title: Python click button on alert

Body:
I am new to python, but need to modify code created by someone else. I am not able to post the full code, but I posted most of it below:

from bs4 import BeautifulSoup
import datetime
import getpass
from gmail import Gmail
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementNotVisibleException
from time import sleep
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.support import expected_conditions as EC

def soupify(session, url):
    """
    Makes parse-able HTML from any given URL.
    :param session: requests.Session()
    :param url: str
    :return: BeautifulSoup object
    """
    while True:
        try:
            r = session.get(url)
            break
        except Exception as e:
            print(e)
    return BeautifulSoup(r.content, 'html.parser')

def create_http_session():
    """
    Quick little function for returning a requests.Session() instance
    with a properly set User-Agent header.
    :return: requests.Session()
    """
    session = requests.Session()
    session.headers.update({'User-Agent':
                            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
                        })
    return session

def retrieve_hidden_input(soup, name):
    return soup.find('input', attrs={
        'type': 'hidden',
        'name': name
    }).get('value')

class AmericanHomesScraper:
    def __init__(self, username, password, testing):
        self.username = username
        self.password = password
        self.testing = testing
        self.chrome_session = webdriver.PhantomJS()
        self.chrome_session.maximize_window()
        self.g = Gmail()
        self.g.login(username, password)
        self.index = 0

    def check_for_new_emails_from_sender(self,
                                     sender='info@mailer.netflix.com'):
        self.index += 1
        if self.index % 1000 == 0:
            print('Checking emails - {0}.'.format(datetime.datetime.now()))
        elif self.index == 1:
            print('Checking emails - {0}.'.format(datetime.datetime.now()))
        else:
            pass
        for s in sender:
            messages = self.g.inbox().mail(sender=s,
                                       unread=True)
            for message in messages:
                message.read()
                print(
                'Email from {0}: {1}.'.format(s, datetime.datetime.now()))
                self.check_for_listings()
            self.g.logout()
            self.g = Gmail()
            self.g.login(self.username, self.password)

 def login(self, username, ahsPassword):
    self.ahsPassword = ahsPassword
    self.chrome_session.get('https://www.aaa.com/Login.aspx')
    self.chrome_session.find_element_by_xpath(
        '//*[@id="txtUsername"]'
    ).send_keys(username)
    self.chrome_session.find_element_by_xpath(
        '//*[@id="txtPassword"]'
    ).send_keys(ahsPassword)
    self.chrome_session.find_element_by_xpath(
        '//*[@id="btnSubmit"]'
    ).click()

 def check_for_listings(self):
    #code block
    links = self.chrome_session.find_elements_by_class_name('link-record')
    links = [(link.text, link.get_attribute('href').decode('utf-8'))
             for link in links]
    if len(links) == 0:
        print("No work orders available at {0}".format(
            datetime.datetime.now())
        )
    else:
        for link_text, link_url in links:
            print("Clicking work order {0} at {1}".format(link_text,datetime.datetime.now()))
            self.chrome_session.get(link_url)
            print("Attempting to accept at {0}".format(datetime.datetime.now()))
            try:
                self.chrome_session.find_element_by_xpath("//input[@value='Accept']").click()
                try:
                    WebDriverWait(self.chrome_session, 1).until(EC.alert_is_present)
                    self.chrome_session.switch_to().alert().accept()
                    print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now()))
                except:
                    print "no alert"
            except ElementNotVisibleException:
                print("Accept input not found at {0}".format(datetime.datetime.now()))
            self.chrome_session.back()

def main():
    username = raw_input(
        'Please enter the username of the GMail account you want to monitor.\n>')
    password = getpass.getpass(
        'Please enter the password of the GMail account you want to monitor.\n>')
    ahsPassword = getpass.getpass('Please enter the password for ahs. \n>')
    ahs = AmericanHomesScraper(username, password, testing)
    ahs.login(username,ahsPassword)
    print("Starting script")
    while True:
        ahs.check_for_new_emails_from_sender([
            'crm@aaa.com',
            'ds@aaa.com',
        ])

if __name__ == '__main__':
    main()

This correctly finds and clicks the "Accept" input button. After clicking accept, a javascript alert (Ok/Cancel) opens to confirm the acceptance. However, the script does not find the resulting alert. Or, at least it is not able to accept it because the exception is called.

As you can see, I have attempted to switch_to().alert(), but that isn't working.

What am I doing wrong? Thank you so much for your help, I have been working on this for hours.

UPDATE

This code is running on a virtual server and does not use a UI. I just realized that the driver is PhantomJS, not Chrome. So, this is probably why it is failing. I have updated the question to reflect this.

I have tried the suggestions from similar questions, but it isn't working. The 3rd party site requires the alert confirmation to finish the process, but my script cannot see it because it is headless.

Body:
I dont know if the below code will help you, at one point I faced the same problem and ended up waiting for an alert and then accepting the alert, worked for me.

from selenium.common.exceptions import NoAlertPresentException,

   def wait_for_alert(self):

        for i in range(50):
            try:
                alert = chrome_session.switch_to.alert
                if alert.text:
                   break
            except NoAlertPresentException:
              pass
            time.sleep(.25)
        else:
            raise NoAlertPresentException("Alert visibility timed out")
    return alert

wait_for_alert().accept()


问:
C# Dynamic extends a object
is it possible to extends a existing object ?

i have the code

```<code>var record = new
{
    id,
    name
};
</code>```

and have a list of anonymous objects

```<code>var list = new List<object>(){ object1, object2 };
</code>```

Can i add them later to the object ?
Like something as

```<code>foreach (var o in list)
{
    record.add(o);
}
</code>```

that i will get this as result

```<code>var record = new
{
    id,
    name,
    object1,
    object2
};
</code>```

答:
What you can do is create a class Extension. It is not possible to add new methods in the runtime, but you can do something like this:

```<code>public class OneClass
{
  private List<object> items;
  public List<object> Items { get { return items; } }
  public void AddOne(object item)
  {
    items.Add(item);
  }
}
</code>```

if you want to extend this class behavior, you can write an extension class. Like this:

```<code>public static class OneClassExtensions
{
  public void AddMany(this OneClass self, params object[] items)
  {
    foreach(object item in items)
    {
      self.Items.Add(item);
    }
  }
}
</code>```

This way you can call this extension method from your OneClass objects:

```<code>OneClass obj = new OneClass();
obj.AddOne("hello");
obj.AddMany("Hello", "world"); // Extension method
</code>```

There are some rules to follow:

The extension class must have the `static' modifier

you need to put the `this' prefix before the first argument. This argument would be the object itself.

In order to use this extension class in your code, you must use the namespace that contains that extension class, like `using Some.Namespace.That.Has.An.Extension' in every .cs file where you want to use extension methods.

ContentLicense: CC BY-SA 2.5

Title: C# Dynamic extends a object

Body:
is it possible to extends a existing object ?

i have the code

var record = new
{
    id,
    name
};

and have a list of anonymous objects

var list = new List<object>(){ object1, object2 };

Can i add them later to the object ?
Like something as

foreach (var o in list)
{
    record.add(o);
}

that i will get this as result

var record = new
{
    id,
    name,
    object1,
    object2
};

Body:
What you can do is create a class Extension. It is not possible to add new methods in the runtime, but you can do something like this:

public class OneClass
{
  private List<object> items;
  public List<object> Items { get { return items; } }
  public void AddOne(object item)
  {
    items.Add(item);
  }
}

if you want to extend this class behavior, you can write an extension class. Like this:

public static class OneClassExtensions
{
  public void AddMany(this OneClass self, params object[] items)
  {
    foreach(object item in items)
    {
      self.Items.Add(item);
    }
  }
}

This way you can call this extension method from your OneClass objects:

OneClass obj = new OneClass();
obj.AddOne("hello");
obj.AddMany("Hello", "world"); // Extension method

There are some rules to follow:

The extension class must have the `static' modifier

you need to put the `this' prefix before the first argument. This argument would be the object itself.

In order to use this extension class in your code, you must use the namespace that contains that extension class, like `using Some.Namespace.That.Has.An.Extension' in every .cs file where you want to use extension methods.


问:
What does this "!string" mean?
I'm going through an old code library at my workplace to document it and re-use it for other projects.
The Library isn't documented at all (not even comments) but that's not a big deal.

I found this strange syntax and I can't find an explanation online to what it is...

```<code>public bool Validate()
    {
        return !string.IsNullOrWhiteSpace(Code) && !string.IsNullOrWhiteSpace(State);
    }
</code>```

I get that the Exclamation point is the negation operator, but it's only possible to use it with Boolean variables. How is it possible to say not(string)? What does that exclamation point before the string keyword does? The tooltip didn't help either..

答:
! means NOT, as in

```<code>**Is `Code` is not a NULL or WhiteSpace**
And
**Is `State` is not a NULL or WhiteSpace**
</code>```

Title: What does this "!string" mean?

Body:
I'm going through an old code library at my workplace to document it and re-use it for other projects.
The Library isn't documented at all (not even comments) but that's not a big deal.

I found this strange syntax and I can't find an explanation online to what it is...

public bool Validate()
    {
        return !string.IsNullOrWhiteSpace(Code) && !string.IsNullOrWhiteSpace(State);
    }

I get that the Exclamation point is the negation operator, but it's only possible to use it with Boolean variables. How is it possible to say not(string)? What does that exclamation point before the string keyword does? The tooltip didn't help either..

Body:
! means NOT, as in

**Is `Code` is not a NULL or WhiteSpace**
And
**Is `State` is not a NULL or WhiteSpace**


问:
Which exception handling should I choose for a client connect
I have a client class which connects to a server via WebRequest. Now I'm struggling with how I could best implement the WebException handling. For a good UI feedback I only need (so far) the exception message and the status.

I came up with three different approaches. The first simply rethrows the exception and I do the handling in the calling method. This might be the most universal solution:

```<code>public class ClientSimpleRethrow
{
    public bool IsConnected { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException)
        {
            IsConnected = false;
            throw;
        }

        IsConnected = true;
    }
}
</code>```

The second version throws a custom exception with the WebException as inner exception. This gives me the benefit of only catching and handling exactly what I expect. For example, there might be another bug which also throws a WebException that I would like to treat differently. So far this is my favorite solution:

```<code>public class ClientThrowCustom
{
    public bool IsConnected { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException ex)
        {
            IsConnected = false;
            throw new ClientConnectionException(ex.Message, ex);
        }

        IsConnected = true;
    }
}
</code>```

There would also be a third possibility I can think about. The exception is catched and I set only the properties I really need to handle the exception in the UI. The info that something went wrong I already have via the IsConnected property. This solution does have the benefit of not catching twice.

```<code>public class ClientProperties
{
    public bool IsConnected { get; set; }
    public string ConnectionErrorMessage { get; set; }
    public WebExceptionStatus? ConnectionErrorStatus { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException ex)
        {
            IsConnected = false;
            ConnectionErrorMessage = ex.Message;
            ConnectionErrorStatus = ex.Status;
            return;
        }

        IsConnected = true;
        ConnectionErrorMessage = null;
        ConnectionErrorStatus = null;
    }
}
</code>```

I would need some best practice advice which one I should choose and why. I hope this question is not too subjective because I really think, there should be some hard facts why to choose one design over the others.

Thanks in advance for your help!

答:
For starters, I think the third method is bad. The nice things about exceptions is they don't force the calling context to check error codes before proceeding. Inside the try block you can write your code as if every function is successful. The third method takes away this nicety and makes the calling code look more complicated.

As for the first two, I prefer the second. It has two benefits in my eyes:

You can make an Exception class that means something in the context of your application and not work around the context of an underlying API. WebException is good for the API, but if you get it in a method when you are trying to log into some system, LogInException is more helpful at the upper layers of your application.

Custom exceptions allow you to start at a base MyApplicationException class and build out from there. From there, you can catch API exceptions and turning them into MyApplicationException child exceptions as soon as possible. This way when an API exception ripples up into your application, you know immediately that there is some corner case that you did not account for and needs to be addressed. Where as an uncaught application exception just means you are not using your own code correctly.

Body:
I have a client class which connects to a server via WebRequest. Now I'm struggling with how I could best implement the WebException handling. For a good UI feedback I only need (so far) the exception message and the status.

I came up with three different approaches. The first simply rethrows the exception and I do the handling in the calling method. This might be the most universal solution:

public class ClientSimpleRethrow
{
    public bool IsConnected { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException)
        {
            IsConnected = false;
            throw;
        }

        IsConnected = true;
    }
}

The second version throws a custom exception with the WebException as inner exception. This gives me the benefit of only catching and handling exactly what I expect. For example, there might be another bug which also throws a WebException that I would like to treat differently. So far this is my favorite solution:

public class ClientThrowCustom
{
    public bool IsConnected { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException ex)
        {
            IsConnected = false;
            throw new ClientConnectionException(ex.Message, ex);
        }

        IsConnected = true;
    }
}

There would also be a third possibility I can think about. The exception is catched and I set only the properties I really need to handle the exception in the UI. The info that something went wrong I already have via the IsConnected property. This solution does have the benefit of not catching twice.

public class ClientProperties
{
    public bool IsConnected { get; set; }
    public string ConnectionErrorMessage { get; set; }
    public WebExceptionStatus? ConnectionErrorStatus { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException ex)
        {
            IsConnected = false;
            ConnectionErrorMessage = ex.Message;
            ConnectionErrorStatus = ex.Status;
            return;
        }

        IsConnected = true;
        ConnectionErrorMessage = null;
        ConnectionErrorStatus = null;
    }
}

I would need some best practice advice which one I should choose and why. I hope this question is not too subjective because I really think, there should be some hard facts why to choose one design over the others.

Thanks in advance for your help!


问:
Get Image from a folder into SQL
I have been searching this problem but I can't find the solution at all..I have my Query on SQL that gives me all the information for each student, I'm going to create an SSRS Report where it shows this information plus I have to show a picture of the student (Every student has a unique ID). I have the picture of every student on a folder, but I don't know how to retrieve it or show it on SQL or if it is even possible to do that..

So..Is there a way to get the image from the folder, get the path or something like that and show it on SQL? All of the images have the same name (ID) that the student.

答:
You can save the image to a SQL column in a table. The link below should help explain how to do it.

How to store image in SQL Server database tables column

Title: Get Image from a folder into SQL


问:
Import Signing Certificate is Failing
I am attempting to create a certificate with a private key (.pfx) that I can use within my application to create and verify digital signatures. I want to install this certificate into the certificate store (Windows).

I am having issues importing the certificate onto my local machine. The certificate import wizard is always reporting 'The password you entered is incorrect'. This is referring to the password for the private key in the pfx file I have created.

Now I know for a fact that the password is correct, so there must be some other factor in play here.

The script I am using to create the key is with a batch file and contains the following command:

```<code>makecert -r -pe -n "CN=%1" -b 01/01/2010 -e 01/01/2060 -sky signature %1.cer -sv %1.pvk
pvk2pfx.exe -pvk %1.pvk -spc %1.cer -pfx %1.pfx
</code>```

Does anyone know what could be causing the import wizard to tell me 'The password you entered is incorrect'?

答:
If you enter the password in the dialogue using pvk2pfx.exe the password will be blank if you try to import the .pfx file later. As others have mentioned you can set a password with -pi. If you wan't a different password than the private key password you can use -po.

pvk2pfx.exe usage instructions:

```<code>pvk2pfx -pvk <pvk-file> [-pi <pvk-pswd>] -spc <spc-file>
       [-pfx <pfx-file> [-po <pfx-pswd>] [-f]]

    -pvk <pvk-file>  - input PVK file name.
    -spc <spc-file>  - input SPC file name.
    -pfx <pfx-file>  - output PFX file name.
    -pi <pvk-pswd>   - PVK password.
    -po <pfx-pswd>   - PFX password; same as -pi if not given.
    -f               - force overwrite existing PFX file.

    if -pfx option is not given, an export wizard will pop up. in
    this case, options -po and -f are ignored.
</code>```

Title: Import Signing Certificate is Failing

Body:
I am attempting to create a certificate with a private key (.pfx) that I can use within my application to create and verify digital signatures. I want to install this certificate into the certificate store (Windows).

I am having issues importing the certificate onto my local machine. The certificate import wizard is always reporting 'The password you entered is incorrect'. This is referring to the password for the private key in the pfx file I have created.

Now I know for a fact that the password is correct, so there must be some other factor in play here.

The script I am using to create the key is with a batch file and contains the following command:

makecert -r -pe -n "CN=%1" -b 01/01/2010 -e 01/01/2060 -sky signature %1.cer -sv %1.pvk
pvk2pfx.exe -pvk %1.pvk -spc %1.cer -pfx %1.pfx

Does anyone know what could be causing the import wizard to tell me 'The password you entered is incorrect'?

Body:
If you enter the password in the dialogue using pvk2pfx.exe the password will be blank if you try to import the .pfx file later. As others have mentioned you can set a password with -pi. If you wan't a different password than the private key password you can use -po.

pvk2pfx.exe usage instructions:

pvk2pfx -pvk <pvk-file> [-pi <pvk-pswd>] -spc <spc-file>
       [-pfx <pfx-file> [-po <pfx-pswd>] [-f]]

    -pvk <pvk-file>  - input PVK file name.
    -spc <spc-file>  - input SPC file name.
    -pfx <pfx-file>  - output PFX file name.
    -pi <pvk-pswd>   - PVK password.
    -po <pfx-pswd>   - PFX password; same as -pi if not given.
    -f               - force overwrite existing PFX file.

    if -pfx option is not given, an export wizard will pop up. in
    this case, options -po and -f are ignored.


问:
Dynamic selection how fetch 'Specific Cities of Specific State of Specific Country'?
I have the following setup of a dynamic select options for Country, State and City using php and jquery ajax.

But the problem with this setup is, if two or more of the states have the same name, all of their associated cities become the output irrespective of country.

Like the image below (please imagine Canada has a state named California for the sake of this example):

How can I solve this problem, that is how can I get the output of Cities of State California of Country USA?

These are the sections I guess I need to improve. I have been trying a few methods but none of them is working. So I'll really appreciate any help.

The ajax:

```<code>$('.action').change(function() {
   if ($(this).val() != '') {
      var action = $(this).attr("id");
      var query = $(this).val();
      var result = '';
      if (action == "country") {
         result = 'state';
      } else {
         result = 'city';
      }
      $.ajax({
         url: "fetch.php",
         method: "POST",
         data: {
            action: action,
            query: query
         },
         success: function(data) {
            $('#' + result).html(data);
         }
      })
   }
});
</code>```

And the php query I have tried:

```<code>$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output.= '<option value="">Select City</option>';

while ($row = mysqli_fetch_array($result))
    {
    $output.= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
    }
</code>```

This is the full code in case you need to have a look:
index.php

```<code><?php
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
    $country .= '<option value="' . $row["country"] . '">' . $row["country"] . '</option>';
}
?>

<select name="country" id="country" class="form-control action">
    <option value="">Select Country</option>
    <?php echo $country; ?>
</select>
<select name="state" id="state" class="form-control action">
    <option value="">Select State</option>
</select>
<select name="city" id="city" class="form-control">
    <option value="">Select City</option>
</select>

<script>
    $(document).ready(function () {
        $('.action').change(function () {
            if ($(this).val() != '')
            {
                var action = $(this).attr("id");
                var query = $(this).val();
                var result = '';
                if (action == "country")
                {
                    result = 'state';
                } else
                {
                    result = 'city';
                }
                $.ajax({
                    url: "fetch.php",
                    method: "POST",
                    data: {action: action, query: query},
                    success: function (data) {
                        $('#' + result).html(data);
                    }
                })
            }
        });
    });
</script>
</code>```

And the fetch.php

```<code><?php

if (isset($_POST["action"])) {
    $output = '';
    if ($_POST["action"] == "country") {
        $query = "SELECT state FROM country_state_city WHERE country = '" . $_POST["query"] . "' GROUP BY state";
        $result = mysqli_query($connect, $query);
        $output .= '<option value="">Select State</option>';
        while ($row = mysqli_fetch_array($result)) {
            $output .= '<option value="' . $row["state"] . '">' . $row["state"] . '</option>';
        }
    }

    if ($_POST["action"] == "state") {
        $query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
        $result = mysqli_query($connect, $query);
        $output .= '<option value="">Select City</option>';
        while ($row = mysqli_fetch_array($result)) {
            $output .= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
        }
    }
    echo $output;
}
?>
</code>```

答:
You need populate next selects for all filled selects before and build right query for data.

@Example for populate CITY you need to know which are COUNTRY and STATE was selected.

PHP

```<code>if(isset($_POST['country']) && $_POST['country'] != ''
    && (!isset($_POST['state']) || $_POST['state'] == '') {
        // return STATES for selected COUNTRY
        $sql = "SELECT country, state FROM tbl WHERE country = {postCountry}";
}
else if(isset($_POST['country']) && $_POST['country'] != ''
    && isset($_POST['state']) && $_POST['state'] == '') {
        // return CITIES for selected COUNTRY and STATE
        $sql = "SELECT country, state, city FROM tbl WHERE country = {postCountry} AND state = {postState}";
}
</code>```

This query

```<code>$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
</code>```

can be changed to DISTINCT

```<code>$query = "SELECT DISTINCT country FROM country_state_city ORDER BY country ASC";
</code>```

JQUERY
Is good approach to wrap data into form because it provides easy work with form elements like selects.

```<code>$('.action').change(function() {
    var formValues = $(this).closest('form').serialize();

    $.ajax({
      url: "fetch.php",
      method: "POST",
      data: formValues,
      success: function (data) {
          $('#' + result).html(data);
      }
  });
});
</code>```

You can check DevTools Console on change and XHR request in Network in demo which values are sent in request to PHP.

DEMO JQUERY

Hope this help.
Happy coding

Body:
I have the following setup of a dynamic select options for Country, State and City using php and jquery ajax.

But the problem with this setup is, if two or more of the states have the same name, all of their associated cities become the output irrespective of country.

Like the image below (please imagine Canada has a state named California for the sake of this example):

How can I solve this problem, that is how can I get the output of Cities of State California of Country USA?

These are the sections I guess I need to improve. I have been trying a few methods but none of them is working. So I'll really appreciate any help.

The ajax:

$('.action').change(function() {
   if ($(this).val() != '') {
      var action = $(this).attr("id");
      var query = $(this).val();
      var result = '';
      if (action == "country") {
         result = 'state';
      } else {
         result = 'city';
      }
      $.ajax({
         url: "fetch.php",
         method: "POST",
         data: {
            action: action,
            query: query
         },
         success: function(data) {
            $('#' + result).html(data);
         }
      })
   }
});

And the php query I have tried:

$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output.= '<option value="">Select City</option>';

while ($row = mysqli_fetch_array($result))
    {
    $output.= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
    }

This is the full code in case you need to have a look:
index.php

<?php
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
    $country .= '<option value="' . $row["country"] . '">' . $row["country"] . '</option>';
}
?>

<select name="country" id="country" class="form-control action">
    <option value="">Select Country</option>
    <?php echo $country; ?>
</select>
<select name="state" id="state" class="form-control action">
    <option value="">Select State</option>
</select>
<select name="city" id="city" class="form-control">
    <option value="">Select City</option>
</select>

And the fetch.php

<?php

if (isset($_POST["action"])) {
    $output = '';
    if ($_POST["action"] == "country") {
        $query = "SELECT state FROM country_state_city WHERE country = '" . $_POST["query"] . "' GROUP BY state";
        $result = mysqli_query($connect, $query);
        $output .= '<option value="">Select State</option>';
        while ($row = mysqli_fetch_array($result)) {
            $output .= '<option value="' . $row["state"] . '">' . $row["state"] . '</option>';
        }
    }

    if ($_POST["action"] == "state") {
        $query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
        $result = mysqli_query($connect, $query);
        $output .= '<option value="">Select City</option>';
        while ($row = mysqli_fetch_array($result)) {
            $output .= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
        }
    }
    echo $output;
}
?>

Body:
You need populate next selects for all filled selects before and build right query for data.

@Example for populate CITY you need to know which are COUNTRY and STATE was selected.

PHP

if(isset($_POST['country']) && $_POST['country'] != ''
    && (!isset($_POST['state']) || $_POST['state'] == '') {
        // return STATES for selected COUNTRY
        $sql = "SELECT country, state FROM tbl WHERE country = {postCountry}";
}
else if(isset($_POST['country']) && $_POST['country'] != ''
    && isset($_POST['state']) && $_POST['state'] == '') {
        // return CITIES for selected COUNTRY and STATE
        $sql = "SELECT country, state, city FROM tbl WHERE country = {postCountry} AND state = {postState}";
}

This query

$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";

can be changed to DISTINCT

$query = "SELECT DISTINCT country FROM country_state_city ORDER BY country ASC";

JQUERY
Is good approach to wrap data into form because it provides easy work with form elements like selects.

$('.action').change(function() {
    var formValues = $(this).closest('form').serialize();

    $.ajax({
      url: "fetch.php",
      method: "POST",
      data: formValues,
      success: function (data) {
          $('#' + result).html(data);
      }
  });
});

You can check DevTools Console on change and XHR request in Network in demo which values are sent in request to PHP.

DEMO JQUERY

Hope this help.
Happy coding


答:
Angular material in itself doesn't provide any directives for setting styles.For this, you need to go old school. Just give an id/class to your input element then use pseudo class (::placeholder).
For reference : https://css-tricks.com/almanac/selectors/p/placeholder/</p>

Title: How to change Angular 5 Material input placeholder?

Body:
How do you change the placeholder colour on a angular/material input placeholder?

<mat-form-field>
    <input matInput placeholder="Name">
  </mat-form-field>


问:
"URLize" string in ruby
I'm getting some strings on human readable format, and those are gonna be titles of my wordpress posts. So, for generate the url for that post, I would like to know if there's some method for "urlize" a string in ruby. For example, if I have the string "Doing some test on my áccented string ", I would like to get "doing-some-test-on-my-accented-string" or do I have to write my own? Thanks in advance!</p>

答:
I used i18n myself on occasion (eg here), but if you don't want to require yet another gem you could also use .tr

```<code>string_with_special_chars.tr(
"ÀÁÂÃÄÅàáâãäåĀāĂăĄąÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňŉŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž",
"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz")
</code>```

Title: "URLize" string in ruby

Body:
I used i18n myself on occasion (eg here), but if you don't want to require yet another gem you could also use .tr

string_with_special_chars.tr(
"ÀÁÂÃÄÅàáâãäåĀāĂăĄąÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňŉŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž",
"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz")


问:
delete whitespace in regular expression
I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt

```<code>import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')

name_files = os.listdir(path_txt)

for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()
</code>```

there are .txt where the sequences appear with spaces between characters, and my regular expression can not find them (example: 00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5)

edit: They are serial numbers, were typed, so sometimes they appear with "." and "-" and other times without them. Sometimes spaces appear because of typos.

答:
You can use \D in your regular expression to match any non-numeric character (including white space) and + to match one or more (or * to match zero or more), so you could rewrite your expression as:

```<code>pattern = r'(\d{5}\D+\d{4}\D+\d{3}\D+\d{2}\D+\d{2}\D+\d)'
re.findall(pattern, '00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5')
# ['00372.2004 .442.02.00-1', '00572.2008.872.02.00- 5']
</code>```

Note I am using re.findall to find every match in the string and return them in a list.

Title: delete whitespace in regular expression

Body:
I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt

import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')

name_files = os.listdir(path_txt)

for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()

there are .txt where the sequences appear with spaces between characters, and my regular expression can not find them (example: 00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5)

edit: They are serial numbers, were typed, so sometimes they appear with "." and "-" and other times without them. Sometimes spaces appear because of typos.

Body:
You can use \D in your regular expression to match any non-numeric character (including white space) and + to match one or more (or * to match zero or more), so you could rewrite your expression as:

pattern = r'(\d{5}\D+\d{4}\D+\d{3}\D+\d{2}\D+\d{2}\D+\d)'
re.findall(pattern, '00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5')
# ['00372.2004 .442.02.00-1', '00572.2008.872.02.00- 5']

Note I am using re.findall to find every match in the string and return them in a list.


问:
powershell verify my array elements type
Sorry for being noob, but I'm trying to understand arrays in powershell.
So I have:

```<code>$a = @("just", "a", "test")
$b = @(1,2,3)
</code>```

No explicit type casting declared.
Is it true that $a array has string elements, and $b has int elements? If so, is there any command to verify and show array elements type? Thanks!

Edited:

```<code>PS> $a | get-member

   TypeName: System.String

Name             MemberType            Definition
----             ----------            ----------
Clone            Method                System.Object Clone()
CompareTo        Method                int CompareTo(System.Object value), int CompareTo(string strB)
Contains         Method                bool Contains(string value)
CopyTo           Method                System.Void CopyTo(int sourceIndex, char[] destination, int destinationIndex,...
EndsWith         Method                bool EndsWith(string value), bool EndsWith(string value, System.StringCompari...
Equals           Method                bool Equals(System.Object obj), bool Equals(string value), bool Equals(string...
GetEnumerator    Method                System.CharEnumerator GetEnumerator()
GetHashCode      Method                int GetHashCode()
GetType          Method                type GetType()
GetTypeCode      Method                System.TypeCode GetTypeCode()
IndexOf          Method                int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf...
IndexOfAny       Method                int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), i...
Insert           Method                string Insert(int startIndex, string value)
IsNormalized     Method                bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normaliz...
LastIndexOf      Method                int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int...
LastIndexOfAny   Method                int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startI...
Normalize        Method                string Normalize(), string Normalize(System.Text.NormalizationForm normalizat...
PadLeft          Method                string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)
PadRight         Method                string PadRight(int totalWidth), string PadRight(int totalWidth, char padding...
Remove           Method                string Remove(int startIndex, int count), string Remove(int startIndex)
Replace          Method                string Replace(char oldChar, char newChar), string Replace(string oldValue, s...
Split            Method                string[] Split(Params char[] separator), string[] Split(char[] separator, int...
StartsWith       Method                bool StartsWith(string value), bool StartsWith(string value, System.StringCom...
Substring        Method                string Substring(int startIndex), string Substring(int startIndex, int length)
ToCharArray      Method                char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)
ToLower          Method                string ToLower(), string ToLower(System.Globalization.CultureInfo culture)
ToLowerInvariant Method                string ToLowerInvariant()
ToString         Method                string ToString(), string ToString(System.IFormatProvider provider)
ToUpper          Method                string ToUpper(), string ToUpper(System.Globalization.CultureInfo culture)
ToUpperInvariant Method                string ToUpperInvariant()
Trim             Method                string Trim(Params char[] trimChars), string Trim()
TrimEnd          Method                string TrimEnd(Params char[] trimChars)
TrimStart        Method                string TrimStart(Params char[] trimChars)
Chars            ParameterizedProperty char Chars(int index) {get;}
Length           Property              System.Int32 Length {get;}
</code>```

As you can see, the get-member doesn't return me string, as expected, but alot of info from which I don't understand anything.

答:
You can use the .GetType() method to verify what Type an object has:

```<code>[PS] $a.GetType().Fullname
[PS] $b.GetType().Fullname
</code>```

You will see that both appear to be:

```<code>System.Object[]
</code>```

Where the [] brackets indicate an array of the System.Object type.

If you use the Get-Member cmdlet you will see what type the data is within the array:

```<code>[PS] $a | Get-Member
[PS] $b | Get-Member
</code>```

You will see the following at the top of the response:

```<code>TypeName: System.String
...

TypeName: System.Int32
....
</code>```

If you have an array with different types, you'll see each type returned.

You can specify what type an array will hold, for example the following array looks like it would hold integers, but actually they are strings:

```<code>[PS] $c = [System.String[]]@(1,2,3)

[PS] $c.GetType().Fullname
System.String[]
</code>```

A bit more on Get-Member...

As we saw above, arrays are often (by default) objects of type [System.Object[]]: these are fairly generic collections which could contain both strings and integers in the array. For example:

```<code>$d = @("One",2,3.0)  # String, Int32, Double

$d | Get-Member
</code>```

When you pipe the object $c into the Get-Member cmdlet, it processes the members of the array and determines their type, hence the second command returns details of all three types.

The extra stuff that is returned by Get-Member tells you what can be done with each type, e.g. a String supports the ToLower method which is not supported for Int or Double types.

A bit more on GetType()...

In order to get the type for each member of the array, you can loop through them:

```<code>[PS] $d | ForEach-Object {$_.GetType().FullName}
System.String
System.Int32
System.Double
</code>```

Looking at the array object in more detail

One thing you might want to experiment with is digging into the nature of the array in which you are holding your data with:

```<code>$d.PSObject
$d.PSObject.BaseObject
$d.PSObject.Members
$d.PSObject.Properties
</code>```

Just remember that you are looking at the array not the data within the array, so the Members and Properties you find relate to the array, not the elements within the array.

Body:
Sorry for being noob, but I'm trying to understand arrays in powershell.
So I have:

$a = @("just", "a", "test")
$b = @(1,2,3)

No explicit type casting declared.
Is it true that $a array has string elements, and $b has int elements? If so, is there any command to verify and show array elements type? Thanks!

Edited:

PS> $a | get-member

   TypeName: System.String

Name             MemberType            Definition
----             ----------            ----------
Clone            Method                System.Object Clone()
CompareTo        Method                int CompareTo(System.Object value), int CompareTo(string strB)
Contains         Method                bool Contains(string value)
CopyTo           Method                System.Void CopyTo(int sourceIndex, char[] destination, int destinationIndex,...
EndsWith         Method                bool EndsWith(string value), bool EndsWith(string value, System.StringCompari...
Equals           Method                bool Equals(System.Object obj), bool Equals(string value), bool Equals(string...
GetEnumerator    Method                System.CharEnumerator GetEnumerator()
GetHashCode      Method                int GetHashCode()
GetType          Method                type GetType()
GetTypeCode      Method                System.TypeCode GetTypeCode()
IndexOf          Method                int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf...
IndexOfAny       Method                int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), i...
Insert           Method                string Insert(int startIndex, string value)
IsNormalized     Method                bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normaliz...
LastIndexOf      Method                int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int...
LastIndexOfAny   Method                int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startI...
Normalize        Method                string Normalize(), string Normalize(System.Text.NormalizationForm normalizat...
PadLeft          Method                string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)
PadRight         Method                string PadRight(int totalWidth), string PadRight(int totalWidth, char padding...
Remove           Method                string Remove(int startIndex, int count), string Remove(int startIndex)
Replace          Method                string Replace(char oldChar, char newChar), string Replace(string oldValue, s...
Split            Method                string[] Split(Params char[] separator), string[] Split(char[] separator, int...
StartsWith       Method                bool StartsWith(string value), bool StartsWith(string value, System.StringCom...
Substring        Method                string Substring(int startIndex), string Substring(int startIndex, int length)
ToCharArray      Method                char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)
ToLower          Method                string ToLower(), string ToLower(System.Globalization.CultureInfo culture)
ToLowerInvariant Method                string ToLowerInvariant()
ToString         Method                string ToString(), string ToString(System.IFormatProvider provider)
ToUpper          Method                string ToUpper(), string ToUpper(System.Globalization.CultureInfo culture)
ToUpperInvariant Method                string ToUpperInvariant()
Trim             Method                string Trim(Params char[] trimChars), string Trim()
TrimEnd          Method                string TrimEnd(Params char[] trimChars)
TrimStart        Method                string TrimStart(Params char[] trimChars)
Chars            ParameterizedProperty char Chars(int index) {get;}
Length           Property              System.Int32 Length {get;}

As you can see, the get-member doesn't return me string, as expected, but alot of info from which I don't understand anything.

Body:
You can use the .GetType() method to verify what Type an object has:

[PS] $a.GetType().Fullname
[PS] $b.GetType().Fullname

You will see that both appear to be:

System.Object[]

Where the [] brackets indicate an array of the System.Object type.

If you use the Get-Member cmdlet you will see what type the data is within the array:

[PS] $a | Get-Member
[PS] $b | Get-Member

You will see the following at the top of the response:

TypeName: System.String
...

TypeName: System.Int32
....

If you have an array with different types, you'll see each type returned.

You can specify what type an array will hold, for example the following array looks like it would hold integers, but actually they are strings:

[PS] $c = [System.String[]]@(1,2,3)

[PS] $c.GetType().Fullname
System.String[]

A bit more on Get-Member...

As we saw above, arrays are often (by default) objects of type [System.Object[]]: these are fairly generic collections which could contain both strings and integers in the array. For example:

$d = @("One",2,3.0)  # String, Int32, Double

$d | Get-Member

When you pipe the object $c into the Get-Member cmdlet, it processes the members of the array and determines their type, hence the second command returns details of all three types.

The extra stuff that is returned by Get-Member tells you what can be done with each type, e.g. a String supports the ToLower method which is not supported for Int or Double types.

A bit more on GetType()...

In order to get the type for each member of the array, you can loop through them:

[PS] $d | ForEach-Object {$_.GetType().FullName}
System.String
System.Int32
System.Double

Looking at the array object in more detail

One thing you might want to experiment with is digging into the nature of the array in which you are holding your data with:

$d.PSObject
$d.PSObject.BaseObject
$d.PSObject.Members
$d.PSObject.Properties

Just remember that you are looking at the array not the data within the array, so the Members and Properties you find relate to the array, not the elements within the array.


问:
Word comparison algorithm
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

```<code>   1,   John Doe,     ACME Comapny   (the typo is on purpose)
</code>```

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

答:
I don't know what language you're coding in, but if it's PHP, you should consider the following algorithms:

levenshtein(): Returns the minimal number of characters you have to replace, insert or delete to transform one string into another.

soundex(): Returns the four-character soundex key of a word, which should be the same as the key for any similar-sounding word.

metaphone(): Similar to soundex, and possibly more effective for you. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.

similar_text(): Similar to levenshtein(), but it can return a percent value instead.

OwnerDisplayName: Discodancer

Title: Word comparison algorithm

Body:
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

   1,   John Doe,     ACME Comapny   (the typo is on purpose)

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

OwnerDisplayName: Phantom Watson

LastEditorDisplayName: Phantom Watson


问:
TransactionScope causes TransactionManagerCommunicationException when used for DB unit tests
I'd like to run some tests of stored procedures in my database without actually affecting the data (or, to put it more exactly, without a lasting impact after the test has run).

After some research I came up with the approach of using TransactionScope within my Visual Studio 2010 test project such as

```<code>using( new TransactionScope())
{
    using( SqlConnection connection = new SqlConnection("someConnectionString"))
    {
        connection.Open();
        using( SqlCommand command = new SqlCommand( "some sql", connection ))
        {
            // Do some database stuff...
        }
     }
}
</code>```

Now this works fine as long as I put all of this within a single test method, i.e. all my changes to the database are automatically rolled back when the using block for TransactionScope is finished.

My problem is now that I'd like to do some database stuff in ClassInitialize so I only have to do it once per test class and not for every test method. When I create a public TransactionScope property and assign it an instance of TransactionScope in the ClassInitialize method, this works okay. As soon as I do any database related stuff in one of my test methods, I run into a TransactionManagerCommunicationException within that method.

I don't quite understand why that is the case, and I'd also like to know whether there is a mistake in my approach or how I can get it to work without having to set up the TransactionScope including all set up stuff for the tests within each test method again.

EDIT

Code excerpt below, I hope this gives enough information:

```<code>public TransactionScope Scope { get; set; }

[ClassInitialize]
public static void ClassInitialize( TestContext testContext )
{
    Scope = new TransactionScope();
    // Do some db set up stuff, e.g. create records used for tests etc.
}

[ClassCleanup]
public static void ClassCleanup()
{
    Scope.Dispose();
}

[TestMethod]
public void MyTestMethod()
{
    using( SqlConnection connection = new SqlConnection( "someConnectionString" ) )
    {
        DataTable result = new DataTable();
        using( SqlCommand command = new SqlCommand( "spName", connection ) )
        {
            command.CommandType = CommandType.StoredProcedure;
            using( SqlDataAdapter adapter = new SqlDataAdapter() )
            {
                adapter.SelecteCommand = command;
                // The next line causes the exception to be thrown
                adapter.Fill( result );
            }
        }

        // Assertions against DataTable result
    }
}
</code>```

The exception is

TransactionManagerCommunicationException was unhandled by user code
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I understand that I could try and change the settings, but I do not understand why I get the exception to begin with - what is different compared to having the code above in a single (test) method?

Thanks in advance and

best regards

G.

答:
Your exception is saying that MSDTC isn't enabled.  My guess is that when you were using TransactionScope individually, it was just creating local SQL transactions -- which don't require DTC.  However, when you share a TransactionScope over multiple connections, the transaction gets "promoted" to a distributed transaction through the DTC, which you may not have enabled.

Try enabling network access on MSDTC on your local machine and the server.  The steps for doing so vary a little depending on your OS. Here's how to do it in Win 2003 Server.  Here's a link for Win 2008.  Note that you will likely need to enable DTC through your firewalls as well (explained in the last link...)

Body:
I'd like to run some tests of stored procedures in my database without actually affecting the data (or, to put it more exactly, without a lasting impact after the test has run).

After some research I came up with the approach of using TransactionScope within my Visual Studio 2010 test project such as

using( new TransactionScope())
{
    using( SqlConnection connection = new SqlConnection("someConnectionString"))
    {
        connection.Open();
        using( SqlCommand command = new SqlCommand( "some sql", connection ))
        {
            // Do some database stuff...
        }
     }
}

Now this works fine as long as I put all of this within a single test method, i.e. all my changes to the database are automatically rolled back when the using block for TransactionScope is finished.

My problem is now that I'd like to do some database stuff in ClassInitialize so I only have to do it once per test class and not for every test method. When I create a public TransactionScope property and assign it an instance of TransactionScope in the ClassInitialize method, this works okay. As soon as I do any database related stuff in one of my test methods, I run into a TransactionManagerCommunicationException within that method.

I don't quite understand why that is the case, and I'd also like to know whether there is a mistake in my approach or how I can get it to work without having to set up the TransactionScope including all set up stuff for the tests within each test method again.

EDIT

Code excerpt below, I hope this gives enough information:

public TransactionScope Scope { get; set; }

[ClassInitialize]
public static void ClassInitialize( TestContext testContext )
{
    Scope = new TransactionScope();
    // Do some db set up stuff, e.g. create records used for tests etc.
}

[ClassCleanup]
public static void ClassCleanup()
{
    Scope.Dispose();
}

[TestMethod]
public void MyTestMethod()
{
    using( SqlConnection connection = new SqlConnection( "someConnectionString" ) )
    {
        DataTable result = new DataTable();
        using( SqlCommand command = new SqlCommand( "spName", connection ) )
        {
            command.CommandType = CommandType.StoredProcedure;
            using( SqlDataAdapter adapter = new SqlDataAdapter() )
            {
                adapter.SelecteCommand = command;
                // The next line causes the exception to be thrown
                adapter.Fill( result );
            }
        }

        // Assertions against DataTable result
    }
}

The exception is

TransactionManagerCommunicationException was unhandled by user code
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I understand that I could try and change the settings, but I do not understand why I get the exception to begin with - what is different compared to having the code above in a single (test) method?

Thanks in advance and

best regards

G.


问:
How to retrieve row when null then take above record in table,with out using loop and update
```<code>id  name
--------------
1   ACTIVE
2   NULL
3   NULL
4   NULL
5   COMPLETED
6   NULL
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  NULL
11  ACTIVE
</code>```

Output:

```<code>id  name
--------------
1   ACTIVE
2   ACTIVE
3   ACTIVE
4   ACTIVE
5   COMPLETED
6   COMPLETED
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  ACTIVE
11  ACTIVE
</code>```

Task: retrieve null records with above values without using a loop and update.
in will come select statement.

答:
With DDL and Sample data:</p>

```<code>CREATE TABLE #Sample (ID int, [Name] varchar(9));
INSERT INTO #Sample
VALUES (1,'ACTIVE'),
       (2,NULL),
       (3,NULL),
       (4,NULL),
       (5,'COMPLETED'),
       (6,NULL),
       (7,'COMPLETED'),
       (8,'COMPLETED'),
       (9,'ACTIVE'),
       (10,NULL),
       (11,'ACTIVE');
GO

SELECT *
FROM #Sample;

UPDATE S
SET [Name] = (SELECT TOP 1 [Name]
              FROM #Sample sq
              WHERE sq.ID < S.ID
                AND sq.[Name] IS NOT NULL
              ORDER BY sq.ID DESC)
FROM #Sample S
WHERE S.[Name] IS NULL;

SELECT *
FROM #Sample;

GO
DROP TABLE #Sample;
</code>```

Body:
id  name
--------------
1   ACTIVE
2   NULL
3   NULL
4   NULL
5   COMPLETED
6   NULL
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  NULL
11  ACTIVE

Output:

id  name
--------------
1   ACTIVE
2   ACTIVE
3   ACTIVE
4   ACTIVE
5   COMPLETED
6   COMPLETED
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  ACTIVE
11  ACTIVE

Task: retrieve null records with above values without using a loop and update.
in will come select statement.

Body:
With DDL and Sample data:

CREATE TABLE #Sample (ID int, [Name] varchar(9));
INSERT INTO #Sample
VALUES (1,'ACTIVE'),
       (2,NULL),
       (3,NULL),
       (4,NULL),
       (5,'COMPLETED'),
       (6,NULL),
       (7,'COMPLETED'),
       (8,'COMPLETED'),
       (9,'ACTIVE'),
       (10,NULL),
       (11,'ACTIVE');
GO

SELECT *
FROM #Sample;

UPDATE S
SET [Name] = (SELECT TOP 1 [Name]
              FROM #Sample sq
              WHERE sq.ID < S.ID
                AND sq.[Name] IS NOT NULL
              ORDER BY sq.ID DESC)
FROM #Sample S
WHERE S.[Name] IS NULL;

SELECT *
FROM #Sample;

GO
DROP TABLE #Sample;


问:
REg Exp allowing ASCII Printable characters, Special characters allowed, Spaces not allowed
I am looking for a Regular Expression which should have Min 1-Max 50 characters accepted and Accepts ASCII Printable characters, Special characters allowed, Spaces not allowed.

Right now I'm having

```<code>^[ -~][^\\s]{1,50}$
</code>```

but when I enter one single character it throws an error. Could anyone please check with this. Thanks.

答:
I think you could go with this:

```<code>^\S{1,50}$
</code>```

It will take any non white space character between 1 and 50 occurrences.
In words your regex is saying: "take a character between space and "~", then take from 1 to 50 characters except any white-space. That is why it wont work with a single character, it needs at least two.

I usually go to regex101 for reference and testing. Hope this helps

Body:
I am looking for a Regular Expression which should have Min 1-Max 50 characters accepted and Accepts ASCII Printable characters, Special characters allowed, Spaces not allowed.

Right now I'm having

^[ -~][^\\s]{1,50}$

but when I enter one single character it throws an error. Could anyone please check with this. Thanks.

Body:
I think you could go with this:

^\S{1,50}$

It will take any non white space character between 1 and 50 occurrences.
In words your regex is saying: "take a character between space and "~", then take from 1 to 50 characters except any white-space. That is why it wont work with a single character, it needs at least two.

I usually go to regex101 for reference and testing. Hope this helps


问:
Adding to a List/Array in a Loop
Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

```<code>budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)
</code>```

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

Title: Adding to a List/Array in a Loop

Body:
Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

Body:
budgets = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

for budget, year in zip(budgets, years):
    if budget < 0:
        nodef.append(year)

print(nodef)