问:
Why CGBitmapInfo remove the kCGBitmapByteOrderDefault which in Objective-C?
In Objective-C, the CGBitmapInfo contains:

```<code>kCGBitmapAlphaInfoMask = 0x1F,
kCGBitmapFloatInfoMask = 0xF00,
kCGBitmapFloatComponents = (1 << 8),
kCGBitmapByteOrderMask     = kCGImageByteOrderMask,
kCGBitmapByteOrderDefault  = (0 << 12),
kCGBitmapByteOrder16Little = kCGImageByteOrder16Little,
kCGBitmapByteOrder32Little = kCGImageByteOrder32Little,
kCGBitmapByteOrder16Big    = kCGImageByteOrder16Big,
kCGBitmapByteOrder32Big    = kCGImageByteOrder32Big
</code>```

However, in Swift 3.0, CGBitmapInfo removed the kCGBitmapByteOrderDefault:

```<code>public struct CGBitmapInfo : OptionSet {

    public init(rawValue: UInt32)
    public static var alphaInfoMask: CGBitmapInfo { get }
    public static var floatInfoMask: CGBitmapInfo { get }
    public static var floatComponents: CGBitmapInfo { get }
    public static var byteOrderMask: CGBitmapInfo { get }
    public static var byteOrder16Little: CGBitmapInfo { get }
    public static var byteOrder32Little: CGBitmapInfo { get }
    public static var byteOrder16Big: CGBitmapInfo { get }
    public static var byteOrder32Big: CGBitmapInfo { get }
}
</code>```

That's why?

Can I init the CGBitmapInfo like CGBitmapInfo(rawValue: 0) to replace the kCGBitmapByteOrderDefault?

答:
see CGBitmapInfo or CGImageByteOrderInfo https://developer.apple.com/documentation/coregraphics/cgimagebyteorderinfo
https://developer.apple.com/documentation/coregraphics/cgbitmapinfo

As long as the 3 bits in the ByteOrderMask are 0, you are good. I have not found any doc stating what a byte order of 0 does. The following result in the same 0 value.

```<code>let b: CGBitmapInfo = []
let b = CGBitmapInfo(rawValue: 0)
</code>```

111000000000000 byteOrder mask

you can grab the possible values for ByteOrder from

```<code>001000000000000 == CGBitmapInfo.byteOrder16Little.rawValue
010000000000000 == CGBitmapInfo.byteOrder32Little.rawValue
011000000000000 == CGBitmapInfo.byteOrder16Big.rawValue
100000000000000 == CGBitmapInfo.byteOrder32Big.rawValue
</code>```

example setting value

```<code>let b: CGBitmapInfo = [ .byteOrder32Big]
print("\(b.contains(.byteOrder32Big))") // true
print("\(b.contains(.byteOrder16Little))") // false
print("\(b.rawValue)") // 16384
</code>```

Body:
In Objective-C, the CGBitmapInfo contains:

kCGBitmapAlphaInfoMask = 0x1F,
kCGBitmapFloatInfoMask = 0xF00,
kCGBitmapFloatComponents = (1 << 8),
kCGBitmapByteOrderMask     = kCGImageByteOrderMask,
kCGBitmapByteOrderDefault  = (0 << 12),
kCGBitmapByteOrder16Little = kCGImageByteOrder16Little,
kCGBitmapByteOrder32Little = kCGImageByteOrder32Little,
kCGBitmapByteOrder16Big    = kCGImageByteOrder16Big,
kCGBitmapByteOrder32Big    = kCGImageByteOrder32Big

However, in Swift 3.0, CGBitmapInfo removed the kCGBitmapByteOrderDefault:

public struct CGBitmapInfo : OptionSet {

    public init(rawValue: UInt32)
    public static var alphaInfoMask: CGBitmapInfo { get }
    public static var floatInfoMask: CGBitmapInfo { get }
    public static var floatComponents: CGBitmapInfo { get }
    public static var byteOrderMask: CGBitmapInfo { get }
    public static var byteOrder16Little: CGBitmapInfo { get }
    public static var byteOrder32Little: CGBitmapInfo { get }
    public static var byteOrder16Big: CGBitmapInfo { get }
    public static var byteOrder32Big: CGBitmapInfo { get }
}

That's why?

Can I init the CGBitmapInfo like CGBitmapInfo(rawValue: 0) to replace the kCGBitmapByteOrderDefault?

Body:
see CGBitmapInfo or CGImageByteOrderInfo https://developer.apple.com/documentation/coregraphics/cgimagebyteorderinfo
https://developer.apple.com/documentation/coregraphics/cgbitmapinfo

As long as the 3 bits in the ByteOrderMask are 0, you are good. I have not found any doc stating what a byte order of 0 does. The following result in the same 0 value.

let b: CGBitmapInfo = []
let b = CGBitmapInfo(rawValue: 0)

111000000000000 byteOrder mask

you can grab the possible values for ByteOrder from

001000000000000 == CGBitmapInfo.byteOrder16Little.rawValue
010000000000000 == CGBitmapInfo.byteOrder32Little.rawValue
011000000000000 == CGBitmapInfo.byteOrder16Big.rawValue
100000000000000 == CGBitmapInfo.byteOrder32Big.rawValue

example setting value

let b: CGBitmapInfo = [ .byteOrder32Big]
print("\(b.contains(.byteOrder32Big))") // true
print("\(b.contains(.byteOrder16Little))") // false
print("\(b.rawValue)") // 16384


来源: stackexchange

问:
Compile error when using vl_compilenn in Mathconvnet in Windows 8.1
I am trying to use Mathconvnet library/package of Matlab for using CNN. While trying to compile the package using the function
    vl_compilenn following this guide http://www.vlfeat.org/matconvnet/install/#compiling  i'm facing errors.

Steps Already Taken:

Installed/uninstalled then reinstalled Microsoft SDK latest version.

Added path in Environment variable

Used Command mex -setup c++ to change compiler to C++

Here is the error message I am getting.

After various stack overflow answers that i went through i have also done this

1.) vl_compilenn('EnableImreadJpeg ',false) although I get different error when I do this.

2.) added gdiplus.lib in matlab sys subfolder

EDIT: Solution is to choose a Visual Studio Compiler 12 or above, if already installed type
        mex -setup -vin Matlab which will show available compilers for choosing,select the latest one available.
if still getting the same error choose same compiler for both mex-setup c++ and mex-setup c and type the command again:
vl_compilenn('EnableImreadJpeg',false).

ContentLicense: CC BY-SA 3.0


问:
How to input text into form during React/Jest/Enzyme Shallow Rendering testing?
I have the following form:

```<code><form onSubmit={ this.handleSubmit } className="form-login">
    <ul>
        <li className="rel">
            <div className="icon-user-circle-o"></div>
            <input type="text" id="input-auth-username" placeholder="username" />
        </li>
        <li className="rel">
            <div className="icon-lock"></div>
            <input type="password" id="input-auth-password" placeholder="password" />
        </li>
        <li>
            <button className="btn-green" type="submit">Login</button>
        </li>
    </ul>
</form>
</code>```

My current test

The first test passes, it's the 2nd test I'm unable to write at the moment.

```<code>describe('User Login', () => {
    it('should fail if no credentials are provided', () => {
        const fakeEvent = { preventDefault: () => '' };
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit', fakeEvent);
        expect(loginComponent.find(Notification).length).toBe(1);
        // console.log(loginComponent.debug());
    });

    it('should log user into dashboard if correct credentials are provided', () => {
        const credentials = { username: 'joe', password: 'myspecialpassword' };

    });
});
</code>```

I want to test a form submission, however I first need to enter in text into the #input-auth-username and the #input-auth-password input fields.

How do you do that with Enzyme?

答:
Still waiting on a better answer, but thanks to this link https://github.com/airbnb/enzyme/issues/76

Was able to accomplish text being entered into my form's inputs using the following code

```<code>it('input fields should be filled correctly', () => {
    const credentials = { username: 'leongaban', password: 'testpass' };
    expect(loginComponent.find('#input-auth-username').length).toBe(1);

    const usernameInput = loginComponent.find('#input-auth-username');
    usernameInput.value = credentials.username;
    expect(usernameInput.value).toBe('leongaban');

    const passwordInput = loginComponent.find('#input-auth-password');
    passwordInput.value = credentials.password;
    expect(passwordInput.value).toBe('testpass');
});
</code>```

Body:
I have the following form:

<form onSubmit={ this.handleSubmit } className="form-login">

            <input type="text" id="input-auth-username" placeholder="username" />

            <input type="password" id="input-auth-password" placeholder="password" />

            <button className="btn-green" type="submit">Login</button>

</form>

My current test

The first test passes, it's the 2nd test I'm unable to write at the moment.

describe('User Login', () => {
    it('should fail if no credentials are provided', () => {
        const fakeEvent = { preventDefault: () => '' };
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit', fakeEvent);
        expect(loginComponent.find(Notification).length).toBe(1);
        // console.log(loginComponent.debug());
    });

    it('should log user into dashboard if correct credentials are provided', () => {
        const credentials = { username: 'joe', password: 'myspecialpassword' };

    });
});

I want to test a form submission, however I first need to enter in text into the #input-auth-username and the #input-auth-password input fields.

How do you do that with Enzyme?

Body:
Still waiting on a better answer, but thanks to this link https://github.com/airbnb/enzyme/issues/76

Was able to accomplish text being entered into my form's inputs using the following code

it('input fields should be filled correctly', () => {
    const credentials = { username: 'leongaban', password: 'testpass' };
    expect(loginComponent.find('#input-auth-username').length).toBe(1);

    const usernameInput = loginComponent.find('#input-auth-username');
    usernameInput.value = credentials.username;
    expect(usernameInput.value).toBe('leongaban');

    const passwordInput = loginComponent.find('#input-auth-password');
    passwordInput.value = credentials.password;
    expect(passwordInput.value).toBe('testpass');
});


