问:
Trouble with detecting gestures over ListView
I have an Activity that contains a ViewFlipper.  The ViewFlipper includes 2 layouts, both of which are essentially just ListViews.

So the idea here is that I have two lists and to navigate from one to the other I would use a horizontal swipe.

I have that working.  However, what ever list item your finger is on when the swipe begins executing, that item will also be long-clicked.

Here is the relevant code I have:

```<code>public class MyActivity extends Activity implements OnItemClickListener, OnClickListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private GestureDetector mGestureDetector;
    View.OnTouchListener mGestureListener;

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_SECONDLIST) {
                        mCurrentScreen = SCREEN_SECONDLIST;
                        mFlipper.setInAnimation(inFromRightAnimation());
                        mFlipper.setOutAnimation(outToLeftAnimation());
                        mFlipper.showNext();
                        updateNavigationBar();
                    }
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_FIRSTLIST) {
                        mCurrentScreen = SCREEN_FIRSTLIST;
                        mFlipper.setInAnimation(inFromLeftAnimation());
                        mFlipper.setOutAnimation(outToRightAnimation());
                        mFlipper.showPrevious();
                        updateNavigationBar();
                    }
                }
            } catch (Exception e) {
                // nothing
            }
            return true;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;
        else
            return false;
    }

    ViewFlipper mFlipper;

    private int mCurrentScreen = SCREEN_FIRSTLIST;

    private ListView mList1;
    private ListView mList2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_flipper);

        mFlipper = (ViewFlipper) findViewById(R.id.flipper);

        mGestureDetector = new GestureDetector(new MyGestureDetector());
        mGestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (mGestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };

        // set up List1 screen

        mList1List = (ListView)findViewById(R.id.list1);
        mList1List.setOnItemClickListener(this);
        mList1List.setOnTouchListener(mGestureListener);

        // set up List2 screen
        mList2List = (ListView)findViewById(R.id.list2);
        mList2List.setOnItemClickListener(this);
        mList2List.setOnTouchListener(mGestureListener);

    }

    …
}
</code>```

If I change the "return true;" statement from the GestureDetector to "return false;", I do not get long-clicks.  Unfortunately, I get regular clicks.

Does anyone know how I can get around this?

答:
Just to throw in a completely different answer with a completely different approach...

I've made a custom view called SwipeView, it's open source etc etc blah blah blah. It should let you do what you want to do as simply as going:

```<code>mSwipeView.addChild(myList1);
mSwipeView.addChild(myList2);
</code>```

You won't have to mess about with gesture detectors or anything, and the the swipe should follow your finger as you do it...

(This reads like a terrible terrible advert, please excuse me. It's been a long day ;)

Have some wonderful links:

http://jasonfry.co.uk/?id=23

http://jasonfry.co.uk/?id=24

https://jasonfry.co.uk/blog/android-swipeview-update/

ContentLicense: CC BY-SA 2.5

Body:
I have an Activity that contains a ViewFlipper.  The ViewFlipper includes 2 layouts, both of which are essentially just ListViews.

So the idea here is that I have two lists and to navigate from one to the other I would use a horizontal swipe.

I have that working.  However, what ever list item your finger is on when the swipe begins executing, that item will also be long-clicked.

Here is the relevant code I have:

public class MyActivity extends Activity implements OnItemClickListener, OnClickListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private GestureDetector mGestureDetector;
    View.OnTouchListener mGestureListener;

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_SECONDLIST) {
                        mCurrentScreen = SCREEN_SECONDLIST;
                        mFlipper.setInAnimation(inFromRightAnimation());
                        mFlipper.setOutAnimation(outToLeftAnimation());
                        mFlipper.showNext();
                        updateNavigationBar();
                    }
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_FIRSTLIST) {
                        mCurrentScreen = SCREEN_FIRSTLIST;
                        mFlipper.setInAnimation(inFromLeftAnimation());
                        mFlipper.setOutAnimation(outToRightAnimation());
                        mFlipper.showPrevious();
                        updateNavigationBar();
                    }
                }
            } catch (Exception e) {
                // nothing
            }
            return true;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;
        else
            return false;
    }

    ViewFlipper mFlipper;

    private int mCurrentScreen = SCREEN_FIRSTLIST;

    private ListView mList1;
    private ListView mList2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_flipper);

        mFlipper = (ViewFlipper) findViewById(R.id.flipper);

        mGestureDetector = new GestureDetector(new MyGestureDetector());
        mGestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (mGestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };

        // set up List1 screen

        mList1List = (ListView)findViewById(R.id.list1);
        mList1List.setOnItemClickListener(this);
        mList1List.setOnTouchListener(mGestureListener);

        // set up List2 screen
        mList2List = (ListView)findViewById(R.id.list2);
        mList2List.setOnItemClickListener(this);
        mList2List.setOnTouchListener(mGestureListener);

    }

    …
}

If I change the "return true;" statement from the GestureDetector to "return false;", I do not get long-clicks.  Unfortunately, I get regular clicks.

Does anyone know how I can get around this?

Body:
Just to throw in a completely different answer with a completely different approach...

I've made a custom view called SwipeView, it's open source etc etc blah blah blah. It should let you do what you want to do as simply as going:

mSwipeView.addChild(myList1);
mSwipeView.addChild(myList2);

You won't have to mess about with gesture detectors or anything, and the the swipe should follow your finger as you do it...

(This reads like a terrible terrible advert, please excuse me. It's been a long day ;)

Have some wonderful links:

http://jasonfry.co.uk/?id=23

http://jasonfry.co.uk/?id=24

https://jasonfry.co.uk/blog/android-swipeview-update/

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to CREATE TABLE with formatted column
I need to create a new empty table, where each new value should be validated by server using format of its column. Like, ###-###-##, where each # is a digit from 0 to 9, and it should contain those - symbols. How?

答:
No. Don't do that! That's not going to work.

If you have multi-tenant application and different customers would like to store the value in different format, you will be trapped.

Best way is to just validate the pattern on client side, and store in db in free form.

ContentLicense: CC BY-SA 3.0


问:
Apollo resetStore doesn't work
please help;
I've got an error "undefined is not an object (evaluating 'this.props.client')</p>

```<code>class FeedProfileBottom extends Component {

_onLogoutPress = function() {
  this.props.client.resetStore();
  return this.props.logout();
}

render() {
  return (
    <Root>
      <LogOutButton onPress={this._onLogoutPress}>
        <LogOutText>
          Logout
        </LogOutText>
      </LogOutButton>
    </Root>
  );
 }
}

export default withApollo(connect(undefined, { logout })(FeedProfileBottom));
</code>```

答:
You might need to explicitly bind the scope of your component to your function.</p>

```<code>class FeedProfileBottom extends Component {
  constructor (props) {
    super(props);
    this._onLogoutPress = this._onLogoutPress.bind(this);
  }
  // ...
</code>```

Title: Apollo resetStore doesn't work

Body:
please help;
I've got an error "undefined is not an object (evaluating 'this.props.client')

class FeedProfileBottom extends Component {

_onLogoutPress = function() {
  this.props.client.resetStore();
  return this.props.logout();
}

render() {
  return (
    <Root>
      <LogOutButton onPress={this._onLogoutPress}>
        <LogOutText>
          Logout
        </LogOutText>
      </LogOutButton>
    </Root>
  );
 }
}

export default withApollo(connect(undefined, { logout })(FeedProfileBottom));

Body:
You might need to explicitly bind the scope of your component to your function.

class FeedProfileBottom extends Component {
  constructor (props) {
    super(props);
    this._onLogoutPress = this._onLogoutPress.bind(this);
  }
  // ...


问:
Do you perform any validation on arguments to methods of Javascript API wrappers you develop?
When I develop API wrappers I always find myself bouncing between the two ends:

performing no validation at all because API server performs it;

performing validation to

avoid bad requests without having to call the API server

avoid data inconsistencies due to type casting

Did you decide? If so, what kind of validation you prefer? Do you throw errors or pass them to the callback?

答: You should validate inputs in both places.  Pushing validation off to just the server hurts the responsiveness of your application.  Anytime you can avoid a server request in favor of client side code is a win in my book, it's faster on the client and less load on your server.  Unfortunately this means you duplicate validation logic on both ends, but that is acceptable in my book.</p>


问:
Dataflow job is timing out. Having issues comparing two collections, and appending the values of one to another.
Hoping someone can help me here. I have two bigquery tables that I read into 2 different p collections, p1 and p2. I essentially want to update product based on a type II transformation that keeps track of history (previous values in the nested column in product) and appends new values from dwsku.

The idea is to check every row in each collection. If there is a match based on some table values (between p1 and p2), then check product's nested data to see if it contains all values in p1 (based on it's sku number and brand). If it does not contain the most recent data from p2 then take a copy of the format of the current nested data in product, and fit the new data into it. Take this nested format and add it to the existing nested products in product.

```<code>def process_changes(element, productdata):
    for data in productdata:
        if element['sku_number'] == data['sku_number'] and element['brand'] == data['brand']:
            logging.info('Processing Product: ' + str(element['sku_number']) + ' brand:' + str(element['brand']))

            datatoappend = []
            for nestline in data['product']:
                logging.info('Nested Data: ' + nestline['product'])
                if nestline['in_use'] == 'Y' and (nestline['sku_description'] != element['sku_description'] or nestline['department_id'] != element['department_id'] or nestline['department_description'] != element['department_description']
                    or nestline['class_id'] != element['class_id'] or nestline['class_description'] != element['class_description'] or nestline['sub_class_id'] != element['sub_class_id'] or nestline['sub_class_description'] != element['sub_class_description'] ):
                    logging.info('we found a sku we need to update')
                    logging.info('sku is ' + data['sku_number'])
                    newline = nestline.copy()
                    logging.info('most recent nested product element turned off...')
                    nestline['in_use'] = 'N'
                    nestline['expiration_date'] = "%s-%s-%s" % (curdate.year, curdate.month, curdate.day) # CURRENT DATE
                    logging.info(nestline)

                    logging.info('inserting most recent change in dwsku inside nest')
                    newline['sku_description'] = element['sku_description']
                    newline['department_id'] = element['department_id']
                    newline['department_description'] = element['department_description']
                    newline['class_id'] = element['class_id']
                    newline['class_description'] = element['class_description']
                    newline['sub_class_id'] = element['sub_class_id']
                    newline['sub_class_description'] = element['sub_class_description']
                    newline['in_use'] = 'Y'
                    newline['effective_date'] = "%s-%s-%s" % (curdate.year, curdate.month, curdate.day) # CURRENT DATE
                    newline['modified_date'] = "%s-%s-%s" % (curdate.year, curdate.month, curdate.day) # CURRENT DATE
                    newline['modified_time'] = "%s:%s:%s" % (curdate.hour, curdate.minute, curdate.second)
                    nestline['expiration_date'] = "9999-01-01"
                    datatoappend.append(newline)
                else:
                    logging.info('Nothing changed for sku ' + str(data['sku_number']))
            for dt in datatoappend:
                logging.info('processed sku ' + str(element['sku_number']))
                logging.info('adding the changes (if any)')
                data['product'].append(dt)

            return data

changed_product = p1 | beam.FlatMap(process_changes, AsIter(p2))
</code>```

Afterwards I want to add all values in p1 not in p2 in a nested format as seen in nestline.

Any help would be appreciated as I'm wondering why my job is taking hours to run with nothing to show. Even the output logs in dataflow UI don't show anything.

Thanks in advance!

答:
This can be quite expensive if side input PCollection p2 is large. From your code snippets it's not clear how PCollection p2 is constructed. But if it is, for example, a text file that is if size 62.7MB, processing it per element can be pretty expensive. Can you consider using CoGroupByKey: https://beam.apache.org/documentation/programming-guide/#cogroupbykey

Also note that from a FlatMap, you are supposed to return a iterator of elements from the processing method. Seems like you are returning a dictionary('data') which probably is incorrect.

Body:
Hoping someone can help me here. I have two bigquery tables that I read into 2 different p collections, p1 and p2. I essentially want to update product based on a type II transformation that keeps track of history (previous values in the nested column in product) and appends new values from dwsku.

The idea is to check every row in each collection. If there is a match based on some table values (between p1 and p2), then check product's nested data to see if it contains all values in p1 (based on it's sku number and brand). If it does not contain the most recent data from p2 then take a copy of the format of the current nested data in product, and fit the new data into it. Take this nested format and add it to the existing nested products in product.

