问:
How to use Xamarin Forms Custom Button Renderer's Touch event to change the Buttons Image
I figured it out.
For anyone needing this. Please see the following.
After Watching Xamarin Evolve a million times I caught on.</p>

```<code>class LoginButtonCustomRenderer : ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);

        Android.Widget.Button thisButton = Control as Android.Widget.Button;

        thisButton.Touch += (object sender, TouchEventArgs e2) =>
        {
            if (e2.Event.Action == MotionEventActions.Down)
            {

                System.Diagnostics.Debug.WriteLine("TouchDownEvent");

                // Had to use the e.NewElement
                e.NewElement.Image = "pressed.png";
            }
            else if (e2.Event.Action == MotionEventActions.Up)
            {
                System.Diagnostics.Debug.WriteLine("TouchUpEvent");
            }
        };

    }

}
</code>```

答:
Here is a sample how to implement a two state ImageButton in Xamarin Forms:

PCL:

```<code>public class FancyButton : Button
{
    public void SendClickedCommand()
    {
        ICommand command = this.Command;
        if (command != null)
        {
            command.Execute(this.CommandParameter);
        }
    }
}
</code>```

Android render:

```<code>public class FancyButtonAndroid : ButtonRenderer
{
    Android.Widget.Button thisButton;

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);
        thisButton = Control as Android.Widget.Button;
        thisButton.SetBackgroundResource(Resource.Drawable.btn_unpress);
        thisButton.Touch += ThisButton_Touch;
        thisButton.Click += HandleButtonClicked;
    }

    private void ThisButton_Touch(object sender, TouchEventArgs e)
    {
        e.Handled = false;
        if (e.Event.Action == MotionEventActions.Down)
        {
            System.Diagnostics.Debug.WriteLine("TouchDownEvent");
            thisButton.SetBackgroundResource(Resource.Drawable.btn_press);
        }
        else if (e.Event.Action == MotionEventActions.Up)
        {
            System.Diagnostics.Debug.WriteLine("TouchUpEvent");
            thisButton.SetBackgroundResource(Resource.Drawable.btn_unpress);
        }
    }

    private void HandleButtonClicked(object sender, EventArgs e)
    {
        if (Element != null && Element is FancyButton)
        {
            (Element as FancyButton).SendClickedCommand();
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (thisButton != null)
        {
            thisButton.Touch -= ThisButton_Touch;
            thisButton.Click -= HandleButtonClicked;
        }
        base.Dispose(disposing);
    }
}
</code>```

Note: in the Touch event set: e.Handled = false; to cause the Click event to rise.

Body:
I figured it out.
For anyone needing this. Please see the following.
After Watching Xamarin Evolve a million times I caught on.

class LoginButtonCustomRenderer : ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);

        Android.Widget.Button thisButton = Control as Android.Widget.Button;

        thisButton.Touch += (object sender, TouchEventArgs e2) =>
        {
            if (e2.Event.Action == MotionEventActions.Down)
            {

                System.Diagnostics.Debug.WriteLine("TouchDownEvent");

                // Had to use the e.NewElement
                e.NewElement.Image = "pressed.png";
            }
            else if (e2.Event.Action == MotionEventActions.Up)
            {
                System.Diagnostics.Debug.WriteLine("TouchUpEvent");
            }
        };

    }

}

Body:
Here is a sample how to implement a two state ImageButton in Xamarin Forms:

PCL:

public class FancyButton : Button
{
    public void SendClickedCommand()
    {
        ICommand command = this.Command;
        if (command != null)
        {
            command.Execute(this.CommandParameter);
        }
    }
}

Android render:

public class FancyButtonAndroid : ButtonRenderer
{
    Android.Widget.Button thisButton;

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);
        thisButton = Control as Android.Widget.Button;
        thisButton.SetBackgroundResource(Resource.Drawable.btn_unpress);
        thisButton.Touch += ThisButton_Touch;
        thisButton.Click += HandleButtonClicked;
    }

    private void ThisButton_Touch(object sender, TouchEventArgs e)
    {
        e.Handled = false;
        if (e.Event.Action == MotionEventActions.Down)
        {
            System.Diagnostics.Debug.WriteLine("TouchDownEvent");
            thisButton.SetBackgroundResource(Resource.Drawable.btn_press);
        }
        else if (e.Event.Action == MotionEventActions.Up)
        {
            System.Diagnostics.Debug.WriteLine("TouchUpEvent");
            thisButton.SetBackgroundResource(Resource.Drawable.btn_unpress);
        }
    }

    private void HandleButtonClicked(object sender, EventArgs e)
    {
        if (Element != null && Element is FancyButton)
        {
            (Element as FancyButton).SendClickedCommand();
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (thisButton != null)
        {
            thisButton.Touch -= ThisButton_Touch;
            thisButton.Click -= HandleButtonClicked;
        }
        base.Dispose(disposing);
    }
}

Note: in the Touch event set: e.Handled = false; to cause the Click event to rise.


来源: stackexchange

问:
How to add typescript typings to NPM module that exports a class?
I would like my design-systems-utils module to include Typescript typings even though the source code is not written using Typescript (I have seen that others have done this).

I have already attempted this here, but it does not work. By the way, my module exports a class...

```<code>declare class DesignSystem {
    constructor(system: object, options?: object);
    multiply(initial: number, multiplier: number): any;
    get(val: string): any;
    bp(bp: string): any;
    z(z: string): any;
    fontSize(size: string|number, toPxl?: boolean): string;
    fs(size: string|number, toPxl?: boolean): string;
    spacing(index: number): string;
    space(index: number): string;
    toPx(value: number, base: number, unit?: string): string;
    pxTo(value: number, base: number): string;
    color(hue:string, value:string): string;
    designSystem: object;
    interface options {
        defaultUnit: string,
        useModularScale: boolean,
        fontSizeUnit: string
    }
}
</code>```

I have also seen that I should be exporting this as a module, like so:

```<code>declare module "DesignSystem" {
    export default class DesignSystem {
        constructor(system: object, options?: object);
        /*~ Multiply two items together */
        multiply(initial: number, multiplier: number): any;
        get(val: string): any;
        bp(bp: string): any;
        z(z: string): any;
        fontSize(size: string|number, toPxl?: boolean): string;
        fs(size: string|number, toPxl?: boolean): string;
        spacing(index: number): string;
        space(index: number): string;
        toPx(value: number, base: number, unit?: string): string;
        pxTo(value: number, base: number): string;
        color(hue:string, value:string): string;
        designSystem: object;
    }
}
</code>```

But that also does not work.

Any help would be greatly appreciated.

答:
In principal:

```<code>declare module "DesignSystem" { ...}
</code>```

should be changed to the name of your npm module:

```<code>declare module "design-systems-utils" { ...}
</code>```

This is the way you tell typescript "Here are the types for when the user does 'import ... from design-systems-utils'". This is mostly useful when you need to extend library types from "outside".

However, since your package.json has types: src/index.d.ts field, we don't even need that. Typescript already knows what library your d.ts file provides definition for.

```<code>export default class DesignSystem {...}
</code>```

should be enough.

Your first attempt declares a global class called DesignSystem.  The general rule of thumb is that your d.ts should mirror you js structure. So if you do export default from js file, do it also from d.ts

(Also, thanks for providing definitions for your library, you make the world a better place)

ContentLicense: CC BY-SA 3.0

Body:
I would like my design-systems-utils module to include Typescript typings even though the source code is not written using Typescript (I have seen that others have done this).

I have already attempted this here, but it does not work. By the way, my module exports a class...

declare class DesignSystem {
    constructor(system: object, options?: object);
    multiply(initial: number, multiplier: number): any;
    get(val: string): any;
    bp(bp: string): any;
    z(z: string): any;
    fontSize(size: string|number, toPxl?: boolean): string;
    fs(size: string|number, toPxl?: boolean): string;
    spacing(index: number): string;
    space(index: number): string;
    toPx(value: number, base: number, unit?: string): string;
    pxTo(value: number, base: number): string;
    color(hue:string, value:string): string;
    designSystem: object;
    interface options {
        defaultUnit: string,
        useModularScale: boolean,
        fontSizeUnit: string
    }
}

I have also seen that I should be exporting this as a module, like so:

declare module "DesignSystem" {
    export default class DesignSystem {
        constructor(system: object, options?: object);
        /*~ Multiply two items together */
        multiply(initial: number, multiplier: number): any;
        get(val: string): any;
        bp(bp: string): any;
        z(z: string): any;
        fontSize(size: string|number, toPxl?: boolean): string;
        fs(size: string|number, toPxl?: boolean): string;
        spacing(index: number): string;
        space(index: number): string;
        toPx(value: number, base: number, unit?: string): string;
        pxTo(value: number, base: number): string;
        color(hue:string, value:string): string;
        designSystem: object;
    }
}

But that also does not work.

Any help would be greatly appreciated.

Body:
In principal:

declare module "DesignSystem" { ...}

should be changed to the name of your npm module:

declare module "design-systems-utils" { ...}

This is the way you tell typescript "Here are the types for when the user does 'import ... from design-systems-utils'". This is mostly useful when you need to extend library types from "outside".

However, since your package.json has types: src/index.d.ts field, we don't even need that. Typescript already knows what library your d.ts file provides definition for.

export default class DesignSystem {...}

should be enough.

Your first attempt declares a global class called DesignSystem.  The general rule of thumb is that your d.ts should mirror you js structure. So if you do export default from js file, do it also from d.ts

(Also, thanks for providing definitions for your library, you make the world a better place)


问:
How to allow only certain words consecutively with Regex in javascript
I'm trying to write a regex that will return true if it matches the format below, otherwise, it should return false. It should only allow words as below:

Positive match (return true)

```<code>UA-1234-1,UA-12345-2,UA-34578-2
</code>```

Negative match (return false or null)

Note: A is missing after U

```<code>UA-1234-1,U-12345-2
</code>```

It should always give me true when the string passed to regex is
UA-1234-1,UA-12345-2,UA-34578-2,...........

Below is what I am trying to do but it is matching only the first element and not returning null.

```<code>var pattern=/^UA-[0-9]+(-[0-9]+)?/g;

pattern.match("UA-1234-1,UA-12345-2,UA-34578-2");

pattern.exec("UA-1234-1,UA-12345-2,UA-34578-2)
</code>```