问:
To select a common record when adding other field
```<code>A   |  B
1-1   10
1-1   10
1-1   12
1-1   22
1-4   20
1-4   20
1-4   10
</code>```

Output Table:

```<code>A  |  B
1    104
</code>```

I have given the table and the output table. I am not able to generate that output. The output I get is given below and the code I used as well.

```<code>A   | B
1     54
1     50
</code>```

The code I used is : select  left(A,2) as A, SUm(KSL05) as B  from LKP_FAGLFLEXT where condition group by A

答:
you can use group by as below:</p>

```<code>select left(a,2), sum(b) from yourtable
    group by left(a,2)
</code>```

Body:
A   |  B
1-1   10
1-1   10
1-1   12
1-1   22
1-4   20
1-4   20
1-4   10

Output Table:

A  |  B
1    104

I have given the table and the output table. I am not able to generate that output. The output I get is given below and the code I used as well.

A   | B
1     54
1     50

The code I used is : select  left(A,2) as A, SUm(KSL05) as B  from LKP_FAGLFLEXT where condition group by A

Body:
you can use group by as below:

select left(a,2), sum(b) from yourtable
    group by left(a,2)


问:
transpose column to rows
My table looks like this

```<code>SurveyId    comments    val paramid
123     test1       100 1
123     test2       200 2
123     test3       300 3
456     test10      200 1
456     test20      150 2
456     test30      320 3
</code>```

and am expecting something like the one below based on paramid

```<code>surveyid    comments1   comments2   comments3   1   2   3
123     test1       test2       test3       100 200 300
456     test10      test20      test30      200 150 320
</code>```

Tried using pivot as below

```<code>select *
from
(
SELECT
     surveyid
     ,val
      ,comments
      ,paramid
  FROM sample_table where comments is not null and surveyid = 123
) a
pivot
(
  max([val])
  for [paramid] in ([1], [2], [3])
) piv;
</code>```

Can someone please suggest what is wrong with the above code?

答:
You can try this..It is simple and uses only a GROUP BY clause.(Tried in MYSQL and it is working fine)

```<code>SELECT
surveyid
,MAX(comments1) AS comments1
,MAX(comments2) AS comments2
,MAX(comments3) AS comments3
,MAX(COL1) AS COL1
,MAX(COL2) AS COL2
,MAX(COL3) AS COL3
FROM
(
SELECT
surveyid
,CASE WHEN paramid=1 then comments else '' END AS comments1
,CASE WHEN paramid=2 then comments else '' END AS comments2
,CASE WHEN paramid=3 then comments else '' END AS comments3
,CASE WHEN paramid=1 then val else '' END AS COL1
,CASE WHEN paramid=2 then val else '' END AS COL2
,CASE WHEN paramid=3 then val else '' END AS COL3
FROM test.sample_table
) TMP
GROUP BY surveyid
</code>```

Result:
123 test1   test2   test3   100 200 300
456 test10  test20  test30  200 150 320

Title: transpose column to rows

Body:
My table looks like this

SurveyId    comments    val paramid
123     test1       100 1
123     test2       200 2
123     test3       300 3
456     test10      200 1
456     test20      150 2
456     test30      320 3

and am expecting something like the one below based on paramid

surveyid    comments1   comments2   comments3   1   2   3
123     test1       test2       test3       100 200 300
456     test10      test20      test30      200 150 320

Tried using pivot as below

select *
from
(
SELECT
     surveyid
     ,val
      ,comments
      ,paramid
  FROM sample_table where comments is not null and surveyid = 123
) a
pivot
(
  max([val])
  for [paramid] in ([1], [2], [3])
) piv;

Can someone please suggest what is wrong with the above code?

Body:
You can try this..It is simple and uses only a GROUP BY clause.(Tried in MYSQL and it is working fine)

SELECT
surveyid
,MAX(comments1) AS comments1
,MAX(comments2) AS comments2
,MAX(comments3) AS comments3
,MAX(COL1) AS COL1
,MAX(COL2) AS COL2
,MAX(COL3) AS COL3
FROM
(
SELECT
surveyid
,CASE WHEN paramid=1 then comments else '' END AS comments1
,CASE WHEN paramid=2 then comments else '' END AS comments2
,CASE WHEN paramid=3 then comments else '' END AS comments3
,CASE WHEN paramid=1 then val else '' END AS COL1
,CASE WHEN paramid=2 then val else '' END AS COL2
,CASE WHEN paramid=3 then val else '' END AS COL3
FROM test.sample_table
) TMP
GROUP BY surveyid

Result:
123 test1   test2   test3   100 200 300
456 test10  test20  test30  200 150 320


问:
Swagger Editor Parameter Errors
I'm trying to draft up an API in Swagger for easy viewing through SwaggerUI, but I'm encountering errors I don't quite understand. As far as I can tell, I'm adhering to the specification.

```<code>/history/tags/{tag_id}:
  get:
    summary: "Gets the history of this tag."
    description: "Warning: not using both the start and end date fields may result in excessively long responses."
    operationId: "get_tag_history"
    produces:
    - "application/json"
    parameters:
    - name: "tag_id"
      in: "path"
      description: "UUID for this tag."
      type: "string"
      required: true
    - name: "start_date"
      in: "query"
      description: "Start date for history"
      type: "String"
      foramt: "date"
      required: false
    - name: "end_date"
      in: "query"
      description: "End date for history"
      type: "String"
      foramt: "date"
      required: false
    responses:
      200:
        description: "Operation success"
        schema:
          $ref: "#/definitions/Tag_history"
      400:
        description: "Invalid request"
</code>```

The second and third parameters are throwing Schema error at paths./history/tags/{tag_id}.get.parameters[1]
is not exactly one from <#/definitions/parameter>,<#/definitions/jsonReference> (or parameters[2], depending on which parameter).

Most other problems I've seen are simply people forgetting to use schema:, but that isn't how query parameters are structured. Any ideas?

答:
Change

```<code>type: "String"
foramt: "date"
</code>```

to

```<code>type: "string"
format: "date"
</code>```

type is case-sensitive, and format was misspelled.

Title: Swagger Editor Parameter Errors

Body:
I'm trying to draft up an API in Swagger for easy viewing through SwaggerUI, but I'm encountering errors I don't quite understand. As far as I can tell, I'm adhering to the specification.

/history/tags/{tag_id}:
  get:
    summary: "Gets the history of this tag."
    description: "Warning: not using both the start and end date fields may result in excessively long responses."
    operationId: "get_tag_history"
    produces:
    - "application/json"
    parameters:
    - name: "tag_id"
      in: "path"
      description: "UUID for this tag."
      type: "string"
      required: true
    - name: "start_date"
      in: "query"
      description: "Start date for history"
      type: "String"
      foramt: "date"
      required: false
    - name: "end_date"
      in: "query"
      description: "End date for history"
      type: "String"
      foramt: "date"
      required: false
    responses:
      200:
        description: "Operation success"
        schema:
          $ref: "#/definitions/Tag_history"
      400:
        description: "Invalid request"

The second and third parameters are throwing Schema error at paths./history/tags/{tag_id}.get.parameters[1]
is not exactly one from <#/definitions/parameter>,<#/definitions/jsonReference> (or parameters[2], depending on which parameter).

Most other problems I've seen are simply people forgetting to use schema:, but that isn't how query parameters are structured. Any ideas?

Body:
Change

type: "String"
foramt: "date"

to

type: "string"
format: "date"

type is case-sensitive, and format was misspelled.


问:
npm joi with null, undefined, empty values and a default value
I am using older version of npm module joi => 10.2.2 and i am trying to figure out how can i build the schema so empty, null, undefined values are allowed with a default value.

This works https://github.com/hapijs/joi/issues/516

```<code>var schema = joi.object().keys({a:[joi.string().optional(), joi.allow(null)]})
</code>```

but i don't know how to specify a default value with this.

What i am looking for is this https://github.com/hapijs/joi/issues/1066 (version v10.5.2) but with the syntax of older version of joi.

答:
empty() is available in joi 10.2.2. The issue you referenced is just a documentation change. </p>

```<code>const joi = require('joi');

const schema = joi.object().keys({
    a: joi.string().optional().allow(null).allow('').empty('').default('default value')
});

let t = {
    a: ''
};

let result = joi.validate(t, schema);

console.log(result);
// { error: null, value: { a: 'default value' } }
</code>```

Body:
I am using older version of npm module joi => 10.2.2 and i am trying to figure out how can i build the schema so empty, null, undefined values are allowed with a default value.

This works https://github.com/hapijs/joi/issues/516

var schema = joi.object().keys({a:[joi.string().optional(), joi.allow(null)]})

but i don't know how to specify a default value with this.

What i am looking for is this https://github.com/hapijs/joi/issues/1066 (version v10.5.2) but with the syntax of older version of joi.

Body:
empty() is available in joi 10.2.2. The issue you referenced is just a documentation change.

const joi = require('joi');

const schema = joi.object().keys({
    a: joi.string().optional().allow(null).allow('').empty('').default('default value')
});

let t = {
    a: ''
};

let result = joi.validate(t, schema);

console.log(result);
// { error: null, value: { a: 'default value' } }


问:
How to know the floating point precision? Specifically, for GPS coordinates is it safe to use double?
Generally, what is the error I get when using a floating point number?
Specifically, is it safe to store GPS coordinates as double floating point numbers?

I think yes. Assuming "safe" to be "6 decimal digits, the same as google maps". I used the following code for verification. It uses Math.ulp of Java.

```<code>class Ulp {

        public static void main(String[]  args) {

              double ulp = Math.ulp(new Double("-181")), ulp2;

              for (double d=new Double("-181"); d<=181; d++) {
                ulp2=Math.ulp(d);
                if (ulp2 != ulp) {
                  System.out.println(""+ulp+" "+ulp2+" "+d);
                  ulp = ulp2;
                }

              }

        }
}
</code>```

From this I get the worst error is 2.8421709430404007E-14, which is safe.

Can you reassure me this reasoning is correct?