def process_changes(element, productdata):
    for data in productdata:
        if element['sku_number'] == data['sku_number'] and element['brand'] == data['brand']:
            logging.info('Processing Product: ' + str(element['sku_number']) + ' brand:' + str(element['brand']))

            datatoappend = []
            for nestline in data['product']:
                logging.info('Nested Data: ' + nestline['product'])
                if nestline['in_use'] == 'Y' and (nestline['sku_description'] != element['sku_description'] or nestline['department_id'] != element['department_id'] or nestline['department_description'] != element['department_description']
                    or nestline['class_id'] != element['class_id'] or nestline['class_description'] != element['class_description'] or nestline['sub_class_id'] != element['sub_class_id'] or nestline['sub_class_description'] != element['sub_class_description'] ):
                    logging.info('we found a sku we need to update')
                    logging.info('sku is ' + data['sku_number'])
                    newline = nestline.copy()
                    logging.info('most recent nested product element turned off...')
                    nestline['in_use'] = 'N'
                    nestline['expiration_date'] = "%s-%s-%s" % (curdate.year, curdate.month, curdate.day) # CURRENT DATE
                    logging.info(nestline)

                    logging.info('inserting most recent change in dwsku inside nest')
                    newline['sku_description'] = element['sku_description']
                    newline['department_id'] = element['department_id']
                    newline['department_description'] = element['department_description']
                    newline['class_id'] = element['class_id']
                    newline['class_description'] = element['class_description']
                    newline['sub_class_id'] = element['sub_class_id']
                    newline['sub_class_description'] = element['sub_class_description']
                    newline['in_use'] = 'Y'
                    newline['effective_date'] = "%s-%s-%s" % (curdate.year, curdate.month, curdate.day) # CURRENT DATE
                    newline['modified_date'] = "%s-%s-%s" % (curdate.year, curdate.month, curdate.day) # CURRENT DATE
                    newline['modified_time'] = "%s:%s:%s" % (curdate.hour, curdate.minute, curdate.second)
                    nestline['expiration_date'] = "9999-01-01"
                    datatoappend.append(newline)
                else:
                    logging.info('Nothing changed for sku ' + str(data['sku_number']))
            for dt in datatoappend:
                logging.info('processed sku ' + str(element['sku_number']))
                logging.info('adding the changes (if any)')
                data['product'].append(dt)

            return data

changed_product = p1 | beam.FlatMap(process_changes, AsIter(p2))

Afterwards I want to add all values in p1 not in p2 in a nested format as seen in nestline.

Any help would be appreciated as I'm wondering why my job is taking hours to run with nothing to show. Even the output logs in dataflow UI don't show anything.

Thanks in advance!


问:
Qlikview Update, append without delete from weekly list
I have tables List1 (9000+/- records) and List2 (9500 records+/-) with the fields;

episodenum (PrimaryKey)
ArchiveDate (Unique to each list)
Data(Multiple fields)

I wish to join the tables each week, retaining

Records present in List1 but not present in List2, clasified as status 'OffList',Data as per List1,

Records present in List1 and List2 classified as status 'OnList', Data as per List2,

Records present in List2 not present in List1 classified as status 'NewToList', Data as per List2 (See attached Diagram)List1 and List2 and desired result

This is a simple enough matter in Sql, but the automatic join that occurs in the Qlikview load has me stumped.

I wish to reduce the number of records loaded as the table will build over time when 'OffList' records are retained, and in order to be able to use simple count expressions rather than the selections and set analysis required when the full set of records is loaded and combined.

Is there a simple method of doing this?

答:
As you were so kind providing an example, I'll leave you with a script using the same data :

```<code>Data:
LOAD * INLINE [
    X, Y
    1, A1
    2, A2
    3, A3
];

Left Join (Data)
LOAD
    X,
    Y as NewY;
LOAD * INLINE [
    X, Y
    1, B1
    2, B2
    4, B4
];

Left Join (Data)
LOAD
    X,
    if(IsNull(NewY), 'OffList', 'OnList') as Status
Resident Data;

DROP FIELD NewY;

LOAD
    *,
    'NewToList' as Status
WHERE Not Exists(X);
LOAD * INLINE [
    X, Y
    2, B2
    3, B3
    4, B3
];
</code>```

Now a step by step explanation :

Load the original table

Load the second version of the table, with a left join, which will add new columns to the right of the existing one. X will be the same column on both tables, so it will link the same record in the first one with the same record on the second one. You'll need to rename Y, otherwise it will also be used as a key joining the tables.

Taking the table Key, do a new Left Join, this time evaluating what you have on the NewY column. If it's null, means that is a new record. If it's filled, already existed. First stage of classification is complete.

You can drop NewY, you don't need it anymore.

Load again the second version of the table, making sure to load only entries that don't exist already (Exists(X)). If you are loading only the new ones, you can state that the status of this ones will be NewToList for sure.

Hope this helps, and that this can be seen as an "easy" solution.

Body:
As you were so kind providing an example, I'll leave you with a script using the same data :

Data:
LOAD * INLINE [
    X, Y
    1, A1
    2, A2
    3, A3
];

Left Join (Data)
LOAD
    X,
    Y as NewY;
LOAD * INLINE [
    X, Y
    1, B1
    2, B2
    4, B4
];

Left Join (Data)
LOAD
    X,
    if(IsNull(NewY), 'OffList', 'OnList') as Status
Resident Data;

DROP FIELD NewY;

LOAD
    *,
    'NewToList' as Status
WHERE Not Exists(X);
LOAD * INLINE [
    X, Y
    2, B2
    3, B3
    4, B3
];

Now a step by step explanation :

Load the original table

Load the second version of the table, with a left join, which will add new columns to the right of the existing one. X will be the same column on both tables, so it will link the same record in the first one with the same record on the second one. You'll need to rename Y, otherwise it will also be used as a key joining the tables.

Taking the table Key, do a new Left Join, this time evaluating what you have on the NewY column. If it's null, means that is a new record. If it's filled, already existed. First stage of classification is complete.

You can drop NewY, you don't need it anymore.

Load again the second version of the table, making sure to load only entries that don't exist already (Exists(X)). If you are loading only the new ones, you can state that the status of this ones will be NewToList for sure.

Hope this helps, and that this can be seen as an "easy" solution.


问:
Calibrate Camera with only radial distortion
I'm trying to run camera calibration using opencv in python. I'm using:

```<code>cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
</code>```

and it seems like it is working well for 5 distortion coefficients. However, I would like to try and run it without the tangential distortion and possibly with only 2 radial distortion coefficients. Is that possible?

答:
I found the answer.

For no tangential distortion:

```<code> ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None, 4,None,None,cv2.CALIB_ZERO_TANGENT_DIST,
                                                   criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 2e-16))
</code>```

For only 2 radial distortion coefficients it seems like the documentation suggests using 4 instead of 5 for the number of coefficients. That does not seem to work. Instead I fix the k3 parameter:

```<code>ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None, 4,None,None,cv2.CALIB_ZERO_TANGENT_DIST+cv2.CALIB_FIX_K3,
                                                   criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 2e-16))
</code>```

Body:
I'm trying to run camera calibration using opencv in python. I'm using:

cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)

and it seems like it is working well for 5 distortion coefficients. However, I would like to try and run it without the tangential distortion and possibly with only 2 radial distortion coefficients. Is that possible?

Body:
I found the answer.

For no tangential distortion:

 ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None, 4,None,None,cv2.CALIB_ZERO_TANGENT_DIST,
                                                   criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 2e-16))

