问:
How to get absolute path to file in /resources folder of your project
Assume standard maven setup.

Say in your resources folder you have a file abc.

In Java, how can I get absolute path to the file please?

答:
There are two problems on our way to the absolute path:

The placement found will be not where the source files lie, but
where the class is saved. And the resource folder almost surely will lie somewhere in
the source folder of the project.

The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

```<code>    URL localPackage = this.getClass().getResource("");
    URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
    String localDir = localPackage.getPath();
    String loaderDir = urlLoader.getPath();
    System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
</code>```

Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.

If the project is not in the plugin, the code if run in JUnit, will print:

```<code>loaderDir = /C:.../ws/source.dir/target/test-classes/
 localDir = /C:.../ws/source.dir/target/test-classes/package/
</code>```

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.

If the class is in the package that is in the plugin, the output of the same test will be:

```<code>loaderDir = /C:.../ws/plugin/bin/
 localDir = /C:.../ws/plugin/bin/package/
</code>```

So, again we should go up and down the folder tree.

The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

```<code>loaderDir = /C:.../ws/plugin/
 localDir = /package/
</code>```

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.

Body:
There are two problems on our way to the absolute path:

The placement found will be not where the source files lie, but
where the class is saved. And the resource folder almost surely will lie somewhere in
the source folder of the project.

The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

    URL localPackage = this.getClass().getResource("");
    URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
    String localDir = localPackage.getPath();
    String loaderDir = urlLoader.getPath();
    System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);

Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.

If the project is not in the plugin, the code if run in JUnit, will print:

loaderDir = /C:.../ws/source.dir/target/test-classes/
 localDir = /C:.../ws/source.dir/target/test-classes/package/

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.

If the class is in the package that is in the plugin, the output of the same test will be:

loaderDir = /C:.../ws/plugin/bin/
 localDir = /C:.../ws/plugin/bin/package/

So, again we should go up and down the folder tree.

The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

loaderDir = /C:.../ws/plugin/
 localDir = /package/

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.


来源: stackexchange

问:
putting 3 strings together using strcpy, strcat, sprintf at least once each
My homework problem is to make a program putting 3 strings together using strcpy, strcat, sprintf at least once each.

I'm wondering if I can use all those three without any garbage code. I've tried using strchr to use sprintf for putting strings together, but the pointer location changed so couldn't print out the whole thing.

```<code>char str1[MAX];
char str2[MAX];
char str3[MAX];
char str4[MAX];

gets(str1);
gets(str2);
gets(str3);

strcat(str1, str2);
strchr(str1, '\0');
sprintf(str1, "%s", str3);
strcpy(str4, str1);

puts(str4);
</code>```

I also want to know if there is any difference in their use between strcpy and sprintf in this case.

答:
This doesn't do anything: strchr(str1,'\0'). Read the documentation of strchar carefully. But you don't need strchr here anyway, you proably just want this:

```<code>...
gets(str1);
gets(str2);
gets(str3);

strcpy(str4, str1);   // copy str1 into str4
strcat(str4, str2);   // append str2 to str4
strcat(str4, str3);   // append str3 to str4

puts(str4);           // print str4
</code>```

As you can see, you don't need sprintf either.

But you can do the same thing using only sprintf

```<code>...
gets(str1);
gets(str2);
gets(str3);
sprintf(str4, "%s%s%s", str1, str2, str3);
puts(str4);
</code>```

but then you don't need strcpy nor strcat.

Using all strcpy, strcat and sprintf is a somewhat pointless requirement, but now you should be able to do it.

ContentLicense: CC BY-SA 4.0

Body:
My homework problem is to make a program putting 3 strings together using strcpy, strcat, sprintf at least once each.

I'm wondering if I can use all those three without any garbage code. I've tried using strchr to use sprintf for putting strings together, but the pointer location changed so couldn't print out the whole thing.

char str1[MAX];
char str2[MAX];
char str3[MAX];
char str4[MAX];

gets(str1);
gets(str2);
gets(str3);

strcat(str1, str2);
strchr(str1, '\0');
sprintf(str1, "%s", str3);
strcpy(str4, str1);

puts(str4);

I also want to know if there is any difference in their use between strcpy and sprintf in this case.

Body:
This doesn't do anything: strchr(str1,'\0'). Read the documentation of strchar carefully. But you don't need strchr here anyway, you proably just want this:

...
gets(str1);
gets(str2);
gets(str3);

strcpy(str4, str1);   // copy str1 into str4
strcat(str4, str2);   // append str2 to str4
strcat(str4, str3);   // append str3 to str4

puts(str4);           // print str4

As you can see, you don't need sprintf either.

But you can do the same thing using only sprintf

...
gets(str1);
gets(str2);
gets(str3);
sprintf(str4, "%s%s%s", str1, str2, str3);
puts(str4);

but then you don't need strcpy nor strcat.

Using all strcpy, strcat and sprintf is a somewhat pointless requirement, but now you should be able to do it.


问:
Why is the openquery returning 0 rows on SQL server but has 900k rows in the target Server?
Need help to figure ut why the remote query I execute on the server return 0 rows , but the same query returns over 900k rows in the target DB.

the string is less 8000 characters long so I won't post it here.  but this is the sctructure basically:

```<code>declare @SQL varchar(MAX);
declare @D varchar(15);
declare @Per varchar(15);
declare @NextPer varchar(15);
declare @NextYPer varchar(15);
set @D = N'01-JUN-2019'
set @Per = N'2020004';
set @NextYPer = N'2021004'
set @NextPer = N'2020005'
set @SQL = N' SELECT  ...... '
set @SQL = N'select * from openquery ([LK1], "'+@SQL+'")';
execute( @SQL);
print @SQL;
</code>```

Note: the linked server works and is used on other openqueries with shorter strings successfully. I tried using EXECUTE (@SQL) AT  and I still get 0 rows.  When i exexute the print output directly on the Oracle DB , the query runs for about 15 min and gives results.

答:
First off, OPENQUERY requires the second parameter to be a query string. A string in SQL Server is written between single quotes. From OPENQUERY documentation:

```<code>OPENQUERY ( linked_server ,'query' )
</code>```

Not only that, the SQL that appears in that string, needs to have any single-quotes that appear in the query to be doubled. Suppose you had SQL you wanted to execute the following query:

```<code>SELECT * FROM some_table WHERE name='TT.';
</code>```

You would write this as:

```<code>OPENQUERY(lks,'SELECT * FROM some_table WHERE name=''TT.''')
</code>```

But if you have this in a dynamic SQL statement, this would become

```<code>DECLARE @s VARCHAR(MAX);
SET @s='SELECT * FROM OPENQUERY(lks,''SELECT * FROM some_table WHERE name=''''TT.'''''')';
</code>```