答: Yes, doubles have 15 digits of relative precision, which corresponds to roughly nanometre resolution of GPS coordinates.</p>

Body:
Generally, what is the error I get when using a floating point number?
Specifically, is it safe to store GPS coordinates as double floating point numbers?

I think yes. Assuming "safe" to be "6 decimal digits, the same as google maps". I used the following code for verification. It uses Math.ulp of Java.

class Ulp {

        public static void main(String[]  args) {

              double ulp = Math.ulp(new Double("-181")), ulp2;

              for (double d=new Double("-181"); d<=181; d++) {
                ulp2=Math.ulp(d);
                if (ulp2 != ulp) {
                  System.out.println(""+ulp+" "+ulp2+" "+d);
                  ulp = ulp2;
                }

              }

        }
}

From this I get the worst error is 2.8421709430404007E-14, which is safe.

Can you reassure me this reasoning is correct?


问:
How do I create two fields where whichever is filled first will auto-populate the other?
I manage facilities for a large complex and am responsible for issuing and tracking physical keys for our clients here. Keys are printed with specific codes (which match the lock itself), and I have also numbered individual doors on a separate system, to account for the fact that locks often change doors.

In my database I am building in Microsoft Access (sorry, very much a SQL noob), I have a table for spaces (which includes building, room and door numbers), and another separate table for keys (key code, key notch code, master keys, etc.). I also have included a field in the spaces table that references the keys table (via the ID field) to indicate which locks are associated with which doors.

Lastly, I have a log table where I record requests from clients for keys. They may request keys by door number or key code. I want to be able to enter in either the door number or the key code in a form (tied to a query which pulls from both tables) and have it automatically populate the other field accordingly. Presently, I managed a configuration where entering the door number would auto-complete the key field, but I cannot get it to work vise-versa.

This may require some kind of structural change, but I am willing to even delve into directly writing SQL code if needed. I even tried my hand at writing INNER JOIN code, but it was already doing a double-join, and I'm not sure if that is something that can be chained.

Halp!

答:
You have a form for entry of log record? This is simply data entry to a new record, right? What data is input - date, keyID, userID? So form is bound to the Log table and controls with ControlSource set to each field so input is saved directly to record in table?

My suggestion is to have 2 comboboxes. One is set up to display the door number and one set up to display the key code but both have ControlSource set to the key field and will save keyID. This is a non-conventional design. Users will have to learn that if they make selection with one combobox they can ignore the other. You could put a label above the two comboboxes "Select door number or key code."

Door combobox RowSource like: SELECT keyID, DoorNum FROM ...;"

Key combobox RowSource like: SELECT keyID, KeyCode FROM ...;

For both comboboxes set properties:

ControlSource: the key field in Log table

ColumnCount: 2

ColumnWidths: 0";1"


问:
Python 3: How to write to the same file from multiple processes without messing it up?
I have a program that can be started or stopped at any moment. The program is used to download data from web pages. First, a user will define a bunch of web pages in a .csv file, then save that .csv file, then start the program. That program will read the .csv file and turn it into a list of jobs. Next, the jobs are split among 5 separate downloader functions that work in parallel but may take different times to download.

After a downloader (which there are 5 of) finished downloading a web page, I need it to open the .csv file and remove the link. This way, as time passes, the .csv file will get smaller and smaller. The issue is that sometimes two download functions will try to update the .csv file at the same time and will cause the program to crash. How can I deal with this?

答:
If this is a continuation of your project from yesterday you already have your download list in memory - just remove the entries from the loaded list as their processes finish download and only write down the whole list over the input file once you're exiting the 'downloader'. There is no reason to constantly write down the changes.

If you want to know (say from an external process) when a url gets downloaded even while your 'downloader' is running, write in a downloaded.dat a new line each time a process returns that download was successful.

Of course, in both cases, write from within your main process/thread so you don't have to worry about mutex.

UPDATE - Here's how to do it with an additional file, using the same code base as yesterday:

```<code>def init_downloader(params):  # our downloader initializator
    downloader = Downloader(**params[0])  # instantiate our downloader
    downloader.run(params[1])  # run our downloader
    return params  # job finished, return the same params for identification

if __name__ == "__main__":  # important protection for cross-platform use

    downloader_params = [  # Downloaders will be initialized using these params
        {"port_number": 7751},
        {"port_number": 7851},
        {"port_number": 7951}
    ]
    downloader_cycle = cycle(downloader_params)  # use a cycle for round-robin distribution

    with open("downloaded_links.dat", "a+") as diff_file:  # open your diff file
        diff_file.seek(0)  # rewind the diff file to the beginning to capture all lines
        diff_links = {row.strip() for row in diff_file}  # load downloaded links into a set
        with open("input_links.dat", "r+") as input_file:  # open your input file
            available_links = []
            download_jobs = []  # store our downloader parameters + a link here
            # read our file line by line and filter out downloaded links
            for row in input_file:  # loop through our file
                link = row.strip()  # remove the extra whitespace to get the link
                if link not in diff_links:  # make sure link is not already downloaded
                    available_links.append(row)
                    download_jobs.append([next(downloader_cycle), link])
            input_file.seek(0)  # rewind our input file
            input_file.truncate()  # clear out the input file
            input_file.writelines(available_links)  # store back the available links
            diff_file.seek(0)  # rewind the diff file
            diff_file.truncate()  # blank out the diff file now that the input is updated
        # and now let's get to business...
        if download_jobs:
            download_pool = Pool(processes=5)  # make our pool use 5 processes
            # run asynchronously so we can capture results as soon as they ar available
            for response in download_pool.imap_unordered(init_downloader, download_jobs):
                # since it returns the same parameters, the second item is a link
                # add the link to our `diff` file so it doesn't get downloaded again
                diff_file.write(response[1] + "\n")
        else:
            print("Nothing left to download...")
</code>```

The whole idea is, as I wrote in the comment, to use a file to store downloaded links as they get downloaded, and then on the next run to filter out the downloaded links and update the input file. That way even if you forcibly kill it, it will always resume where it left off (except for the partial downloads).

Body:
If this is a continuation of your project from yesterday you already have your download list in memory - just remove the entries from the loaded list as their processes finish download and only write down the whole list over the input file once you're exiting the 'downloader'. There is no reason to constantly write down the changes.

If you want to know (say from an external process) when a url gets downloaded even while your 'downloader' is running, write in a downloaded.dat a new line each time a process returns that download was successful.

Of course, in both cases, write from within your main process/thread so you don't have to worry about mutex.

UPDATE - Here's how to do it with an additional file, using the same code base as yesterday:

def init_downloader(params):  # our downloader initializator
    downloader = Downloader(**params[0])  # instantiate our downloader
    downloader.run(params[1])  # run our downloader
    return params  # job finished, return the same params for identification

if __name__ == "__main__":  # important protection for cross-platform use

    downloader_params = [  # Downloaders will be initialized using these params
        {"port_number": 7751},
        {"port_number": 7851},
        {"port_number": 7951}
    ]
    downloader_cycle = cycle(downloader_params)  # use a cycle for round-robin distribution

    with open("downloaded_links.dat", "a+") as diff_file:  # open your diff file
        diff_file.seek(0)  # rewind the diff file to the beginning to capture all lines
        diff_links = {row.strip() for row in diff_file}  # load downloaded links into a set
        with open("input_links.dat", "r+") as input_file:  # open your input file
            available_links = []
            download_jobs = []  # store our downloader parameters + a link here
            # read our file line by line and filter out downloaded links
            for row in input_file:  # loop through our file
                link = row.strip()  # remove the extra whitespace to get the link
                if link not in diff_links:  # make sure link is not already downloaded
                    available_links.append(row)
                    download_jobs.append([next(downloader_cycle), link])
            input_file.seek(0)  # rewind our input file
            input_file.truncate()  # clear out the input file
            input_file.writelines(available_links)  # store back the available links
            diff_file.seek(0)  # rewind the diff file
            diff_file.truncate()  # blank out the diff file now that the input is updated
        # and now let's get to business...
        if download_jobs:
            download_pool = Pool(processes=5)  # make our pool use 5 processes
            # run asynchronously so we can capture results as soon as they ar available
            for response in download_pool.imap_unordered(init_downloader, download_jobs):
                # since it returns the same parameters, the second item is a link
                # add the link to our `diff` file so it doesn't get downloaded again
                diff_file.write(response[1] + "\n")
        else:
            print("Nothing left to download...")

The whole idea is, as I wrote in the comment, to use a file to store downloaded links as they get downloaded, and then on the next run to filter out the downloaded links and update the input file. That way even if you forcibly kill it, it will always resume where it left off (except for the partial downloads).


问:
Unable to take username and password in Twitter account using Selenium
I am using below code to login in twitter</p>

```<code>    driver.get("https://twitter.com/login/");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input")).sendKeys("viaxpath");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input")).sendKeys("viaxpath");
</code>```

答:
To get a CSS Selector in Chrome:

Right-click on the element and select 'Inspect'

Right-click on the element in the DOM explorer of DevTools

Select "Copy" > "Copy selector"

Alternatively you could get the XPath here too

I was able to input a user name by getting a CSS Selector from Chrome's DevTools and testing it out in the Console.

```<code>document.querySelector("#page-container > div > div.signin-wrapper > form > fieldset > div:nth-child(2) > input").value = "Timothy"
</code>```

In (Java) Selenium it would look like:

```<code>driver.findElement(By.cssSelector("#page-container > div > div.signin-wrapper > form > fieldset > div:nth-child(2) > input")).sendKeys("Timothy");
</code>```

One problem you might be experiencing is that you load the page and try to input before its ready. So I recommend doing an explicit wait between navigating to the page and interacting with the input.

Body:
I am using below code to login in twitter

    driver.get("https://twitter.com/login/");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input")).sendKeys("viaxpath");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input")).sendKeys("viaxpath");

Body:
To get a CSS Selector in Chrome:

Right-click on the element and select 'Inspect'

Right-click on the element in the DOM explorer of DevTools

Select "Copy" > "Copy selector"