For only 2 radial distortion coefficients it seems like the documentation suggests using 4 instead of 5 for the number of coefficients. That does not seem to work. Instead I fix the k3 parameter:

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None, 4,None,None,cv2.CALIB_ZERO_TANGENT_DIST+cv2.CALIB_FIX_K3,
                                                   criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 2e-16))


问:
MEL Script Button deletes object if it exists
My MEL knowledge isn't great and I have created a small script that duplicates your object and brings it next to your main one. I want to make it like when you click the MEL button the object appears but when you click it again the object gets deleted (if exists). Any help would be great as I'm almost at the point where I'm gonna start hitting my head on the wall.

Thanks

答:
Here's a bit of code that will delete an object if its found:</p>

```<code>if (objExists("YOUR_OBJECT_NAME_HERE"))
{
delete("YOUR_OBJECT_NAME_HERE");
}
</code>```

Body:
Here's a bit of code that will delete an object if its found:

if (objExists("YOUR_OBJECT_NAME_HERE"))
{
delete("YOUR_OBJECT_NAME_HERE");
}


问:
Get letters from string swift
I want to get all letters into an array from the string.
Suppose I have string which contains letters and numeric then I want to get only all letters of the string.

```<code>let myString = "so123han"
</code>```

Then output should be in array like this:

```<code>let arrayOfLetters = ["s","o","h","a","n"]
</code>```

答:
You can do it this way:</p>

```<code>let myString = "so123han"
let alphaChars = myString.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).map({ Character($0) })
</code>```

Title: Get letters from string swift

Body:
I want to get all letters into an array from the string.
Suppose I have string which contains letters and numeric then I want to get only all letters of the string.

let myString = "so123han"

Then output should be in array like this:

let arrayOfLetters = ["s","o","h","a","n"]

Body:
You can do it this way:

let myString = "so123han"
let alphaChars = myString.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).map({ Character($0) })


问:
Subversion - Async development cycle... two trunks?
Currently in our enterprise we have a situation that i think it's not very common, or at least i haven't found a similar case in Internet. My problem is that we have software that can evolve by more than one requirement, and both not necessarily will coincide in their release date.

We have a development cycle where all software is developed in a "DEV" environment, and then it's handled to SQA so it can be tested on "LAB" environment; if all works OK then this software is moved to "PROD" environment. The problem i am facing here is that i cant use a single trunk and i don't see how a single branch could work either.

For example, lets say i have requirements A and B, one to be released today and the other a week from today. Both have reached LAB environment but today's release to PROD environment only has to contain A, since B is not yet needed by our business users (and it cannot be released early because it would introduce some error's to others systems). Both requirements where developed in different branches (they respond to different needs). In this case my problem is that i can't have a single trunk where developers can merge to see both changes in "DEV" environment, and then use the same trunk to feed "LAB" environment since it would have source code not yet scheduled for release.

I think i should also mention that having a separate development environment for each branch is not possible because this software is based on PL/SQL (Oracle) and our current test database is about 350Mb in size, so having a different one for each requirement would be quite expensive and hard to manage.

Any suggestion or similar experience would be appreciated.

Regards

答: It sounds to me like you could benefit from using a distributed VCS (git, mercurial, bazaar, etc.)</p>

OwnerDisplayName: Patricio Téllez

LastEditorDisplayName: Adam Lassek

OwnerDisplayName: JesperE


问:
Golden Gate Replication condition
In goldengate i want all the replications to happen only when a certain condition satisfies else it should wait until the condition satisfies.

Suppose I’m having a Table ‘T’ with only one row and a column ‘Flag’ in it. For every replication happening in the target database i want to make sure it happens only when the value of the ‘Flag’ is ‘A’ else the replication should wait until the value of the ‘Flag ‘ becomes ‘A’.

I’m not sure if it is possible, can you please help me and tell if it is possible and how can i make it possible.

答:
You can use conditional filtering in the extract process itself so that you don't have to extract and replicate the ones that are not matching the condition.
You could either use FILTER as mentioned in comment(s) or you could use SQLPREDICATE in your EXTRACT

i.e.

TABLE schema.T, SQLPREDICATE "WHERE FLAG = 'A'";

Advantage of using SQLPREDICATE is that you can filter the data that you want to extract with complex SQL "WHERE" conditions as well.

Title: Golden Gate Replication condition


问:
Efficiently convert an unsigned short to a char*
What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25').

I'd like to avoid things such as getting (std::string) strings involved.  Performance is important in this case since this conversion will need to happen quickly and often.

I was looking into things such as using sprintf but would like to explorer any and all ideas.

答: I would say at least try sprintf and since you have this tagged as C++, try StringStream, and actually profile them. In many cases the compiler is smart enough to build something that works pretty well. Only when you know it's going to be a bottleneck do you need to actually find a faster way.</p>


问:
Python 3.6 Module cannot be found: Folium
I am trying to import folium into a Jupyter notebook I'm working on and I cannot seem to solve the import issues with the Folium library.  Has anyone else solved this problem?

```<code>!pip install folium
import pandas as pd
import folium
</code>```

Output from the above yields:

```<code>`ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-7-a9938c267a0c> in <module>()
      1 get_ipython().system('pip install folium')
      2 import pandas as pd
----> 3 import folium

ModuleNotFoundError: No module named 'folium'`
</code>```

答:
I had the same problem while installing with pip3 (macOS with python3).

Manually cloning the github repo solved it.

Move to the package folder of python 3

cd /usr/local/lib/python3.6/site-packages/
```
</li>
<li>Then
<pre class="lang-none prettyprint-override"><code>git clone https://github.com/python-visualization/folium
cd folium
python setup.py install
</code>```

Body:
I am trying to import folium into a Jupyter notebook I'm working on and I cannot seem to solve the import issues with the Folium library.  Has anyone else solved this problem?

!pip install folium
import pandas as pd
import folium

Output from the above yields:

`ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-7-a9938c267a0c> in <module>()
      1 get_ipython().system('pip install folium')
      2 import pandas as pd
----> 3 import folium

ModuleNotFoundError: No module named 'folium'`

Body:
I had the same problem while installing with pip3 (macOS with python3).

Manually cloning the github repo solved it.

Move to the package folder of python 3

cd /usr/local/lib/python3.6/site-packages/

Then

git clone https://github.com/python-visualization/folium
cd folium
python setup.py install


问:
Circle not draw in Google Maps with OpenLayers
I am trying to draw a circle in OpenLayers using Google Maps (olGM).
I don´t know why it not draw a circle, because in OSM working perfectly.

```<code>var circle = new ol.geom.Circle(ol.proj.transform([latd, lond], 'EPSG:4326',
'EPSG:3857'), 1000);
var center = circle.getCenter();
var CircleFeature = new ol.Feature(circle);
</code>```

Edit again. Finally I could to draw the Circle. But, my question is, how can I access to Radius and Center from Circle1? And modifying Circle1, I modify Circle in the same time.

I am using:

```<code>var circle1 = new ol.geom.Circle(ol.proj.transform([latd, lond],
'EPSG:4326', 'EPSG:3857'), radius);
var circle = new ol.geom.Polygon.fromCircle(circle1, 232, 0);
var CircleFeature = new ol.Feature(circle);
</code>```

答:
Circle geometries are currently not supported in ol3-google-maps, see: https://github.com/mapgears/ol3-google-maps/blob/master/LIMITATIONS.md#circle-geometry

If you wish to contribute it, you can create a pull request on the library's GitHub.

Body:
I am trying to draw a circle in OpenLayers using Google Maps (olGM).
I don´t know why it not draw a circle, because in OSM working perfectly.

var circle = new ol.geom.Circle(ol.proj.transform([latd, lond], 'EPSG:4326',
'EPSG:3857'), 1000);
var center = circle.getCenter();
var CircleFeature = new ol.Feature(circle);

Edit again. Finally I could to draw the Circle. But, my question is, how can I access to Radius and Center from Circle1? And modifying Circle1, I modify Circle in the same time.

I am using:

var circle1 = new ol.geom.Circle(ol.proj.transform([latd, lond],
'EPSG:4326', 'EPSG:3857'), radius);
var circle = new ol.geom.Polygon.fromCircle(circle1, 232, 0);
var CircleFeature = new ol.Feature(circle);


问:
split byte array into even and odd byte array and store in file
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

```<code>        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }
</code>```

In FOR loop i have tried array.length, even.length nothing is working.

答:
Increment the index in the source array by 2 and in the destination arrays by 1 only. This allows you to assign the bytes to odd and even arrays in one bunch without additional even/odd tests.

```<code>for (int src = 0, dst = 0; src < array.Length; src += 2, dst++)
{
    even[dst] = array[src];
    odd[dst] = array[src + 1];
}
</code>```

If the array length is odd, then odd[] must be one shorter than even[]. Also, special care must be taken to avoid running into an index out of range exception.

A solution also working with odd array lengths and avoiding additional tests within the loop:

```<code>byte[] array = { 0, 1, 2, 3, 4 };
bool isOdd = array.Length % 2 == 1;

byte[] even = new byte[(array.Length + 1) / 2];
byte[] odd = new byte[array.Length / 2];

int length = isOdd ? array.Length - 1 : array.Length;
for (int src = 0, dst = 0; src < length; src += 2, dst++) {
    even[dst] = array[src];
    odd[dst] = array[src + 1];
}

if (isOdd) { // If array length is odd, the last index is even (= length - 1).
    // Assign the last remaining entry.
    even[even.Length - 1] = array[array.Length - 1];
}
</code>```

Body:
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }

In FOR loop i have tried array.length, even.length nothing is working.

Body:
Increment the index in the source array by 2 and in the destination arrays by 1 only. This allows you to assign the bytes to odd and even arrays in one bunch without additional even/odd tests.

for (int src = 0, dst = 0; src < array.Length; src += 2, dst++)
{
    even[dst] = array[src];
    odd[dst] = array[src + 1];
}