So that's some explosion of single quotes for even the more trivial SQL queries. Count ye quotes, make sure the query itself is up to snuff (i.e. quotes have been properly doubled).

Body:
Need help to figure ut why the remote query I execute on the server return 0 rows , but the same query returns over 900k rows in the target DB.

the string is less 8000 characters long so I won't post it here.  but this is the sctructure basically:

declare @SQL varchar(MAX);
declare @D varchar(15);
declare @Per varchar(15);
declare @NextPer varchar(15);
declare @NextYPer varchar(15);
set @D = N'01-JUN-2019'
set @Per = N'2020004';
set @NextYPer = N'2021004'
set @NextPer = N'2020005'
set @SQL = N' SELECT  ...... '
set @SQL = N'select * from openquery ([LK1], "'+@SQL+'")';
execute( @SQL);
print @SQL;

Note: the linked server works and is used on other openqueries with shorter strings successfully. I tried using EXECUTE (@SQL) AT  and I still get 0 rows.  When i exexute the print output directly on the Oracle DB , the query runs for about 15 min and gives results.

Body:
First off, OPENQUERY requires the second parameter to be a query string. A string in SQL Server is written between single quotes. From OPENQUERY documentation:

OPENQUERY ( linked_server ,'query' )

Not only that, the SQL that appears in that string, needs to have any single-quotes that appear in the query to be doubled. Suppose you had SQL you wanted to execute the following query:

SELECT * FROM some_table WHERE name='TT.';

You would write this as:

OPENQUERY(lks,'SELECT * FROM some_table WHERE name=''TT.''')

But if you have this in a dynamic SQL statement, this would become