Alternatively you could get the XPath here too

I was able to input a user name by getting a CSS Selector from Chrome's DevTools and testing it out in the Console.

document.querySelector("#page-container > div > div.signin-wrapper > form > fieldset > div:nth-child(2) > input").value = "Timothy"

In (Java) Selenium it would look like:

driver.findElement(By.cssSelector("#page-container > div > div.signin-wrapper > form > fieldset > div:nth-child(2) > input")).sendKeys("Timothy");

One problem you might be experiencing is that you load the page and try to input before its ready. So I recommend doing an explicit wait between navigating to the page and interacting with the input.


问:
text over img hover with jquery
I'm a complete beginner at coding and I've already searched here but I couldn't really find a proper solution to my problem.

I'm trying to get a text to appear in place of the image when I hover over the image with the mouse.
Unfortunately jQuery has to be used, I know it can be done by just using CSS.

So far I have the following which I found on here:

In the head:

```<code><script>
 $(function(){
    $('.parent').mouseenter(function(){
        $(this).children('.child').fadeIn();
    }).mouseleave(function(){
        $(this).children('.child').fadeOut();
    });
});
</script>
</code>```

In the body:

```<code><div class='parent'>
<img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image'/>
<div class='child'>
<p>Random text.</p>
</div>
</div>
</code>```

CSS:

```<code>.parent
{
    position:relative;
}
.child
{
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
    padding:10px;

    display:none;
}
</code>```

Thank you for an easy tip or explanation on what I'm doing wrong and how I can solve that problem.

Edit:

This is my full code in my PHP file:

```<code>    echo "
    <!DOCTYPE html>
    <html lang=\"en\">
    <head>
        <meta charset=\"UTF-8\">
        <title>Test Blog</title>

    <script>
$(document).ready(function() {

      $('.gallery-item').hover(function() {
        $(this).find('.img-title').fadeIn(300);
      }, function() {
        $(this).find('.img-title').fadeOut(100);
      });

    });
    </script>

    </head>
    <body>

    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>

    <div class=\"wrapper clearfix\">

      <figure class=\"gallery-item\">
        <img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image'>
        <figcaption class=\"img-title\">
          <h5>Random text.</h5>
        </figcaption>
      </figure>

    </div>
</code>```

And there it continues with a dropdown menu routing to the other pages.
The CSS code is in my CSS file which I linked to above (the link is correct since all the other CSS code is working).

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

  $('.gallery-item').hover(function() {
    $(this).find('.img-title').fadeIn(300);
  }, function() {
    $(this).find('.img-title').fadeOut(100);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gallery {
  width: 25em;
  margin: 2em auto;
}

.gallery-item {
  height: auto;
  width: 48.618784527%;
  float: left;
  margin-bottom: 2em;
  position: relative;
}

.gallery-item:first-child {
  margin-right: 2.762430939%;
}

.gallery-item img {
  width: 100%;
}

.gallery-item:hover .img-title {}

.img-title {
  position: absolute;
  top: 0;
  margin: 0;
  height: 100%;
  width: 100%;
  text-align: center;
  display: none;
  background-color: #333;
}

.img-title h5 {
  position: absolute;
  color: #fff;
  top: 33%;
  width: 100%;
  text-align: center;
}</code>```

Random text.

```

ContentLicense: CC BY-SA 4.0

Title: text over img hover with jquery

Body:
I'm a complete beginner at coding and I've already searched here but I couldn't really find a proper solution to my problem.

I'm trying to get a text to appear in place of the image when I hover over the image with the mouse.
Unfortunately jQuery has to be used, I know it can be done by just using CSS.

So far I have the following which I found on here:

In the head:

In the body:

Random text.

CSS:

.parent
{
    position:relative;
}
.child
{
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
    padding:10px;

    display:none;
}

Thank you for an easy tip or explanation on what I'm doing wrong and how I can solve that problem.

Edit:

This is my full code in my PHP file:

    echo "
    <!DOCTYPE html>

        <meta charset=\"UTF-8\">
        <title>Test Blog</title>

Random text.

And there it continues with a dropdown menu routing to the other pages.
The CSS code is in my CSS file which I linked to above (the link is correct since all the other CSS code is working).

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

  $('.gallery-item').hover(function() {
    $(this).find('.img-title').fadeIn(300);
  }, function() {
    $(this).find('.img-title').fadeOut(100);
  });

});

.gallery {
  width: 25em;
  margin: 2em auto;
}

.gallery-item {
  height: auto;
  width: 48.618784527%;
  float: left;
  margin-bottom: 2em;
  position: relative;
}

.gallery-item:first-child {
  margin-right: 2.762430939%;
}

.gallery-item img {
  width: 100%;
}

.gallery-item:hover .img-title {}

.img-title {
  position: absolute;
  top: 0;
  margin: 0;
  height: 100%;
  width: 100%;
  text-align: center;
  display: none;
  background-color: #333;
}

.img-title h5 {
  position: absolute;
  color: #fff;
  top: 33%;
  width: 100%;
  text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrapper clearfix">

  <figure class="gallery-item">
    <img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image'>
    <figcaption class="img-title">
      <h5>Random text.</h5>
    </figcaption>
  </figure>

</div>


问:
How to draw a "speech bubble" on an iPhone?
I'm trying to get a "speech bubble" effect similar to the one in Mac OS X when you right click on something in the dock.  Here's what I have now:

I need to get the "triangle" part of the lower portion.  Is there any way I can draw something like that and get a border around it?  This will be for an iPhone app.

Thanks in advance!

EDIT:  Many thanks to Brad Larson, here's what it looks like now:

答:
There are two ways you might be able to accomplish this:

Add a UIImageView with a triangle image in the right place. Make sure the rest of the image is transparent so as not to block your background.

Override the drawRect: method on your UIView to custom-draw the view. You can then add linear path components for your triangle, filling and bordering the path as necessary.

To draw a simple triangle using drawRect:, you might do something like this. This snippet will draw a triangle pointing downwards at the bottom of your view.

```<code>// Get the context
CGContextRef context = UIGraphicsGetCurrentContext();

// Pick colors
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);

// Define triangle dimensions
CGFloat baseWidth = 30.0;
CGFloat height = 20.0;

// Define path
CGContextMoveToPoint(context, self.bounds.size.width / 2.0 - baseWidth / 2.0,
                              self.bounds.size.height - height);
CGContextAddLineToPoint(context, self.bounds.size.width / 2.0 + baseWidth / 2.0,
                                 self.bounds.size.height - height);
CGContextAddLineToPoint(context, self.bounds.size.width / 2.0,
                                 self.bounds.size.height);

// Finalize and draw using path
CGContextClosePath(context);
CGContextStrokePath(context);
</code>```

For more info, see the CGContext reference.

ContentLicense: CC BY-SA 2.5

Body:
There are two ways you might be able to accomplish this:

Add a UIImageView with a triangle image in the right place. Make sure the rest of the image is transparent so as not to block your background.

Override the drawRect: method on your UIView to custom-draw the view. You can then add linear path components for your triangle, filling and bordering the path as necessary.

To draw a simple triangle using drawRect:, you might do something like this. This snippet will draw a triangle pointing downwards at the bottom of your view.

// Get the context
CGContextRef context = UIGraphicsGetCurrentContext();

// Pick colors
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);

// Define triangle dimensions
CGFloat baseWidth = 30.0;
CGFloat height = 20.0;

// Define path
CGContextMoveToPoint(context, self.bounds.size.width / 2.0 - baseWidth / 2.0,
                              self.bounds.size.height - height);
CGContextAddLineToPoint(context, self.bounds.size.width / 2.0 + baseWidth / 2.0,
                                 self.bounds.size.height - height);
CGContextAddLineToPoint(context, self.bounds.size.width / 2.0,
                                 self.bounds.size.height);

// Finalize and draw using path
CGContextClosePath(context);
CGContextStrokePath(context);

For more info, see the CGContext reference.