Thanks in advance. Help is greatly appreciated.

答:
The pattern you need is a pattern enclosed with anchors (^ - start of string and $ - end of string) that matches your pattern at first (the initial "block") and then matches 0 or more occurrences of a , followed with the block pattern.

It looks like /^BLOCK(?:,BLOCK)*$/. You may introduce optional whitespaces in between, e.g. /^BLOCK(?:,\s*BLOCK)*$/.

In the end, the pattern looks like ^UA-[0-9]+(?:-[0-9]+)?(?:,UA-[0-9]+(?:-[0-9]+)?)*$. It is best to build it dynamically to keep it readable and easy to maintain:

const block = "UA-[0-9]+(?:-[0-9]+)?";
let rx = new RegExp(`^${block}(?:,${block})*$`); // RegExp("^" + block + "(?:," + block + ")*$") // for non-ES6
let tests = ['UA-1234-1,UA-12345-2,UA-34578-2', 'UA-1234-1,U-12345-2'];
for (var s of tests) {
  console.log(s, "=>", rx.test(s));
}```

Body:
I'm trying to write a regex that will return true if it matches the format below, otherwise, it should return false. It should only allow words as below:

Positive match (return true)

UA-1234-1,UA-12345-2,UA-34578-2

Negative match (return false or null)

Note: A is missing after U

UA-1234-1,U-12345-2

It should always give me true when the string passed to regex is
UA-1234-1,UA-12345-2,UA-34578-2,...........

Below is what I am trying to do but it is matching only the first element and not returning null.

var pattern=/^UA-[0-9]+(-[0-9]+)?/g;

pattern.match("UA-1234-1,UA-12345-2,UA-34578-2");

pattern.exec("UA-1234-1,UA-12345-2,UA-34578-2)

Thanks in advance. Help is greatly appreciated.


问:
Should I use async I/O on memorystreams?
Is it better to not use any Async methods (CopyToAsync, ReadAsync, etc...) if I know that the stream I'm operating on is a MemoryStream ?

A comment of Stephen Clearly on this SO question made me doubt on the approach I'm using in a server-application that should be able to handle many concurrent requests.

In that application, all I/O is done async so that no threads are wasted.  However, as it seems that CopyToAsync f.i. is not really asynchronous on a MemoryStream, I wonder if I have any benefit -even in a server-application- to use async operations on a MemoryStream.

答:
Well, if you check MemoryStream implementation, you'll find that ReadAsync (and WriteAsync) are actually sync without using any additional threads. And while there is some overhead, it's pretty small and should be negligible.

CopyToAsync is a different beast. While other async methods works only on one thread, CopyToAsync works on two. And while your source MemoryStream doesn't benefit from async, destination thread can. Of course, if both streams are memory streams you won't get any benefit at all.

So, answering your question in general, MemoryStream have async methods only for consistency with other stream implementations. But you won't get any significant performance degradation when you are using it.

P.S. If you need good performance with MemoryStream, it is better avoid re-allocations, re-use underlying buffers, etc. But it's different topic unrelated to async.


问:
Select Price value only from td in python
I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here

here is the code i have written

```<code>from  builtins import any as b_any
from urllib.parse import urlparse
from urllib.parse import urljoin
from collections import Counter
import urllib.request
import csv
import schedule
import time
import re
from bs4 import BeautifulSoup

url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"

req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'})

htmlpage = urllib.request.urlopen(req)

html = htmlpage.read().decode('utf-8')

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('td',{'class':'onheadNav'})

'''for txt in table:
    nametxt = txt.text
    result = ''.join([i for i in nametxt if not i.isdigit()])
    cleantxt = result.replace('(','')
    print(cleantxt.replace(')',''))

    rank = txt.a.text
    print(rank)'''
price = soup.select('td.contentValueFont')
for pr in price:
    print(pr.text)
</code>```

If i slice price in for loop it will get only first price but i want to have all prices at once.

Edited description:
I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now

答:
Short solution:

```<code>from bs4 import BeautifulSoup
import requests

url = "http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"
html = requests.get(url).content
soup = BeautifulSoup(html, "html.parser")

prices =[ price.string.replace('\xa0', ' ')
          for price in soup.select('td.contentValueFont') if price.string.endswith('EUR')]