If the array length is odd, then odd[] must be one shorter than even[]. Also, special care must be taken to avoid running into an index out of range exception.

A solution also working with odd array lengths and avoiding additional tests within the loop:

byte[] array = { 0, 1, 2, 3, 4 };
bool isOdd = array.Length % 2 == 1;

byte[] even = new byte[(array.Length + 1) / 2];
byte[] odd = new byte[array.Length / 2];

int length = isOdd ? array.Length - 1 : array.Length;
for (int src = 0, dst = 0; src < length; src += 2, dst++) {
    even[dst] = array[src];
    odd[dst] = array[src + 1];
}

if (isOdd) { // If array length is odd, the last index is even (= length - 1).
    // Assign the last remaining entry.
    even[even.Length - 1] = array[array.Length - 1];
}


问:
Visual Studio - Some breakpoints not breaking
I have a solution in Visual Studio 2010 with 9 projects which is under source control with Source Safe. I just recently swiped my hard-drive and upgraded to Win7 x64 from WinXP x86 (long overdue!). When I checked the solution out to the "new" machine, some parts are not working correctly now, so I'm trying to debug it.

Perhaps worth noting is that I was working in VS2008 before. When I upgraded, I first opened the project in VS2008 to make sure it worked and I noticed there were problems that I needed to debug. I set some breakpoints and a couple worked and a couple didn't. I couldn't immediately figure out why some weren't breaking, so I decided to go ahead and upgrade the project to VS2010 hoping it would work itself out. It didn't.

The main project calls a public sub in a public module in a project that is a library referenced by every other project. I have a breakpoint on the main form Form_Load which breaks successfully as soon as the code begins running. The Form_Load calls the aforementioned public sub which also has a breakpoint. But that breakpoint DOES NOT break. In other words, the debugger will stop on the call ProjectStartupActions() but will not stop on the definition Public Sub ProjectStartupActions() or any line in it.

If I "Go To Definition" on the sub call in Form_Load, it jumps to the correct place where I have the breakpoint, so I'm certain I've placed the breakpoint correctly.

My Project >> Debug >> Configuration is set to "Active (Debug)" and Platform is "Active (Any CPU)" for all projects. To further confirm that it should be running in Debug rather than Release, if I open an explorer window to the "Debug" folder for the library project and clean the project, the folder empties out. When I rebuild or run the files are all replaced.

Thanks for any help.

Oh yeah, also I made a change to the code of Public Sub ProjectStartupActions(). I added MsgBox("Hello") to the first line in the sub, but it never pops up.

答:
Set the target to x86 to debug it. –
  Hans Passant

This worked! Thanks!! I used the Configuration Manager to change the target for the entire solution to x86.

But why did it work? Why did the "Any CPU" option break on the main project but not the library?