问:
Gaussian does not fit correctly to data
I am trying to fit a gaussian curve to my data which is a list of density variations with height, however the plot of the fitted curve generated is always off (peak doesn't align, width is overestimated). Here is my code:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

#Gaussian function
def gauss_function(x, a, x0, sigma):
    return a*np.exp(-(x-x0)**2/float((2*sigma**2)))

x = heights5
y = demeans5 #density values at each height

amp = max(y)
center = x[np.argmax(y)]
width = 20 #eye-balled estimate

#p0 = amp, width, center
popt, pcov = curve_fit(gauss_function, x, y, p0 = [amp, width, center])

#plot
dataplot = plt.scatter(x, y, marker = '.', label = 'Observations')
gausplot = plt.plot(x,gauss_function(x, *popt), color='red', label ='Gaussian fit')

string = 'fwhm = ' + str(2.355*popt[2]) + '\npeak = ' + str(popt[0]) + '\nmean = ' + str(popt[1]) + '\nsigma = ' + str(popt[2])

#plot labels etc.
plt.xlabel("Height[km]")
plt.ylabel("Density")
plt.legend([dataplot, gausplot], labels = ['fit', 'Observations'])
plt.text(130, 2000, string)
plt.show()
</code>```

This is the plot it generates:

How do I fit the curve more accurately? And also, is there a way to estimate the width with the data?

答:
For a more accurate fit, you could look into scipy.interpolate module. The functions there do a good job with interpolating and fitting.

Other fitting techniques which could do a good job are:
a) CSTs
b) BSplines
c) Polynomial interpolation

Scipy also has an implementation for BSplines. The other two, you may have to implement yourself.

Title: Gaussian does not fit correctly to data

Body:
I am trying to fit a gaussian curve to my data which is a list of density variations with height, however the plot of the fitted curve generated is always off (peak doesn't align, width is overestimated). Here is my code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

#Gaussian function
def gauss_function(x, a, x0, sigma):
    return a*np.exp(-(x-x0)**2/float((2*sigma**2)))

x = heights5
y = demeans5 #density values at each height

amp = max(y)
center = x[np.argmax(y)]
width = 20 #eye-balled estimate

#p0 = amp, width, center
popt, pcov = curve_fit(gauss_function, x, y, p0 = [amp, width, center])

#plot
dataplot = plt.scatter(x, y, marker = '.', label = 'Observations')
gausplot = plt.plot(x,gauss_function(x, *popt), color='red', label ='Gaussian fit')

string = 'fwhm = ' + str(2.355*popt[2]) + '\npeak = ' + str(popt[0]) + '\nmean = ' + str(popt[1]) + '\nsigma = ' + str(popt[2])

#plot labels etc.
plt.xlabel("Height[km]")
plt.ylabel("Density")
plt.legend([dataplot, gausplot], labels = ['fit', 'Observations'])
plt.text(130, 2000, string)
plt.show()

This is the plot it generates:

How do I fit the curve more accurately? And also, is there a way to estimate the width with the data?


问:
Why is the type of an instance of the GeneratorFunction constructor 'function'?
As I am still digging through ES6 and because I am usually very curious and I always try to find the reasons for everything, I was playing a bit with generator functions trying to understand how does a compiler like Traceur or Babel compile the ES6 code to ES5. So I saved the constructor whose instance is any generator function and I alerted the type of one of its instances. The result was 'function'

window.GeneratorFunction = Object.getPrototypeOf(function*() {}).constructor
console.log(typeof new GeneratorFunction()) // 'function'```
</div>
</div>
</p>
<p>As far as I know, an instance of a constructor is an object</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(typeof new String()) // 'object'
console.log(typeof new Number()) // 'object'</code>```

Why does the GeneratorFunction() constructor has function instances?

答: Probably because also typeof new Function() === 'function' is true. See What is Function's Data Type : function or object? in JavaScript

Body:
As I am still digging through ES6 and because I am usually very curious and I always try to find the reasons for everything, I was playing a bit with generator functions trying to understand how does a compiler like Traceur or Babel compile the ES6 code to ES5. So I saved the constructor whose instance is any generator function and I alerted the type of one of its instances. The result was 'function'

window.GeneratorFunction = Object.getPrototypeOf(function*() {}).constructor
console.log(typeof new GeneratorFunction()) // 'function'

As far as I know, an instance of a constructor is an object

console.log(typeof new String()) // 'object'
console.log(typeof new Number()) // 'object'

Why does the GeneratorFunction() constructor has function instances?


答:
Hope it helps you out.

$(function(){
    $('.parent').mouseenter(function(){
        //alert();
        $(this).children('.child').show().fadeIn(200);//have some timeout for fading in
    }).mouseleave(function(){
        $(this).children('.child').fadeOut(400);
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent
{
    position:relative;
}
.child
{
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: black;
    opacity: 1.0;
    padding:10px;
    display:none;
    /*
    add width and height attribute to the elem
    */
    width:100%;
    height:300px;
    color:white;
}</code>```

Random text.

```

Title: text over img hover with jquery

Body:
Hope it helps you out.

$(function(){
    $('.parent').mouseenter(function(){
        //alert();
        $(this).children('.child').show().fadeIn(200);//have some timeout for fading in
    }).mouseleave(function(){
        $(this).children('.child').fadeOut(400);
    });
});

.parent
{
    position:relative;
}
.child
{
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: black;
    opacity: 1.0;
    padding:10px;
    display:none;
    /*
    add width and height attribute to the elem
    */
    width:100%;
    height:300px;
    color:white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image'/>
<div class='child'>
<p>Random text.</p>
</div>
</div>


问:
Location of Application.persistentDataPath in a build
When I run my game from the editor and save load data, I find that data in: C:\Users\User\AppData\LocalLow\DefaultCompany\projectname\data.

When I build it and get an executable, that data still loads fine, but if I save and restart, it does not get saved. However it does when I launch it from the Editor.

Is this a fault in my code or is the files somewhere else when I don't run it from Unity Editor?

Later when I export the game to launch it, I have persistent data I Json files that have to come with it for the game to work.

For clarity, here is the class that handles save/load of Json:

```<code>public class DataHandler
{
    //Save Data
    public static void saveData<T>(T dataToSave, string dataFileName)
    {
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Convert To Json then to bytes
        string jsonData = JsonUtility.ToJson(dataToSave, true);
        byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);

        //Create Directory if it does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
        }
        //Debug.Log(path);

        try
        {
            File.WriteAllBytes(tempPath, jsonByte);
            Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
            Debug.LogWarning("Error: " + e.Message);
        }
    }

    //Load Data
    public static T loadData<T>(string dataFileName)
    {
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Exit if Directory or File does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Debug.LogWarning("Directory does not exist");
            return default(T);
        }

        if (!File.Exists(tempPath))
        {
            Debug.Log("File does not exist");
            return default(T);
        }

        //Load saved Json
        byte[] jsonByte = null;
        try
        {
            jsonByte = File.ReadAllBytes(tempPath);
            Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
            Debug.LogWarning("Error: " + e.Message);
        }

        //Convert to json string
        string jsonData = Encoding.ASCII.GetString(jsonByte);

        //Convert to Object
        object resultValue = JsonUtility.FromJson<T>(jsonData);
        return (T)Convert.ChangeType(resultValue, typeof(T));
    }

    public static bool deleteData(string dataFileName)
    {
        bool success = false;

        //Load Data
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Exit if Directory or File does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Debug.LogWarning("Directory does not exist");
            return false;
        }

        if (!File.Exists(tempPath))
        {
            Debug.Log("File does not exist");
            return false;
        }

        try
        {
            File.Delete(tempPath);
            Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
            success = true;
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To Delete Data: " + e.Message);
        }

        return success;
    }
}
</code>```

答:
In the answer below:

companyname = Company name from the Build Settings

productname = Product name from the Build Settings

Windows:

```<code>C:\Users\<userprofile>\AppData\LocalLow\<companyname>\<productname>
</code>```

Windows Store:

```<code>%userprofile%\AppData\Local\Packages\<productname>\LocalState
</code>```

Mac:

```<code>~/Library/Application Support/companyname/productname
</code>```

older version of Unity on Mac:

~/Library/Caches folder

~/Library/Application Support/unity.companyname.productname.

Linux:

```<code>$XDG_CONFIG_HOME/unity3d/<companyname>/<productname>
</code>```

which is the-same as

```<code>~/.config/unity3d/<companyname>/<productname>
</code>```

Android:

```<code>/Data/Data/com.<companyname>.<productname>/files
</code>```

with SD card on the Android device:

```<code>/storage/sdcard0/Android/data/com.<companyname>.<productname>/files
</code>```

iOS:

```<code>/var/mobile/Containers/Data/Application/<RandomFolderName>/Documents
</code>```

Example of the RandomFolderName full name:

```<code>/var/mobile/Containers/Data/Application/<055811B9-D125-41B1-A078-F898B06F8C58>/Documents
</code>```

On iOS, you will be given access to the app's sandbox which is the Document folder. You must create folder inside this directory in order to create a new file inside it.

If you have a default data values in a json file, put the file in Assets/Resources folder so that it will be read-only then read it with TextAsset. When the game loads, you can use PlayerPrefs to check if this is the first time the game being loaded.

If this is the first time, use the value from TextAsset.text. If it is not use then value saved with the DataHandler class.

Roughly something like this:

```<code>if (PlayerPrefs.GetInt("FIRSTTIMEOPENING", 1) == 1)
{
    Debug.Log("First Time Opening");

    //Set first time opening to false
    PlayerPrefs.SetInt("FIRSTTIMEOPENING", 0);

    //USE TextAsset to load data
    TextAsset txtAsset = (TextAsset)Resources.Load("player", typeof(TextAsset));
    string tileFile = txtAsset.text;
    PlayerInfo pInfo = JsonUtility.FromJson<PlayerInfo>(tileFile);
}
else
{
    Debug.Log("NOT First Time Opening");

    //USE DataHandler to load data
    PlayerInfo pInfo = DataHandler.loadData<PlayerInfo>("player");
}
</code>```

Body:
When I run my game from the editor and save load data, I find that data in: C:\Users\User\AppData\LocalLow\DefaultCompany\projectname\data.

When I build it and get an executable, that data still loads fine, but if I save and restart, it does not get saved. However it does when I launch it from the Editor.

Is this a fault in my code or is the files somewhere else when I don't run it from Unity Editor?

Later when I export the game to launch it, I have persistent data I Json files that have to come with it for the game to work.

For clarity, here is the class that handles save/load of Json:

public class DataHandler
{
    //Save Data
    public static void saveData<T>(T dataToSave, string dataFileName)
    {
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Convert To Json then to bytes
        string jsonData = JsonUtility.ToJson(dataToSave, true);
        byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);

        //Create Directory if it does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
        }
        //Debug.Log(path);

        try
        {
            File.WriteAllBytes(tempPath, jsonByte);
            Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
            Debug.LogWarning("Error: " + e.Message);
        }
    }

    //Load Data
    public static T loadData<T>(string dataFileName)
    {
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Exit if Directory or File does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Debug.LogWarning("Directory does not exist");
            return default(T);
        }

        if (!File.Exists(tempPath))
        {
            Debug.Log("File does not exist");
            return default(T);
        }

        //Load saved Json
        byte[] jsonByte = null;
        try
        {
            jsonByte = File.ReadAllBytes(tempPath);
            Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
            Debug.LogWarning("Error: " + e.Message);
        }

        //Convert to json string
        string jsonData = Encoding.ASCII.GetString(jsonByte);

        //Convert to Object
        object resultValue = JsonUtility.FromJson<T>(jsonData);
        return (T)Convert.ChangeType(resultValue, typeof(T));
    }

    public static bool deleteData(string dataFileName)
    {
        bool success = false;

        //Load Data
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Exit if Directory or File does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Debug.LogWarning("Directory does not exist");
            return false;
        }

        if (!File.Exists(tempPath))
        {
            Debug.Log("File does not exist");
            return false;
        }

        try
        {
            File.Delete(tempPath);
            Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
            success = true;
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To Delete Data: " + e.Message);
        }

        return success;
    }
}

Body:
In the answer below:

companyname = Company name from the Build Settings

productname = Product name from the Build Settings

Windows:

C:\Users\<userprofile>\AppData\LocalLow\<companyname>\<productname>

Windows Store:

%userprofile%\AppData\Local\Packages\<productname>\LocalState

Mac:

~/Library/Application Support/companyname/productname

older version of Unity on Mac:

~/Library/Caches folder

~/Library/Application Support/unity.companyname.productname.

Linux:

$XDG_CONFIG_HOME/unity3d/<companyname>/<productname>

which is the-same as

~/.config/unity3d/<companyname>/<productname>

Android:

/Data/Data/com.<companyname>.<productname>/files

with SD card on the Android device:

/storage/sdcard0/Android/data/com.<companyname>.<productname>/files

iOS:

/var/mobile/Containers/Data/Application/<RandomFolderName>/Documents

Example of the RandomFolderName full name:

/var/mobile/Containers/Data/Application/<055811B9-D125-41B1-A078-F898B06F8C58>/Documents

On iOS, you will be given access to the app's sandbox which is the Document folder. You must create folder inside this directory in order to create a new file inside it.

If you have a default data values in a json file, put the file in Assets/Resources folder so that it will be read-only then read it with TextAsset. When the game loads, you can use PlayerPrefs to check if this is the first time the game being loaded.

If this is the first time, use the value from TextAsset.text. If it is not use then value saved with the DataHandler class.

Roughly something like this:

if (PlayerPrefs.GetInt("FIRSTTIMEOPENING", 1) == 1)
{
    Debug.Log("First Time Opening");

    //Set first time opening to false
    PlayerPrefs.SetInt("FIRSTTIMEOPENING", 0);

    //USE TextAsset to load data
    TextAsset txtAsset = (TextAsset)Resources.Load("player", typeof(TextAsset));
    string tileFile = txtAsset.text;
    PlayerInfo pInfo = JsonUtility.FromJson<PlayerInfo>(tileFile);
}
else
{
    Debug.Log("NOT First Time Opening");

    //USE DataHandler to load data
    PlayerInfo pInfo = DataHandler.loadData<PlayerInfo>("player");
}


问:
How to compare 2 ISODate fields in Mongo?
I have 2 fields like this in my document

```<code>"DATE_1" : ISODate("2017-08-11T04:00:00Z")
"DATE_2" : ISODate("2017-06-12T04:00:00Z")
</code>```

I would like to select documents with "DATE_1" is greater than "DATE_2" and i tried the following query which should return the above document.But its not giving any result

```<code>db.collection.find({"DATE_1":{$gte:"DATE_2"}})
</code>```

How do I compare 2 ISODate fields in Mongo? Also how do I make this query using Spring date mongodb? something like this?

```<code>Criteria.where("DATE_1").gte("DATE_2");
</code>```

答:
This should work. Can you please try this and give your feedback.</p>

```<code>db.getCollection('collectionName').find({$where: function() {
    return this.DATE_1 > this.DATE_2;
}})
</code>```

Body:
I have 2 fields like this in my document

"DATE_1" : ISODate("2017-08-11T04:00:00Z")
"DATE_2" : ISODate("2017-06-12T04:00:00Z")

I would like to select documents with "DATE_1" is greater than "DATE_2" and i tried the following query which should return the above document.But its not giving any result

db.collection.find({"DATE_1":{$gte:"DATE_2"}})

How do I compare 2 ISODate fields in Mongo? Also how do I make this query using Spring date mongodb? something like this?

Criteria.where("DATE_1").gte("DATE_2");

Body:
This should work. Can you please try this and give your feedback.

db.getCollection('collectionName').find({$where: function() {
    return this.DATE_1 > this.DATE_2;
}})


问:
deleting object from realm database.
I am writing Todo app. My app is simple. I have two pages. One page for showing tasks in table view. And one page for adding new tasks. In this page I post to server and then in main page I get data from server and then save it in realm database.

When I Want to delete them in my main page , my app crashes by this error.

```<code>  Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TodoApp.TodosTableViewController delete:]: unrecognized selector sent to instance 0x7fca7b40b4c0
</code>```

Anyone knows why?
It is my deleting function :

```<code>public func delete<T:Object>(_ model: T) {
    let realm = try! Realm()

    try! realm.write {

        realm.delete(model)

        }
}
</code>```

And this is the place that I use this function to delete from database :

```<code>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){

        if editingStyle == UITableViewCellEditingStyle.delete {
            rowHere = indexPath.row
            // it crashes the app when I want to delete from database

//            delete(self.todos[self.rowHere!])

            self.todos.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath as IndexPath], with:           UITableViewRowAnimation.automatic)

        }
    }
</code>```

答:
I implemented something similar in my app, hope it helps you.</p>

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    //deleteRecords()
    delete(index: indexPath.row)
    retrieveFoods()
    tableView.reloadData()
}

func retrieveFoods() {
    let realm = try! Realm()
    myFoodsArray = realm.objects(MyFoods.self).sorted(byKeyPath: "name", ascending: true)
}

func delete(index: Int) {
    let myFood = myFoodsArray[index]
    let realm = try! Realm()
    try! realm.write {
        realm.delete(myFood)
        self.tableView.reloadData()
    }
}
</code>```

Title: deleting object from realm database.

Body:
I am writing Todo app. My app is simple. I have two pages. One page for showing tasks in table view. And one page for adding new tasks. In this page I post to server and then in main page I get data from server and then save it in realm database.

When I Want to delete them in my main page , my app crashes by this error.

  Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TodoApp.TodosTableViewController delete:]: unrecognized selector sent to instance 0x7fca7b40b4c0

Anyone knows why?
It is my deleting function :

public func delete<T:Object>(_ model: T) {
    let realm = try! Realm()

    try! realm.write {

        realm.delete(model)

        }
}

And this is the place that I use this function to delete from database :

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){

        if editingStyle == UITableViewCellEditingStyle.delete {
            rowHere = indexPath.row
            // it crashes the app when I want to delete from database

//            delete(self.todos[self.rowHere!])

            self.todos.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath as IndexPath], with:           UITableViewRowAnimation.automatic)

        }
    }

Body:
I implemented something similar in my app, hope it helps you.

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    //deleteRecords()
    delete(index: indexPath.row)
    retrieveFoods()
    tableView.reloadData()
}

func retrieveFoods() {
    let realm = try! Realm()
    myFoodsArray = realm.objects(MyFoods.self).sorted(byKeyPath: "name", ascending: true)
}

func delete(index: Int) {
    let myFood = myFoodsArray[index]
    let realm = try! Realm()
    try! realm.write {
        realm.delete(myFood)
        self.tableView.reloadData()
    }
}


问:
Gradient mask not showing
I am trying to draw a gradient, fading in opacity.

I see no effect from drawing. Tried changing the colors. The frames look right. Why isn't this opacity fade showing up?

```<code>func createGradient() {
        let h = UIScreen.mainScreen().bounds.size.height
        let y = collectionView.frame.origin.y + (cellSize() * 3)
        let v = UIView(frame: CGRect(x: 0, y: y, width: collectionView.frame.size.width, height: h - y))

        let l = CAGradientLayer()
        l.frame = v.bounds
        l.colors = [UIColor.greenColor().CGColor, UIColor.blueColor().CGColor]

        l.startPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(0.0));
        l.endPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(1.0));
        v.layer.mask = l;
        view.addSubview(v)
    }