print(prices)
</code>```

The output:

```<code>['4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '14,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR']
</code>```

Body:
I am trying to capture just price value from html td tag but the problem is there are other td with same class name: please see the picture below. enter image description here

here is the code i have written

from  builtins import any as b_any
from urllib.parse import urlparse
from urllib.parse import urljoin
from collections import Counter
import urllib.request
import csv
import schedule
import time
import re
from bs4 import BeautifulSoup

url="http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"

req = urllib.request.Request(url, headers={'User-agent': 'Mozilla/5.0'})

htmlpage = urllib.request.urlopen(req)

html = htmlpage.read().decode('utf-8')

soup = BeautifulSoup(html,"html.parser")

table = soup.find_all('td',{'class':'onheadNav'})

'''for txt in table:
    nametxt = txt.text
    result = ''.join([i for i in nametxt if not i.isdigit()])
    cleantxt = result.replace('(','')
    print(cleantxt.replace(')',''))

    rank = txt.a.text
    print(rank)'''
price = soup.select('td.contentValueFont')
for pr in price:
    print(pr.text)

If i slice price in for loop it will get only first price but i want to have all prices at once.

Edited description:
I want to capture all prices but problem is there are three td with same class name one td is for price one for Cantidad(quantity) and the one which is for date these all have same class. and when i try to get only price section my code returns all three td's. I hope you get it now

Body:
Short solution:

from bs4 import BeautifulSoup
import requests

url = "http://offer.ebay.es/ws/eBayISAPI.dll?ViewBidsLogin&item=122713288532&rt=nc&_trksid=p2047675.l2564"
html = requests.get(url).content
soup = BeautifulSoup(html, "html.parser")

prices =[ price.string.replace('\xa0', ' ')
          for price in soup.select('td.contentValueFont') if price.string.endswith('EUR')]
print(prices)

The output:

['4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '8,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR', '14,90 EUR', '4,90 EUR', '4,90 EUR', '4,90 EUR']


问:
Fast way to find a position of any unset bit in a memory buffer
So I had an interview today, the question is:

Given a memory buffer, find a position of unset bit

int getPosition(const char *start, const int len)

If all bits in this memory buffer is 1, return -1

otherwise return an index of the unset bit, started from 0

Performance is first priority

Example

```<code>start, len=4
0x00|0x00|0x00|0x00: valid return: 0 to 31
0xFF|0xF0|0xFF|0xFF: valid return: 8,9,10,11
0xFF|0xFF|0xFF|0xFF: valid return: -1
</code>```

Update Example

it does not have to be the leftmost or rightmost bit, any position as long as the bit is 0 is ok

```<code>00000000|00000000 : valid return 0 to 15
10101010|10101010 : valid return 0,2,4,6,8,10,12,14
11110111|11111111 : valid return 11
</code>```

And my answer was

```<code>int getPosition(const char *start, const int len) {
    if(len<=0) return -1;
    int i;
    char *p;
    for(i=0;i<len*8;i++) {
      p = start + i/8;
      if(((*p) & (1<<(i%8)) == 0) return i;
    }
}
</code>```

but the interviewer said you have to loop many times if the last bit is 0, can you improve it?

I really do not know how to.

答:
There's no need to test every single bit in a char that has all bits set, it will compare equal to (unsigned char)-1. With that and also taking into account that a char could have more than 8 bits, the following code should do the job:

```<code>#include <stdio.h>
#include <limits.h>

const char test[] = { 0xff, 0xf0, 0xff, 0xff };

long getpos(const char *buf, size_t len)
{
    size_t i;
    for (i = 0; i < len; ++i)
    {
        if ((unsigned char)buf[i] != (unsigned char)-1) break;
    }
    if (i == len) return -1;

    unsigned char x = buf[i];
    int bit = 0;
    while (x&1)
    {
        x >>= 1;
        ++bit;
    }
    return CHAR_BIT * i + bit;
}

int main(void)
{
    printf("%ld\n", getpos(test, sizeof test));
}
</code>```

Body:
So I had an interview today, the question is:

Given a memory buffer, find a position of unset bit

int getPosition(const char *start, const int len)

If all bits in this memory buffer is 1, return -1

otherwise return an index of the unset bit, started from 0

Performance is first priority

Example

start, len=4
0x00|0x00|0x00|0x00: valid return: 0 to 31
0xFF|0xF0|0xFF|0xFF: valid return: 8,9,10,11
0xFF|0xFF|0xFF|0xFF: valid return: -1

Update Example

it does not have to be the leftmost or rightmost bit, any position as long as the bit is 0 is ok

00000000|00000000 : valid return 0 to 15
10101010|10101010 : valid return 0,2,4,6,8,10,12,14
11110111|11111111 : valid return 11

And my answer was

int getPosition(const char *start, const int len) {
    if(len<=0) return -1;
    int i;
    char *p;
    for(i=0;i<len*8;i++) {
      p = start + i/8;
      if(((*p) & (1<<(i%8)) == 0) return i;
    }
}

but the interviewer said you have to loop many times if the last bit is 0, can you improve it?

I really do not know how to.

Body:
There's no need to test every single bit in a char that has all bits set, it will compare equal to (unsigned char)-1. With that and also taking into account that a char could have more than 8 bits, the following code should do the job:

#include <stdio.h>
#include <limits.h>

const char test[] = { 0xff, 0xf0, 0xff, 0xff };

long getpos(const char *buf, size_t len)
{
    size_t i;
    for (i = 0; i < len; ++i)
    {
        if ((unsigned char)buf[i] != (unsigned char)-1) break;
    }
    if (i == len) return -1;

    unsigned char x = buf[i];
    int bit = 0;
    while (x&1)
    {
        x >>= 1;
        ++bit;
    }
    return CHAR_BIT * i + bit;
}

int main(void)
{
    printf("%ld\n", getpos(test, sizeof test));
}


问:
How to enable/ disable javascript based on environment?
I am trying to put in scripts for google analytics in my code. But I want it to run only if the environment is production and not in dev or qa. This javascript runs at page load itself and I am confused how to make it run conditionally. My app is an asp.net app.

Javascript is always confusing to me. There are many other javascripts in the page and I just need to disable this one. Had it been a .net code/function I would check for the environment and conditionally run the function. But I am confused about how to accomplish this type of functionality with javascript

答:
it depends a lot what it does, and how you have your JS architecture done in your site.

For example, in my site I have this commons.js file that is loaded in every page of the site, as this behavior could be useful in other code, i'll have this global variable called "DEBUG"

For production:

```<code>var DEBUG = false;
</code>```

For development and QA:

```<code>var DEBUG = true;
</code>```

and in you function something like:

```<code>if (!DEBUG) {
   // DO YOUR THING...
</code>```

}

You can also, have this variable (DEBUG) done dynamically depending on some logic in your controller layer.

ContentLicense: CC BY-SA 2.5

Body:
it depends a lot what it does, and how you have your JS architecture done in your site.

For example, in my site I have this commons.js file that is loaded in every page of the site, as this behavior could be useful in other code, i'll have this global variable called "DEBUG"

For production:

var DEBUG = false;

For development and QA:

var DEBUG = true;

and in you function something like:

if (!DEBUG) {
   // DO YOUR THING...

}

You can also, have this variable (DEBUG) done dynamically depending on some logic in your controller layer.


问:
Why does "\u1FFF:foo".StartsWith(":") return true?
The string "\u1FFF:foo" starts with \u1FFF (or "῿"), right?

So how can these both be true?

```<code>"\u1FFF:foo".StartsWith(":")       // equals true
"\u1FFF:foo".StartsWith("\u1FFF")  // equals true

// alternatively, the same:
"῿:foo".StartsWith(":")           // equals true
"῿:foo".StartsWith("῿")          // equals true
</code>```

Does .NET claim that this string starts with two different characters?

And while I find this very surprising and would like to understand the "why", I'm equally interested in how I can force .NET to search exclusively by codepoints instead (using InvariantCulture doesn't seem to do a thing)?

And for comparison, one characters below that, "\u1FFE:foo".StartsWith(":") returns false.

答:
Because you are using String.StartsWith() incorrectly. You should use String.StartsWith (String, StringComparison) overload and StringComparison.Ordinal.

There is no character assigned to \u1FFF. I.e. there is no linguistic meaning attached to this code. See Greek Extended, Range: 1F00–1FFF excerpt from character code tables for Unicode Standard. Best Practices for Using Strings in .NET document from MSDN explicitly states that if you need to compare strings in a manner that ignores features of natural languages then you should use StringComparison.Ordinal:

Specifying the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase value in a method call signifies a non-linguistic comparison in which the features of natural languages are ignored. Methods that are invoked with these StringComparison values base string operation decisions on simple byte comparisons instead of casing or equivalence tables that are parameterized by culture. In most cases, this approach best fits the intended interpretation of strings while making code faster and more reliable.

Moreover, it recommends to always explicitly specify StringComparison in such method calls:

When you develop with .NET, follow these simple recommendations when you use strings:

Use overloads that explicitly specify the string comparison rules for string operations. Typically, this involves calling a method overload that has a parameter of type StringComparison.

Body:
The string "\u1FFF:foo" starts with \u1FFF (or "῿"), right?

So how can these both be true?

"\u1FFF:foo".StartsWith(":")       // equals true
"\u1FFF:foo".StartsWith("\u1FFF")  // equals true

// alternatively, the same:
"῿:foo".StartsWith(":")           // equals true
"῿:foo".StartsWith("῿")          // equals true

Does .NET claim that this string starts with two different characters?

And while I find this very surprising and would like to understand the "why", I'm equally interested in how I can force .NET to search exclusively by codepoints instead (using InvariantCulture doesn't seem to do a thing)?

And for comparison, one characters below that, "\u1FFE:foo".StartsWith(":") returns false.


问:
else if and elif not working for my python code
This is my first day of learning to code. I tried this code and do not know why did it fail. Any help is much appreciated:

```<code>a=int(input())

if a>10:
    print("your number is greater than 10")
    else:
</code>```

I get SyntaxError: invalid syntax

答:
Your indentation is incorrect. It should look like the following:

```<code>a=input()
if a>10:
    print("your number is greater than 10")
else:
    # You didn't have anything in your else statement so either remove it or add a statement...
    print("your number is <= 10")
</code>```

See the python documentation on indentation.

Body:
This is my first day of learning to code. I tried this code and do not know why did it fail. Any help is much appreciated:

a=int(input())

if a>10:
    print("your number is greater than 10")
    else:

I get SyntaxError: invalid syntax

Body:
Your indentation is incorrect. It should look like the following:

a=input()
if a>10:
    print("your number is greater than 10")
else:
    # You didn't have anything in your else statement so either remove it or add a statement...
    print("your number is <= 10")

See the python documentation on indentation.


问:
Kotlin upgrade causes DefaultWhiteList loading issue
Am I correct in observing that Corda 1.0 is using Kotlin plugin 1.1.4? Just out of interest I tried to use 1.1.51 and ran into defaultWhiteList loading issues...although I'm not entirely sure why tbh...suspect classpath loading issues on the ServiceLoader.load in DefaultKryonCustomizer?? Anyway, when I revert to 1.1.1 (am still on M13) all is well again.

Just wanted to gain some understanding around why an inadvertent upgrade of the Kotlin plugin to 1.1.51 would cause issues with the serialisation default whitelist loading?
Thanks

答:
A somewhat non-answer, but I'll try anyway: As we see the kotlin language mature and as Corda uses quite a wide feature set of what's available in kotlin, it doesn't surprise me that sometimes the frequently published newer versions of Kotlin don't work with older versions of Corda - especially if they make some internal changes to objects then I'm not surprised we see kryo serialisation issues.  We publish the recommended / supported version of kotlin in the constants.properties file which, for release 1, is as you've correctly pointed out, 1.1.4 (which can be confirmed here: https://github.com/corda/corda/blob/e564edaa572a011869d692b05518113632363216/constants.properties ).

It does look as if we have updated this for the forthcoming v2 release to 1.1.50 if that helps. It may be a little late in the day to bump this to 1.1.51 though (a fair amount of testing and QA has already been performed).


问:
What is module's "themes" folder used for?
PS documentation says that when developing a module you can create the /themes/[theme_name]/modules subfolder and that it is used for:

"Sub-folder for overriding .tpl files and languages files, if necessary."

and that it:

"enables you to handle the module's template files in various ways, depending on the current theme.",

but i don't really understand its practical usage. What would be a use case of it?

Thanks

答:
When you develop a Prestashop website you should never change core files. This mean that you can only create new modules in the /modules/ folder but not alter existing one. Because if you update a module you altered, all your changes will be gone.

Each time Prestashop needs to load a module template file it will first look in the current theme /themes/your_theme/modules/the_module/path_to_tpl.tpl if an override of this template exists. If not it will load the template from the /modules directory.

This recommandation is also valid for .css and .js files.

The documentation you mentioned in the comment below is wrong and should be updated. You can't put a themes folder inside a module.

Here is the _isTemplateOverloadedStatic() method from Module class called everytime we need a module template:

/*
** Template management (display, overload, cache)
*/
protected static function _isTemplateOverloadedStatic($module_name, $template)
{
    if (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/'.$template)) {
        return _PS_THEME_DIR_.'modules/'.$module_name.'/'.$template;
    } elseif (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/hook/'.$template)) {
        return _PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/hook/'.$template;
    } elseif (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/front/'.$template)) {
        return _PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/front/'.$template;
    } elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/views/templates/hook/'.$template)) {
        return false;
    } elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/views/templates/front/'.$template)) {
        return false;
    } elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/'.$template)) {
        return false;
    }
    return null;
}
```

As you can see in this code, Prestashop will never look into a themes folder inside your module when loading a template.

Body:
When you develop a Prestashop website you should never change core files. This mean that you can only create new modules in the /modules/ folder but not alter existing one. Because if you update a module you altered, all your changes will be gone.

Each time Prestashop needs to load a module template file it will first look in the current theme /themes/your_theme/modules/the_module/path_to_tpl.tpl if an override of this template exists. If not it will load the template from the /modules directory.

This recommandation is also valid for .css and .js files.

The documentation you mentioned in the comment below is wrong and should be updated. You can't put a themes folder inside a module.

Here is the _isTemplateOverloadedStatic() method from Module class called everytime we need a module template:

/*
** Template management (display, overload, cache)
*/
protected static function _isTemplateOverloadedStatic($module_name, $template)
{
    if (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/'.$template)) {
        return _PS_THEME_DIR_.'modules/'.$module_name.'/'.$template;
    } elseif (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/hook/'.$template)) {
        return _PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/hook/'.$template;
    } elseif (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/front/'.$template)) {
        return _PS_THEME_DIR_.'modules/'.$module_name.'/views/templates/front/'.$template;
    } elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/views/templates/hook/'.$template)) {
        return false;
    } elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/views/templates/front/'.$template)) {
        return false;
    } elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/'.$template)) {
        return false;
    }
    return null;
}

As you can see in this code, Prestashop will never look into a themes folder inside your module when loading a template.


问:
Wordpress ajax call not triggering for non website member
I am making ajax call to retrieve posts from functions.php and the following problem is particular to non website members only.It is triggering sometimes only and other times it is not triggering at all.

I am adding actions in functions.php in the following manner

```<code>add_action('wp_ajax_load_posts_by_ajax_snp', 'load_posts_by_ajax_callback_snp');
add_action('wp_ajax_nopriv_load_posts_by_ajax_snp', 'load_posts_by_ajax_callback_snp');
</code>```

the following function is there in functions.php

```<code><?php
function load_posts_by_ajax_callback_snp() {
    check_ajax_referer('load_more_posts_snp', 'security');
    $paged_snp= $_POST['page'];
    $args_snp = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => '16',
        'cat' => '70',
        'paged' => $paged_snp,
        );
    $my_posts_snp = new WP_Query( $args_snp );
    if ( $my_posts_snp->have_posts() ) : ?>
        <?php while ( $my_posts_snp->have_posts() ) : $my_posts_snp->the_post() ?>
            <?php
            echo "<div>";
            Content
            echo "</div>";
            ?>
        <?php endwhile ?>
    <?php endif; ?>
<?php wp_die();
}
?>
</code>```

I Am Using The Following Script To Call Posts On Page page-custom-template.php