问:
Building data structures at compile time with template-metaprogramming, constexpr or macros
I want to optimize a little program/library I'm writing and since 2 weeks I'm somewhat stuck and now wondering if what I had in mind is even possible like that.
(Please be gentle I don't have very much experience in meta-programming.)

My goal is of course to have certain computations be done by the compiler, so that the programmer - hopefully - only has to edit code at one point in the program and have the compiler "create" all the boilerplate. I do have a reasonably good idea how to do what i want with macros, but it is wished that I do it with templates if possible.

My goal is:
Lets say I have a class that a using programmer can derive from. There he can have multiple incoming and outgoing datatypes that I want to register somehow so that the base class can do it's operations on them.

```<code>class my_own_multiply : function_base {
  in<int> a;
  in<float> b;
  out<double> c;

  // ["..."] // other content of the class that actually does something but is irrelevant
  register_ins<a, b> ins_of_function; // example meta-function calls
  register_outs<c> outs_of_function;
}
</code>```

The meta-code I have up till now is this: (but it's not yet working/complete)

```<code>template <typename... Ts>
struct register_ins {
  const std::array<std::unique_ptr<in_type_erasured>, sizeof...(Ts)> ins;

  constexpr std::array<std::unique_ptr<in_type_erasured>, sizeof...(Ts)>
    build_ins_array() {
      std::array<std::unique_ptr<in_type_erasured>, sizeof...(Ts)> ins_build;
      for (unsigned int i = 0; i < sizeof...(Ts); ++i) {
        ins_build[i] = std::make_unique<in_type_erasured>();
      }
    return ins_build;
  }

  constexpr register_ins() : ins(build_ins_array()) {
  }

  template <typename T>
  T getValueOf(unsigned int in_nr) {
    return ins[in_nr]->getValue();
  }
};
</code>```

As you may see, I want to call my meta-template-code with a variable number of ins. (Variable in the sense that the programmer can put however many he likes in there, but they won't change at runtime so they can be "baked" in at compile time)

The meta-code is supposed to be creating an array, that is of the length of the number of ins and is initialized so that every field points to the original in in the my_own_multiply class. Basically giving him an indexable data structure that will always have the correct size. And that I could access from the function_base class to use all ins for certain functions which are also iterable making things convenient for me.

Now I have looked into how one might do that, but I now am getting the feeling that I might not really be allowed to "create" this array at compile time in a fashion that allows me to still have the ins a and b be non static and non const so that I can mutate them. From my side they wouldn't have to be const anyway, but my compiler seems to not like them to be free. The only thing I need const is the array with the pointers. But using constexpr possibly "makes" me make them const?

Okay, I will clarify what I don't get:
When I'm trying to create an "instance" of my meta-stuff-structure then it fails because it expects all kinds of const, constexpr and so on. But I don't want them since I need to be able to mutate most of those variables. I only need this meta-stuff to create an array of the correct size already at compile time. But I don't want to sacrifice having to make everything static and const in order to achieve this. So is this even possible under these kinds of terms?

答:
I do not get all the things you have in mind (also regarding that std::unique_ptr in your example), but maybe this helps:

Starting from C++14 (or C++11, but that is strictly limited) you may write constexpr functions which can be evaluated at compile-time. As a precondition (in simple words), all arguments "passed by the caller" must be constexpr. If you want to enforce that the compiler replaces that "call" by the result of a compile-time computation, you must assign the result to a constexpr.

Writing usual functions (just with constexpr added) allows to write code which is simple to read. Moreover, you can use the same code for both: compile-time computations and run-time computations.

C++17 example (similar things are possible in C++14, although some stuff from std is just missing the constexpr qualifier):

http://coliru.stacked-crooked.com/a/154e2dfcc41fb6c7

```<code>#include <cassert>

#include <array>

template<class T, std::size_t N>
constexpr std::array<T, N> multiply(
  const std::array<T, N>& a,
  const std::array<T, N>& b
) {
// may be evaluated in `constexpr` or in non-`constexpr` context

// ... in simple man's words this means:
// inside this function, `a` and `b` are not `constexpr`
// but the return can be used as `constexpr` if all arguments are `constexpr` for the "caller"
  std::array<T, N> ret{};
  for(size_t n=0; n<N; ++n) ret[n] = a[n] * b[n];
  return ret;
}

int main() {
  {// compile-time evaluation is possible if the input data is `constexpr`
    constexpr auto a = std::array{2, 4, 6};
    constexpr auto b = std::array{1, 2, 3};
    constexpr auto c = multiply(a, b);// assigning to a `constexpr` guarantees compile-time evaluation

    static_assert(c[0] == 2);
    static_assert(c[1] == 8);
    static_assert(c[2] == 18);
  }
  {// for run-time data, the same function can be used
    auto a = std::array{2, 4, 6};
    auto b = std::array{1, 2, 3};
    auto c = multiply(a, b);

    assert(c[0] == 2);
    assert(c[1] == 8);
    assert(c[2] == 18);
  }
  return 0;
}
</code>```

Body:
I want to optimize a little program/library I'm writing and since 2 weeks I'm somewhat stuck and now wondering if what I had in mind is even possible like that.
(Please be gentle I don't have very much experience in meta-programming.)

My goal is of course to have certain computations be done by the compiler, so that the programmer - hopefully - only has to edit code at one point in the program and have the compiler "create" all the boilerplate. I do have a reasonably good idea how to do what i want with macros, but it is wished that I do it with templates if possible.

My goal is:
Lets say I have a class that a using programmer can derive from. There he can have multiple incoming and outgoing datatypes that I want to register somehow so that the base class can do it's operations on them.

class my_own_multiply : function_base {
  in<int> a;
  in<float> b;
  out<double> c;

  // ["..."] // other content of the class that actually does something but is irrelevant
  register_ins ins_of_function; // example meta-function calls
  register_outs<c> outs_of_function;
}

The meta-code I have up till now is this: (but it's not yet working/complete)

template <typename... Ts>
struct register_ins {
  const std::array<std::unique_ptr<in_type_erasured>, sizeof...(Ts)> ins;

  constexpr std::array<std::unique_ptr<in_type_erasured>, sizeof...(Ts)>
    build_ins_array() {
      std::array<std::unique_ptr<in_type_erasured>, sizeof...(Ts)> ins_build;
      for (unsigned int i = 0; i < sizeof...(Ts); ++i) {
        ins_build[i] = std::make_unique<in_type_erasured>();
      }
    return ins_build;
  }

  constexpr register_ins() : ins(build_ins_array()) {
  }

  template <typename T>
  T getValueOf(unsigned int in_nr) {
    return ins[in_nr]->getValue();
  }
};

As you may see, I want to call my meta-template-code with a variable number of ins. (Variable in the sense that the programmer can put however many he likes in there, but they won't change at runtime so they can be "baked" in at compile time)

The meta-code is supposed to be creating an array, that is of the length of the number of ins and is initialized so that every field points to the original in in the my_own_multiply class. Basically giving him an indexable data structure that will always have the correct size. And that I could access from the function_base class to use all ins for certain functions which are also iterable making things convenient for me.

Now I have looked into how one might do that, but I now am getting the feeling that I might not really be allowed to "create" this array at compile time in a fashion that allows me to still have the ins a and b be non static and non const so that I can mutate them. From my side they wouldn't have to be const anyway, but my compiler seems to not like them to be free. The only thing I need const is the array with the pointers. But using constexpr possibly "makes" me make them const?

Okay, I will clarify what I don't get:
When I'm trying to create an "instance" of my meta-stuff-structure then it fails because it expects all kinds of const, constexpr and so on. But I don't want them since I need to be able to mutate most of those variables. I only need this meta-stuff to create an array of the correct size already at compile time. But I don't want to sacrifice having to make everything static and const in order to achieve this. So is this even possible under these kinds of terms?

Body:
I do not get all the things you have in mind (also regarding that std::unique_ptr in your example), but maybe this helps:

Starting from C++14 (or C++11, but that is strictly limited) you may write constexpr functions which can be evaluated at compile-time. As a precondition (in simple words), all arguments "passed by the caller" must be constexpr. If you want to enforce that the compiler replaces that "call" by the result of a compile-time computation, you must assign the result to a constexpr.

Writing usual functions (just with constexpr added) allows to write code which is simple to read. Moreover, you can use the same code for both: compile-time computations and run-time computations.

C++17 example (similar things are possible in C++14, although some stuff from std is just missing the constexpr qualifier):

http://coliru.stacked-crooked.com/a/154e2dfcc41fb6c7

#include <cassert>

#include <array>

template<class T, std::size_t N>
constexpr std::array<T, N> multiply(
  const std::array<T, N>& a,
  const std::array<T, N>& b
) {
// may be evaluated in `constexpr` or in non-`constexpr` context

// ... in simple man's words this means:
// inside this function, `a` and `b` are not `constexpr`
// but the return can be used as `constexpr` if all arguments are `constexpr` for the "caller"
  std::array<T, N> ret{};
  for(size_t n=0; n<N; ++n) ret[n] = a[n] * b[n];
  return ret;
}

int main() {
  {// compile-time evaluation is possible if the input data is `constexpr`
    constexpr auto a = std::array{2, 4, 6};
    constexpr auto b = std::array{1, 2, 3};
    constexpr auto c = multiply(a, b);// assigning to a `constexpr` guarantees compile-time evaluation

    static_assert(c[0] == 2);
    static_assert(c[1] == 8);
    static_assert(c[2] == 18);
  }
  {// for run-time data, the same function can be used
    auto a = std::array{2, 4, 6};
    auto b = std::array{1, 2, 3};
    auto c = multiply(a, b);

    assert(c[0] == 2);
    assert(c[1] == 8);
    assert(c[2] == 18);
  }
  return 0;
}


问:
Redirect all ASP.NET Core logging into a single NLog logger
I have an ASP.NET project that sends its logs to NLog.

However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.

I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.

How can this be accomplished?

This is the code that creates the logger:

```<code>        // create the module name
        var ProcessName = Process.GetCurrentProcess().ProcessName;
        _ModuleName = ProcessName  + " (\"" + Oracle.GuessMyName() + "\")";

        // create the logger configuration
        var Configuration = new LoggingConfiguration();

        // create the file target
        var FileTarget = new FileTarget ("file")
        {
            FileName            = @"x:\Logs\${processname}.log",
            ArchiveFileName     = @"x:\Logs\${processname}.{#}.log",
            Layout              = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
            ArchiveEvery        = FileArchivePeriod.Day,
            ArchiveNumbering    = ArchiveNumberingMode.Rolling,
            MaxArchiveFiles     = 7,
            ConcurrentWrites    = true
        };

        Configuration.AddTarget(FileTarget);

        // create the viewer target
        var ViewerTarget = new NLogViewerTarget ("viewer")
        {
            Layout              = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
            IncludeSourceInfo   = true,
            IncludeCallSite     = true,
            Address             = @"udp://127.0.0.1:9999"
        };

        Configuration.AddTarget(ViewerTarget);

        // set the rules
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));

        // set the configuration
        LogManager.Configuration = Configuration;

        // create a new logger
        _Logger = LogManager.GetLogger(_ModuleName);
</code>```

and this is also how ASP.net gets attached to nlog:

```<code>        LoggerFactory.AddNLog();
        Application.AddNLogWeb();
</code>```

Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)

so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.

the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.

答:
You could also create a custom-target, and redirect all non-global-logger messages to this target using NLog rules:

https://github.com/nlog/NLog/wiki/Configuration-file#rules

The custom target can then just forward the log-event to the global-logger:

https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target

You should be careful with cyclic logging. Maybe have a filter in the custom-target to ignore messages from the global-logger.

But I think this is an ugly solution, and I fail to understand the restriction of only one logger-object. Especially when the reason is because it should be named after the application. Why not not a global variable for the name instead of abusing the logger-name?

Body:
I have an ASP.NET project that sends its logs to NLog.

However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.

I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.

How can this be accomplished?

This is the code that creates the logger:

        // create the module name
        var ProcessName = Process.GetCurrentProcess().ProcessName;
        _ModuleName = ProcessName  + " (\"" + Oracle.GuessMyName() + "\")";

        // create the logger configuration
        var Configuration = new LoggingConfiguration();

        // create the file target
        var FileTarget = new FileTarget ("file")
        {
            FileName            = @"x:\Logs\${processname}.log",
            ArchiveFileName     = @"x:\Logs\${processname}.{#}.log",
            Layout              = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
            ArchiveEvery        = FileArchivePeriod.Day,
            ArchiveNumbering    = ArchiveNumberingMode.Rolling,
            MaxArchiveFiles     = 7,
            ConcurrentWrites    = true
        };

        Configuration.AddTarget(FileTarget);

        // create the viewer target
        var ViewerTarget = new NLogViewerTarget ("viewer")
        {
            Layout              = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
            IncludeSourceInfo   = true,
            IncludeCallSite     = true,
            Address             = @"udp://127.0.0.1:9999"
        };

        Configuration.AddTarget(ViewerTarget);

        // set the rules
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));

        // set the configuration
        LogManager.Configuration = Configuration;

        // create a new logger
        _Logger = LogManager.GetLogger(_ModuleName);

and this is also how ASP.net gets attached to nlog:

        LoggerFactory.AddNLog();
        Application.AddNLogWeb();

Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)

so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.

the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.


问:
Not sure why typedef is being used when a struct tag has been set
Considering the following code:

```<code>struct TreeNode {
  int key;
  struct TreeNode *left;
  struct TreeNode *right;
};

struct ListNode {
  int key;
  struct ListNode *next;
};
</code>```

I understand this as two structs with individual struct tags. And that the declaration (if I understand correctly):

```<code>struct ListNode *next;
</code>```

Is creating a pointer that points to a struct of type ListNode. And that

```<code>struct ListNode node1;
</code>```

Is creating a struct of type ListNode.
However, I do not understand the following two lines:

```<code>typedef struct TreeNode *TreeNodePtr;
typedef struct ListNode *ListNodePtr;
</code>```

If this is creating a pointer that points to a struct node of type TreeNode/ListNode I do not understand the purpose of typedef in this situation.

答:
```<code>typedef struct TreeNode *TreeNodePtr;
</code>```

allows you to type

```<code>TreeNodePtr p;
</code>```

instead of

```<code>struct TreeNode *p;
</code>```

Note : People commonly do

```<code>typedef struct TreeNode TreeNode;
</code>```

this allows

```<code>TreeNode tn;
</code>```

This can also be done in the struct definition itself (a struct tag, but yr example doesn't have it)

```<code>struct TreeNode {
  int key;
  struct TreeNode *left;
  struct TreeNode *right;
} TreeNode;
</code>```

Also Note - in c++ this is not needed, a struct (or class) in c++ is always 'its own tag'

Body:
Considering the following code:

struct TreeNode {
  int key;
  struct TreeNode *left;
  struct TreeNode *right;
};

struct ListNode {
  int key;
  struct ListNode *next;
};

I understand this as two structs with individual struct tags. And that the declaration (if I understand correctly):

struct ListNode *next;

Is creating a pointer that points to a struct of type ListNode. And that

struct ListNode node1;

Is creating a struct of type ListNode.
However, I do not understand the following two lines:

typedef struct TreeNode *TreeNodePtr;
typedef struct ListNode *ListNodePtr;

If this is creating a pointer that points to a struct node of type TreeNode/ListNode I do not understand the purpose of typedef in this situation.

Body:
typedef struct TreeNode *TreeNodePtr;

allows you to type

TreeNodePtr p;

instead of

struct TreeNode *p;

Note : People commonly do

typedef struct TreeNode TreeNode;

this allows

TreeNode tn;

This can also be done in the struct definition itself (a struct tag, but yr example doesn't have it)

struct TreeNode {
  int key;
  struct TreeNode *left;
  struct TreeNode *right;
} TreeNode;

Also Note - in c++ this is not needed, a struct (or class) in c++ is always 'its own tag'


问:
Angular2 Jasmine Test Image Source
I have a component with an image in template

```<code> <div class="logo"><img src="../images/logo.png"/></div>
</code>```

When running karma task it throws such error

```<code>Uncaught Error: Cannot find module "../images/logo.png"
</code>```

To mention that app renders the image fine , only karma is complaining.

Any advice will be appreciated.

答:
You could try something like this:</p>

```<code>it('should render the logo', async(() => {
  const fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  const compiled = fixture.debugElement.nativeElement;
  expect(compiled.querySelector('div.logo>img').src).toContain('/images/logo.png');
}));
</code>```

Title: Angular2 Jasmine Test Image Source

Body:
I have a component with an image in template

When running karma task it throws such error

Uncaught Error: Cannot find module "../images/logo.png"

To mention that app renders the image fine , only karma is complaining.

Any advice will be appreciated.

Body:
You could try something like this:

it('should render the logo', async(() => {
  const fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  const compiled = fixture.debugElement.nativeElement;
  expect(compiled.querySelector('div.logo>img').src).toContain('/images/logo.png');
}));


问:
Upgrade Android Studio 3, and logcat screen was modified
Upgrade Android Studio 3, and logcat screen was modified, now i can't see the log filter. Does't enter in the width screen:

Old Version, in two lines, because have "logcat" and "monitors"

link Image:

New Version, not have "logcat" and "monitors", so don't enter in widht ("verbose, search, regex, no filters")

link Image:

I do not know if something similar happens to someone,thanks.

答: I noticed the same and then stumbled upon the documentations regarding this. As per android developers guide, Android Monitor was removed from studio 3.0 in favor of Android profiler.


问:
How to mock a coldbox.system.web.context.RequestContext and initialize it?
I have inherited some code at my work. A previous person wrote some ColdFusion code that looks like this:

```<code>public struct function GetData(Event,RC,PRC){};
</code>```

I am trying to write a unit-test for this function but I don't know how to mock this "Event".
This is my code:

```<code>mockEvent=createMock(className='coldbox.system.web.context.RequestContext');
</code>```

ColdBox is throwing an exception that I must initialize mockEvent when I run that code. Does anyone see what I am doing wrong?

答:
Within a test, which extends the Coldbox.system.testing.BaseTestCase, you can easily mock the Coldbox RequestContext object.

You need to set the following variable in your tests : this.loadColdbox=true and then, after you call the super.beforeAll() method from within your test, each time you call setup(), the context is rebuilt.

After that, the RequestContext is available with the method getRequestContext(). Here's an example of mocking the request getHTTPMethod() function (I typically use this method to mock API methods which are configured to respond to different HTTP verbs):

```<code>function newEventArgs( method = "GET" ) {
        //rebuild the context
        setup();
        //mock the context
        var event = getRequestContext();
        prepareMock( event ).$( "getHTTPMethod", arguments.method );
        var rc = event.getCollection();
        var prc = event.getCollection( private=true );
        prc.response = getWirebox().getInstance( "APIResponse" );

        return {
            "event":event,
            "rc":rc,
            "prc":prc
        };
}
</code>```

Then you might test a create method like so:

```<code>it( "Tests Widgets.create", function(){

        var testWidget = {
            "name"  : "Test Widget"
        };

        var eventArgs = newEventArgs( "POST" );

        structAppend( eventArgs.rc, testWidget, true );

        var event = execute(
            route="/api/v1/widgets"
            eventArgs=eventArgs
        );

        expect( event.getPrivateValue( "response" ).getStatusCode() ).toBe( 201, "Event response did not return the proper status code." );

});
</code>```

Body:
I have inherited some code at my work. A previous person wrote some ColdFusion code that looks like this:

public struct function GetData(Event,RC,PRC){};

I am trying to write a unit-test for this function but I don't know how to mock this "Event".
This is my code:

mockEvent=createMock(className='coldbox.system.web.context.RequestContext');

ColdBox is throwing an exception that I must initialize mockEvent when I run that code. Does anyone see what I am doing wrong?

Body:
Within a test, which extends the Coldbox.system.testing.BaseTestCase, you can easily mock the Coldbox RequestContext object.

You need to set the following variable in your tests : this.loadColdbox=true and then, after you call the super.beforeAll() method from within your test, each time you call setup(), the context is rebuilt.

After that, the RequestContext is available with the method getRequestContext(). Here's an example of mocking the request getHTTPMethod() function (I typically use this method to mock API methods which are configured to respond to different HTTP verbs):

function newEventArgs( method = "GET" ) {
        //rebuild the context
        setup();
        //mock the context
        var event = getRequestContext();
        prepareMock( event ).$( "getHTTPMethod", arguments.method );
        var rc = event.getCollection();
        var prc = event.getCollection( private=true );
        prc.response = getWirebox().getInstance( "APIResponse" );

        return {
            "event":event,
            "rc":rc,
            "prc":prc
        };
}

Then you might test a create method like so:

it( "Tests Widgets.create", function(){

        var testWidget = {
            "name"  : "Test Widget"
        };

        var eventArgs = newEventArgs( "POST" );

        structAppend( eventArgs.rc, testWidget, true );

        var event = execute(
            route="/api/v1/widgets"
            eventArgs=eventArgs
        );

        expect( event.getPrivateValue( "response" ).getStatusCode() ).toBe( 201, "Event response did not return the proper status code." );

});


问:
RShiny: Operation not allowed without an active reactive context
I've looked everywhere for the solution for this, but I just can't figure out how to get rid of the Operation not allowed without an active reactive context. error in RShiny for my situtation. Here's my server code:

```<code>library(ggplot2)

# Surprisingly there is no correlation between charged kw and time
s <- data[,14:16]
s <- s[complete.cases(s),]
cor(s$charged_kwh, s$connected_time_hours)

car_types <- data %>% group_by(car) %>%
  summarise(nrUsers = n_distinct(user_id), n=n()) %>%
  filter(car!="Unknown", car!= " ") %>%
  arrange(desc(nrUsers))

# Connected hours vs actually charging hours
carged_cars <- reactive({
  data %>%
  filter(!is.na(charged_kwh)) %>%
  mutate(charging_time =  charged_kwh / kw_charge_point_speed)
})

filteredData <- carged_cars()[carged_cars()$start_date >= input$cvc_date_diagram[1] & carged_cars()$start_date <= input$cvc_date_diagram[2] &
  carged_cars()$connected_time_hours <= input$cvc_max,]

connTimeVsStart <- ggplot(reactive(filteredData), aes(x=start_date, y=connected_time_hours)) +
  geom_point(shape=16) +
  geom_point(reactive(filterData), aes(x=start_date, y=charging_time), col='red') +
  ggtitle("Charging time")

output$connTimeVsStart <- renderPlot({
  d <- data()
  connTimeVsStart
})
</code>```

data here, is a dataframe that contains data about electric car charging behavior. The console says that my script crashes at line 20 of this server script, so the part where filteredData is defined. I feel like I've tried every combination of making source variables reactive or not, using reactive({}) vs reactive(), etc. Can anyone spot what I'm doing wrong?

答:
Maybe this piece of code can help you.

NB :

 1/ I don't see any use of car_types

 2/ I don't know where your variable data is created

```<code>library(ggplot2)

# Surprisingly there is no correlation between charged kw and time
s <- data[,14:16]
s <- s[complete.cases(s),]
cor(s$charged_kwh, s$connected_time_hours)

car_types <- data %>% group_by(car) %>%
  summarise(nrUsers = n_distinct(user_id), n=n()) %>%
  filter(car!="Unknown", car!= " ") %>%
  arrange(desc(nrUsers))

# Connected hours vs actually charging hours
carged_cars <- reactive({
  data %>%
  filter(!is.na(charged_kwh)) %>%
  mutate(charging_time =  charged_kwh / kw_charge_point_speed)
})

filteredData <- reactive({
    req(carged_cars())
    req(input$cvc_date_diagram)
    carged_cars()[carged_cars()$start_date >= input$cvc_date_diagram[1] & carged_cars()$start_date <= input$cvc_date_diagram[2] &
        carged_cars()$connected_time_hours <= input$cvc_max,]
})

connTimeVsStart <- reactive({
    ggplot(filteredData(), aes(x=start_date, y=connected_time_hours)) +
        geom_point(shape=16) +
        geom_point(reactive(filterData), aes(x=start_date, y=charging_time), col='red') +
        ggtitle("Charging time")
})

output$connTimeVsStart <- renderPlot({
  connTimeVsStart()
})
</code>```

Body:
I've looked everywhere for the solution for this, but I just can't figure out how to get rid of the Operation not allowed without an active reactive context. error in RShiny for my situtation. Here's my server code:

library(ggplot2)

# Surprisingly there is no correlation between charged kw and time
s <- data[,14:16]
s <- s[complete.cases(s),]
cor(s$charged_kwh, s$connected_time_hours)

car_types <- data %>% group_by(car) %>%
  summarise(nrUsers = n_distinct(user_id), n=n()) %>%
  filter(car!="Unknown", car!= " ") %>%
  arrange(desc(nrUsers))

# Connected hours vs actually charging hours
carged_cars <- reactive({
  data %>%
  filter(!is.na(charged_kwh)) %>%
  mutate(charging_time =  charged_kwh / kw_charge_point_speed)
})

filteredData <- carged_cars()[carged_cars()$start_date >= input$cvc_date_diagram[1] & carged_cars()$start_date <= input$cvc_date_diagram[2] &
  carged_cars()$connected_time_hours <= input$cvc_max,]

connTimeVsStart <- ggplot(reactive(filteredData), aes(x=start_date, y=connected_time_hours)) +
  geom_point(shape=16) +
  geom_point(reactive(filterData), aes(x=start_date, y=charging_time), col='red') +
  ggtitle("Charging time")

output$connTimeVsStart <- renderPlot({
  d <- data()
  connTimeVsStart
})

data here, is a dataframe that contains data about electric car charging behavior. The console says that my script crashes at line 20 of this server script, so the part where filteredData is defined. I feel like I've tried every combination of making source variables reactive or not, using reactive({}) vs reactive(), etc. Can anyone spot what I'm doing wrong?

Body:
Maybe this piece of code can help you.

NB :

 1/ I don't see any use of car_types

 2/ I don't know where your variable data is created

library(ggplot2)

# Surprisingly there is no correlation between charged kw and time
s <- data[,14:16]
s <- s[complete.cases(s),]
cor(s$charged_kwh, s$connected_time_hours)

car_types <- data %>% group_by(car) %>%
  summarise(nrUsers = n_distinct(user_id), n=n()) %>%
  filter(car!="Unknown", car!= " ") %>%
  arrange(desc(nrUsers))

# Connected hours vs actually charging hours
carged_cars <- reactive({
  data %>%
  filter(!is.na(charged_kwh)) %>%
  mutate(charging_time =  charged_kwh / kw_charge_point_speed)
})

filteredData <- reactive({
    req(carged_cars())
    req(input$cvc_date_diagram)
    carged_cars()[carged_cars()$start_date >= input$cvc_date_diagram[1] & carged_cars()$start_date <= input$cvc_date_diagram[2] &
        carged_cars()$connected_time_hours <= input$cvc_max,]
})

connTimeVsStart <- reactive({
    ggplot(filteredData(), aes(x=start_date, y=connected_time_hours)) +
        geom_point(shape=16) +
        geom_point(reactive(filterData), aes(x=start_date, y=charging_time), col='red') +
        ggtitle("Charging time")
})

output$connTimeVsStart <- renderPlot({
  connTimeVsStart()
})


问:
python3/syslog: multiple syslog streams?
My python3 program has a number of submodules, and I want them each to send syslog messages with a different syslog ident value. For example, one of them might send to myprogram/submod0, and another one might send to myprogram/submod1. I use syslog-ng to route these messages to different log files.

What I'd like to do is something like this, which I know is not currently possible in the way that I'm writing it here:

```<code>syslog0 = syslog.openlog('myprogram/submod0',
                         syslog.LOG_PID, syslog.LOG_MAIL)
syslog1 = syslog.openlog('myprogram/submod1',
                         syslog.LOG_PID, syslog.LOG_MAIL)
</code>```

... and then, within submod0, I want to send syslog messages like this ...

```<code>syslog0.syslog('some sort of message')
</code>```

... and this way within submod1 ...

```<code>syslog1.syslog('another message')
</code>```

But, of course, syslog.openlog doesn't return any kind of object that I can use as a handle in this way.

Is there any way that I can accomplish what I want using the syslog facilities of python3?

I suppose that I could issue a new openlog for each syslog message that I want to send. For example ...

```<code>def mysyslog(ident, message):
    syslog.openlog('myprogram/{}'.format(ident),
                   syslog.LOG_PID, syslog.LOG_MAIL)
    syslog.syslog(message)
</code>```

... and then use mysyslog('submod0', message) within my submod0 and mysyslog('submod1', message) within my submod1. Is this the only way I can accomplish what I want to do?

Thank you in advance.

答:
I couldn't find any existing python modules which do what I want, so I decided to write my own syslog wrapper. It is written to open a syslog connection based on either host:port or a socket file such as /dev/log, and to then accept all of the other parameters like facility, severity, program, etc. on each call to send a syslog message.

With all the parameters at the level of the individual logging method call, this class could be wrapped at a higher level to provide handles to, for example, unique connections via program, which is what I have specified in my original question here.

I have only tested the following code with python3.6 and in the /dev/log case. It works for me, but use it at your own risk.

```<code>#!/usr/bin/python3.6

import os
import sys
import socket
import datetime

# Only imported for the syslog.LOG_INFO and syslog.LOG_USER constants.
import syslog

# Appends a newline in all cases.
def _log_stderr(message):
    if message:
        sys.stderr.write(message)
    sys.stderr.write('\n')
    sys.stderr.flush()

# XSyslog: a syslog wrapper class.
#
# This module allows the facility (such as LOG_USER), the
# severity (such as LOG_INFO), and other syslog parameters
# to be set on a message-by-message basis via one, single
# syslog connection.
#
# Usage:
#
#   slog = XSyslog([server=server], [port=port], [proto=proto],
#                  [clientname=clientname], [maxlen=maxlen])
#
# This allows three  cases:
# (1) Connect to syslog via UDP to a host and port:
#     Specify host, port, and proto='UDP'.
# (2) Connect to syslog via TCP to a host and port:
#     Specify host, port, and proto='TCP'.
# (3) Connect to syslog via a socket file such as /dev/log.
#     Specify proto=filename (e.g., proto='/dev/log').
#     In this case, host and port are ignored.
#
# clientname is an optional field for the syslog message.
# maxlen is the maximum message length.
#
# Once the XSyslog object is created, the message can be sent as follows:
#
#   slog = XSyslog([... parameters ...])
#   slog.log(message, [facility=facility], [severity=severity],
#                     [timestamp=timestamp], [hostame=hostname],
#                     [program=program], [pid=pid])
#     facility  defaults to LOG_USER
#     severity  defaults to LOG_INFO
#     timestamp defaults to now
#     hostname  if None, use clientname if it exists; if '', no hostname.
#     program   defaults to "logger"
#     pid       defaults to os.getpid()

class XSyslog(object):

    def __init__(self, server=None, port=None, proto='udp', clientname=None, maxlen=1024):
        self.server       = server
        self.port         = port
        self.proto        = socket.SOCK_DGRAM
        self.clientname   = None
        self.maxlen       = maxlen
        self._protoname   = ''
        self._socket      = None
        self._sockfile    = None
        self._connectargs = ()
        self._me          = os.path.splitext(self.__class__.__name__)[1][1:]

        if proto:
            if proto.lower() == 'udp':
                self._protoname  = proto.lower()
                self.proto       = socket.SOCK_DGRAM
                self._socketargs = (self.server, self.port, socket.AF_UNSPEC, self.proto)
            elif proto.lower() == 'tcp':
                self._protoname  = proto.lower()
                self.proto       = socket.SOCK_STREAM
                self._socketargs = (self.server, self.port, socket.AF_UNSPEC, self.proto)
            elif len(proto) > 0:
                self._sockfile   = proto
                self._protoname  = self._sockfile
                self.proto       = socket.SOCK_DGRAM
                self._socketargs = (socket.AF_UNIX, self.proto)

        badargs = False
        if self._sockfile:
            pass
        elif self.server and self.port:
            pass
        else:
            badargs = True
        if not self.proto:
            badargs = True
        if badargs:
            raise ValueError("'proto' must be 'udp' or 'tcp' with 'server' and 'port', or else a socket filename like '/dev/log'")

        if not self.clientname:
            try:
                self.clientname = socket.getfqdn()
                if not self.clientname:
                    self.clientname = socket.gethostname()
            except:
                self.clientname = None

    def _connect(self):
        if self._socket is None:
            if self._sockfile:
                self._socket = socket.socket(*self._socketargs)
                if not self._socket:
                    _log_stderr(':::::::: {}: unable to open socket file {}'.format(self._me, self._sockfile))
                    return False
                try:
                    self._socket.connect(self._sockfile)
                    return True
                except socket.timeout as e:
                    _log_stderr(':::::::: {}: sockfile timeout e={}'.format(self._me, e))
                    # Force-close the socket and its contained fd, to avoid fd leaks.
                    self.close()
                except socket.error as e:
                    _log_stderr(':::::::: {}: sockfile error f={}, e={}'.format(self._me, self._sockfile, e))
                    # Force-close the socket and its contained fd, to avoid fd leaks.
                    self.close()
                except Exception as e:
                    # Any other exception which might occur ...
                    _log_stderr(':::::::: {}: sockfile exception f={}, e={}'.format(self._me, self._sockfile, e))
                    # Force-close the socket and its contained fd, to avoid fd leaks.
                    self.close()
                return False
            else:
                addrinfo = socket.getaddrinfo(*self._socketargs)
                if addrinfo is None:
                    return False
                # Check each socket family member until we find one we can connect to.
                for (addr_fam, sock_kind, proto, ca_name, sock_addr) in addrinfo:
                    self._socket = socket.socket(addr_fam, self.proto)
                    if not self._socket:
                        _log_stderr(':::::::: {}: unable to get a {} socket'.format(self._me, self._protoname))
                        return False
                    try:
                        self._socket.connect(sock_addr)
                        return True
                    except socket.timeout as e:
                        _log_stderr(':::::::: {}: {} timeout e={}'.format(self.me, self._protoname, e))
                        # Force-close the socket and its contained fd, to avoid fd leaks.
                        self.close()
                        continue
                    except socket.error as e:
                        _log_stderr(':::::::: {}: {} error e={}'.format(self._me, self._protoname, e))
                        # Force-close the socket and its contained fd, to avoid fd leaks.
                        self.close()
                        continue
                    except Exception as e:
                        # Any other exception which might occur ...
                        _log_stderr(':::::::: {}: {} exception e={}'.format(self._me, self._protoname, e))
                        # Force-close the socket and its contained fd, to avoid fd leaks.
                        self.close()
                        continue
                # Force-close the socket and its contained fd, to avoid fd leaks.
                self.close()
                return False
        else:
            return True

    def close(self):
        try:
            self._socket.close()
        except:
            pass
        self._socket = None

    def log(self, message, facility=None, severity=None, timestamp=None, hostname=None, program=None, pid=None):

        if message is None:
            return

        if not facility:
            facility = syslog.LOG_USER

        if not severity:
            severity = syslog.LOG_INFO

        pri = facility + severity

        data = '<{}>'.format(pri)

        if timestamp:
            t = timestamp
        else:
            t = datetime.datetime.now()
        data = '{}{}'.format(data, t.strftime('%Y-%m-%dT%H:%M:%S.%f'))

        if hostname is None:
            if self.clientname:
                data = '{} {}'.format(data, self.clientname)
        elif not hostname:
            # For hostname == '', leave out the hostname, altogether.
            pass
        else:
            data = '{} {}'.format(data, hostname)

        if program:
            data = '{} {}'.format(data, program)
        else:
            data = '{} logger'.format(data)

        if not pid:
            pid = os.getpid()

        data = '{}[{}]: {}'.format(data, pid, message).encode('ascii', 'ignore')

        if not self._socket:
            self._connect()

        if not self._socket:
            raise Exception('{}: unable to connect to {} syslog via {}'.format(self._me, self._protoname, self._socketargs))
        try:
            if self.maxlen:
                self._socket.sendall(data[:self.maxlen])
            else:
                self._socket.sendall(data)
        except IOError as e:
            _log_stderr(':::::::: {}: {} syslog io error {} via {}'.format(self._me, self._protoname, e, self._socketargs))
            self.close()
            raise
        except Exception as e:
            # Any other exception which might occur ...
            _log_stderr(':::::::: {}: {} syslog exception {} via {}'.format(self._me, self._protoname, e, self._socketargs))
            self.close()
            raise
</code>```

Body:
My python3 program has a number of submodules, and I want them each to send syslog messages with a different syslog ident value. For example, one of them might send to myprogram/submod0, and another one might send to myprogram/submod1. I use syslog-ng to route these messages to different log files.

What I'd like to do is something like this, which I know is not currently possible in the way that I'm writing it here:

syslog0 = syslog.openlog('myprogram/submod0',
                         syslog.LOG_PID, syslog.LOG_MAIL)
syslog1 = syslog.openlog('myprogram/submod1',
                         syslog.LOG_PID, syslog.LOG_MAIL)

... and then, within submod0, I want to send syslog messages like this ...

syslog0.syslog('some sort of message')

... and this way within submod1 ...

syslog1.syslog('another message')

But, of course, syslog.openlog doesn't return any kind of object that I can use as a handle in this way.

Is there any way that I can accomplish what I want using the syslog facilities of python3?

I suppose that I could issue a new openlog for each syslog message that I want to send. For example ...

def mysyslog(ident, message):
    syslog.openlog('myprogram/{}'.format(ident),
                   syslog.LOG_PID, syslog.LOG_MAIL)
    syslog.syslog(message)

... and then use mysyslog('submod0', message) within my submod0 and mysyslog('submod1', message) within my submod1. Is this the only way I can accomplish what I want to do?

Thank you in advance.

Body:
I couldn't find any existing python modules which do what I want, so I decided to write my own syslog wrapper. It is written to open a syslog connection based on either host:port or a socket file such as /dev/log, and to then accept all of the other parameters like facility, severity, program, etc. on each call to send a syslog message.

With all the parameters at the level of the individual logging method call, this class could be wrapped at a higher level to provide handles to, for example, unique connections via program, which is what I have specified in my original question here.

I have only tested the following code with python3.6 and in the /dev/log case. It works for me, but use it at your own risk.

#!/usr/bin/python3.6

import os
import sys
import socket
import datetime

# Only imported for the syslog.LOG_INFO and syslog.LOG_USER constants.
import syslog

# Appends a newline in all cases.
def _log_stderr(message):
    if message:
        sys.stderr.write(message)
    sys.stderr.write('\n')
    sys.stderr.flush()

# XSyslog: a syslog wrapper class.
#
# This module allows the facility (such as LOG_USER), the
# severity (such as LOG_INFO), and other syslog parameters
# to be set on a message-by-message basis via one, single
# syslog connection.
#
# Usage:
#
#   slog = XSyslog([server=server], [port=port], [proto=proto],
#                  [clientname=clientname], [maxlen=maxlen])
#
# This allows three  cases:
# (1) Connect to syslog via UDP to a host and port:
#     Specify host, port, and proto='UDP'.
# (2) Connect to syslog via TCP to a host and port:
#     Specify host, port, and proto='TCP'.
# (3) Connect to syslog via a socket file such as /dev/log.
#     Specify proto=filename (e.g., proto='/dev/log').
#     In this case, host and port are ignored.
#
# clientname is an optional field for the syslog message.
# maxlen is the maximum message length.
#
# Once the XSyslog object is created, the message can be sent as follows:
#
#   slog = XSyslog([... parameters ...])
#   slog.log(message, [facility=facility], [severity=severity],
#                     [timestamp=timestamp], [hostame=hostname],
#                     [program=program], [pid=pid])
#     facility  defaults to LOG_USER
#     severity  defaults to LOG_INFO
#     timestamp defaults to now
#     hostname  if None, use clientname if it exists; if '', no hostname.
#     program   defaults to "logger"
#     pid       defaults to os.getpid()

class XSyslog(object):

    def __init__(self, server=None, port=None, proto='udp', clientname=None, maxlen=1024):
        self.server       = server
        self.port         = port
        self.proto        = socket.SOCK_DGRAM
        self.clientname   = None
        self.maxlen       = maxlen
        self._protoname   = ''
        self._socket      = None
        self._sockfile    = None
        self._connectargs = ()
        self._me          = os.path.splitext(self.__class__.__name__)[1][1:]

        if proto:
            if proto.lower() == 'udp':
                self._protoname  = proto.lower()
                self.proto       = socket.SOCK_DGRAM
                self._socketargs = (self.server, self.port, socket.AF_UNSPEC, self.proto)
            elif proto.lower() == 'tcp':
                self._protoname  = proto.lower()
                self.proto       = socket.SOCK_STREAM
                self._socketargs = (self.server, self.port, socket.AF_UNSPEC, self.proto)
            elif len(proto) > 0:
                self._sockfile   = proto
                self._protoname  = self._sockfile
                self.proto       = socket.SOCK_DGRAM
                self._socketargs = (socket.AF_UNIX, self.proto)

        badargs = False
        if self._sockfile:
            pass
        elif self.server and self.port:
            pass
        else:
            badargs = True
        if not self.proto:
            badargs = True
        if badargs:
            raise ValueError("'proto' must be 'udp' or 'tcp' with 'server' and 'port', or else a socket filename like '/dev/log'")

        if not self.clientname:
            try:
                self.clientname = socket.getfqdn()
                if not self.clientname:
                    self.clientname = socket.gethostname()
            except:
                self.clientname = None

    def _connect(self):
        if self._socket is None:
            if self._sockfile:
                self._socket = socket.socket(*self._socketargs)
                if not self._socket:
                    _log_stderr(':::::::: {}: unable to open socket file {}'.format(self._me, self._sockfile))
                    return False
                try:
                    self._socket.connect(self._sockfile)
                    return True
                except socket.timeout as e:
                    _log_stderr(':::::::: {}: sockfile timeout e={}'.format(self._me, e))
                    # Force-close the socket and its contained fd, to avoid fd leaks.
                    self.close()
                except socket.error as e:
                    _log_stderr(':::::::: {}: sockfile error f={}, e={}'.format(self._me, self._sockfile, e))
                    # Force-close the socket and its contained fd, to avoid fd leaks.
                    self.close()
                except Exception as e:
                    # Any other exception which might occur ...
                    _log_stderr(':::::::: {}: sockfile exception f={}, e={}'.format(self._me, self._sockfile, e))
                    # Force-close the socket and its contained fd, to avoid fd leaks.
                    self.close()
                return False
            else:
                addrinfo = socket.getaddrinfo(*self._socketargs)
                if addrinfo is None:
                    return False
                # Check each socket family member until we find one we can connect to.
                for (addr_fam, sock_kind, proto, ca_name, sock_addr) in addrinfo:
                    self._socket = socket.socket(addr_fam, self.proto)
                    if not self._socket:
                        _log_stderr(':::::::: {}: unable to get a {} socket'.format(self._me, self._protoname))
                        return False
                    try:
                        self._socket.connect(sock_addr)
                        return True
                    except socket.timeout as e:
                        _log_stderr(':::::::: {}: {} timeout e={}'.format(self.me, self._protoname, e))
                        # Force-close the socket and its contained fd, to avoid fd leaks.
                        self.close()
                        continue
                    except socket.error as e:
                        _log_stderr(':::::::: {}: {} error e={}'.format(self._me, self._protoname, e))
                        # Force-close the socket and its contained fd, to avoid fd leaks.
                        self.close()
                        continue
                    except Exception as e:
                        # Any other exception which might occur ...
                        _log_stderr(':::::::: {}: {} exception e={}'.format(self._me, self._protoname, e))
                        # Force-close the socket and its contained fd, to avoid fd leaks.
                        self.close()
                        continue
                # Force-close the socket and its contained fd, to avoid fd leaks.
                self.close()
                return False
        else:
            return True

    def close(self):
        try:
            self._socket.close()
        except:
            pass
        self._socket = None

    def log(self, message, facility=None, severity=None, timestamp=None, hostname=None, program=None, pid=None):

        if message is None:
            return

        if not facility:
            facility = syslog.LOG_USER

        if not severity:
            severity = syslog.LOG_INFO

        pri = facility + severity

        data = '<{}>'.format(pri)

        if timestamp:
            t = timestamp
        else:
            t = datetime.datetime.now()
        data = '{}{}'.format(data, t.strftime('%Y-%m-%dT%H:%M:%S.%f'))

        if hostname is None:
            if self.clientname:
                data = '{} {}'.format(data, self.clientname)
        elif not hostname:
            # For hostname == '', leave out the hostname, altogether.
            pass
        else:
            data = '{} {}'.format(data, hostname)

        if program:
            data = '{} {}'.format(data, program)
        else:
            data = '{} logger'.format(data)

        if not pid:
            pid = os.getpid()

        data = '{}[{}]: {}'.format(data, pid, message).encode('ascii', 'ignore')

        if not self._socket:
            self._connect()

        if not self._socket:
            raise Exception('{}: unable to connect to {} syslog via {}'.format(self._me, self._protoname, self._socketargs))
        try:
            if self.maxlen:
                self._socket.sendall(data[:self.maxlen])
            else:
                self._socket.sendall(data)
        except IOError as e:
            _log_stderr(':::::::: {}: {} syslog io error {} via {}'.format(self._me, self._protoname, e, self._socketargs))
            self.close()
            raise
        except Exception as e:
            # Any other exception which might occur ...
            _log_stderr(':::::::: {}: {} syslog exception {} via {}'.format(self._me, self._protoname, e, self._socketargs))
            self.close()
            raise


问:
REST requests no longer able to authenticate after enabling Windows Authentication
In Kentico 10, I had rest requests working fine within Kentico (and from Postman). After enabling Windows Authentication I now receive a 401 unauthorized message when trying to make the exact same rest requests. The user account making the request is a non-active directory account, and is not marked as an external or domain user. In the IIS authentication area I have Anonymous and Windows Authentication enabled. Do I need to enable Basic authentication there, or is there anything else I need to do so that my user account for the rest service can authenticate once again?</p>

答: I think you can do only basic or hash parameter authentication,  take a look at Authenticating REST requests.  Are you saying that requests that were working perfectly in Postman before, stopped working  after you've enabled Windows Authentication in Kentico?  Does anonymous authentication is enabled at your IIS?</p>