</code>```

My logs:

```<code>(lldb) po l
<CAGradientLayer:0x618000228b00; position = CGPoint (207 101); bounds = CGRect (0 0; 414 202); allowsGroupOpacity = YES; colors = (
    "<CGColor 0x6180000b2c00> [<CGColorSpace 0x6100000376c0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0 1 0 1 )",
    "<CGColor 0x6180000b2c60> [<CGColorSpace 0x6100000376c0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0 0 1 1 )"
)>

(lldb) po v
<UIView: 0x7fe1b3d1d3b0; frame = (0 534; 414 202); layer = <CALayer: 0x618000228880>>

(lldb)
</code>```

答:
replace v.layer.mask = l with v.layer.addSublayer(l)

```<code>func createGradient() {
        let h = UIScreen.mainScreen().bounds.size.height
        let y = collectionView.frame.origin.y + (cellSize() * 3)
        let v = UIView(frame: CGRect(x: 0, y: y, width: collectionView.frame.size.width, height: h - y))

        let l = CAGradientLayer()
        l.frame = v.bounds
        l.colors = [UIColor.greenColor().CGColor, UIColor.blueColor().CGColor]

        l.startPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(0.0));
        l.endPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(1.0));
        v.layer.addSublayer(l)
        view.addSubview(v)
    }