```<code><div class="loadmore" style="text-align:center;font-size:1.4em;color:#4a235a;padding:1% 0 1% 0;font-weight:900;">
<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;outline:none;"><span id="lmp">Load More Posts</span><span id="lng" style="display:none;">Loading </span><img id="loader" src="http://www.nvidia.com/docs/IO/151309/loader.gif" width="25em;" height="25em;" id="lmi" style="display:none;"></button>
</div>

<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {

    var data = {
        'action': 'load_posts_by_ajax_snp',
        'page': page,
        'security': '<?php echo wp_create_nonce("load_more_posts_snp"); ?>'
      };

    $.post(ajaxurl, data, function(response) {
        $('.my-posts').append(response);
        page++;
    });
});
});
</script>
</code>```

How do I make it work perfectly for non subscribers and non logged in members ?

答:
First

Why you don't use WP debug? Read this topic.
Or write this code in wp-config.php and check log file in wp-content folder

```<code>// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );
</code>```

Second

```<code><?php
echo "<div>";
Content
echo "</div>";
?>
</code>```

Why you don't close php tag ?>, where you print your Content? For example:

```<code><?php echo "<div>"; ?>
Content
<?php echo "</div>"; ?>
</code>```

Third

Use this code for print ajax_url

```<code>add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){

    wp_localize_script('twentyfifteen-script', 'myajax',
        array(
            'url' => admin_url('admin-ajax.php')
        )
    );

}
</code>```

And you need to replace in js code

```<code>var ajaxurl = url;
</code>```

Body:
I am making ajax call to retrieve posts from functions.php and the following problem is particular to non website members only.It is triggering sometimes only and other times it is not triggering at all.

I am adding actions in functions.php in the following manner

add_action('wp_ajax_load_posts_by_ajax_snp', 'load_posts_by_ajax_callback_snp');
add_action('wp_ajax_nopriv_load_posts_by_ajax_snp', 'load_posts_by_ajax_callback_snp');

the following function is there in functions.php

<?php
function load_posts_by_ajax_callback_snp() {
    check_ajax_referer('load_more_posts_snp', 'security');
    $paged_snp= $_POST['page'];
    $args_snp = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => '16',
        'cat' => '70',
        'paged' => $paged_snp,
        );
    $my_posts_snp = new WP_Query( $args_snp );
    if ( $my_posts_snp->have_posts() ) : ?>
        <?php while ( $my_posts_snp->have_posts() ) : $my_posts_snp->the_post() ?>
            <?php
            echo "
";
            Content
            echo "
";
            ?>
        <?php endwhile ?>
    <?php endif; ?>
<?php wp_die();
}
?>

I Am Using The Following Script To Call Posts On Page page-custom-template.php

<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;outline:none;">Load More PostsLoading </button>

How do I make it work perfectly for non subscribers and non logged in members ?

Body:
First

Why you don't use WP debug? Read this topic.
Or write this code in wp-config.php and check log file in wp-content folder

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );

Second

<?php
echo "<div>";
Content
echo "</div>";
?>

Why you don't close php tag ?>, where you print your Content? For example:

<?php echo "<div>"; ?>
Content
<?php echo "</div>"; ?>

Third

Use this code for print ajax_url

add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){

    wp_localize_script('twentyfifteen-script', 'myajax',
        array(
            'url' => admin_url('admin-ajax.php')
        )
    );

}

And you need to replace in js code

var ajaxurl = url;


问:
Ionic 2 doesn't recognize es6 code on index.html and service worker
I updated Ionic 2, codova and the app-scripts to the latest versions and when I un-commented the service worker block in index.html file, I get this

error: "Uncaught SyntaxError: Unexpected token )" on line 27 in
  index.html file

and right after it, this

error: "Uncaught TypeError: Cannot read property 'insertBefore' of
  null".

It seems to me that maybe index.html and serice-worker.js aren't transpiled (when I used es5 code in index.html file, there wasn't an error in index.html file, but there was in service-worker.js file).

答:
You must be getting this error due to arrow functions, if that is the case you can solve it by changing the service worker code in index.html with this</p>

```<code>if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('service-worker.js')
            .then(function ()  { console.log('service worker installed');})
            .catch(function(err) { console.error('Error', err);});
}
</code>```

Body:
You must be getting this error due to arrow functions, if that is the case you can solve it by changing the service worker code in index.html with this

if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('service-worker.js')
            .then(function ()  { console.log('service worker installed');})
            .catch(function(err) { console.error('Error', err);});
}


问:
iOS with Swift: App crashes on UITableView scroll down event
I am writing an iOS app in Swift that puts data from an API into a TableView. The goal is that the user can scroll down a continuous list of blog posts. What is happening is that data is filling the first screen's amount of cells fine, but when the user scrolls down, the app crashes as one of the cell properties, cellImageView becomes nil and is unwrapped (as force unwrap is specified in the cell class's code):

```<code>class BlogPostEntryCell: UITableViewCell {
    //MARK: Properites
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var bodyTextView: UITextView!
    @IBOutlet weak var initialsImageView: UIImageView!
}
</code>```

Here is the code that causes the crash:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCell

    apiCaller.getAPIDataThroughAsyncCall(id: nextCell, entry: { cellContent in
        DispatchQueue.main.async(execute: {
            cell.cellLabel.text = cellContent.labelText
            cell.cellTextView.text = cellContent.textViewText
            // App crashes at the below line
            cell.initialsImageView = self.createPicture(initials: cellContent.pictureText)
        })
    })

    nextCell += 1

    return cell
}
</code>```

The interesting thing is that if do this:

```<code>    cell.cellLabel?.text = cellContent.labelText
    cell.cellTextView?.text = cellContent.textViewText
    // App does NOT crash at the below line
    cell.initialsImageView? = self.createPicture(initials: cellContent.pictureText)
</code>```

, the app doesn't crash but the data just repeats over and over again as the user scrolls.

I've tried the solution to a similar problem here: Why does data returned from coredata become nil after tableview scroll in swift?, but that did not work. However, I do believe this has to do with the asynchronous API calls.

I am thinking that possible solutions may include population an array of API data before generating the cells, but I would like some insight on the source of this problem before a rethink the architecture of the code.

答: It is bad practice to call any API in cellForRowAt indexPath: IndexPath, it produces crashes as you see, have a look at MVVM. It is like wining a war without having to go to battle and I refer to this instance where you call API in cellForRowAt indexPath: IndexPath and the outlets are not initialised.</p>

Body:
I am writing an iOS app in Swift that puts data from an API into a TableView. The goal is that the user can scroll down a continuous list of blog posts. What is happening is that data is filling the first screen's amount of cells fine, but when the user scrolls down, the app crashes as one of the cell properties, cellImageView becomes nil and is unwrapped (as force unwrap is specified in the cell class's code):

class BlogPostEntryCell: UITableViewCell {
    //MARK: Properites
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var bodyTextView: UITextView!
    @IBOutlet weak var initialsImageView: UIImageView!
}

Here is the code that causes the crash:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCell

    apiCaller.getAPIDataThroughAsyncCall(id: nextCell, entry: { cellContent in
        DispatchQueue.main.async(execute: {
            cell.cellLabel.text = cellContent.labelText
            cell.cellTextView.text = cellContent.textViewText
            // App crashes at the below line
            cell.initialsImageView = self.createPicture(initials: cellContent.pictureText)
        })
    })

    nextCell += 1

    return cell
}

The interesting thing is that if do this:

    cell.cellLabel?.text = cellContent.labelText
    cell.cellTextView?.text = cellContent.textViewText
    // App does NOT crash at the below line
    cell.initialsImageView? = self.createPicture(initials: cellContent.pictureText)

, the app doesn't crash but the data just repeats over and over again as the user scrolls.

I've tried the solution to a similar problem here: Why does data returned from coredata become nil after tableview scroll in swift?, but that did not work. However, I do believe this has to do with the asynchronous API calls.

I am thinking that possible solutions may include population an array of API data before generating the cells, but I would like some insight on the source of this problem before a rethink the architecture of the code.


答: Put your GA code in a control. Put that control on your Master Page. Sniff the IP of the server. If it's not production, "hide" the control on that page. .NET can do it all by itself. No need for "confusing" javascript.</p>

Title: How to enable/ disable javascript based on environment?

Body:
I am trying to put in scripts for google analytics in my code. But I want it to run only if the environment is production and not in dev or qa. This javascript runs at page load itself and I am confused how to make it run conditionally. My app is an asp.net app.

Javascript is always confusing to me. There are many other javascripts in the page and I just need to disable this one. Had it been a .net code/function I would check for the environment and conditionally run the function. But I am confused about how to accomplish this type of functionality with javascript


问:
Mac: SSH doesn't work anymore without changing something
After searching the web for one day without a good solution I'm here to tell you my problem.

Three days ago I set up a SSH-key to use git with SSH. Everything worked fine and I was able to push and pull everything to GitHub. Since yesterday I'm not able to do it anymore. I always get the same error (shown below). SSH-key is part of the ssh-agent, config-files weren't changed and even a normal connection through SSH to GitHub is not possible. Tried it with other projects and other repos as well and got the same error. I didn't update Sierra or something else in the last days, so this can't be the reason as well.

Terminal in- and output:

```<code>User-MBP:data-analysis user$ git push -v origin master
Pushing to git@github.com:Username/data-analysis.git
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Normal SSH-connection:

```<code>User-MBP:data-analysis user$ ssh -v git@github.com
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /Users/user/.ssh/config
debug1: /Users/user/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to github.com [192.30.253.113] port 443.
debug1: Connection established.
debug1: identity file /Users/user/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/user/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
ssh_exchange_identification: Connection closed by remote host
</code>```

Thank you for your help!

UPDATE

Changed port back to 22 to get the following:

```<code>User-MBP:data-analysis user$ git push origin master
ssh: connect to host github.com port 22: Connection refused
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

and

```<code>User-MBP:data-analysis user$ ssh -v git@github.com
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /Users/user/.ssh/config
debug1: /Users/user/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to github.com [192.30.253.113] port 22.
debug1: connect to address 192.30.253.113 port 22: Connection refused
debug1: Connecting to github.com [192.30.253.112] port 22.
debug1: connect to address 192.30.253.112 port 22: Connection refused
ssh: connect to host github.com port 22: Connection refused
</code>```

答:
For all searching for a solution:
I did the following several times and then it worked:

```<code>User-MacBook-Pro:~ user$ ssh git@github.com
The authenticity of host 'github.com (192.30.253.112)' can't be established.
RSA key fingerprint is  <fingerprint>.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.253.112' (RSA) to the list of known hosts.
PTY allocation request failed on channel 0
Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.
</code>```

Now git and ssh work again. Don't know why this solution didn't work before.

Anyway thanks for all responses.

Body:
After searching the web for one day without a good solution I'm here to tell you my problem.

Three days ago I set up a SSH-key to use git with SSH. Everything worked fine and I was able to push and pull everything to GitHub. Since yesterday I'm not able to do it anymore. I always get the same error (shown below). SSH-key is part of the ssh-agent, config-files weren't changed and even a normal connection through SSH to GitHub is not possible. Tried it with other projects and other repos as well and got the same error. I didn't update Sierra or something else in the last days, so this can't be the reason as well.

Terminal in- and output:

User-MBP:data-analysis user$ git push -v origin master
Pushing to git@github.com:Username/data-analysis.git
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Normal SSH-connection:

User-MBP:data-analysis user$ ssh -v git@github.com
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /Users/user/.ssh/config
debug1: /Users/user/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to github.com [192.30.253.113] port 443.
debug1: Connection established.
debug1: identity file /Users/user/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/user/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
ssh_exchange_identification: Connection closed by remote host

Thank you for your help!

UPDATE

Changed port back to 22 to get the following:

User-MBP:data-analysis user$ git push origin master
ssh: connect to host github.com port 22: Connection refused
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

and

User-MBP:data-analysis user$ ssh -v git@github.com
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /Users/user/.ssh/config
debug1: /Users/user/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to github.com [192.30.253.113] port 22.
debug1: connect to address 192.30.253.113 port 22: Connection refused
debug1: Connecting to github.com [192.30.253.112] port 22.
debug1: connect to address 192.30.253.112 port 22: Connection refused
ssh: connect to host github.com port 22: Connection refused

Body:
For all searching for a solution:
I did the following several times and then it worked:

User-MacBook-Pro:~ user$ ssh git@github.com
The authenticity of host 'github.com (192.30.253.112)' can't be established.
RSA key fingerprint is  <fingerprint>.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.253.112' (RSA) to the list of known hosts.
PTY allocation request failed on channel 0
Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.

Now git and ssh work again. Don't know why this solution didn't work before.

Anyway thanks for all responses.


问:
How to share data between two web pages?
Im trying working on a web app project and trying to figure out how to display my answer on the second web page.

I have put a a text box on my first webpage and have corrected the coding of my application as I have received the correct answers in the textbox after I have debugged it.

Ideally I want to remove this textbox and want my answers which I managed to display on my textbox displayed on a label in the next webpage. Here is the calculation part of my code;

```<code>var cost = ((int)duration.TotalMinutes) * 0.35m;
                txtCost.Text = cost.ToString("c");
</code>```

I'd like to make my answer appear in my second webpage and not have it displayed in the first. I have tried using Session["Cost"] = cost; on the button click event handler of the first webpage double cost = (double)(Session["Cost"]);
                lblDisplay.Text = cost.ToString("c");
and this on the second webpage but every time I Debug it and run I always get $0.00 displayed on my label. Can someone help me fix this?

答:
Sharing value between two views in MVC application, try following

```<code>// To save into the Cache
System.Web.HttpContext.Current.Cache["CostKey"] = cost;

// To retrieve Cache Value
var cachedValue = System.Web.HttpContext.Current.Cache["CostKey"] as double;
</code>```

For Session State, have a look at this link

Body:
Im trying working on a web app project and trying to figure out how to display my answer on the second web page.

I have put a a text box on my first webpage and have corrected the coding of my application as I have received the correct answers in the textbox after I have debugged it.

Ideally I want to remove this textbox and want my answers which I managed to display on my textbox displayed on a label in the next webpage. Here is the calculation part of my code;

var cost = ((int)duration.TotalMinutes) * 0.35m;
                txtCost.Text = cost.ToString("c");

I'd like to make my answer appear in my second webpage and not have it displayed in the first. I have tried using Session["Cost"] = cost; on the button click event handler of the first webpage double cost = (double)(Session["Cost"]);
                lblDisplay.Text = cost.ToString("c");
and this on the second webpage but every time I Debug it and run I always get $0.00 displayed on my label. Can someone help me fix this?

Body:
Sharing value between two views in MVC application, try following

// To save into the Cache
System.Web.HttpContext.Current.Cache["CostKey"] = cost;

// To retrieve Cache Value
var cachedValue = System.Web.HttpContext.Current.Cache["CostKey"] as double;

For Session State, have a look at this link


问:
Xamarin IF statement to match image button and it's background
I am currently following up on this problem here: Setting Image Button via it's id into a 8x8 2d array. Android. Xamarin.

I have successfully set the 64 image button's id into an 8x8 array. In my image button, there are some buttons with an image on the button with the following code:

```<code>        android:src="@android:drawable/ic_menu_gallery"
        android:background="@drawable/white"
</code>```

There are other image buttons that are blank with no image. My question is: Of all my 64 image button, I would like to count how many buttons that has a background image white, based on the code I have above.

Currently I have the following code:

```<code>        for (int i = 0; i < 8; i++) //Rows of the array "buttons"
        {
            for (int j = 0; j < 8; j++) //Column of the array "buttons"
            {
                if(buttons[i, j] ==  ....???) //Check if the id of the image button has a white drawable image.
            }
        }
</code>```

What should I input to finish up the code?

答:
In C#.NET I try to put these kind of information in Tags. To use Tags in Android you have to create a String resource in values/Strings.xml. This is used to make sure, that the tag is unique.

```<code><?xml version="1.0" encoding="utf-8"?>
  <resources>
    <string name="ColorOfButton">color</string>
  </resources>
</code>```

When you initialize the buttons you can create a tag like so:

```<code>buttons[i, j].SetTag(Resource.String.ColorOfButton, "white");
//sets it to white
</code>```

Or in XML:

```<code><Button
    android:id="@+id/testBtn">
    <tag android:id="@string/ColorOfButton" android:value="white" />
</Button>
<Button
    android:id="@+id/testBtn2">
    <tag android:id="@string/ColorOfButton" android:value="black" />
</Button>
</code>```

Then you can get the tag and look if it is white, black or empty:

```<code>switch(buttons[i, j].GetTag(Resource.String.ColorOfButton).ToString())
{
  case "white":
    //Your picture is white
  break;
  case "black":
    //Your picture is black
  break;
  case "empty":
    //Your picture is empty
  break;
}
</code>```

You can put the following strings in your tag:

white - for white piece

black - for black piece

empty - for no piece

Body:
I am currently following up on this problem here: Setting Image Button via it's id into a 8x8 2d array. Android. Xamarin.

I have successfully set the 64 image button's id into an 8x8 array. In my image button, there are some buttons with an image on the button with the following code:

        android:src="@android:drawable/ic_menu_gallery"
        android:background="@drawable/white"

There are other image buttons that are blank with no image. My question is: Of all my 64 image button, I would like to count how many buttons that has a background image white, based on the code I have above.

Currently I have the following code:

        for (int i = 0; i < 8; i++) //Rows of the array "buttons"
        {
            for (int j = 0; j < 8; j++) //Column of the array "buttons"
            {
                if(buttons[i, j] ==  ....???) //Check if the id of the image button has a white drawable image.
            }
        }

What should I input to finish up the code?

Body:
In C#.NET I try to put these kind of information in Tags. To use Tags in Android you have to create a String resource in values/Strings.xml. This is used to make sure, that the tag is unique.

<?xml version="1.0" encoding="utf-8"?>
  <resources>
    <string name="ColorOfButton">color</string>
  </resources>

When you initialize the buttons you can create a tag like so:

buttons[i, j].SetTag(Resource.String.ColorOfButton, "white");
//sets it to white

Or in XML:

<Button
    android:id="@+id/testBtn">
    <tag android:id="@string/ColorOfButton" android:value="white" />
</Button>
<Button
    android:id="@+id/testBtn2">
    <tag android:id="@string/ColorOfButton" android:value="black" />
</Button>

Then you can get the tag and look if it is white, black or empty:

switch(buttons[i, j].GetTag(Resource.String.ColorOfButton).ToString())
{
  case "white":
    //Your picture is white
  break;
  case "black":
    //Your picture is black
  break;
  case "empty":
    //Your picture is empty
  break;
}

You can put the following strings in your tag:

white - for white piece

black - for black piece

empty - for no piece


问:
Get last but one value using SQL function FIRST_VALUE
Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE? Here is a way to get the last value.

```<code>select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl
</code>```

Is it possible to modify it to get second last value?

Update. I am familiar with different ways of getting the last but one value mentioned i.e. here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.

答:
```<code>SELECT
  *
FROM
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY [Category]
                           ORDER BY [MyValue] DESC)   AS ordinal
  FROM
    tbl
)
  ordered_tbl
WHERE
  ordinal = 2
</code>```

Body:
Is it possible to get last but one value of sorted variable using SQL function FIRST_VALUE? Here is a way to get the last value.

select
[MyVal_Last] = FIRST_VALUE([MyValue]) OVER (PARTITION BY [Category] ORDER BY [MyValue] DESC)
from tbl

Is it possible to modify it to get second last value?

Update. I am familiar with different ways of getting the last but one value mentioned i.e. here Those answers are old and have grown long beards. I wonder if new version of SQL Server can do it in a more elegant way, using new functions.


问:
Remove duplicates in array separated by double commas in JavaScript
I have an array in JavaScript like this

```<code>var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
</code>```

when I alert in JavaScript it gives as below

,A_1_VII,VII,V2

,A_1_VII,VII,V2

,A_1_VII,VII,V2

,B_1_XIV,XIV,V3

,B_2_XVI,XVI,V3

But I want like this which is duplicates removed array

```<code>var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
</code>```

On alert it should give like this

,A_1_VII,VII,V2

,B_1_XIV,XIV,V3

,B_2_XVI,XVI,V3

答:
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:

```<code>var data [/* ... */];
var unique_data = [];