DECLARE @s VARCHAR(MAX);
SET @s='SELECT * FROM OPENQUERY(lks,''SELECT * FROM some_table WHERE name=''''TT.'''''')';

So that's some explosion of single quotes for even the more trivial SQL queries. Count ye quotes, make sure the query itself is up to snuff (i.e. quotes have been properly doubled).


问:
cocos2d/box2d trouble
I have just started working with cocos2d and box2d for iOS SDK, and have a few problems. I got the templates working, and got the test app (the one where you click the screen and a box with a random letter appears) to compile.

My first problem is that I can't figure out how to get a blank template. Is there a quick way to do this when I begin a new app?

My second problem is that I can't figure out how to just simply change the color of an object. I can define something like this:

```<code>b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape circle;
circle.m_radius = .5f;//These are mid points for our 1m box

b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.3f;
body->CreateFixture(&fixtureDef);
</code>```

But is there a simple way to make something a certain color?

Final question: does this sample app have the accelerometer-gravity enabled?

Thanks!

答:
For making a certain body a specific color, assign 'userData' to the body. userData is your sprite with specific color you wanted

And reply to your final answer is YES.

ContentLicense: CC BY-SA 2.5

Title: cocos2d/box2d trouble

Body:
I have just started working with cocos2d and box2d for iOS SDK, and have a few problems. I got the templates working, and got the test app (the one where you click the screen and a box with a random letter appears) to compile.

My first problem is that I can't figure out how to get a blank template. Is there a quick way to do this when I begin a new app?

My second problem is that I can't figure out how to just simply change the color of an object. I can define something like this:

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape circle;
circle.m_radius = .5f;//These are mid points for our 1m box

b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.3f;
body->CreateFixture(&fixtureDef);

But is there a simple way to make something a certain color?

Final question: does this sample app have the accelerometer-gravity enabled?

Thanks!

ContentLicense: CC BY-SA 3.0


问:
ImportError: No module named _sqlite3
I'm writing for the Google App Engine and my local tests are getting the following error:

```<code>-->  --> -->

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3185, in _HandleRequest
    self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3128, in _Dispatch
    base_env_dict=env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 515, in Dispatch
    base_env_dict=base_env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2387, in Dispatch
    self._module_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2297, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2193, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "C:\Users\Chris Reade\Documents\SI 182\Final\geneticsalesman\Final.py", line 7, in <module>
    from pyevolve import DBAdapters
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1922, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1824, in FindAndLoadModule
    description)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1775, in LoadModuleRestricted
    description)
  File "C:\Users\Chris Reade\Documents\SI 182\Final\geneticsalesman\pyevolve\DBAdapters.py", line 21, in <module>
    import sqlite3
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1922, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1824, in FindAndLoadModule
    description)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1775, in LoadModuleRestricted
    description)
  File "C:\Python26\lib\sqlite3\__init__.py", line 24, in <module>
    from dbapi2 import *
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1922, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1824, in FindAndLoadModule
    description)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1775, in LoadModuleRestricted
    description)
  File "C:\Python26\lib\sqlite3\dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
</code>```

My python direction has a lib file for sqlite3 but I can't tell why it can't find it. Any help would be greatly appreciated.

答:
App engine tries to raise an error when one wanted to use sqlite3 for the first time. This happens not because App engine (local) doesn't allow the use of sqlite3 as an alternate database, this is because the sqlite3 is not supported at a production level. So App engine is doing its based to discourage you from using the sqlite3 so that you won't mistake deploying the App with sqlite3.

So to use sqlite3 in your local App Engine, you need to white list the sqlite3 as follows:

go to C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\python\runtime\sandbox.py

Open the file and you'll find a constant variable _WHITE_LIST_C_MODULES declared as:

```<code>  _WHITE_LIST_C_MODULES = [
        'array',
        '_ast',
        'binascii',
        '_bisect',
         .
         .
         .,
]
</code>```

Then add sqlite3 as follows:

```<code>  _WHITE_LIST_C_MODULES = [
                'array',
                '_ast',
                'binascii',
                '_bisect',
                 .
                 .
                 .,
                _sqlite3,
        ]
</code>```

I hope this will work for you.

Title: ImportError: No module named _sqlite3

Body:
I'm writing for the Google App Engine and my local tests are getting the following error:

-->  --> -->

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3185, in _HandleRequest
    self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3128, in _Dispatch
    base_env_dict=env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 515, in Dispatch
    base_env_dict=base_env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2387, in Dispatch
    self._module_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2297, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2193, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "C:\Users\Chris Reade\Documents\SI 182\Final\geneticsalesman\Final.py", line 7, in <module>
    from pyevolve import DBAdapters
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1922, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1824, in FindAndLoadModule
    description)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1775, in LoadModuleRestricted
    description)
  File "C:\Users\Chris Reade\Documents\SI 182\Final\geneticsalesman\pyevolve\DBAdapters.py", line 21, in <module>
    import sqlite3
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1922, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1824, in FindAndLoadModule
    description)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1775, in LoadModuleRestricted
    description)
  File "C:\Python26\lib\sqlite3\__init__.py", line 24, in <module>
    from dbapi2 import *
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1922, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1824, in FindAndLoadModule
    description)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1272, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1775, in LoadModuleRestricted
    description)
  File "C:\Python26\lib\sqlite3\dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3

My python direction has a lib file for sqlite3 but I can't tell why it can't find it. Any help would be greatly appreciated.

Body:
App engine tries to raise an error when one wanted to use sqlite3 for the first time. This happens not because App engine (local) doesn't allow the use of sqlite3 as an alternate database, this is because the sqlite3 is not supported at a production level. So App engine is doing its based to discourage you from using the sqlite3 so that you won't mistake deploying the App with sqlite3.

So to use sqlite3 in your local App Engine, you need to white list the sqlite3 as follows:

go to C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\python\runtime\sandbox.py

Open the file and you'll find a constant variable _WHITE_LIST_C_MODULES declared as:

  _WHITE_LIST_C_MODULES = [
        'array',
        '_ast',
        'binascii',
        '_bisect',
         .
         .
         .,
]

Then add sqlite3 as follows:

  _WHITE_LIST_C_MODULES = [
                'array',
                '_ast',
                'binascii',
                '_bisect',
                 .
                 .
                 .,
                _sqlite3,
        ]

I hope this will work for you.


问:
Uploading APK file using Selenium
I'm struggling with one problem in my test. I'm trying to upload an APK file, but when it comes to that step, nothing happens.

I've already tried simple sendKeys with path to the file and using AutoIT script, but both of them don't work.

Here is input:

```<code><button uib-tooltip-html="uploadTooltip" ng-if="(privileges.update && !uploadForm.$visible) || createNew" ng-click="this.value = null;" ng-file-select="uploadFile($files, uploadForm)" class="btn btn-xs btn-default ng-scope ng-isolate-scope" ng-disabled="status.disabled || progressPercentage" type="button" style="overflow: hidden;">
<i class="fa fa-fw fa-upload"></i>
        <input type="file" tabindex="-1" ng-file-generated-elem="true" style="width: 1px; height: 1px; opacity: 0; position: absolute; padding: 0px; margin: 0px; overflow: hidden;">
<input type="file" tabindex="-1" ng-file-generated-elem="true" style="width: 1px; height: 1px; opacity: 0; position: absolute; padding: 0px; margin: 0px; overflow: hidden;">
</button>
</code>```

And what I tried(also using string with a full path for sendKeys):

```<code>String filePath = System.getProperty("user.dir") + "src\\test\\APK\\com.airbnb.android.apk";
        tryToClearAndSendKeysForSeconds(5, UPLOAD_FILE_BUTTON, filePath); // method for sendKeys with wait, locator and string
</code>```

```<code>Runtime.getRuntime().exec("C:\\Users\\IdeaProjects\\Automated_Tests\\src\\test\\APK\\FileUpload.exe");
</code>```

AutoIT:

```<code>ControlFocus(“Open”,””,”Edit1″)
ControlSetText(“Open”,””,”Edit1″,”D:\HDimage\profile.jpeg”)
ControlClick(“Open”,””,”Button1″)
</code>```

I'm not sure if I am supposed to click upload button before sending a file when it comes to sendKeys, but when I do this (I'm using win 10 btw):

Will appreciate any help!

答:
Please follow steps to upload APK or any file:

a) Upload your file in tmp directory on server for temporary backup. like

```<code>String path = FILE_UPLOAD_COMMON_PATH + File.separatorChar + file.getName();

try(FileOutputStream fileOutputStream = new FileOutputStream(path)){
    fileOutputStream.write(bs); // byte[] bs
}catch(Exception e) {
    throw e;
}
</code>```

b) Now get from tmp directory and upload file using driver like,

```<code>String path = FILE_UPLOAD_COMMON_PATH + File.separatorChar + file.getName();
driver.findElements(By.id("files")).get(0).sendKeys(path);
</code>```

May it will solve your problem.

Title: Uploading APK file using Selenium

Body:
I'm struggling with one problem in my test. I'm trying to upload an APK file, but when it comes to that step, nothing happens.

I've already tried simple sendKeys with path to the file and using AutoIT script, but both of them don't work.

Here is input:

<button uib-tooltip-html="uploadTooltip" ng-if="(privileges.update && !uploadForm.$visible) || createNew" ng-click="this.value = null;" ng-file-select="uploadFile($files, uploadForm)" class="btn btn-xs btn-default ng-scope ng-isolate-scope" ng-disabled="status.disabled || progressPercentage" type="button" style="overflow: hidden;">

        <input type="file" tabindex="-1" ng-file-generated-elem="true" style="width: 1px; height: 1px; opacity: 0; position: absolute; padding: 0px; margin: 0px; overflow: hidden;">
<input type="file" tabindex="-1" ng-file-generated-elem="true" style="width: 1px; height: 1px; opacity: 0; position: absolute; padding: 0px; margin: 0px; overflow: hidden;">
</button>

And what I tried(also using string with a full path for sendKeys):

String filePath = System.getProperty("user.dir") + "src\\test\\APK\\com.airbnb.android.apk";
        tryToClearAndSendKeysForSeconds(5, UPLOAD_FILE_BUTTON, filePath); // method for sendKeys with wait, locator and string

Runtime.getRuntime().exec("C:\\Users\\IdeaProjects\\Automated_Tests\\src\\test\\APK\\FileUpload.exe");

AutoIT:

ControlFocus(“Open”,””,”Edit1″)
ControlSetText(“Open”,””,”Edit1″,”D:\HDimage\profile.jpeg”)
ControlClick(“Open”,””,”Button1″)

I'm not sure if I am supposed to click upload button before sending a file when it comes to sendKeys, but when I do this (I'm using win 10 btw):

Will appreciate any help!

Body:
Please follow steps to upload APK or any file:

a) Upload your file in tmp directory on server for temporary backup. like

String path = FILE_UPLOAD_COMMON_PATH + File.separatorChar + file.getName();

try(FileOutputStream fileOutputStream = new FileOutputStream(path)){
    fileOutputStream.write(bs); // byte[] bs
}catch(Exception e) {
    throw e;
}

b) Now get from tmp directory and upload file using driver like,

String path = FILE_UPLOAD_COMMON_PATH + File.separatorChar + file.getName();
driver.findElements(By.id("files")).get(0).sendKeys(path);

May it will solve your problem.


问:
Partition table without Incremental Update Statistics
Do I have to enable incremental update statistics when I want to have partitions on my table? Are there any automatic mechanisms  that will update statistics on my table utomatically?</p>

答:
From SQL Server Auto Update and Auto Create Statistics Options

The statistics are automatically created for each new index.

If the    database setting AUTO_CREATE_STATISTICS is on, then the SQL
Server    will automatically create statistics for non-indexed
columns that are    used in your queries.


问:
What method can I use to get a different date value for a stored field in my database?
I am working on a project that is asking me to return different date values based on the scenario and I am not quite sure how to write this out. I think that I'm just not understanding how to apply the logic:

PAYFREQ is A then TRANS_DATE is 1st of the Year of COMPEFFDT

PAYFREQ is M then TRANS_DATE is 1st of the Month of COMPEFFDT

PAYFREQ is B then 1st day of the biweekly period ending with COMPEFFDT

PAYFREQ  <> A and the only non-zero FIC amount for a calendar year has COMPEFFDT of December 31, then TRANS DATE is 1st of the Year of COMPEFFDT

Can anyone give me at least a base starting point in how to formulate this statement?

答:
Assuming this is in a query, try the SWITCH statement. I'm not sure what you mean by the "1st of year of COMPEFFDT" though.

SELECT SWITCH (
               PAYFREQ = "A", "1st of year of COMPEFFDT",
               PAYFREQ = "M", "1st of the Month of COMPEFFDT",
               ...
              ) AS Result

Also, you should look at the guide for submitted a new question.


问:
How to make Azure API Management (API Gateway) CORS policy dynamic?
I want to add domains(Origins) in allowed-origins section dynamically in Azure API gateway. Is it possible ? Or is there another way we can setup the CORS, so that we can allow origins dynamically. </p>

```<code>    <cors>
        <allowed-origins>
            <origin>http://www.example.com</origin>
        </allowed-origins>
        <allowed-methods>
            <method>GET</method>
            <method>POST</method>
        </allowed-methods>
    </cors>
</code>```

答:
I found one way that I'm mentioning bellow.

```<code><inbound>
    <base />
    <send-request mode="new" response-variable-name="variable" timeout="600" ignore-error="true">
        <set-url>@("http://MyDomain/ApiMethod?Origin="(string)context.Request.Headers["Origin"].Last())</set-url>
        <set-method>GET</set-method>
        <set-body />
    </send-request>
    <cors>
        <allowed-origins>
            <origin>@((string)((IResponse)context.Variables["variable"]).Body.As<JObject>(true)["Origin"])</origin>
        </allowed-origins>
        <allowed-methods>
            <method>GET</method>
            <method>POST</method>
        </allowed-methods>
    </cors>
</inbound
</code>```

First called a API which takes the Origin as query parameter.

stored the response in variable parameter.

API Returns Json Object
eg: { "Origin": "http://www.example.com" }

Form the response I retrieve the Origin Value. and assign it to <origin></origin>

Body:
I want to add domains(Origins) in allowed-origins section dynamically in Azure API gateway. Is it possible ? Or is there another way we can setup the CORS, so that we can allow origins dynamically.

    <cors>
        <allowed-origins>
            <origin>http://www.example.com</origin>
        </allowed-origins>
        <allowed-methods>
            <method>GET</method>
            <method>POST</method>
        </allowed-methods>
    </cors>

Body:
I found one way that I'm mentioning bellow.

<inbound>
    <base />
    <send-request mode="new" response-variable-name="variable" timeout="600" ignore-error="true">
        <set-url>@("http://MyDomain/ApiMethod?Origin="(string)context.Request.Headers["Origin"].Last())</set-url>
        <set-method>GET</set-method>
        <set-body />
    </send-request>
    <cors>
        <allowed-origins>
            <origin>@((string)((IResponse)context.Variables["variable"]).Body.As<JObject>(true)["Origin"])</origin>
        </allowed-origins>
        <allowed-methods>
            <method>GET</method>
            <method>POST</method>
        </allowed-methods>
    </cors>
</inbound

First called a API which takes the Origin as query parameter.

stored the response in variable parameter.

API Returns Json Object
eg: { "Origin": "http://www.example.com" }

Form the response I retrieve the Origin Value. and assign it to <origin></origin>


问:
What is the difference between sqlite3 and sqlalchemy?
Beginner question- what is the difference between sqlite and sqlalchemy? </p>

答:
sqlite3 is a embedded RDBMS.

According to this article :

A relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. Most popular commercial and open source databases currently in use are based on the relational database model.
  A short definition of an RDBMS may be a DBMS in which data is stored in the form of tables and the relationship among the data is also stored in the form of tables.

SQLAlchemy is a Python ORM.

According to this article :

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.


问:
Pandas date range returns "could not convert string to Timestamp" for yyyy-ww
I have a dataframe with two columns; Sales and Date.

```<code>dataset.head(10)

        Date    Sales
0   2015-01-02  34988.0
1   2015-01-03  32809.0
2   2015-01-05  9802.0
3   2015-01-06  15124.0
4   2015-01-07  13553.0
5   2015-01-08  14574.0
6   2015-01-09  20836.0
7   2015-01-10  28825.0
8   2015-01-12  6938.0
9   2015-01-13  11790.0
</code>```

I want to convert the Date column from yyyy-mm-dd (e.g. 2015-06-01) to yyyy-ww (e.g. 2015-23), so I run the following piece of code:

```<code>dataset["Date"] = pd.to_datetime(dataset["Date"]).dt.strftime('%Y-%V')
</code>```

Then I group by my Sales based on weeks, i.e.

```<code>data = dataset.groupby(['Date'])["Sales"].sum().reset_index()

data.head(10)

    Date    Sales
0   2015-01 67797.0
1   2015-02 102714.0
2   2015-03 107011.0
3   2015-04 121480.0
4   2015-05 148098.0
5   2015-06 132152.0
6   2015-07 133914.0
7   2015-08 136160.0
8   2015-09 185471.0
9   2015-10 190793.0
</code>```

Now I want to create a date range based on the Date column, since I'm predicting sales based on weeks:

```<code>ds = data.Date.values
ds_pred = pd.date_range(start=ds.min(), periods=len(ds) + num_pred_weeks,
freq="W")
</code>```

However I'm getting the following error: could not convert string to Timestamp which I'm not really sure how to fix. So, if I use 2015-01-01 as the starting date of my date-import I get no error, which makes me realize that I'm using the functions wrong. However, I'm not sure how?

I would like to basically have a date range that spans weekly from the current week and then 52 weeks into the future.

答:
If ds contains dates as string formatted as '2015-01' which should be '%Y-%W' (or '%G-%V' in datetime library) you have to add a day number to obtain a day. Here, assuming that you want the monday you should to:

```<code>ds_pred = pd.date_range(start=pd.to_datetime(ds.min() + '-1', format='%Y-%W-%w',
                                             periods=len(ds) + num_pred_weeks, freq="W")
</code>```

Body:
I have a dataframe with two columns; Sales and Date.

dataset.head(10)

        Date    Sales
0   2015-01-02  34988.0
1   2015-01-03  32809.0
2   2015-01-05  9802.0
3   2015-01-06  15124.0
4   2015-01-07  13553.0
5   2015-01-08  14574.0
6   2015-01-09  20836.0
7   2015-01-10  28825.0
8   2015-01-12  6938.0
9   2015-01-13  11790.0

I want to convert the Date column from yyyy-mm-dd (e.g. 2015-06-01) to yyyy-ww (e.g. 2015-23), so I run the following piece of code:

dataset["Date"] = pd.to_datetime(dataset["Date"]).dt.strftime('%Y-%V')

Then I group by my Sales based on weeks, i.e.

data = dataset.groupby(['Date'])["Sales"].sum().reset_index()

data.head(10)

    Date    Sales
0   2015-01 67797.0
1   2015-02 102714.0
2   2015-03 107011.0
3   2015-04 121480.0
4   2015-05 148098.0
5   2015-06 132152.0
6   2015-07 133914.0
7   2015-08 136160.0
8   2015-09 185471.0
9   2015-10 190793.0

Now I want to create a date range based on the Date column, since I'm predicting sales based on weeks:

ds = data.Date.values
ds_pred = pd.date_range(start=ds.min(), periods=len(ds) + num_pred_weeks,
freq="W")

However I'm getting the following error: could not convert string to Timestamp which I'm not really sure how to fix. So, if I use 2015-01-01 as the starting date of my date-import I get no error, which makes me realize that I'm using the functions wrong. However, I'm not sure how?

I would like to basically have a date range that spans weekly from the current week and then 52 weeks into the future.

Body:
If ds contains dates as string formatted as '2015-01' which should be '%Y-%W' (or '%G-%V' in datetime library) you have to add a day number to obtain a day. Here, assuming that you want the monday you should to:

ds_pred = pd.date_range(start=pd.to_datetime(ds.min() + '-1', format='%Y-%W-%w',
                                             periods=len(ds) + num_pred_weeks, freq="W")


问:
how to convert date to date drop down and drop down could be separate day, month,year
]2

  Date of birth:
  <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth">

```

i am getting data from database by using django and i am trying to show in drop down date but i am getting date table

答:
Are you looking for something like this?

If you are.. not a good idea <3

<select name='day'>
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4'>4</option>
  <option value='5'>5</option>
  <option value='6'>6</option>
  <option value='7'>7</option>
  <option value='8'>8</option>
  <option value='9'>9</option>
  <option value='10'>10</option>
  <option value='11'>11</option>
  <option value='12'>12</option>
  <option value='13'>13</option>
  <option value='14'>14</option>
  <option value='15'>15</option>
  <option value='16'>16</option>
  <option value='17'>17</option>
  <option value='18'>18</option>
  <option value='19'>19</option>
  <option value='20'>20</option>
  <option value='21'>21</option>
  <option value='22'>22</option>
  <option value='23'>23</option>
  <option value='24'>24</option>
  <option value='25'>25</option>
  <option value='26'>26</option>
  <option value='27'>27</option>
  <option value='28'>28</option>
  <option value='29'>29</option>
  <option value='30'>30</option>
  <option value='31'>31</option>
</select>

<select name='month'>
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4'>4</option>
  <option value='5'>5</option>
  <option value='6'>6</option>
  <option value='7'>7</option>
  <option value='8'>8</option>
  <option value='9'>9</option>
  <option value='10'>10</option>
  <option value='11'>11</option>
  <option value='12'>12</option>
</select>

<select name='day'>
  <option value='2019'>2019</option>
  <option value='2018'>2018</option>
  <option value='2017'>2017</option>
  <option value='2016'>2016</option>
  <option value='2015'>2015</option>
  <option value='2014'>2014</option>
  <option value='2013'>2013</option>
  <option value='2012'>2012</option>
  <option value='2011'>2011</option>
  <option value='2010'>2010</option>
  <option value='2009'>2009</option>
  <option value='2008'>2008</option>
  <option value='2007'>2007</option>
  <option value='2006'>2006</option>
  <option value='2005'>2005</option>
  <option value='2004'>2004</option>
  <option value='2003'>2003</option>
  <option value='2002'>2002</option>
  <option value='2001'>2001</option>
  <option value='2000'>2000</option>
  <option value='1999'>1999</option>
  <option value='1998'>1998</option>
  <option value='1997'>1997</option>
  <option value='1996'>1996</option>
  <option value='1995'>1995</option>
  <option value='1994'>1994</option>
  <option value='1993'>1993</option>
  <option value='1992'>1992</option>
  <option value='1991'>1991</option>
  <option value='1990'>1990</option>
</select>```

Body:
]2

  Date of birth:
  <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth">

i am getting data from database by using django and i am trying to show in drop down date but i am getting date table


问:
Using FORFILES in a FOR loop and trying to override the error
I'm writing a for loop to execute the forfiles command on both .xml and .psr files. Currently, if it finds one file type but not the other, it will display "ERROR: No files found with the specified search criteria", but I want the error to say which file type wasn't found. I have an if statement inside the for loop that's supposed to override the error, but it's not working. Here's the loop:

```<code>FOR %%G IN (.xml, .psr) DO (
    FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE"
    IF %ERRORLEVEL% NEQ 0 (
        ECHO No matches found for %%G files older than %days% days
    )
)
</code>```

Edit: Thanks for the answers. My for loop now works as intended and ended up looking like this:

```<code>FOR %%G IN (.xml, .psr) DO (
    FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE" >nul 2>nul
    IF ERRORLEVEL 1 (
        ECHO No %%G files %days% days old or older were found.
    ) ELSE (
        ECHO %%G files as old as %days% days or older have been deleted.
    )
)
</code>```

答:
Standard delayed expansion error - You need to invoke delayedexpansion [hundreds of SO articles about that - use the search feature] in order to display or use the run-time value of any variable that's changed within a parenthesised series of instructions (aka "code block").

```<code>IF %ERRORLEVEL% NEQ 0 (
</code>```

is the problem - errorlevel is replaced by its value when the for is encountered.

The easy way around this is to use conventional errorlevel processing:

```<code>if errorlevel 1 (
</code>```

ie. if errorlevel is (1 or greater than 1)

As for the message, try 2>nul to redirect errormessages to nul OR use

```<code>if exist "%xmldir%\%%G" (forfiles...
 ) else (echo no %%G files found)
</code>```

Body:
I'm writing a for loop to execute the forfiles command on both .xml and .psr files. Currently, if it finds one file type but not the other, it will display "ERROR: No files found with the specified search criteria", but I want the error to say which file type wasn't found. I have an if statement inside the for loop that's supposed to override the error, but it's not working. Here's the loop:

FOR %%G IN (.xml, .psr) DO (
    FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE"
    IF %ERRORLEVEL% NEQ 0 (
        ECHO No matches found for %%G files older than %days% days
    )
)

Edit: Thanks for the answers. My for loop now works as intended and ended up looking like this:

FOR %%G IN (.xml, .psr) DO (
    FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE" >nul 2>nul
    IF ERRORLEVEL 1 (
        ECHO No %%G files %days% days old or older were found.
    ) ELSE (
        ECHO %%G files as old as %days% days or older have been deleted.
    )
)

Body:
Standard delayed expansion error - You need to invoke delayedexpansion [hundreds of SO articles about that - use the search feature] in order to display or use the run-time value of any variable that's changed within a parenthesised series of instructions (aka "code block").

IF %ERRORLEVEL% NEQ 0 (

is the problem - errorlevel is replaced by its value when the for is encountered.

The easy way around this is to use conventional errorlevel processing:

if errorlevel 1 (

ie. if errorlevel is (1 or greater than 1)

As for the message, try 2>nul to redirect errormessages to nul OR use

if exist "%xmldir%\%%G" (forfiles...
 ) else (echo no %%G files found)


问:
Getting error when adding firebase to my Android project
I am adding Firebase to my app, to use Crashlytics. That's nice, but when I followed official guide to install it, I got error from Gradle, that google play services not found. Why it's telling me not found?

My app is running latest Gradle "v3.4.1", and I searched for this problem, and got this answer:

So as a quick fix I added another repository, that has it:

```<code>repositories {
    maven { url 'https://dl.bintray.com/android/android-tools' }
}

</code>```

Link: Error: could not find com.google.gms:google-services:4.2.0

But that didn't help me, still getting not found error.

Here is my Gradle config files:

Project gradle:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        // Check for v3.1.2 or higher
        classpath 'com.google.gms.google-services:4.2.0'

        // Add dependency
        classpath 'io.fabric.tools:gradle:1.29.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
            google()
            jcenter()
            maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

App Gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.developerfromjokela.edison"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 42
        versionName "3.4-BETA12"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-vector-drawable:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    // Older okhttp because not working on android 4.0 for new versions
    //noinspection GradleDependency
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1"
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.thoughtbot:expandablerecyclerview:1.4'
    implementation 'org.jsoup:jsoup:1.11.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation "com.android.support:support-emoji:28.0.0"
    implementation 'io.github.lizhangqu:coreprogress:1.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.9'
}

apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

</code>```

Error from Gradle:

```<code>ERROR: Could not find com.google.gms.google-services:4.2.0:.
Required by:
    project :
Search in build.gradle files

</code>```

答:
Because google-services:4.2.0 is not available at Central Repository, so it needs to be downloaded from Android Tools Repository. To add this to your project add
this to build-script repositories. For more refer to https://mvnrepository.com/artifact/com.google.gms/google-services/4.2.0

```<code>buildscript {
    repositories {
        jcenter()
        google()
        maven {
            url 'https://maven.fabric.io/public'
        }
        //  Add this to your project
        maven { url 'https://dl.bintray.com/android/android-tools' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.2.0'

        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.27.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
        }
        google()
    }
}
</code>```

And in your app level build file, the Google-service plugin moves to the bottom.

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

Body:
I am adding Firebase to my app, to use Crashlytics. That's nice, but when I followed official guide to install it, I got error from Gradle, that google play services not found. Why it's telling me not found?

My app is running latest Gradle "v3.4.1", and I searched for this problem, and got this answer:

So as a quick fix I added another repository, that has it:

repositories {
    maven { url 'https://dl.bintray.com/android/android-tools' }
}

Link: Error: could not find com.google.gms:google-services:4.2.0

But that didn't help me, still getting not found error.

Here is my Gradle config files:

Project gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        // Check for v3.1.2 or higher
        classpath 'com.google.gms.google-services:4.2.0'

        // Add dependency
        classpath 'io.fabric.tools:gradle:1.29.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
            google()
            jcenter()
            maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.developerfromjokela.edison"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 42
        versionName "3.4-BETA12"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-vector-drawable:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    // Older okhttp because not working on android 4.0 for new versions
    //noinspection GradleDependency
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1"
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.thoughtbot:expandablerecyclerview:1.4'
    implementation 'org.jsoup:jsoup:1.11.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation "com.android.support:support-emoji:28.0.0"
    implementation 'io.github.lizhangqu:coreprogress:1.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.9'
}

apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

Error from Gradle:

ERROR: Could not find com.google.gms.google-services:4.2.0:.
Required by:
    project :
Search in build.gradle files

Body:
Because google-services:4.2.0 is not available at Central Repository, so it needs to be downloaded from Android Tools Repository. To add this to your project add
this to build-script repositories. For more refer to https://mvnrepository.com/artifact/com.google.gms/google-services/4.2.0

buildscript {
    repositories {
        jcenter()
        google()
        maven {
            url 'https://maven.fabric.io/public'
        }
        //  Add this to your project
        maven { url 'https://dl.bintray.com/android/android-tools' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.2.0'

        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.27.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
        }
        google()
    }
}

And in your app level build file, the Google-service plugin moves to the bottom.

apply plugin: 'com.google.gms.google-services'


问:
PHP cURL, extract an XML response
I am invoking PHP cURL method on a server and the response is XML type. cURL is saving the output (after removing the tags) in a scalar type variable. Is there a way to store it in an object/hash/array so that it's easy to parse?</p>

答:
```<code><?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}
</code>```

OwnerDisplayName: Rakesh

Title: PHP cURL, extract an XML response

OwnerDisplayName: Alan Storm


问:
Implementing an iterator for a stack
I defined an interface StringStack

```<code>public interface StringStack{
    //add a value to the stack
    public void push(String value);
    //fetch top-most element of the stack. element is removed
    public String pop();
    //fetch top-most element of the stack. element is not removed
    public String peek();
}
</code>```

Further I defined a class SimpleStack that uses an ArrayList to manage the stack

```<code>public class SimpleStack implements StringStack{
    private ArrayList<String> list = new ArrayList<String>();

    public void push(String value){
        list.add(value);
    }

    public String pop(){
        if(!list.isEmpty()){
                return list.remove(list.size() - 1);
        }else{
                return null;
        }
    }

   public String peek(){
        if(!list.isEmpty()){
                return list.get(list.size() - 1);
        }else{
                return null;
        }
}
</code>```

Now I want define an iterator for my stack class but I don't want to use the built-in ArrayList iterator. So I came up implementing a inner class and extending my SimpleStack with the Iterable interface.

So I have now:

```<code> public class SimpleStack implements StringStack, Iterable<String>

 ...

 public Iterator<String> iterator(){
    return new StackEnum();
 }

 class StackEnum implements Iterator<String>{

    int pos = list.size();

    public boolean hasNext(){
        return pos != 0;
    }

    public String next(){
        if(pos != 0){
            String str = list.get(pos);
            pos--;
        }else{
            throw new NoSuchElementException();
        }
    }

    public void remove(){
        throw new UnsupportedOperationException();
    }
 }
</code>```

I am absolutely not sure how to perform the iteration inside the iterator. Since my stack is represented by an array list I used list.size() as top-element.

Am I right with my implementation of the iterator, especially the next method?

答:
I don't know if an Iterator for a stack is a good idea, as the typical behavior of a stack does not conform to the iterator-protocol, as you'd have to pop an element to reveal the next one. I would suggest to add a public method like getList() which returns a list-representation of the stack. The list then could implement the Iterator interface. You could just return a copy of the ArrayList like that:

```<code>public List<String> returnList() {
  return new ArrayList<String>(list); // Return a copy of the ArrayList
}
</code>```

Title: Implementing an iterator for a stack

Body:
I defined an interface StringStack

public interface StringStack{
    //add a value to the stack
    public void push(String value);
    //fetch top-most element of the stack. element is removed
    public String pop();
    //fetch top-most element of the stack. element is not removed
    public String peek();
}

Further I defined a class SimpleStack that uses an ArrayList to manage the stack

public class SimpleStack implements StringStack{
    private ArrayList<String> list = new ArrayList<String>();

    public void push(String value){
        list.add(value);
    }

    public String pop(){
        if(!list.isEmpty()){
                return list.remove(list.size() - 1);
        }else{
                return null;
        }
    }

   public String peek(){
        if(!list.isEmpty()){
                return list.get(list.size() - 1);
        }else{
                return null;
        }
}

Now I want define an iterator for my stack class but I don't want to use the built-in ArrayList iterator. So I came up implementing a inner class and extending my SimpleStack with the Iterable interface.

So I have now:

 public class SimpleStack implements StringStack, Iterable<String>

 ...

 public Iterator<String> iterator(){
    return new StackEnum();
 }

 class StackEnum implements Iterator<String>{

    int pos = list.size();

    public boolean hasNext(){
        return pos != 0;
    }

    public String next(){
        if(pos != 0){
            String str = list.get(pos);
            pos--;
        }else{
            throw new NoSuchElementException();
        }
    }

    public void remove(){
        throw new UnsupportedOperationException();
    }
 }

I am absolutely not sure how to perform the iteration inside the iterator. Since my stack is represented by an array list I used list.size() as top-element.

Am I right with my implementation of the iterator, especially the next method?

Body:
I don't know if an Iterator for a stack is a good idea, as the typical behavior of a stack does not conform to the iterator-protocol, as you'd have to pop an element to reveal the next one. I would suggest to add a public method like getList() which returns a list-representation of the stack. The list then could implement the Iterator interface. You could just return a copy of the ArrayList like that:

public List<String> returnList() {
  return new ArrayList<String>(list); // Return a copy of the ArrayList
}


问:
C code to move file to trash
I'm trying to remove a file in a C program, but when I use the remove() function it completely removes the file and not sending it to the trash. How can I remove a file to trash?

Thanks in advance!

答:
Almost every operating system provides an API to perform a soft delete by moving files to the trash. Unfortunately there is no unified specification on how a trash / recycling bin should work. On Windows you can use IFileOperation, macOS has the NSFileManager and on Linux and BSD you either use a tool that implements the FreeDesktop.org trash specification such as gio trash (GNOME), kioclient5 move (KDE), trash-cli or implement your own.

Another solution is using a cross-platform library that allows to move files and directories to the trash / recycling bin like libtrashcan. This simplifies development because you only use a single function call without worrying about platform specific details.

Title: C code to move file to trash


问:
How to find routines that are created with SET ANSI_NULLS OFF?
I have created a filtered non-clustered index in order to optimize particular set of queries, but I started to get the following errors from various sources:

UPDATE failed because the following SET options have incorrect
  settings: 'ANSI_NULLS'. Verify that SET options are correct for use
  with indexed views and/or indexes on computed columns and/or filtered
  indexes and/or query notifications and/or XML data type methods and/or
  spatial index operations.

It seems that some of the legacy routines are created with the SET ANSI_NULLS OFF option and when the engine is trying to update the destination table from given context the error is thrown.

I am wondering is there a way to see which of the routines are created with this option. For example, if you script such routine you get something like this:

```<code>SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE ....
</code>```

I usually use scripts like the below one to found things in the objects definitions, but this settings is not part of it:

```<code>DECLARE @SearchWord NVARCHAR(128) = 'SET ANSI_NULLS OFF'
SELECT [ROUTINE_NAME]
FROM [INFORMATION_SCHEMA].[ROUTINES]
WHERE [ROUTINE_DEFINITION] LIKE '%' + @SearchWord+'%'
UNION
SELECT OBJECT_NAME([id])
FROM [SYSCOMMENTS]
WHERE [text] LIKE '%' + @SearchWord + '%'
GROUP BY OBJECT_NAME([id])
UNION
SELECT OBJECT_NAME(object_id)
FROM [sys].[sql_modules]
WHERE [definition] LIKE '%' + @SearchWord + '%' ;
</code>```

答:
You could just install SQL Search from Redgate or similar products from other vendors.  Then it's easy to search for things like this.

For a one-off, something like

```<code>SELECT * FROM sys.sql_modules WHERE definition LIKE '% ansi %'
</code>```

should do it. or

```<code>SELECT * FROM sys.sql_modules WHERE definition uses_ansi_nulls = 1
</code>```

see sys.sql_modules (Transact-SQL)

Body:
I have created a filtered non-clustered index in order to optimize particular set of queries, but I started to get the following errors from various sources:

UPDATE failed because the following SET options have incorrect
  settings: 'ANSI_NULLS'. Verify that SET options are correct for use
  with indexed views and/or indexes on computed columns and/or filtered
  indexes and/or query notifications and/or XML data type methods and/or
  spatial index operations.

It seems that some of the legacy routines are created with the SET ANSI_NULLS OFF option and when the engine is trying to update the destination table from given context the error is thrown.

I am wondering is there a way to see which of the routines are created with this option. For example, if you script such routine you get something like this:

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE ....

I usually use scripts like the below one to found things in the objects definitions, but this settings is not part of it:

DECLARE @SearchWord NVARCHAR(128) = 'SET ANSI_NULLS OFF'
SELECT [ROUTINE_NAME]
FROM [INFORMATION_SCHEMA].[ROUTINES]
WHERE [ROUTINE_DEFINITION] LIKE '%' + @SearchWord+'%'
UNION
SELECT OBJECT_NAME([id])
FROM [SYSCOMMENTS]
WHERE [text] LIKE '%' + @SearchWord + '%'
GROUP BY OBJECT_NAME([id])
UNION
SELECT OBJECT_NAME(object_id)
FROM [sys].[sql_modules]
WHERE [definition] LIKE '%' + @SearchWord + '%' ;

Body:
You could just install SQL Search from Redgate or similar products from other vendors.  Then it's easy to search for things like this.

For a one-off, something like

SELECT * FROM sys.sql_modules WHERE definition LIKE '% ansi %'

should do it. or

SELECT * FROM sys.sql_modules WHERE definition uses_ansi_nulls = 1

see sys.sql_modules (Transact-SQL)


问:
How to set timeout on client socket connection?
I am trying to set the timeout of a connection on the client socket in Java. I have set the connection timeout to 2000 milliseconds, i.e:

```<code>this.socket.connect(this.socketAdd, timeOut);
</code>```

This I am trying on a web application. When a user makes a request, I am passing values to socket server, but if I don't receive any response in 5 secs the socket should disconnect.

But in my case the whole request is getting submitted once again. Can any one please tell me where am I going wrong?

I want to cut the socket connection, if I don't get any response in 5 secs. How can I set it? Any sample code would help.

答:
What you show is a timeout for the connection, this will timeout if it cannot connect within a certain time.

Your question implies you want a timeout for when you are already connected and send a request, you want to timeout if there is no response within a certain amount of time.

Presuming you mean the latter, then you need to timeout the socket.read() which can be done by setting SO_TIMEOUT with the Socket.setSoTimeout(int timeout) method. This will throw an exception if the read takes longer than the number of milliseconds specified.  For example:

```<code>this.socket.setSoTimeout(timeOut);
</code>```

An alternative method is to do the read in a thread, and then wait on the thread with a timeout and close the socket if it timesout.

Body:
I am trying to set the timeout of a connection on the client socket in Java. I have set the connection timeout to 2000 milliseconds, i.e:

this.socket.connect(this.socketAdd, timeOut);

This I am trying on a web application. When a user makes a request, I am passing values to socket server, but if I don't receive any response in 5 secs the socket should disconnect.

But in my case the whole request is getting submitted once again. Can any one please tell me where am I going wrong?

I want to cut the socket connection, if I don't get any response in 5 secs. How can I set it? Any sample code would help.

Body:
What you show is a timeout for the connection, this will timeout if it cannot connect within a certain time.

Your question implies you want a timeout for when you are already connected and send a request, you want to timeout if there is no response within a certain amount of time.

Presuming you mean the latter, then you need to timeout the socket.read() which can be done by setting SO_TIMEOUT with the Socket.setSoTimeout(int timeout) method. This will throw an exception if the read takes longer than the number of milliseconds specified.  For example:

this.socket.setSoTimeout(timeOut);

An alternative method is to do the read in a thread, and then wait on the thread with a timeout and close the socket if it timesout.


问:
touchescancelled is called instead of touchesended
I'm trying to glow a view on touch and unglow it when touch is ended. While doing this, I noticed that when I raise my finger from the view, - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event method is not called but instead - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event method is called on the view. Is that a normal behaviour? I thought touchesCancelled is called if touches are cancelled because of a system issue like low memory warning. I did my job by using touchesCancelled but nevertheless I am wondering why it does not properly call touchesEnded. Is it a bug?

答:
This is not normal behavior. On raising your finger, touchesEnded should be called.

touchesCancelled should be called when your view is removed during touch or a system event happens (e.g. lock the phone while your finger is touching the screen)

See the documentation for touchesEnded and touchesCancelled.

Without your code, it is impossible to tell what is happening. However it seems that even if you manage to get touchedEnded called as it should, you would want to respond to both cases. In swift:

class MyView: UIView {
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        stopGlow()
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        stopGlow()
    }

    private func stopGlow() {
        //Your code here...
    }
}
```


问:
Debugging a Chrome instance with "remote-debugging-port" flag
I'm trying to follow the steps described under Basics: Using DevTools as protocol client on https://chromedevtools.github.io/devtools-protocol/. I launch two Chrome instances with google-chrome --remote-debugger-port=9222
 and google-chrome --user-data-dir=/home/whatever/Desktop/chrome/. After that, I navigate to http://127.0.0.1:9222/ but I get a "This site can’t be reached" error page.

If instead of this I launch Chrome with google-chrome --headless --remote-debugging-port=9222, when I navigate to http://127.0.0.1:9222/ I can see "Inspectable WebContents" and a link to a blank page .

Anyone has an idea on why the remote-debugging-port flag is only working with a headless instance? From what i can understand it should work both ways.

Note: What I'm attempting is to be able to use Puppeteer on a Chorme instance using the connect method (https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerconnectoptions).

答: I managed to get it to work by launching chrome as following: google-chrome --remote-debugging-port=9222 --user-data-dir=/home/whatever/Desktop/chrome/


问:
Configuration Management for Installation of OS
I was looking for a uniform configuration management tool for remote installation of OS on remote servers(similar to puppet/chef) having wide range of platform support. I think we can use PXE/kickstart for remote installation. I am not sure that can be used to install OS on multiple servers in parallel?  Other way to spin up the EC2 instance from AWS and pay amazon for the usage. I was wondering is there any other best option for this requirement?

Regards
Bubunia

答: Sparrow6 cm supports quite a range of platforms/os. You can choose Sparrowdo to run configuration jobs in push manner over ssh.</p>


问:
How to use the same route with different query parameter
I have two conflicting endpoints:.

GET/phone? status=available; and

GET/phone? status=available &min_price=value &max_price=value;

My route is :

```<code>app.get('/phone', getAvailablePhones);

app.get('/phone', getAvailablePhonesbyPrice);
</code>```

Only the 1st route executes.

How do I use this route for both endpoints??

答:
There are a few ways to do this, the easiest way to do it, changing the least code based on what you have now would be to call next() in the first of your two functions if min/ max are set.

```<code>    const getAvailablePhones = (req, res, next) => {
        if (req.query.min_price || req.query.min_price) return next();
        //rest of your code
    }
</code>```

Express will try the next function that matches if next() is called.

edit for more context:
https://expressjs.com/en/guide/routing.html see the routing documentation. I would use params instead in this use case.

```<code>    app.get("phone/:status/:min_price/:max_price",
    getAvailablePhonesByPrice);
    app.get("phone/:status", getAvailablePhones);
</code>```

This way your routes don't overlap, they are unique.

Body:
I have two conflicting endpoints:.

GET/phone? status=available; and

GET/phone? status=available &min_price=value &max_price=value;

My route is :

app.get('/phone', getAvailablePhones);

app.get('/phone', getAvailablePhonesbyPrice);

Only the 1st route executes.

How do I use this route for both endpoints??

Body:
There are a few ways to do this, the easiest way to do it, changing the least code based on what you have now would be to call next() in the first of your two functions if min/ max are set.

    const getAvailablePhones = (req, res, next) => {
        if (req.query.min_price || req.query.min_price) return next();
        //rest of your code
    }

Express will try the next function that matches if next() is called.

edit for more context:
https://expressjs.com/en/guide/routing.html see the routing documentation. I would use params instead in this use case.

    app.get("phone/:status/:min_price/:max_price",
    getAvailablePhonesByPrice);
    app.get("phone/:status", getAvailablePhones);

This way your routes don't overlap, they are unique.