</code>```

Title: Gradient mask not showing

Body:
I am trying to draw a gradient, fading in opacity.

I see no effect from drawing. Tried changing the colors. The frames look right. Why isn't this opacity fade showing up?

func createGradient() {
        let h = UIScreen.mainScreen().bounds.size.height
        let y = collectionView.frame.origin.y + (cellSize() * 3)
        let v = UIView(frame: CGRect(x: 0, y: y, width: collectionView.frame.size.width, height: h - y))

        let l = CAGradientLayer()
        l.frame = v.bounds
        l.colors = [UIColor.greenColor().CGColor, UIColor.blueColor().CGColor]

        l.startPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(0.0));
        l.endPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(1.0));
        v.layer.mask = l;
        view.addSubview(v)
    }

My logs:

(lldb) po l
<CAGradientLayer:0x618000228b00; position = CGPoint (207 101); bounds = CGRect (0 0; 414 202); allowsGroupOpacity = YES; colors = (
    "<CGColor 0x6180000b2c00> [<CGColorSpace 0x6100000376c0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0 1 0 1 )",
    "<CGColor 0x6180000b2c60> [<CGColorSpace 0x6100000376c0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0 0 1 1 )"
)>

(lldb) po v
<UIView: 0x7fe1b3d1d3b0; frame = (0 534; 414 202); layer = <CALayer: 0x618000228880>>

(lldb)

Body:
replace v.layer.mask = l with v.layer.addSublayer(l)

func createGradient() {
        let h = UIScreen.mainScreen().bounds.size.height
        let y = collectionView.frame.origin.y + (cellSize() * 3)
        let v = UIView(frame: CGRect(x: 0, y: y, width: collectionView.frame.size.width, height: h - y))

        let l = CAGradientLayer()
        l.frame = v.bounds
        l.colors = [UIColor.greenColor().CGColor, UIColor.blueColor().CGColor]

        l.startPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(0.0));
        l.endPoint = CGPoint(x: CGFloat(0.5), y: CGFloat(1.0));
        v.layer.addSublayer(l)
        view.addSubview(v)
    }


问:
Initialized empty numpy array is not really empty (contains zeros)
In order to store many 3D points coordinates tuples in a numpy.ndarray I initialize an empty numpy array before entering a loop for each of some features.

To do so, I currently do this before entering the loop:

```<code>import numpy as np
pointsarrray = np.empty((1,3))
</code>```

but this results in an array which is all but empty:

```<code>array([[  5.30498948e-315,   0.00000000e+000,   7.81250000e-003]])
</code>```

When filling pointsarray in my loop after, I do this:

```<code>pointsarray = np.vstack((pointsarray, [np.array(myPoint)]))
</code>```

(it also works with np.append)

and I finally need to delete the first line of the array after exiting the loop because this first line always contains the values from the initialization step!

It's not a big deal but I wonder if there is a cleaner way to achieve a really empty array, I mean; with nothing inside it (it shows 1 row yet, I can not figure out why) but at the right dimensions?

答:
You need the shape to be (0, 3) so you have the correct number of columns to stack but have actually no data inside:

```<code>import numpy as np
pointsarrray = np.empty((0,3))

pointsarrray
# array([], shape=(0, 3), dtype=float64)
</code>```

Body:
In order to store many 3D points coordinates tuples in a numpy.ndarray I initialize an empty numpy array before entering a loop for each of some features.

To do so, I currently do this before entering the loop:

import numpy as np
pointsarrray = np.empty((1,3))

but this results in an array which is all but empty:

array([[  5.30498948e-315,   0.00000000e+000,   7.81250000e-003]])

When filling pointsarray in my loop after, I do this:

pointsarray = np.vstack((pointsarray, [np.array(myPoint)]))

(it also works with np.append)

and I finally need to delete the first line of the array after exiting the loop because this first line always contains the values from the initialization step!

It's not a big deal but I wonder if there is a cleaner way to achieve a really empty array, I mean; with nothing inside it (it shows 1 row yet, I can not figure out why) but at the right dimensions?

Body:
You need the shape to be (0, 3) so you have the correct number of columns to stack but have actually no data inside:

import numpy as np
pointsarrray = np.empty((0,3))

pointsarrray
# array([], shape=(0, 3), dtype=float64)


问:
How do you iterate through a mixed List<t> and print contents to console in C#?
I have a List<object> which contains strings and even additional lists.

```<code>List<object> NewArray = new List<object>();
</code>```

so basically the list contains a mixture....

As a sanity check, I want to print out the contents to the console.  I start by iterating through and test to see whether the element is a list.  If it isn't then it will be a string and can be printed to the console.  If it is a list, I want to iterate through and print the string contents to the console but with a tab to indent it.

I have this so far:

```<code>    for (int outer = 0; outer < NewArray.Count; outer++)
            {

                var innerList = NewArray[outer];

                if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
                {

                    for (int inner = 0; inner < innerList.Count; inner++)
                    {

                        //print string
                    }
                }
                else
                {
                    //print string
                }
    }
</code>```

I didn't want to use a foreach loop as I'm not sure the order of the list would be guaranteed and will be in the future adding a increment number (which can be provided by the inner and outer variables).

The issue I am getting is an error here:

```<code>inner < innerList.Count
</code>```

which is:

Operator '<' cannot be applied to operands of type 'int' and 'method group'

What do I need to do to overcome this?  I'm not sure it is the most efficient way of achieving the end result but....

答:
If you know your object is a List<> of some generic type, you could always cast to IList and loop through it that way.

To paraphrase your code:

```<code>if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
    var list = (IList)innerList;
    for (int inner = 0; inner < list.Count; inner++)
    {
        Console.WriteLine(list[inner].ToString());
        //print string
    }
}
</code>```

But in reality, you should be doing what itsme86 said, and making strong types with an overriden ToString() or Display() method.

Body:
I have a List<object> which contains strings and even additional lists.

List<object> NewArray = new List<object>();

so basically the list contains a mixture....

As a sanity check, I want to print out the contents to the console.  I start by iterating through and test to see whether the element is a list.  If it isn't then it will be a string and can be printed to the console.  If it is a list, I want to iterate through and print the string contents to the console but with a tab to indent it.

I have this so far:

    for (int outer = 0; outer < NewArray.Count; outer++)
            {

                var innerList = NewArray[outer];

                if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
                {

                    for (int inner = 0; inner < innerList.Count; inner++)
                    {

                        //print string
                    }
                }
                else
                {
                    //print string
                }
    }

I didn't want to use a foreach loop as I'm not sure the order of the list would be guaranteed and will be in the future adding a increment number (which can be provided by the inner and outer variables).

The issue I am getting is an error here:

inner < innerList.Count

which is:

Operator '<' cannot be applied to operands of type 'int' and 'method group'

What do I need to do to overcome this?  I'm not sure it is the most efficient way of achieving the end result but....

Body:
If you know your object is a List<> of some generic type, you could always cast to IList and loop through it that way.

To paraphrase your code:

if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
    var list = (IList)innerList;
    for (int inner = 0; inner < list.Count; inner++)
    {
        Console.WriteLine(list[inner].ToString());
        //print string
    }
}

But in reality, you should be doing what itsme86 said, and making strong types with an overriden ToString() or Display() method.


问:
How do you access an ember data store instance in an integration test?
This is for Ember 2.2.0. I want to test my component with live data from my API server using ember-data not mock data from a test helper, manual AJAX requests, or from a tool like ember-cli-mirage. Currently all I have in my test is this code:

```<code>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('checkbox-group', 'Integration | Component | checkbox group', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{checkbox-group}}`);
  assert.equal(this.$().text().trim(), '');
});
</code>```

What I would like to do is something like this:

```<code>test('it renders', function(assert) {
  const store = getStoreFromSomewhere();
  const model = store.find('data').then(() => {
    this.render(hbs`{{checkbox-group data=model}}`);
    // Do testing on component with model from server
  });
});
</code>```

The problem is I have no idea how to get the store instance, and additionally I don't know how ember does async testing.

The docs have been less than helpful :/. Could someone let me know how to get the store instance, and if that's not possible, another way to do this test with ember-data?

答:
In a moduleForComponent spec I believe the cannonical way to do this is like so:

var store = Ember.getOwner(this).lookup("service:store");

as opposed to:

var store = this.container.lookup('service:store');

And, you can mock it like so inside of a beforeEach:

```<code>this.promise = new Ember.RSVP.Promise((resolve) => {
  var response  = anEmberObject;
  resolve(response);
});

this.storeMock = Ember.Service.extend({
  save: ()=>{
    return this.promise;
  },
  reload: (query)=>{
    return this.promise;
  }
});

Ember.getOwner(this).register('service:store', this.storeMock);
Ember.getOwner(this).inject('component', 'store', 'service:store');
</code>```

Body:
This is for Ember 2.2.0. I want to test my component with live data from my API server using ember-data not mock data from a test helper, manual AJAX requests, or from a tool like ember-cli-mirage. Currently all I have in my test is this code:

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('checkbox-group', 'Integration | Component | checkbox group', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{checkbox-group}}`);
  assert.equal(this.$().text().trim(), '');
});

What I would like to do is something like this:

test('it renders', function(assert) {
  const store = getStoreFromSomewhere();
  const model = store.find('data').then(() => {
    this.render(hbs`{{checkbox-group data=model}}`);
    // Do testing on component with model from server
  });
});

The problem is I have no idea how to get the store instance, and additionally I don't know how ember does async testing.

The docs have been less than helpful :/. Could someone let me know how to get the store instance, and if that's not possible, another way to do this test with ember-data?

Body:
In a moduleForComponent spec I believe the cannonical way to do this is like so:

var store = Ember.getOwner(this).lookup("service:store");

as opposed to:

var store = this.container.lookup('service:store');

And, you can mock it like so inside of a beforeEach:

this.promise = new Ember.RSVP.Promise((resolve) => {
  var response  = anEmberObject;
  resolve(response);
});

this.storeMock = Ember.Service.extend({
  save: ()=>{
    return this.promise;
  },
  reload: (query)=>{
    return this.promise;
  }
});

Ember.getOwner(this).register('service:store', this.storeMock);
Ember.getOwner(this).inject('component', 'store', 'service:store');


问:
Can't get my Ranges set up from my spreadsheet using VBA
My overall goal here is to grab the values and row indices of three different columns on the original spreadsheet, evaluate them, and then save them to a new spreadsheet. I am wanted to accomplish this by using a macro initiated by a button on the original spreadsheet.

The plan to accomplish this was to

create a Range for each column

Loop through the most significant Range to grab and evaluate the each cell      value

perform nested loops within the first loop to further evaluate the other two Ranges and grab their values

assign values to variables

create the new spreadsheet from a template

write the values to the respective columns

save the new spreadsheet

When I run the code below I get the error listed below. I'm confused because I thought this is how you reference an entire column:

```<code>Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  ' Grab data from original spreadsheet
  analysisDate = ActiveWorkbook.Sheets(1).Cells(1, 9).Value

  initial = ActiveWorkbook.Sheets(1).Cells(1, 2).Value
  aInitial = Split(initial, "/")
  analystInit = aInitial(1)

  Set dataRangeA = Range("A4:A").Select ' <-- Line causing error
  Set dataRangeB = Range("B4:B").Select
  Set dataRangeI = Range("I4:I").Select

  For i = 1 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
  Next i

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")

  ActiveWorkbook.Sheets(1).Cells(3, 2).Value = analysisDate
  ActiveWorkbook.Sheets(1).Cells(3, 4).Value = analystInit

  ActiveWorkbook.SaveAs (newsheet & ".xlsx")