for(let i = 0; i < data.length; i++) {
    if (data[i] && unique_data.indexOf(data[i]) === -1) {
        unique_data.push(data[i]);
    }
}
</code>```

Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().

Body:
I have an array in JavaScript like this

var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]

when I alert in JavaScript it gives as below

,A_1_VII,VII,V2

,A_1_VII,VII,V2

,A_1_VII,VII,V2

,B_1_XIV,XIV,V3

,B_2_XVI,XVI,V3

But I want like this which is duplicates removed array

var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]

On alert it should give like this

,A_1_VII,VII,V2

,B_1_XIV,XIV,V3

,B_2_XVI,XVI,V3

Body:
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:

var data [/* ... */];
var unique_data = [];

for(let i = 0; i < data.length; i++) {
    if (data[i] && unique_data.indexOf(data[i]) === -1) {
        unique_data.push(data[i]);
    }
}

Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().


问:
Matlab- split cell array column by delimiter
I have many 33213168x1 cell arrays, where each cell contains an 85 x 1 column.

Each cell in the column is in the form

```<code>[0.55;0.25;0.75]

[0.33;0.66;0.99]
</code>```

I want to split up this single column by the semi-colon delimiter so that each cell in the cell array is 85x3, like:

```<code>[0.55][0.25][0.75]

[0.33][0.66][0.99]
</code>```

I've tried numerous techniques to solve this, but most commonly get the errors 'cell elements must be character arrays' or 'input must be a string.'

Some of the approaches I've tried:

```<code>splitcells = strsplit(regress_original_053108,';');
splitcells = cellfun(@(x) strsplit(regress_original_053108, ';'),regress_original_053108 , 'UniformOutput',0);
splitcells = regexp(regress_original_053108, ';', 'split');
splitcells = textscan(regress_original_053108, 'delimiter', ';');
</code>```

Etc. Any feedback about how to do this would be appreciated.

答:
Hope this solves your problem:</p>

```<code>% Example input
input = {[0.55;0.25;0.75]};
cellArray(1:85,1) = input;

% Create array
doubleArray = zeros(85,3);

% Fill array
for i=1:85
   doubleArray(i,:) =  cellArray{i,1}';
end
</code>```

Body:
I have many 33213168x1 cell arrays, where each cell contains an 85 x 1 column.

Each cell in the column is in the form

[0.55;0.25;0.75]

[0.33;0.66;0.99]

I want to split up this single column by the semi-colon delimiter so that each cell in the cell array is 85x3, like:

[0.55][0.25][0.75]

[0.33][0.66][0.99]

I've tried numerous techniques to solve this, but most commonly get the errors 'cell elements must be character arrays' or 'input must be a string.'

Some of the approaches I've tried:

splitcells = strsplit(regress_original_053108,';');
splitcells = cellfun(@(x) strsplit(regress_original_053108, ';'),regress_original_053108 , 'UniformOutput',0);
splitcells = regexp(regress_original_053108, ';', 'split');
splitcells = textscan(regress_original_053108, 'delimiter', ';');

Etc. Any feedback about how to do this would be appreciated.

Body:
Hope this solves your problem:

% Example input
input = {[0.55;0.25;0.75]};
cellArray(1:85,1) = input;

% Create array
doubleArray = zeros(85,3);

% Fill array
for i=1:85
   doubleArray(i,:) =  cellArray{i,1}';
end


问:
How does Maven come to know which is a test class and which is not

I have worked with junits but never gave a thought on how maven comes to know that the class defined src/test/java is a test class and not a normal class.

One possibility is it may scan for @Test in the class. Is this how it is achived? If not how?.

What exactly are Runners and what is their role.
Can I have test cases without Runners?

答:
The @Test is an annotation and allows frameworks like junit and maven to identify which tests should be run.

They also allow other things to be specified (for example, an expected exception).

http://junit.org/junit4/javadoc/4.12/org/junit/Test.html

Test runners are more complicated and allow you to have more control over how the tests are executed, for example if you are using frameworks. But for "plain vanilla" testing you shouldnt need them.

https://www.mscharhag.com/java/understanding-junits-runner-architecture


问:
Why enums require an explicit cast to int type?
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

```<code>PerformOperation ( OperationType.Silent type )
</code>```

where PerformOperation calls a wrapped C++ method that's exposed as such:

```<code>_unmanaged_perform_operation ( int operation_type )
</code>```

答:
Would it not be more intuitive if it was implicit, say when you have a higher level method like:

I actually think not.  In this case, you're trying to use an Enum in an edge case.

However, if enums were implicitly converted to integer values, this would dramatically reduce their effectiveness.  By forcing an int conversion explicitly, the compiler is treating enum as a special type - one of many options, not as an integer.  This more clearly demonstrates the intent of the enum, and reduces the chance of programmer mistakes (ie: assigning values that aren't defined in the enum to an enum variable, etc).

I personally am glad that enum in C# is more than (effectively) a constant int value.

Body:
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

PerformOperation ( OperationType.Silent type )

where PerformOperation calls a wrapped C++ method that's exposed as such:

_unmanaged_perform_operation ( int operation_type )


答:
```<code>if a>10:
    print("your number is greater than 10") #indent the print statement
else:
    print('Not greater than 10')
    #you need to perform an action inside the else condition
</code>```

Title: else if and elif not working for my python code

Body:
This is my first day of learning to code. I tried this code and do not know why did it fail. Any help is much appreciated:

a=int(input())

if a>10:
    print("your number is greater than 10")
    else:

I get SyntaxError: invalid syntax


问:
SQL Query result with contains values from an array
I search a MySQL solution to collect queries, which contains some ints (ids in an array).

```<code>Example-Table:

id1 id2 id3
1   2   2
2   3   2
3   3   5
4   4   2
5   4   5
6   4   7
</code>```

I have an array like

```<code>$id3array = (2,5);
</code>```

I need id2 = 3 (not 4, because id2 "4" has one more id3 argument (7)

If I have an array like

```<code>$id3array = (2,5,6); // array can contains 20 and more arguments
</code>```

In this example Table I need id2 = 0 (because no match)

My Tests with IN(2,5) or Group by was not successful - Is this possible to solve with MySQL?

http://www.sqlfiddle.com/#!9/b71306/2

答:
Try following query. Put inner query which will match records which is not in desired array. Then group and count exact element

```<code>SELECT `id2` FROM `exampletable` WHERE `id3` IN (2,5) AND `id2` NOT IN (
  SELECT e.id2 from exampletable e WHERE e.id3 not in (2,5))  GROUP BY `id2`
HAVING count(`id2`) = 2;
</code>```

Here I have added count(id2) = 2 because you have 2 elements in array

DEMO

Body:
I search a MySQL solution to collect queries, which contains some ints (ids in an array).

Example-Table:

id1 id2 id3
1   2   2
2   3   2
3   3   5
4   4   2
5   4   5
6   4   7

I have an array like

$id3array = (2,5);

I need id2 = 3 (not 4, because id2 "4" has one more id3 argument (7)

If I have an array like

$id3array = (2,5,6); // array can contains 20 and more arguments

In this example Table I need id2 = 0 (because no match)

My Tests with IN(2,5) or Group by was not successful - Is this possible to solve with MySQL?

http://www.sqlfiddle.com/#!9/b71306/2

Body:
Try following query. Put inner query which will match records which is not in desired array. Then group and count exact element

SELECT `id2` FROM `exampletable` WHERE `id3` IN (2,5) AND `id2` NOT IN (
  SELECT e.id2 from exampletable e WHERE e.id3 not in (2,5))  GROUP BY `id2`
HAVING count(`id2`) = 2;

Here I have added count(id2) = 2 because you have 2 elements in array

DEMO


问:
React NPM package(Dragula) works in development but not in production
I've built a nice drag'n Drop with React 15 and Dragula 3.7.2 but when i bundle my Application for Production the whole dnd thing doesn't work except i'm able to lift up a single Element but can't find a container to drop it in.

I'm assigning my containers with a reference to my drake instance which i currently create in componentDidMount.

I've assigned multiple EventListener to the drake instance, but the only one which is firing is the 'drag'-eventListener. I console.logged the drake instance in there and saw all my relevant containers correctly assigned

I've also thought that there could be a minification failure with the dragula bundle and so i used the version from the cdn

class ProcessGridDrag extends React.Component {
  constructor() {
    super();
    this.dragContext = null;
    this.dragContainers = [];
  }

  componentDidMount() {
    // eslint-disable-next-line no-undef
    this.drake = dragula(this.dragContainers, options);
    console.log('didMount');
    console.log(this.drake.containers);
    this.drake.on('drop', this.onDropTile);
    this.drake.on('out', this.onOutContainer);
    this.drake.on('over', console.log);
    this.drake.on('drag', () => {
      debugger;
      console.log(this.drake);
    });
    this.drake.on('shadow', console.log);
    // Override for touchmove for correct behaviour on iPad
    window.addEventListener('touchmove', () => {});
  }

  componentWillUnmount() {
    this.dragContainers = [];
    console.log('will Unmount');
    this.drake.containers = [];
    this.drake.off('drop', this.onDropTile);
    this.drake.off('out', this.onOutContainer);
    this.dragContext = null;
    this.drake.destroy();
  }

  // This one is passed down to components which should act as a drag container
  dragulaDecorator = componentBackingInstance => {
    if (
      componentBackingInstance &&
      this.dragContainers.indexOf(componentBackingInstance) === -1
    ) {
      this.dragContainers.push(componentBackingInstance);
    }
  };```

webpack.config.prod: https://pastebin.com/BLu2hmmv
webpack.config.dev: https://pastebin.com/3wczNisj

答:
I had a Problem with my css. I've overwritten the top-value of the dragged element.

Because of a different LoadOrder in Production this problem only occured there

Body:
I've built a nice drag'n Drop with React 15 and Dragula 3.7.2 but when i bundle my Application for Production the whole dnd thing doesn't work except i'm able to lift up a single Element but can't find a container to drop it in.

I'm assigning my containers with a reference to my drake instance which i currently create in componentDidMount.

I've assigned multiple EventListener to the drake instance, but the only one which is firing is the 'drag'-eventListener. I console.logged the drake instance in there and saw all my relevant containers correctly assigned

I've also thought that there could be a minification failure with the dragula bundle and so i used the version from the cdn

class ProcessGridDrag extends React.Component {
  constructor() {
    super();
    this.dragContext = null;
    this.dragContainers = [];
  }