End Sub
</code>```

答:
try this:</p>

```<code>Set dataRangeA = Range("A:A").Select
Set dataRangeB = Range("B:B").Select
Set dataRangeI = Range("I:I").Select

For i = 4 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
Next i
</code>```

Body:
My overall goal here is to grab the values and row indices of three different columns on the original spreadsheet, evaluate them, and then save them to a new spreadsheet. I am wanted to accomplish this by using a macro initiated by a button on the original spreadsheet.

The plan to accomplish this was to

create a Range for each column

Loop through the most significant Range to grab and evaluate the each cell      value

perform nested loops within the first loop to further evaluate the other two Ranges and grab their values

assign values to variables

create the new spreadsheet from a template

write the values to the respective columns

save the new spreadsheet

When I run the code below I get the error listed below. I'm confused because I thought this is how you reference an entire column:

Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  ' Grab data from original spreadsheet
  analysisDate = ActiveWorkbook.Sheets(1).Cells(1, 9).Value

  initial = ActiveWorkbook.Sheets(1).Cells(1, 2).Value
  aInitial = Split(initial, "/")
  analystInit = aInitial(1)

  Set dataRangeA = Range("A4:A").Select ' <-- Line causing error
  Set dataRangeB = Range("B4:B").Select
  Set dataRangeI = Range("I4:I").Select

  For i = 1 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
  Next i

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")

  ActiveWorkbook.Sheets(1).Cells(3, 2).Value = analysisDate
  ActiveWorkbook.Sheets(1).Cells(3, 4).Value = analystInit

  ActiveWorkbook.SaveAs (newsheet & ".xlsx")

End Sub

Body:
try this:

Set dataRangeA = Range("A:A").Select
Set dataRangeB = Range("B:B").Select
Set dataRangeI = Range("I:I").Select

For i = 4 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
Next i


问:
'ascii' codec can't encode character u'\xd7' in position 0: ordinal not in range(128)
```<code>import urllib2
import html2text

print 'Please input URL with the text you want to analyze: '
url = raw_input()
page = urllib2.urlopen(url)
html_content = page.read()
print html_content
rendered_content = html2text.html2text(html_content)
f = open('file_text.txt', 'w')
f.write(rendered_content)
f.close()
</code>```

Was trying to save the file to my computer. I know there is a problem with the ASCII

答:
Change from

```<code>html_content = page.read()
</code>```

to

```<code>html_content = page.read().decode(errors='replace')
</code>```

str.decode

Body:
import urllib2
import html2text

print 'Please input URL with the text you want to analyze: '
url = raw_input()
page = urllib2.urlopen(url)
html_content = page.read()
print html_content
rendered_content = html2text.html2text(html_content)
f = open('file_text.txt', 'w')
f.write(rendered_content)
f.close()

Was trying to save the file to my computer. I know there is a problem with the ASCII

Body:
Change from

html_content = page.read()

to

html_content = page.read().decode(errors='replace')

str.decode


问:
Logical Operators not subsetting as expected
I am trying to create a subset of the rows that have a value of 1 for variable A, and a value of 1 for at least one of the following variables: B, C, or D.

```<code>Subset1 <-  subset(Data,
              Data$A==1 &
                Data$B ==1  ||
                Data$C ==1 |
                Data$D == 1,
              select= A)
Subset1
</code>```

The problem is that the code above returns some  rows that have A=0 and I am not sure why.

To troublehsoot:

I know that && and || are the long forms or and and or which vectorizes it.
I have run this code several times using  &&,  ||,& and | in different places. Nothing returns what I am looking for exactly.

When I shorten the code, it works fine and I subset only the rows that I would expect:

Subset1 <- subset(Data,
                       Data$A==1 &
                       Data$B==0,
                      select= A)

Subset1

Unfortunately, this doesn't suffice since I also need to capture rows whose C or D value = 1.
Can anyone explain why my first code block is not subsetting what I am expecting it to?

答:
You can use parens to be more specific about what your & is referring to.  Otherwise (as @Patrick Trentin clarified) your logical operators are combined according to operator precedence (within the same level of precedence they are evaluated from left to right).

Example:

```<code>> FALSE & TRUE | TRUE #equivalent to (FALSE & TRUE) | TRUE
[1] TRUE
> FALSE & (TRUE | TRUE)
[1] FALSE
</code>```

So in your case you can try something like below (assuming you want items that A == 1 & that meet one of the other conditions):

```<code>Data$A==1 & (Data$B==1 | Data$C==1 | Data$D==1)
</code>```

Body:
I am trying to create a subset of the rows that have a value of 1 for variable A, and a value of 1 for at least one of the following variables: B, C, or D.

Subset1 <-  subset(Data,
              Data$A==1 &
                Data$B ==1  ||
                Data$C ==1 |
                Data$D == 1,
              select= A)
Subset1

The problem is that the code above returns some  rows that have A=0 and I am not sure why.

To troublehsoot:

I know that && and || are the long forms or and and or which vectorizes it.
I have run this code several times using  &&,  ||,& and | in different places. Nothing returns what I am looking for exactly.

When I shorten the code, it works fine and I subset only the rows that I would expect:

Subset1 <- subset(Data,
                       Data$A==1 &
                       Data$B==0,
                      select= A)

Subset1

Unfortunately, this doesn't suffice since I also need to capture rows whose C or D value = 1.
Can anyone explain why my first code block is not subsetting what I am expecting it to?

Body:
You can use parens to be more specific about what your & is referring to.  Otherwise (as @Patrick Trentin clarified) your logical operators are combined according to operator precedence (within the same level of precedence they are evaluated from left to right).

Example:

> FALSE & TRUE | TRUE #equivalent to (FALSE & TRUE) | TRUE
[1] TRUE
> FALSE & (TRUE | TRUE)
[1] FALSE

So in your case you can try something like below (assuming you want items that A == 1 & that meet one of the other conditions):

Data$A==1 & (Data$B==1 | Data$C==1 | Data$D==1)


问:
How to switch test provider from MSAA to UIA in custom control for VS Coded UI Test Builder
I am implementing automation providers for some 3-rd party controls, so I can test my application's UI with VS coded ui tests. I am using UI Automation approach for doing this. In standard inspect tools they looked fine, but when I used VS coded UI test builder, all my controls are treated as MSAA in technology name (instead of UIA), so most of my properties are missed. What should I do, so VS Coded UI treated it as UIA?
Here is my code for returning automation provider:

```<code>LRESULT CALLBACK ControlWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_GETOBJECT:
        {
            // If the lParam matches the RootObjectId, send back the RawElementProvider
            if (static_cast<long>(lParam) == static_cast<long>(UiaRootObjectId))
            {
                CustomButton* pControl = reinterpret_cast<CustomButton*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
                IRawElementProviderSimple* pRootProvider = pControl->GetUIAutomationProvider();
                return UiaReturnRawElementProvider(hwnd, wParam, lParam, pRootProvider);
            }

            return 0;
        }
    ...
}
</code>```

This code is called when I used complex automation tool such Ranorex or simply Inspect.exe with UIA mode. But with VS there was no any UiaRootObjectId request.
Instead it call this with lParam == OBJID_CLIENT param. So it returns some default MSAA provider.

UI Control Map snapshot

答:
In case that someone stuck with the same problem, here is a solution I've found. You should create your custom server-side provider, which will be used for your controls class name (it should be VS plugin .dll or something like this).

Your custom provider .dll should be placed to your visual studio directory, after that all your controls in VS coded ui plugin will have technology name, fields and roles that you have described by itself. Example for custom provider can be found on msdn and other resources

Body:
I am implementing automation providers for some 3-rd party controls, so I can test my application's UI with VS coded ui tests. I am using UI Automation approach for doing this. In standard inspect tools they looked fine, but when I used VS coded UI test builder, all my controls are treated as MSAA in technology name (instead of UIA), so most of my properties are missed. What should I do, so VS Coded UI treated it as UIA?
Here is my code for returning automation provider:

LRESULT CALLBACK ControlWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_GETOBJECT:
        {
            // If the lParam matches the RootObjectId, send back the RawElementProvider
            if (static_cast<long>(lParam) == static_cast<long>(UiaRootObjectId))
            {
                CustomButton* pControl = reinterpret_cast<CustomButton*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
                IRawElementProviderSimple* pRootProvider = pControl->GetUIAutomationProvider();
                return UiaReturnRawElementProvider(hwnd, wParam, lParam, pRootProvider);
            }

            return 0;
        }
    ...
}

This code is called when I used complex automation tool such Ranorex or simply Inspect.exe with UIA mode. But with VS there was no any UiaRootObjectId request.
Instead it call this with lParam == OBJID_CLIENT param. So it returns some default MSAA provider.

UI Control Map snapshot


问:
Garbage Collection in Delphi
Does Delphi have Garbage Collection?</p>

答:
Yes, it does.

Delphi Win32 does not include a garbage collector out of the box so the other answers to this question are technically correct. However, this doesn't imply that it isn't possible or that one doesn't already exist. Thanks to Delphi's replaceable memory manager Barry Kelly implemented a fully functional wrapper for the Boehm garbage collector back in 2004.

It includes sample code demonstrating its use (basically creating unassigned objects and watching the GC chew them up). There are more advanced GCs than the Boehm GC but this clearly demonstrates its possible and it can be used almost transparently. You just add the gc unit to the beginning of your project's uses clause.

And while I've not heard of any projects attempting it there is nothing preventing someone from wrapping or porting a more advanced gc.

Title: Garbage Collection in Delphi

Body: Does Delphi have Garbage Collection?