  componentDidMount() {
    // eslint-disable-next-line no-undef
    this.drake = dragula(this.dragContainers, options);
    console.log('didMount');
    console.log(this.drake.containers);
    this.drake.on('drop', this.onDropTile);
    this.drake.on('out', this.onOutContainer);
    this.drake.on('over', console.log);
    this.drake.on('drag', () => {
      debugger;
      console.log(this.drake);
    });
    this.drake.on('shadow', console.log);
    // Override for touchmove for correct behaviour on iPad
    window.addEventListener('touchmove', () => {});
  }

  componentWillUnmount() {
    this.dragContainers = [];
    console.log('will Unmount');
    this.drake.containers = [];
    this.drake.off('drop', this.onDropTile);
    this.drake.off('out', this.onOutContainer);
    this.dragContext = null;
    this.drake.destroy();
  }

  // This one is passed down to components which should act as a drag container
  dragulaDecorator = componentBackingInstance => {
    if (
      componentBackingInstance &&
      this.dragContainers.indexOf(componentBackingInstance) === -1
    ) {
      this.dragContainers.push(componentBackingInstance);
    }
  };

webpack.config.prod: https://pastebin.com/BLu2hmmv
webpack.config.dev: https://pastebin.com/3wczNisj


答:
There are two primary and inconsistent uses of enums:

```<code>enum Medals
{ Gold, Silver, Bronze }

[Flags]
enum FilePermissionFlags
{
    CanRead = 0x01,
    CanWrite = 0x02,
    CanDelete = 0x04
}
</code>```

In the first case, it makes no sense to treat these things as numbers. The fact that they are stored as integers is an implementation detail. You can't logically add, subtract, multiply or divide Gold, Silver and Bronze.

In the second case, it also makes no sense to treat these things as numbers. You can't add, subtract, multiply or divide them. The only sensible operations are bitwise operations.

Enums are lousy numbers, so you should not be able to treat them as numbers accidentally.

Title: Why enums require an explicit cast to int type?

Body:
There are two primary and inconsistent uses of enums:

enum Medals
{ Gold, Silver, Bronze }

[Flags]
enum FilePermissionFlags
{
    CanRead = 0x01,
    CanWrite = 0x02,
    CanDelete = 0x04
}

In the first case, it makes no sense to treat these things as numbers. The fact that they are stored as integers is an implementation detail. You can't logically add, subtract, multiply or divide Gold, Silver and Bronze.

In the second case, it also makes no sense to treat these things as numbers. You can't add, subtract, multiply or divide them. The only sensible operations are bitwise operations.

Enums are lousy numbers, so you should not be able to treat them as numbers accidentally.


问:
UDF with Intersect runs slow
So I am creating a function to replace some manual index/match formulas. Note that this function works, but my problem is with speed. So I have a PivotTable with 6 columns and approx. 200.000 rows. I want this to find the value (and I don't use the pivotfunctions, meaning that this is just a table in pivot format) I found that this runs faster than having it in a regular data table. Both would be imported from a SQL table.

A single piece of this formula runs instantly, but the performance slows down when I have a few hundreds in the same sheet.

So any ideas on how to speed this up?

```<code>Function getnum2(ByVal Comp As String, Period As String, Measure As String, Optional BU As String, _
    Optional Country As String, Optional Table As String, Optional TableSheet As String) As Double

Dim pTable As PivotTable, wTableSheet As Worksheet

If BU = "" Then
    BU = "Group"
End If
If Country = "" Then
    Country = "Total"
End If
If TableSheet = "" Then
    Set wTableSheet = Worksheets("Data")
Else
    Set wTableSheet = Worksheets(TableSheet)
End If
If Table = "" Then
    Set pTable = wTableSheet.PivotTables("PivotTable1")
Else
    Set pTable = wTableSheet.PivotTables(Table)
End If

'Find match
If Intersect(pTable.PivotFields("Bank").PivotItems(Comp).DataRange.EntireRow, _
    pTable.PivotFields("Date").PivotItems(Period).DataRange.EntireRow, _
    pTable.PivotFields("Business Unit").PivotItems(BU).DataRange.EntireRow, _
    pTable.PivotFields("Country").PivotItems(Country).DataRange.EntireRow, _
    pTable.PivotFields("Name").PivotItems(Measure).DataRange) Is Nothing Then
        getnum2 = "No match"
ElseIf Intersect(pTable.PivotFields("Bank").PivotItems(Comp).DataRange.EntireRow, _
    pTable.PivotFields("Date").PivotItems(Period).DataRange.EntireRow, _
    pTable.PivotFields("Business Unit").PivotItems(BU).DataRange.EntireRow, _
    pTable.PivotFields("Country").PivotItems(Country).DataRange.EntireRow, _
    pTable.PivotFields("Name").PivotItems(Measure).DataRange).Count > 1 Then
        getnum2 = "More than 1 match"
Else
    getnum2 = Intersect(pTable.PivotFields("Bank").PivotItems(Comp).DataRange.EntireRow, _
    pTable.PivotFields("Date").PivotItems(Period).DataRange.EntireRow, _
    pTable.PivotFields("Business Unit").PivotItems(BU).DataRange.EntireRow, _
    pTable.PivotFields("Country").PivotItems(Country).DataRange.EntireRow, _
    pTable.PivotFields("Name").PivotItems(Measure).DataRange)
End If

End Function
</code>```

答:
Here's the fastest way to do this: using Binary Match on a sorted lookup table.
On the left I have 5 columns x 1048575 rows of random numbers between 1 and 10. These have been concatenated in column G to make a non-unique key, and then sorted ascending on that key.

(Because the concatenated key is text, it gets sorted alphabetical from left to right, which is why 1|1|1|1|10 appears between 1|1|1|1|1 and 1|1|1|1|2)

I gave the data in Column G the named range of Concat to simplify the formula. My lookup formula in J2 returns the row number of the lookup item if and only if that item is unique to the dataset. The formula is:

```<code>=IF(OR( AND(INDEX(Concat,MATCH(I2,Concat,1))=I2, MATCH(I2,Concat,1)=1),  AND(INDEX(Concat,MATCH(I2,Concat,1))=I2,INDEX(Concat,MATCH(I2,Concat,1)-1)<>I2)),MATCH(I2,Concat,1),NA())
</code>```

This executes in 0.01 milliseconds for one instance, for a lookup table of 1048576 rows. My double GETPIVOTDATA approach above took 6 milliseconds. So there you have it: a complex formula that gives a 600 times efficiency boost.

I can explain the formula later in need, but note that some of the complexity is due to the edge case where you may have a unique item appearing in row 1. If I leave out that edge case, then the formula is as follows:

```<code>=IF( AND(INDEX(Concat,MATCH(I3,Concat,1))=I3,INDEX(Concat,MATCH(I3,Concat,1)-1)<>I3),MATCH(I3,Concat,1),NA())
</code>```

Title: UDF with Intersect runs slow

Body:
So I am creating a function to replace some manual index/match formulas. Note that this function works, but my problem is with speed. So I have a PivotTable with 6 columns and approx. 200.000 rows. I want this to find the value (and I don't use the pivotfunctions, meaning that this is just a table in pivot format) I found that this runs faster than having it in a regular data table. Both would be imported from a SQL table.

A single piece of this formula runs instantly, but the performance slows down when I have a few hundreds in the same sheet.

So any ideas on how to speed this up?

Function getnum2(ByVal Comp As String, Period As String, Measure As String, Optional BU As String, _
    Optional Country As String, Optional Table As String, Optional TableSheet As String) As Double

Dim pTable As PivotTable, wTableSheet As Worksheet

If BU = "" Then
    BU = "Group"
End If
If Country = "" Then
    Country = "Total"
End If
If TableSheet = "" Then
    Set wTableSheet = Worksheets("Data")
Else
    Set wTableSheet = Worksheets(TableSheet)
End If
If Table = "" Then
    Set pTable = wTableSheet.PivotTables("PivotTable1")
Else
    Set pTable = wTableSheet.PivotTables(Table)
End If

'Find match
If Intersect(pTable.PivotFields("Bank").PivotItems(Comp).DataRange.EntireRow, _
    pTable.PivotFields("Date").PivotItems(Period).DataRange.EntireRow, _
    pTable.PivotFields("Business Unit").PivotItems(BU).DataRange.EntireRow, _
    pTable.PivotFields("Country").PivotItems(Country).DataRange.EntireRow, _
    pTable.PivotFields("Name").PivotItems(Measure).DataRange) Is Nothing Then
        getnum2 = "No match"
ElseIf Intersect(pTable.PivotFields("Bank").PivotItems(Comp).DataRange.EntireRow, _
    pTable.PivotFields("Date").PivotItems(Period).DataRange.EntireRow, _
    pTable.PivotFields("Business Unit").PivotItems(BU).DataRange.EntireRow, _
    pTable.PivotFields("Country").PivotItems(Country).DataRange.EntireRow, _
    pTable.PivotFields("Name").PivotItems(Measure).DataRange).Count > 1 Then
        getnum2 = "More than 1 match"
Else
    getnum2 = Intersect(pTable.PivotFields("Bank").PivotItems(Comp).DataRange.EntireRow, _
    pTable.PivotFields("Date").PivotItems(Period).DataRange.EntireRow, _
    pTable.PivotFields("Business Unit").PivotItems(BU).DataRange.EntireRow, _
    pTable.PivotFields("Country").PivotItems(Country).DataRange.EntireRow, _
    pTable.PivotFields("Name").PivotItems(Measure).DataRange)
End If

End Function

Body:
Here's the fastest way to do this: using Binary Match on a sorted lookup table.
On the left I have 5 columns x 1048575 rows of random numbers between 1 and 10. These have been concatenated in column G to make a non-unique key, and then sorted ascending on that key.

(Because the concatenated key is text, it gets sorted alphabetical from left to right, which is why 1|1|1|1|10 appears between 1|1|1|1|1 and 1|1|1|1|2)

I gave the data in Column G the named range of Concat to simplify the formula. My lookup formula in J2 returns the row number of the lookup item if and only if that item is unique to the dataset. The formula is:

=IF(OR( AND(INDEX(Concat,MATCH(I2,Concat,1))=I2, MATCH(I2,Concat,1)=1),  AND(INDEX(Concat,MATCH(I2,Concat,1))=I2,INDEX(Concat,MATCH(I2,Concat,1)-1)<>I2)),MATCH(I2,Concat,1),NA())

This executes in 0.01 milliseconds for one instance, for a lookup table of 1048576 rows. My double GETPIVOTDATA approach above took 6 milliseconds. So there you have it: a complex formula that gives a 600 times efficiency boost.

I can explain the formula later in need, but note that some of the complexity is due to the edge case where you may have a unique item appearing in row 1. If I leave out that edge case, then the formula is as follows:

=IF( AND(INDEX(Concat,MATCH(I3,Concat,1))=I3,INDEX(Concat,MATCH(I3,Concat,1)-1)<>I3),MATCH(I3,Concat,1),NA())


问:
getBoundingClientRect not working as expected on body after transform

$( document ).ready(function() {

    $('body').append('

');
    $('#tester2').css({
     position:'absolute',
      background:'blue',
      width: 10,
      height:10
    });
    setInterval(function(){
      var x = $('#tester')[0].getBoundingClientRect();
      $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
      $('#tester2').css({
       top:x.top,
       left:x.left
     });
    }, 1000);

    $('#jquery-version').text('jquery version: ' + $.fn.jquery);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tester{
  position:absolute;
  top:50px;
  left:50px;
  width:10px;
  height:10px;
  background:red;
}

#page{
  min-height:200px;
}

body{
  border:2px solid green;
  transform: scale(1) translate(20px, 40px);
}</code>```

getBoundingClientRect on red tester returned:

```
</div>
</div>
</p>

<p>I need to place a <code>div</code> over an existing <code>div</code>. The existing <code>div</code> is contained inside the body of and HTML document that has the CSS transform property set. I need to place the new <code>div</code> after the document was rendered and transformed.</p>

<p>When I call <code>getBoundingClientRect()</code> on the <code>div</code> that I need to hide (red square in attached fiddle) I get the wrong top/left. I set the top/left of the blue square to the output of <code>getBoundingClientRect()</code> and they do not overlap.</p>

```setInterval(function(){
    var x = $('#tester')[0].getBoundingClientRect();
    $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
    $('#tester2').css({
        top:x.top,
        left:x.left
    });
}, 1000);
```

How can this be solved?

答:
You can just take the offsetTop and offsetLeft without worrying about the transform as the same transform is applied to the newly added div as well. I'm guessing that from the example.

$(document).ready(function() {

  $('body').append('

');
  $('#tester2').css({
    position: 'absolute',
    background: 'blue',
    width: 10,
    height: 10,
    opacity: 0.6
  });
  var tester = document.getElementById('tester');
  $('#tester2').css({
    top: tester.offsetTop - 2, // 2px border for body
    left: tester.offsetLeft - 2
  });

  $('#jquery-version').text('jquery version: ' + $.fn.jquery);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tester {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 10px;
  height: 10px;
  background: red;
}

#page {
  min-height: 200px;
}

body {
  border: 2px solid green;
  transform: scale(1) translate(20px, 40px);
}</code>```

  getBoundingClientRect on red tester returned:

```

Body:
$( document ).ready(function() {

    $('body').append('

');
    $('#tester2').css({
     position:'absolute',
      background:'blue',
      width: 10,
      height:10
    });
    setInterval(function(){
      var x = $('#tester')[0].getBoundingClientRect();
      $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
      $('#tester2').css({
       top:x.top,
       left:x.left
     });
    }, 1000);

    $('#jquery-version').text('jquery version: ' + $.fn.jquery);
});

#tester{
  position:absolute;
  top:50px;
  left:50px;
  width:10px;
  height:10px;
  background:red;
}

#page{
  min-height:200px;
}

body{
  border:2px solid green;
  transform: scale(1) translate(20px, 40px);
}

getBoundingClientRect on red tester returned:

I need to place a div over an existing div. The existing div is contained inside the body of and HTML document that has the CSS transform property set. I need to place the new div after the document was rendered and transformed.

When I call getBoundingClientRect() on the div that I need to hide (red square in attached fiddle) I get the wrong top/left. I set the top/left of the blue square to the output of getBoundingClientRect() and they do not overlap.

setInterval(function(){
    var x = $('#tester')[0].getBoundingClientRect();
    $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
    $('#tester2').css({
        top:x.top,
        left:x.left
    });
}, 1000);

How can this be solved?

Body:
You can just take the offsetTop and offsetLeft without worrying about the transform as the same transform is applied to the newly added div as well. I'm guessing that from the example.

$(document).ready(function() {

  $('body').append('<div id="tester2"></div>');
  $('#tester2').css({
    position: 'absolute',
    background: 'blue',
    width: 10,
    height: 10,
    opacity: 0.6
  });
  var tester = document.getElementById('tester');
  $('#tester2').css({
    top: tester.offsetTop - 2, // 2px border for body
    left: tester.offsetLeft - 2
  });

  $('#jquery-version').text('jquery version: ' + $.fn.jquery);
});

#tester {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 10px;
  height: 10px;
  background: red;
}

#page {
  min-height: 200px;
}

body {
  border: 2px solid green;
  transform: scale(1) translate(20px, 40px);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tester">
</div>
<div id="page">
  getBoundingClientRect on red tester returned:
  <span id="tester-pos"></span>
  <div id="jquery-version"></div>
</div>


问:
add an effect dynamically over all controls in xamarin forms
I have developed an effect and i wanted to add this dynamically over all my controls. For example i wrote an effect for date pickers and i would like to add this effect over all my date pickers in the app.
I don't want to repeat this code for all my controls.

```<code><Entry.Effects>
    <local:FocusEffect />
</Entry.Effects>
</code>```

I've followed this article: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/effects/creating/

答:
You can add your effect using attached property. Then you can use styles to add that attached property to all your date pickers.

More info at:

https://medium.com/@ysmoradi/how-to-add-xamarin-native-platform-effect-to-all-elements-9214cf6d7b8a

and

https://github.com/ysmoradi/XamarinEffectsArticle

Body:
I have developed an effect and i wanted to add this dynamically over all my controls. For example i wrote an effect for date pickers and i would like to add this effect over all my date pickers in the app.
I don't want to repeat this code for all my controls.

<Entry.Effects>
    <local:FocusEffect />
</Entry.Effects>

I've followed this article: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/effects/creating/


问:
Reading from CSV file into python
I am doing coursework where it requires me to make a Quiz programme where an account for a user is created and stored to a CSV along with personal information. It then requires me to read from a CSV file and read the questions and answers for the module to run and then it stores the test data to the CSV where all the account information is stored.

I have successfully written to the CSV however I am having a problem with reading correctly.
 The CSV is set up with 2 columns and 5 rows in A1, A2, A3, A4 and A5 is where the questions are stored and in B1, B2, B3, B4 and B5 is where the answers are stored for the question on the row. Currently I am attempting to print the Question into an input and then use an if statement to check it against the answer I have stored in the CSV.

Currently I am having problems with printing everything within the cell and I am having to use ranges. A section of my python code is as follows...

```<code>import csv

with open("questions.csv", 'r') as f:
   for row in f:
       question1 = row[0:94]
       answer1 = row[95]

print(question1)
print(answer1)
</code>```

How do I print the whole cell into the input without having to do the ranges in the row?

答:
You have imported the csv module but you never use it, try this:

```<code>import csv

with open('questions.csv', 'r') as f:
   reader = csv.reader(f)
   for row in reader:
      print('Question: {}'.format(row[0]))
      print('Answer: {}'.format(row[1]))
</code>```

Title: Reading from CSV file into python

Body:
I am doing coursework where it requires me to make a Quiz programme where an account for a user is created and stored to a CSV along with personal information. It then requires me to read from a CSV file and read the questions and answers for the module to run and then it stores the test data to the CSV where all the account information is stored.

I have successfully written to the CSV however I am having a problem with reading correctly.
 The CSV is set up with 2 columns and 5 rows in A1, A2, A3, A4 and A5 is where the questions are stored and in B1, B2, B3, B4 and B5 is where the answers are stored for the question on the row. Currently I am attempting to print the Question into an input and then use an if statement to check it against the answer I have stored in the CSV.

Currently I am having problems with printing everything within the cell and I am having to use ranges. A section of my python code is as follows...

import csv

with open("questions.csv", 'r') as f:
   for row in f:
       question1 = row[0:94]
       answer1 = row[95]

print(question1)
print(answer1)

How do I print the whole cell into the input without having to do the ranges in the row?

Body:
You have imported the csv module but you never use it, try this:

import csv

with open('questions.csv', 'r') as f:
   reader = csv.reader(f)
   for row in reader:
      print('Question: {}'.format(row[0]))
      print('Answer: {}'.format(row[1]))


问:
When have you come upon the halting problem in the field?
When have you ever personally come upon the halting problem in the field? This can be when a co-worker / boss suggested a solution which would violate the fundamental limits of computation, or when you realized yourself that a problem you were trying to solve was, in fact, impossible to solve.

The most recent time I came up with it was when studying type checkers. Our class realized that it would be impossible to write a perfect type checker (one that would accept all programs that would run without type errors, and reject all programs that would run with type errors) because this would, in fact, solve the halting problem. Another was when we realized, in the same class, that it would be impossible to determine whether a division would ever occur by zero, in the type-checking stage, because checking whether a number, at run-time, is zero, is also a version of the halting problem.

答:
Years ago, I remember reading a review (in Byte magazine, I believe) of a product called Basic Infinite Loop Finder or BILF. BILF was supposed to scan your Microsoft Basic source code and find any loops which didn't terminate. It claimed to be able any find any infinite loops in the code.

The reviewer was savvy enough to point out that for that program to work in all cases, it would have to solve the halting problem and went so far as to provide a mathematical proof of why it couldn't work in all cases.

In the next issue, they published a letter from a company representative explaining that the problem would be fixed in the next release.

Update: I ran across an image of the article on imgur. I remembered the wrong magazine. It was Creative Computing, not Byte. Otherwise, it's pretty much as I remembered it.

You can see a hi-res version of it on imgur.

OwnerDisplayName: Claudiu

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Kip

OwnerDisplayName: Ferruccio


问:
How do I hide the header in a WPF Expander?
I have a business requirement that when the user clicks a series of checkboxes in a WPF application that it will show panels depending upon what checkboxes they select.  I would like to use the expander panel but I am not sure how to hide the header.  The user should not be allowed to see it unless they check the checkbox.  Does anyone know?</p>

答:
This answer has all that you need: WPF Expander Button Styled so it is inside Expander Header

If you use the style he mentions and set no header content, the header disappears