问:
Mac OS: Intl extension is not loaded

macOS Mojave 10.14.3

PHP 7.1.23

Prestashop 1.7.5.1

I tried to install PHP intl extension on my local server in order to use Prestashop.

I added extension=php_intl.so to etc/php.ini

When I try to install Prestashop I get Intl extension is not loaded.

$ php -m | grep intl

When I do $ php -m | grep intl, I get:

PHP Warning:  PHP Startup: Unable to load dynamic library
'/usr/local/lib/php/pecl/20160303/php_intl.so' - d
lopen(/usr/local/lib/php/pecl/20160303/php_intl.so, 9): image not found in Unknown on line 0
Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/pecl/20160303/php_intl.so' - dlopen
(/usr/local/lib/php/pecl/20160303/php_intl.so, 9): image not found in Unknown on line 0
intl

It seems that the file php_intl.so doesn't exist.

$ sudo pecl install intl

I also tried $ sudo pecl install intland I get:

make: *** [php_intl.lo] Error 1
ERROR:make' failed`

$ curl -s http://php-osx.liip.ch/install.sh | bash -s 7.1

I also tried $ curl -s http://php-osx.liip.ch/install.sh | bash -s 7.1 and it doesn't create the intl.so file.

How can I solve this problem?

答:
Brew's PHP 7.1, 7.2 and 7.3 all have INTL enabled by default.

Most probably, you're just using your Mac OS' bundles version of PHP.

Run

ls -l $(which php)

to find out where the current PHP binary is located and whether it is symlinked to a Brew installation or not. In my case, for example:

```<code>lrwxr-xr-x 1 27 May 23 16:30 /usr/local/bin/php -> ../Cellar/php/7.3.5/bin/php
</code>```

Meaning that my php is linked to Brew's 7.3.5 version.

If you are NOT using Brew's PHP, you'll see something like

```<code>-rwxr-xr-x 1 11169664 Mar 21 07:09 /usr/bin/php
</code>```

Installing PHP through Brew

Find out whether you've already installed PHP:

```<code>brew list | grep php
</code>```

If there is any output, and your version of PHP is present, go to step 2, or use step 1 to update PHP to the latest version.

1. Install Homebrew's PHP

```<code>brew install php@7.3
</code>```

(or 7.2, 7.1). If Brew complains about not being able to find a formula, you might have messed with taps. Instead of php@7.3, you could try to supply the full path to the current php formula:

```<code>brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/php.rb
</code>```

Still not working, check whether you are running a recent version of Homebrew brew --version.

```<code>Homebrew 2.1.3-31-geaf2370
Homebrew/homebrew-core (git revision fd1ef; last commit 2019-05-25)
Homebrew/homebrew-cask (git revision 16d50; last commit 2019-05-26)
</code>```

2. Link Homebrew's PHP

Now, to have php 'in your path', there are two options.

a) Either homebrew's version must be linked from its install location (/usr/local/bin/Cellar/php....) to a directory in your path (e.g., /usr/local/bin). To do this, run:

```<code>brew link --force php@7.3
</code>```

If you are not able to link, this is typically caused by set permissions or System Integrity Protection. In the first case, try sudo chown "$USER":admin /usr/local/bin/php.

b) Or, add the /usr/local/opt/php@7.3 directory (opt-prefix) to your $PATH variable. E.g., for Bash:

```<code>echo 'export PATH="/usr/local/opt/php@7.3/bin:/usr/local/opt/php@7.3/sbin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
</code>```

3. Validate installation

ls -l $(which php)

should show that php is linked to a Homebrew PHP installation in /usr/local/bin/Cellar.

php -v

should show the recently installed version of PHP. Try to restart your terminal if that's not the case.

php -i | grep -i intl

should show some information about the current install of intl.

If you're using webservers and/or PHP FPM, this is the time to restart those services. (Or restart your system, if you don't know how to do that and cannot figure out).

Possible issues

If you still get warnings about missing extensions (Unable to load dynamic library, etc.), then your php.ini is messed up.

Find the current location of php's ini

```<code>$ php -i | grep \.ini

Configuration File (php.ini) Path => /usr/local/etc/php/7.3
Loaded Configuration File => /usr/local/etc/php/7.3/php.ini
Scan this dir for additional .ini files => /usr/local/etc/php/7.3/conf.d
Additional .ini files parsed => /usr/local/etc/php/7.3/conf.d/ext-opcache.ini
....
</code>```

Edit /usr/local/etc/php/7.3/php.ini and find the offending extension load (e.g., extension="myext.so"). Comment out those that cannot be found.

Homebrew permissions

Some argue that it's a good idea to chown /usr/local.

sudo chown -R "$USER":admin /usr/local

This will make installing things here, by hand and through Homebrew, a lot easier, but also a bit less secure too, since non-root processes are now allowed to write here too.

Your web-application is using a different version of PHP.

Make sure that it doesn't... The configuration of this depends on the used webserver. A first step would be to output the current PHP configuration in your web-application with <?php phpinfo();.

This explains steps for Apache.

Another way to get a webserver + PHP stack running quicly is using Laravel Valet.

Installing additional extensions

To install additional PHP extensions, use PEAR.

pear -V
should output the current PEAR and PHP version.

```<code>PEAR Version: 1.10.9
PHP Version: 7.3.5
Zend Engine Version: 3.3.5
</code>```

Now, to install an extension, for example, PHP's yaml extension:

```<code>-rwxr-xr-x 1 11169664 Mar 21 07:09 /usr/bin/php
</code>```0

Title: Mac OS: Intl extension is not loaded

Body:
Brew's PHP 7.1, 7.2 and 7.3 all have INTL enabled by default.

Most probably, you're just using your Mac OS' bundles version of PHP.

Run

ls -l $(which php)

to find out where the current PHP binary is located and whether it is symlinked to a Brew installation or not. In my case, for example:

lrwxr-xr-x 1 27 May 23 16:30 /usr/local/bin/php -> ../Cellar/php/7.3.5/bin/php

Meaning that my php is linked to Brew's 7.3.5 version.

If you are NOT using Brew's PHP, you'll see something like

-rwxr-xr-x 1 11169664 Mar 21 07:09 /usr/bin/php

Installing PHP through Brew

Find out whether you've already installed PHP:

brew list | grep php

If there is any output, and your version of PHP is present, go to step 2, or use step 1 to update PHP to the latest version.

1. Install Homebrew's PHP

brew install php@7.3

(or 7.2, 7.1). If Brew complains about not being able to find a formula, you might have messed with taps. Instead of php@7.3, you could try to supply the full path to the current php formula:

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/php.rb

Still not working, check whether you are running a recent version of Homebrew brew --version.

Homebrew 2.1.3-31-geaf2370
Homebrew/homebrew-core (git revision fd1ef; last commit 2019-05-25)
Homebrew/homebrew-cask (git revision 16d50; last commit 2019-05-26)

2. Link Homebrew's PHP

Now, to have php 'in your path', there are two options.

a) Either homebrew's version must be linked from its install location (/usr/local/bin/Cellar/php....) to a directory in your path (e.g., /usr/local/bin). To do this, run:

brew link --force php@7.3

If you are not able to link, this is typically caused by set permissions or System Integrity Protection. In the first case, try sudo chown "$USER":admin /usr/local/bin/php.

b) Or, add the /usr/local/opt/php@7.3 directory (opt-prefix) to your $PATH variable. E.g., for Bash:

echo 'export PATH="/usr/local/opt/php@7.3/bin:/usr/local/opt/php@7.3/sbin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

3. Validate installation

ls -l $(which php)

should show that php is linked to a Homebrew PHP installation in /usr/local/bin/Cellar.

php -v

should show the recently installed version of PHP. Try to restart your terminal if that's not the case.

php -i | grep -i intl

should show some information about the current install of intl.

If you're using webservers and/or PHP FPM, this is the time to restart those services. (Or restart your system, if you don't know how to do that and cannot figure out).

Possible issues

If you still get warnings about missing extensions (Unable to load dynamic library, etc.), then your php.ini is messed up.

Find the current location of php's ini

$ php -i | grep \.ini

Configuration File (php.ini) Path => /usr/local/etc/php/7.3
Loaded Configuration File => /usr/local/etc/php/7.3/php.ini
Scan this dir for additional .ini files => /usr/local/etc/php/7.3/conf.d
Additional .ini files parsed => /usr/local/etc/php/7.3/conf.d/ext-opcache.ini
....

Edit /usr/local/etc/php/7.3/php.ini and find the offending extension load (e.g., extension="myext.so"). Comment out those that cannot be found.

Homebrew permissions

Some argue that it's a good idea to chown /usr/local.

sudo chown -R "$USER":admin /usr/local

This will make installing things here, by hand and through Homebrew, a lot easier, but also a bit less secure too, since non-root processes are now allowed to write here too.

Your web-application is using a different version of PHP.

Make sure that it doesn't... The configuration of this depends on the used webserver. A first step would be to output the current PHP configuration in your web-application with <?php phpinfo();.

This explains steps for Apache.

Another way to get a webserver + PHP stack running quicly is using Laravel Valet.

Installing additional extensions

To install additional PHP extensions, use PEAR.

pear -V
should output the current PEAR and PHP version.

PEAR Version: 1.10.9
PHP Version: 7.3.5
Zend Engine Version: 3.3.5

Now, to install an extension, for example, PHP's yaml extension:

pear install yaml


来源: stackexchange

问:
How does indirect manipulation of dynamically allocated string literals truly work in C?
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

#include <stdio.h>
#include <stdlib.h>

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}
```

<p>However, upon studying how <code>tolower()</code> and <code>toupper()</code> work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}
</code>```

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

答:
There are no dynamically allocated string literals in C.

```<code> p = "literal";
</code>```

In this line in your code you overwrite the value stored in tho pointer with the reference to the string literal. The memory allocated by the malloc  is lost. Then you try to modify the string literal and this is an Undefined Behavior.

You need to copy it instead

```<code>strcpy(p, "literal");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

#include <stdio.h>
#include <stdlib.h>

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}

However, upon studying how tolower() and toupper() work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:

#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

Body:
There are no dynamically allocated string literals in C.

 p = "literal";

In this line in your code you overwrite the value stored in tho pointer with the reference to the string literal. The memory allocated by the malloc  is lost. Then you try to modify the string literal and this is an Undefined Behavior.

You need to copy it instead

strcpy(p, "literal");


问:
distinguish between the scanner and the keyboard
hey all.
I have a barcode scanner connected to a PC that working with a c# program.now i want to distinguish between the scanner and the keyboard which one is sending data to my program.
can everyone help me with a code or advise in c#?

somebody said this to me in another topic(but i can't do this yet):
basically you can configure the scanner to send some characters that basically tell the computer "hi, it's me". When you see those characters in your input stream, you know the information is coming from the barcode scanner, not from something the user typed on the keyboard. Did you check the manual that came with your barcode scanner? It should have more information about this.

答:
See update, as at March 2019:
https://stackoverflow.com/a/55411255/495455

If your application works with particular barcodes (eg all same char length or ones that can be matched with a RegEx) then you could possibly work it out by coding up a Robot Typing test. eg:

VB.Net:

```<code>Private sw As Stopwatch
Private Sub FirstCharacterEntered()
    sw.Start()
End Sub
Private Sub txt_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt.TextChanged
    If txt.length = 0 Then FirstCharacterEntered()
    If txt.Length = BarCodeSerialLength Or New RegularExpressions.Regex("your pattern").IsMatch(txt.Text) Then
        sw.Stop()
        If sw.ElapsedMilliseconds < TimeAHumanWouldTakeToType Then
            'Input is from the BarCode Scanner
        End If
    End If
End Sub
</code>```

C#:

```<code>private Stopwatch sw;
private void FirstCharacterEntered()
{
    sw.Start();
}
private void txt_TextChanged(System.Object sender, System.EventArgs e)
{
    if (txt.length == 0)
        FirstCharacterEntered();
    if (txt.Length == BarCodeSerialLength | new RegularExpressions.Regex("your pattern").IsMatch(txt.Text)) {
        sw.Stop();
        if (sw.ElapsedMilliseconds < TimeAHumanWouldTakeToType) {
            //Input is from the BarCode Scanner
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
See update, as at March 2019:
https://stackoverflow.com/a/55411255/495455

If your application works with particular barcodes (eg all same char length or ones that can be matched with a RegEx) then you could possibly work it out by coding up a Robot Typing test. eg:

VB.Net:

Private sw As Stopwatch
Private Sub FirstCharacterEntered()
    sw.Start()
End Sub
Private Sub txt_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt.TextChanged
    If txt.length = 0 Then FirstCharacterEntered()
    If txt.Length = BarCodeSerialLength Or New RegularExpressions.Regex("your pattern").IsMatch(txt.Text) Then
        sw.Stop()
        If sw.ElapsedMilliseconds < TimeAHumanWouldTakeToType Then
            'Input is from the BarCode Scanner
        End If
    End If
End Sub

C#:

private Stopwatch sw;
private void FirstCharacterEntered()
{
    sw.Start();
}
private void txt_TextChanged(System.Object sender, System.EventArgs e)
{
    if (txt.length == 0)
        FirstCharacterEntered();
    if (txt.Length == BarCodeSerialLength | new RegularExpressions.Regex("your pattern").IsMatch(txt.Text)) {
        sw.Stop();
        if (sw.ElapsedMilliseconds < TimeAHumanWouldTakeToType) {
            //Input is from the BarCode Scanner
        }
    }
}


问:
Using G++ to compile multiple .cpp and .h files
I've just inherited some C++ code that was written poorly with one cpp file which contained the main and a bunch of other functions. There are also .h files that contain classes and their function definitions.

Until now the program was compiled using the command g++ main.cpp. Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the g++ main.cpp command?

答:
As rebenvp said I used:

```<code>g++ *.cpp -o output
</code>```

And then do this for output:

```<code>./output
</code>```

But a better solution is to use make file. Read here to know more about make files.

Also make sure that you have added the required .h files in the .cpp files.

Body:
As rebenvp said I used:

g++ *.cpp -o output

And then do this for output:

./output

But a better solution is to use make file. Read here to know more about make files.

Also make sure that you have added the required .h files in the .cpp files.


问:
Login failed when querying linked server
I am trying to create a linked server in SQL Server:

```<code>--Create the link to server "uranium"
EXEC master.dbo.sp_addlinkedserver
      @server = N'uranium',
      @srvproduct=N'',
      @provider=N'SQLNCLI'

--Add the catch-all login with SQL Server authentication
EXEC master.dbo.sp_addlinkedsrvlogin
      @rmtsrvname=N'uranium',
      @useself=N'False',
      @locallogin=NULL,
      @rmtuser=N'BatteryStaple',
      @rmtpassword='Horsecorrect'
</code>```

And it creates fine. But any attempt to query the linked server, e.g.:

```<code>SELECT * FROM uranium.Periodic.dbo.Users
</code>```

results in

```<code>Msg 18456, Level 14, State 1, Line 1
Login failed for user 'BatteryStaple'.
</code>```

Except i know the credentials are correct:

Login: BatteryStaple

Password: Horsecorrect

because i can login when i connect directly using SQL Server Management Studio, or any other technology that is able to connect to a database.

Bonus Reading

Login Failed for linked server (he forgot to call sp_addlinkedsrvlogin)

Why am I getting a “login failed” when creating this linked server? (he's trying to use integrated authentication)

MSDN Blogs: SQL Linked Server Query failed with “Login failed for user …” (he's trying to make integrated authentication work)

Note: New SQL Server 2014 install. Every existing SQL 2000, 2005, 2008, 2008 R2 can communicate to their uranium linked server. I'm certain it is related to Microsoft's frustrating broken by default policy.

答: Old post, but might be useful still. In my case it was that only Windows Authentication was set. Setting authentication for both Windows and SQL Server on the linked server fixed it.</p>

Body:
I am trying to create a linked server in SQL Server:

--Create the link to server "uranium"
EXEC master.dbo.sp_addlinkedserver
      @server = N'uranium',
      @srvproduct=N'',
      @provider=N'SQLNCLI'

--Add the catch-all login with SQL Server authentication
EXEC master.dbo.sp_addlinkedsrvlogin
      @rmtsrvname=N'uranium',
      @useself=N'False',
      @locallogin=NULL,
      @rmtuser=N'BatteryStaple',
      @rmtpassword='Horsecorrect'

And it creates fine. But any attempt to query the linked server, e.g.:

SELECT * FROM uranium.Periodic.dbo.Users

results in

Msg 18456, Level 14, State 1, Line 1
Login failed for user 'BatteryStaple'.

Except i know the credentials are correct:

Login: BatteryStaple

Password: Horsecorrect

because i can login when i connect directly using SQL Server Management Studio, or any other technology that is able to connect to a database.

Bonus Reading

Login Failed for linked server (he forgot to call sp_addlinkedsrvlogin)

Why am I getting a “login failed” when creating this linked server? (he's trying to use integrated authentication)

MSDN Blogs: SQL Linked Server Query failed with “Login failed for user …” (he's trying to make integrated authentication work)

Note: New SQL Server 2014 install. Every existing SQL 2000, 2005, 2008, 2008 R2 can communicate to their uranium linked server. I'm certain it is related to Microsoft's frustrating broken by default policy.


问:
TabLayout highlite and Ripple effect
I have two question with TabLayout

1)Can i remove TabLayout highlight or change highlight color of tab layout?

2)Can i  add ripple effect for tab. Each tab contain TextView i try to add  custom background something like this

```<code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <item android:drawable="@drawable/btn_white_bg" />
</ripple>
</code>```

but it doesn't work.

答:
To remove the highlight, add the below line to your XML:</p>

```<code>app:tabRippleColor="@android:color/transparent"
</code>```

Title: TabLayout highlite and Ripple effect

Body:
I have two question with TabLayout

1)Can i remove TabLayout highlight or change highlight color of tab layout?

2)Can i  add ripple effect for tab. Each tab contain TextView i try to add  custom background something like this

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <item android:drawable="@drawable/btn_white_bg" />
</ripple>

but it doesn't work.

Body:
To remove the highlight, add the below line to your XML:

app:tabRippleColor="@android:color/transparent"


问:
Swift - make String conform to RandomAccessCollection
According to Swift 5 docs, String has method randomElement() with complexity O(1) or O(*n*) depending on conformance to RandomAccessCollection protocol.

Therefore, I am wondering how to make cases where randomElement() of String complexity will be O(1).

My string is just:

```<code>let letters = "abcdefghijklmnopqrstuvwxyz"
</code>```

Questions:

How do I check if my particular string conforms to RandomAccessCollection?

How to create / remove conformance to RandomAccessCollection protocol from a string?

答:
randomElement is a requirement of the Collection protocol, as you can see here.

So String is merely conforming to Collection by implementing this method, and the documentation comment is just a copy-paste from the original one in Collection.

If you read the documentation comment in the context of Collection instead of String, it makes a lot more sense. It's saying that if self is also a RandomAccessCollection, then it's O(1), otherwise it's O(n).

String does not conform to RandomAccessCollection, as you can see here, so String.randomElement is O(n).

EDIT:

To check if something is a RandomAccessCollection of Character, you can't do it directly with is, because RandomAccessCollection has associated types. One way to do this is to define a function that accepts a constrained type parameter:

```<code>let letters = Array("abcdefghijklmnopqrstuvwxyz")
func f<T>(_ x: T) where T : RandomAccessCollection, T.Element == Character {}
f(letters) // if this compiles, then Array<Character> conforms to RandomAccessCollection and Element is Character
</code>```

Body:
According to Swift 5 docs, String has method randomElement() with complexity O(1) or O(*n*) depending on conformance to RandomAccessCollection protocol.

Therefore, I am wondering how to make cases where randomElement() of String complexity will be O(1).

My string is just:

let letters = "abcdefghijklmnopqrstuvwxyz"

Questions:

How do I check if my particular string conforms to RandomAccessCollection?

How to create / remove conformance to RandomAccessCollection protocol from a string?

Body:
randomElement is a requirement of the Collection protocol, as you can see here.

So String is merely conforming to Collection by implementing this method, and the documentation comment is just a copy-paste from the original one in Collection.

If you read the documentation comment in the context of Collection instead of String, it makes a lot more sense. It's saying that if self is also a RandomAccessCollection, then it's O(1), otherwise it's O(n).

String does not conform to RandomAccessCollection, as you can see here, so String.randomElement is O(n).

EDIT:

To check if something is a RandomAccessCollection of Character, you can't do it directly with is, because RandomAccessCollection has associated types. One way to do this is to define a function that accepts a constrained type parameter:

let letters = Array("abcdefghijklmnopqrstuvwxyz")
func f<T>(_ x: T) where T : RandomAccessCollection, T.Element == Character {}
f(letters) // if this compiles, then Array<Character> conforms to RandomAccessCollection and Element is Character


问:
UI Automator viewer error : Error taking device screenshot: EOF Error taking device screenshot: EOF
I am getting error while taking device screenshot from UI Automator viewer.

"Error taking device screenshot: EOF" error is getting display

enter image description here

答:
First of all try shuting down the Appium Server or Appium Desktop as they might share the same ADB connection and cause malfunction of the software which relies on the connection. When you finish taking screenshots or inspecting UI hierarchy - start Appium again.

Consider using alternative tool like

Android Device Monitor (lives under tools folder of your Android SDK distribution)

Layout Inspector

Appium Studio


问:
INSERT into table with array of composite type
So I am trying to copy values from temporary tables into a table with an array type and I get the following error which I can't find a way to overcome.

```<code>ERROR:  cannot assign to field "addressid" of column "address" because its type addresstype[] is not a composite type
LINE 32: ...nID,Person.Title,Person.FirstName,Person.LastName,Person.Add...
                                                              ^
********** Error **********

ERROR: cannot assign to field "addressid" of column "address" because its type addresstype[] is not a composite type
SQL state: 42804
</code>```

Here is the query I try:

```<code>INSERT INTO Customer (CustomerID,Person.PersonID,Person.Title,Person.FirstName,Person.LastName,Person.Address.AddressID,Person.Address.AddressLine1,Person.Address.AddressLine2,Person.Address.City,Person.Address.PostalCode)
SELECT TCustomer.CustomerID,TPerson.PersonID,TPerson.Title,TPerson.FirstName,TPerson.LastName,TAddress.AddressID,TAddress.AddressLine1,TAddress.AddressLine2,TAddress.City,TAddress.PostalCode
FROM TCustomer,TPerson,TPersonAddress,TAddress
WHERE TCustomer.PersonID = TPerson.PersonID
AND TPerson.PersonID = TPersonAddress.PersonID
AND TPersonAddress.AddressID = TAddress.AddressID;
</code>```

tables&types:

```<code>CREATE TYPE AddressType AS(
AddressID integer,
AddressLine1 text,
AddressLine2 text,
City text,
PostalCode text);

CREATE TYPE PersonType AS(
PersonID integer,
Title text,
FirstName text,
LastName text,
Address AddressType[]);

CREATE TABLE Customer(
CustomerID integer,
Person PersonType,
PRIMARY KEY(CustomerID));

CREATE TEMPORARY TABLE TAddress (AddressID integer,AddressLine1 text,AddressLine2 text,City text,PostalCode text);
CREATE TEMPORARY TABLE TPerson (PersonID integer,Title text,FirstName text,LastName text);
CREATE TEMPORARY TABLE TCustomer (CustomerID integer,PersonID integer);
CREATE TEMPORARY TABLE TPersonAddress (PersonID integer,AddressID integer);
</code>```

Temporary tables have copied data from CSV files.
The problem is that each person can have many different Addresses.
So I have to load all the address to an AddressType Array.
But that seems impossible right now and I can't find a way to handle the array.

All I found around the internet to handle the array is:

```<code>INSERT INTO aa VALUES (3, ARRAY[ARRAY[1,2],ARRAY[3,4]]);
INSERT INTO sal_emp
    VALUES ('Bill',
    '{10000, 10000, 10000, 10000}',
    '{{"meeting", "lunch"}, {"training", "presentation"}}');
</code>```

And such but these example just add specified values that don't help with my case at all. So how to I make it copy values from:
    TAddress.AddressID,TAddress.AddressLine1,TAddress.AddressLine2,TAddress.City,TAddress.PostalCode

to array:

```<code>Person.Address.AddressID,Person.Address.AddressLine1,Person.Address.AddressLine2,Person.Address.City,Person.Address.PostalCode
</code>```

And if it's the same person it has to add all the addresses to the same array.

答:
At least on PostgreSQL 10, you can do this:

```<code>CREATE TYPE Child AS ( Name VARCHAR(10), Age INTEGER );

CREATE TABLE Father ( Name VARCHAR(10), Children Child[] );

INSERT INTO Father(Name, Children) VALUES (
    'Thanos',
    ARRAY[
        ('Nebula', 25)::Child,
        ('Gamora', 28)::Child
    ]
)
</code>```

The nice aspect of this solution is that if you have VARCHAR in your TYPE, you don't need to deal with escape sequences.

Body:
So I am trying to copy values from temporary tables into a table with an array type and I get the following error which I can't find a way to overcome.

ERROR:  cannot assign to field "addressid" of column "address" because its type addresstype[] is not a composite type
LINE 32: ...nID,Person.Title,Person.FirstName,Person.LastName,Person.Add...
                                                              ^
********** Error **********

ERROR: cannot assign to field "addressid" of column "address" because its type addresstype[] is not a composite type
SQL state: 42804

Here is the query I try:

INSERT INTO Customer (CustomerID,Person.PersonID,Person.Title,Person.FirstName,Person.LastName,Person.Address.AddressID,Person.Address.AddressLine1,Person.Address.AddressLine2,Person.Address.City,Person.Address.PostalCode)
SELECT TCustomer.CustomerID,TPerson.PersonID,TPerson.Title,TPerson.FirstName,TPerson.LastName,TAddress.AddressID,TAddress.AddressLine1,TAddress.AddressLine2,TAddress.City,TAddress.PostalCode
FROM TCustomer,TPerson,TPersonAddress,TAddress
WHERE TCustomer.PersonID = TPerson.PersonID
AND TPerson.PersonID = TPersonAddress.PersonID
AND TPersonAddress.AddressID = TAddress.AddressID;

tables&types:

CREATE TYPE AddressType AS(
AddressID integer,
AddressLine1 text,
AddressLine2 text,
City text,
PostalCode text);

CREATE TYPE PersonType AS(
PersonID integer,
Title text,
FirstName text,
LastName text,
Address AddressType[]);

CREATE TABLE Customer(
CustomerID integer,
Person PersonType,
PRIMARY KEY(CustomerID));

CREATE TEMPORARY TABLE TAddress (AddressID integer,AddressLine1 text,AddressLine2 text,City text,PostalCode text);
CREATE TEMPORARY TABLE TPerson (PersonID integer,Title text,FirstName text,LastName text);
CREATE TEMPORARY TABLE TCustomer (CustomerID integer,PersonID integer);
CREATE TEMPORARY TABLE TPersonAddress (PersonID integer,AddressID integer);

Temporary tables have copied data from CSV files.
The problem is that each person can have many different Addresses.
So I have to load all the address to an AddressType Array.
But that seems impossible right now and I can't find a way to handle the array.

All I found around the internet to handle the array is:

INSERT INTO aa VALUES (3, ARRAY[ARRAY[1,2],ARRAY[3,4]]);
INSERT INTO sal_emp
    VALUES ('Bill',
    '{10000, 10000, 10000, 10000}',
    '{{"meeting", "lunch"}, {"training", "presentation"}}');

And such but these example just add specified values that don't help with my case at all. So how to I make it copy values from:
    TAddress.AddressID,TAddress.AddressLine1,TAddress.AddressLine2,TAddress.City,TAddress.PostalCode

to array:

Person.Address.AddressID,Person.Address.AddressLine1,Person.Address.AddressLine2,Person.Address.City,Person.Address.PostalCode

And if it's the same person it has to add all the addresses to the same array.

Body:
At least on PostgreSQL 10, you can do this:

CREATE TYPE Child AS ( Name VARCHAR(10), Age INTEGER );

CREATE TABLE Father ( Name VARCHAR(10), Children Child[] );

INSERT INTO Father(Name, Children) VALUES (
    'Thanos',
    ARRAY[
        ('Nebula', 25)::Child,
        ('Gamora', 28)::Child
    ]
)

The nice aspect of this solution is that if you have VARCHAR in your TYPE, you don't need to deal with escape sequences.


问:
App Crashing- Core Data Problem Or Memory Management?
Console Message:

Had to use picture because wasn't formatting correctly in post as text.

the received memory warning level 2 showed up before the app crashed.

errror comes at this line - cell.textLabel.text = tempRoutine.name;

link to full-size picture (http://www.box.net/shared/static/7igj3r4trh.png)

ViewController:

```<code>@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize entered;
@synthesize managedObjectContext;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

-(void)toggleEdit
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [entered release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark Add an event

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
            Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
           // Routine *tempRoutine = [[Routine alloc]init];
            //tempRoutine.name = entered;
            [eventsArray addObject:tempRoutine];
            [tempRoutine release];
            [tableView reloadData];
            [self addEvent];
        }
        /*
        if(eventsArray && entered)
        {
            [eventsArray addObject:entered];
            [tableView reloadData];
            [self addEvent];
        }
        */
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    // Dequeue or create a new cell.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = tempRoutine.name;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }
 }
</code>```

答: When you create your Routines, you create them with insertNewObjectForEntityForName:inManagedObjectContext:. Then you release them. But insertNewObjectForEntityForName:inManagedObjectContext: doesn't return an object you own according to the memory management rules or the method's documentation, so you shouldn't be releasing.

Body:
Console Message:

Had to use picture because wasn't formatting correctly in post as text.

the received memory warning level 2 showed up before the app crashed.

errror comes at this line - cell.textLabel.text = tempRoutine.name;

link to full-size picture (http://www.box.net/shared/static/7igj3r4trh.png)

ViewController:

@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize entered;
@synthesize managedObjectContext;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

-(void)toggleEdit
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [entered release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark Add an event

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
            Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
           // Routine *tempRoutine = [[Routine alloc]init];
            //tempRoutine.name = entered;
            [eventsArray addObject:tempRoutine];
            [tempRoutine release];
            [tableView reloadData];
            [self addEvent];
        }
        /*
        if(eventsArray && entered)
        {
            [eventsArray addObject:entered];
            [tableView reloadData];
            [self addEvent];
        }
        */
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    // Dequeue or create a new cell.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = tempRoutine.name;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }
 }


问:
Cannot resample time series data, TypeError
I am trying to resample this data downloaded from quandl but keep have a TypeError thrown my way even though it looks to be of the datetime64[ns] type.

I have tried running pd.to_datetime(df['Date']) to ensure it of the datetime type with no luck.

```<code>df = pd.read_pickle('data1')
print(df.Close.head())
df = df.reset_index()
df = df[['Date', 'Close']]
print(df.Date.head())
df = df.resample('W').mean

Date
2004-08-19    100.335
2004-08-20    108.310
2004-08-23    109.400
2004-08-24    104.870
2004-08-25    106.000
Name: Close, dtype: float64
0   2004-08-19
1   2004-08-20
2   2004-08-23
3   2004-08-24
4   2004-08-25
Name: Date, dtype: datetime64[ns]
Traceback (most recent call last):
  File "/Users/raymond.devries/PycharmProjects/untitled2/datatry.py", line 15, in <module>
    df = df.resample('W').mean
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/generic.py", line 8155, in resample
    base=base, key=on, level=level)
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/resample.py", line 1250, in resample
    return tg._get_resampler(obj, kind=kind)
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/resample.py", line 1380, in _get_resampler
    "but got an instance of %r" % type(ax).__name__)
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
</code>```

答:
I did not realize that the date time data times needed to be set as the index. The resample function reads the index of the data frame. The index of data frame was already set to a date time index, therefore I did not need to run df = df.reset_index() and by doing so I turned my index into a range object.

Working code:

```<code>df = pd.read_pickle('data1')
df = df[['Close']]
df = df.resample('W').mean()
print(df.head())
</code>```

Output:

```<code>               Close
Date
2004-08-22  104.3225
2004-08-29  106.8660
2004-09-05  101.2300
2004-09-12  102.8800
2004-09-19  112.4900

Process finished with exit code 0
</code>```

Body:
I am trying to resample this data downloaded from quandl but keep have a TypeError thrown my way even though it looks to be of the datetime64[ns] type.

I have tried running pd.to_datetime(df['Date']) to ensure it of the datetime type with no luck.

df = pd.read_pickle('data1')
print(df.Close.head())
df = df.reset_index()
df = df[['Date', 'Close']]
print(df.Date.head())
df = df.resample('W').mean

Date
2004-08-19    100.335
2004-08-20    108.310
2004-08-23    109.400
2004-08-24    104.870
2004-08-25    106.000
Name: Close, dtype: float64
0   2004-08-19
1   2004-08-20
2   2004-08-23
3   2004-08-24
4   2004-08-25
Name: Date, dtype: datetime64[ns]
Traceback (most recent call last):
  File "/Users/raymond.devries/PycharmProjects/untitled2/datatry.py", line 15, in <module>
    df = df.resample('W').mean
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/generic.py", line 8155, in resample
    base=base, key=on, level=level)
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/resample.py", line 1250, in resample
    return tg._get_resampler(obj, kind=kind)
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/resample.py", line 1380, in _get_resampler
    "but got an instance of %r" % type(ax).__name__)
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

Body:
I did not realize that the date time data times needed to be set as the index. The resample function reads the index of the data frame. The index of data frame was already set to a date time index, therefore I did not need to run df = df.reset_index() and by doing so I turned my index into a range object.

Working code:

df = pd.read_pickle('data1')
df = df[['Close']]
df = df.resample('W').mean()
print(df.head())

Output:

               Close
Date
2004-08-22  104.3225
2004-08-29  106.8660
2004-09-05  101.2300
2004-09-12  102.8800
2004-09-19  112.4900

Process finished with exit code 0


问:
AWS RDS Postgres Crypto functions doesn't work even with the pgcrypto extension enabled
I have the fresh AWS RDS Postgres (v 11) instance. I've installed the pgcrypto extension and it doesn't allow to do that again:

```<code>CREATE EXTENSION pgcrypto;
Error in query (7): ERROR: extension "pgcrypto" already exists
</code>```

But I can't use the extension functions:

```<code>select gen_salt('bf');
Error in query (7): ERROR: function gen_salt(unknown) does not exist
LINE 1: select gen_salt('bf')
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
</code>```

What I'm doing wrong?

答:
The issue was that the extension probably was added when a schema was active. Thank you @ Antti Haapala for the link to the same question: https://dba.stackexchange.com/questions/135093/in-rds-digest-function-is-undefined-after-creating-pgcrypto-extension .

I've made the following when no schema selected:

```<code>DROP EXTENSION pgcrypto;
Query executed OK, 0 rows affected. (0.031 s)

CREATE EXTENSION pgcrypto;
Query executed OK, 0 rows affected. (0.046 s)

SELECT gen_salt('bf');
gen_salt
$2a$06$kyj11fcRtpwxrqgCfZEIaO
</code>```

And everything works fine now.

Body:
I have the fresh AWS RDS Postgres (v 11) instance. I've installed the pgcrypto extension and it doesn't allow to do that again:

CREATE EXTENSION pgcrypto;
Error in query (7): ERROR: extension "pgcrypto" already exists

But I can't use the extension functions:

select gen_salt('bf');
Error in query (7): ERROR: function gen_salt(unknown) does not exist
LINE 1: select gen_salt('bf')
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

What I'm doing wrong?

Body:
The issue was that the extension probably was added when a schema was active. Thank you @ Antti Haapala for the link to the same question: https://dba.stackexchange.com/questions/135093/in-rds-digest-function-is-undefined-after-creating-pgcrypto-extension .

I've made the following when no schema selected:

DROP EXTENSION pgcrypto;
Query executed OK, 0 rows affected. (0.031 s)

CREATE EXTENSION pgcrypto;
Query executed OK, 0 rows affected. (0.046 s)

SELECT gen_salt('bf');
gen_salt
$2a$06$kyj11fcRtpwxrqgCfZEIaO

And everything works fine now.


问:
Vue axios (and fetch) responses not passing into data property
I have a Vue (2.2.1) component that should display a membership directory by making a request to a Laravel API. The request succeeds, and the response is correct when I console.log it. Likewise, the API request succeeds in Postman and the JSON object is correctly formatted. But, the response won't pass into the variable in the Vue instance data object to which I attempt to assign it. My code:

```<code><template>
  <div>
    {{ entries }}
  </div>
</template>

<script>
  export default {
    name: 'directory',
    data() {
      return {
        entries: []
      }
    },
    created() {
      this.getEntries()
    },
    methods: {
      getEntries: function() {
        axios.get('/api/directory')
          .then(response => {
             this.entries = response.data;
          });
      }
    }
  }
</script>
</code>```

When I load the page (after npm run dev), empty brackets representing the initial state of entries (an empty array) is displayed and not the raw JSON data. (I'm just testing now, not yet styling or building the table). However, if I add a console.log(this.entries) or console.log(response) or console.log(response.data), the correct form of the JSON is displayed in console and there are no errors.

I have replaced the axios code with the appropriate fetch code, including the ->json() line and get the same results. I have also used a "practice" API (JSONPlaceholder) to make sure it wasn't a problem with my API and likewise got the same results. This suggests that I'm doing something wrong in my Vue component

答:
I would make your entries a computed property so it will update on the call, it seems like your template is not updating a computed property may solve this.
 Try this:

```<code>data(){
   return {
      dataEntries: null
    }

computed: {
   entries(){
       if (dataEntries) return dataEntries
       return []
    }
</code>```

Body:
I have a Vue (2.2.1) component that should display a membership directory by making a request to a Laravel API. The request succeeds, and the response is correct when I console.log it. Likewise, the API request succeeds in Postman and the JSON object is correctly formatted. But, the response won't pass into the variable in the Vue instance data object to which I attempt to assign it. My code:

<template>

    {{ entries }}

</template>

When I load the page (after npm run dev), empty brackets representing the initial state of entries (an empty array) is displayed and not the raw JSON data. (I'm just testing now, not yet styling or building the table). However, if I add a console.log(this.entries) or console.log(response) or console.log(response.data), the correct form of the JSON is displayed in console and there are no errors.

I have replaced the axios code with the appropriate fetch code, including the ->json() line and get the same results. I have also used a "practice" API (JSONPlaceholder) to make sure it wasn't a problem with my API and likewise got the same results. This suggests that I'm doing something wrong in my Vue component

Body:
I would make your entries a computed property so it will update on the call, it seems like your template is not updating a computed property may solve this.
 Try this:

data(){
   return {
      dataEntries: null
    }

computed: {
   entries(){
       if (dataEntries) return dataEntries
       return []
    }


问:
request.path in django template
I try something like this:

```<code>{% if request.path == 'contact' %}
    <p>You are in Contact</p>
{% endif %}

{% if request.path == 'shop' %}
    <p>You are in Shop</p>
{% endif %}
</code>```

Why does not that work?

答:
Try this:</p>

```<code>{% if 'contact' in request.path %}
</code>```

Title: request.path in django template

Body:
I try something like this:

{% if request.path == 'contact' %}

You are in Contact

{% endif %}

{% if request.path == 'shop' %}

You are in Shop

{% endif %}

Why does not that work?

Body:
Try this:

{% if 'contact' in request.path %}


问:
.replace() is not replacing elements
new to pandas, learning.
Have a column in my df where I need to replace certain elements in it with specific data.

Daily_Report is my df. I need to replace "LI" and "MC" in my "Country" column with "CH", "FR". I wrote the below which worked at first, but at rerunning the notebook from the beginning in Jupyter notebook, it doesn;t do anything anymore)

```<code>Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
Daily_Report['Country'].value_counts()

GB    8132
FR    5811
DE    3390
ES    2280
IT    1930
CH    1516
NL    1414
SE     938
LI      31
MC      24
Name: Country, dtype: int64
</code>```

For a successful replace, LI an MC would not show after running value.counts()
What am I missing here?

Thanks a lot

答:
For me working nice in pandas 0.24.2:

```<code>Daily_Report = pd.DataFrame({ 'Country':['LI','MC','SE','NL']})
Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
print (Daily_Report)
  Country
0      CH
1      FR
2      SE
3      NL
</code>```

Alternative with DataFrame.replace and nested dicts - outer specify column for replace and inner mapping:

```<code>Daily_Report = pd.DataFrame({ 'Country':['LI','MC','SE','NL']})
Daily_Report1 = Daily_Report.replace({'Country':{'LI':'CH','MC':'FR'}})
print (Daily_Report1)
  Country
0      CH
1      FR
2      SE
3      NL
</code>```

Title: .replace() is not replacing elements

Body:
new to pandas, learning.
Have a column in my df where I need to replace certain elements in it with specific data.

Daily_Report is my df. I need to replace "LI" and "MC" in my "Country" column with "CH", "FR". I wrote the below which worked at first, but at rerunning the notebook from the beginning in Jupyter notebook, it doesn;t do anything anymore)

Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
Daily_Report['Country'].value_counts()

GB    8132
FR    5811
DE    3390
ES    2280
IT    1930
CH    1516
NL    1414
SE     938
LI      31
MC      24
Name: Country, dtype: int64

For a successful replace, LI an MC would not show after running value.counts()
What am I missing here?

Thanks a lot

Body:
For me working nice in pandas 0.24.2:

Daily_Report = pd.DataFrame({ 'Country':['LI','MC','SE','NL']})
Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
print (Daily_Report)
  Country
0      CH
1      FR
2      SE
3      NL

Alternative with DataFrame.replace and nested dicts - outer specify column for replace and inner mapping:

Daily_Report = pd.DataFrame({ 'Country':['LI','MC','SE','NL']})
Daily_Report1 = Daily_Report.replace({'Country':{'LI':'CH','MC':'FR'}})
print (Daily_Report1)
  Country
0      CH
1      FR
2      SE
3      NL


问:
Azure Windows Server license not activated
I have spun up a Windows Server Datacenter 2019 image on Azure.  When I go to the Activation screen in Settings, it shows that Windows is not activated.  How do I activate Windows?  Do I need to buy a server license?

I just created a new VM. I log into the server using RDP, and check if the machine is activated. It isn't. The error is:

We can't activate Windows on this device as we can't connect to your
  organization's activation server. Make sure you're connected to your
  organization's network and try again. If you continue having problems
  with activation, contact your organization's support person. Error
  code: 0xC004F074. Then I try to hit the Troubleshooting box:
  Troubleshooting has completed: We can't activate Windows. Make sure
  you're connected to the Internet.

答:
The server doesn't seems to be able to connect to Microsoft's KMS servers. To verify if that is the case run the following from Powershell:

```<code>Invoke-Expression "$env:windir\system32\cscript.exe $env:windir\system32\slmgr.vbs /skms kms.core.windows.net:1688"

Test-NetConnection kms.core.windows.net -Port 1688
</code>```

TcpTestSucceeded must be True , if false then your VM can't reach the KMS and therefore not activate it. So test and see if your VM can reach kms.core.windows.net on port 1688.

Body:
The server doesn't seems to be able to connect to Microsoft's KMS servers. To verify if that is the case run the following from Powershell:

Invoke-Expression "$env:windir\system32\cscript.exe $env:windir\system32\slmgr.vbs /skms kms.core.windows.net:1688"

Test-NetConnection kms.core.windows.net -Port 1688

TcpTestSucceeded must be True , if false then your VM can't reach the KMS and therefore not activate it. So test and see if your VM can reach kms.core.windows.net on port 1688.


问:
How to extract manually annotated tweets using Twitter API?
I'm using text classification to classify dialects. First I need a large manually annotated tweets, and I have read a research paper that says:

We have collected tweets that were published during June 2015. Arabic
  linguists manually annotated a small part of these tweets, so we got
  51,589 tweets with correct dialectal labels. These tweets were
  manually found in Twitter and annotated by the linguists.

So this researcher was able to extract those tweets, I wanted to contact him but their emails weren't valid. He says those tweets were published during June 2015. How can I extract those tweets?

答: as I know researchers didn't have permission to publish tweets that they collect with twitter APIs.</p>


问:
Pick random but unique array in JavaScript
I am working on a project in which I need to create a simple html page questionnaire for work. Its been more that 8 years I have not done any programming. Now suddenly be given a project. Stack Overflow helped me in getting through most of the project. But now I have hit a wall.

I need to pick a random but NO repeated question from array of questions. I am using JavaScript to display the questions and  using this code example as basis for project.

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>
<style>

</style>
<script type="text/javascript">

var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0, randomq=0;

var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];

function get(x){
  return document.getElementById(x);

}

function renderQuestion(){
  test = get("test");

  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";

    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;

    // stops rest of renderQuestion function running when test is completed
    return false;
  }
</code>```

// shuffle questions

```<code>  random1 = Math.floor(Math.random() * (questions.length)) ;
   get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;

  question = questions[random1][0];
  chA = questions[random1][1];
  chB = questions[random1][2];
  chC = questions[random1][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[random1][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
 pos++;
 // then the renderQuestion function runs again to go to next question
  renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>
</html>
</code>```

I am looking for a way that there is no repeated questions.

Please advice...

Thanks in advance.

答:
Thank you all for help.

i have found the solution with : fisher-yate shuffle

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Body:
I am working on a project in which I need to create a simple html page questionnaire for work. Its been more that 8 years I have not done any programming. Now suddenly be given a project. Stack Overflow helped me in getting through most of the project. But now I have hit a wall.

I need to pick a random but NO repeated question from array of questions. I am using JavaScript to display the questions and  using this code example as basis for project.

<!DOCTYPE html>

<meta charset="utf-8"/>
<title>Quiz</title>

I am looking for a way that there is no repeated questions.

Please advice...

Thanks in advance.


问:
Web Directory is visible after React app deployed on cPanel
I have created a simple react app and built the app using npm run build command and uploaded it to host. it works but whole application directory is visible in web browser console. So how do i fix it to not to show web directory on web console. Once the application kept growing and sensible data will visible. So is there any method to avoid that.

Here's the on cPanel File Manager

and js directory has minified js like this,

But once it loads on web browser it shows App.js content,

Any suggestions.

答: After running "npm run build" , publish your "build" folder. Not your "public" folder. </p>


问:
Regex splitting strings on a character, not contained in ()
I'm trying to split a string on a , where that character is not contained in ().

Example String:

```<code>`table1`.`lname`,`table1`.`fname`,if(foo is not null,foo,if(bar is not null,bar,table3.baz)),`table3`.`shu`
</code>```

I want to split it into an array looking like

```<code>(
  0=>`table1`.`lname`
  1=>`table1`.`fname`
  2=>if(foo is not null,foo,if(bar is not null,bar,table3.baz))
  3=>`table3`.`shu`
)
</code>```

Any ideas on how to tackle this problem?

--
Dave

答:
I'd look into your favorite language to see if there is a specific module for handling CSV files.  Ruby has CSV (replaced by FasterCSV in recent versions) that would handle your problem just fine.

It is more complicated than a single regex but will get the job done.

Perl has this Parse::CSV module.

OwnerDisplayName: david walker

LastEditorDisplayName: Lawrence Johnston

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to split a string on a , where that character is not contained in ().

Example String:

`table1`.`lname`,`table1`.`fname`,if(foo is not null,foo,if(bar is not null,bar,table3.baz)),`table3`.`shu`

I want to split it into an array looking like

(
  0=>`table1`.`lname`
  1=>`table1`.`fname`
  2=>if(foo is not null,foo,if(bar is not null,bar,table3.baz))
  3=>`table3`.`shu`
)

Any ideas on how to tackle this problem?

--
Dave

OwnerDisplayName: Keltia


问:
Is it possible to prevent IE from displaying the "Submit Form" button over PDF forms?
My organization wants to distribute fillable PDF forms, but the PDFs will not be submitted online or via email - they will be printed out. The idea is simply to cut down on handwritten forms. I know that Acrobat has a "typewriter" tool, but most of our end users probably do not know about this, and we want to take advantage of drop-down lists, etc.

When you open fillable forms in IE, a "Submit Form" button appears at the top of the page, even though the form cannot be submitted online. Clicking "Submit Form" doesn't do anything, and we're concerned that some of our end users will believe they are electronically submitting a form.

I've researched various methods that force PDFs to download, rather than open in the browser, but implementing those changes would be fairly intense considering that our network that has hundreds of PDFs scattered across hundreds of pages. We'd prefer a more simple solution.

TL;DR: We want to distribute PDF forms that users can fill out and print, but we don't want the "Submit Form" button to appear in IE.

Thanks!

答:
I guess the problem is that the Submit Form button was added at form creation. You might need to open the pdf using Adobe LiveCycle Designer and simply remove the button.

If you are using Adobe Acrobat Pro, go to Forms>Edit Form in Designer...


问:
MVC change a route after postback
I have an action that is returning data like this,

```<code>return _aPartialPopupView(model)
</code>```

And after code streaming, site route changing to

```<code>../User/_aPartialPopupView
</code>```

but I want to update this route to

```<code>../User/
</code>```

after the action call, because it should redirect to the index action

I think this is https://stackoverflow.com/a/19090444/914284 answering my question but there should be more clear way to hang up

答:
Lets get a route like that.

```<code>routes.MapRoute("old", "foo/{controller}/{action}/{id}");
</code>```

And a method using like that

```<code>var new = routes.MapRoute("new", "bar/{controller}/{id}/{action}");
var old = routes.MapRoute("new", "foo/{controller}/{action}/{id}");
routes.Redirect(old).To(new);
</code>```

MapRoute method to create the route. Or, we could have done this:

```<code>var new = routes.MapRoute("new", "bar/{controller}/{id}/{action}");
var throwAway = new RouteCollection();
var old = throwAway.MapRoute("new", "foo/{controller}/{action}/{id}");
routes.Redirect(old).To(new);
</code>```

The implementation of GetNewRouteData which is the method called when matching incoming requests.

```<code>public override RouteData GetNewRouteData (HttpContextBase httpContext) {
    // Use the original route to match
    var routeData = SourceRoute.GetNewRouteData(httpContext);
    if (routeData == null) {
        return null;
    }
    // But swap its route handler with our own
    routeData.RouteHandler = this;
    return routeData;
}
</code>```

RedirectRoute implements IRouteHandler, so we should look at its implementation.

```<code>  public IHttpHandler GetHttpHandler(RequestContext requestContext) {
      var requestRouteValues = requestContext.RouteData.Values;

      var routeValues = AdditionalRouteValues.Merge(requestRouteValues);

      var vpd = TargetRoute.GetVirtualPath(requestContext, routeValues);
      string targetUrl = null;
      if (vpd != null) {
        targetUrl = "~/" + vpd.VirtualPath;
        return new RedirectHttpHandler(targetUrl, Permanent, isReusable: false);
      }
      return new DelegateHttpHandler(    httpContext => httpContext.Response.StatusCode = 404, false);
    }
</code>```

Title: MVC change a route after postback

Body:
I have an action that is returning data like this,

return _aPartialPopupView(model)

And after code streaming, site route changing to

../User/_aPartialPopupView

but I want to update this route to

../User/

after the action call, because it should redirect to the index action

I think this is https://stackoverflow.com/a/19090444/914284 answering my question but there should be more clear way to hang up

Body:
Lets get a route like that.

routes.MapRoute("old", "foo/{controller}/{action}/{id}");

And a method using like that

var new = routes.MapRoute("new", "bar/{controller}/{id}/{action}");
var old = routes.MapRoute("new", "foo/{controller}/{action}/{id}");
routes.Redirect(old).To(new);

MapRoute method to create the route. Or, we could have done this:

var new = routes.MapRoute("new", "bar/{controller}/{id}/{action}");
var throwAway = new RouteCollection();
var old = throwAway.MapRoute("new", "foo/{controller}/{action}/{id}");
routes.Redirect(old).To(new);

The implementation of GetNewRouteData which is the method called when matching incoming requests.

public override RouteData GetNewRouteData (HttpContextBase httpContext) {
    // Use the original route to match
    var routeData = SourceRoute.GetNewRouteData(httpContext);
    if (routeData == null) {
        return null;
    }
    // But swap its route handler with our own
    routeData.RouteHandler = this;
    return routeData;
}

RedirectRoute implements IRouteHandler, so we should look at its implementation.

  public IHttpHandler GetHttpHandler(RequestContext requestContext) {
      var requestRouteValues = requestContext.RouteData.Values;

      var routeValues = AdditionalRouteValues.Merge(requestRouteValues);

      var vpd = TargetRoute.GetVirtualPath(requestContext, routeValues);
      string targetUrl = null;
      if (vpd != null) {
        targetUrl = "~/" + vpd.VirtualPath;
        return new RedirectHttpHandler(targetUrl, Permanent, isReusable: false);
      }
      return new DelegateHttpHandler(    httpContext => httpContext.Response.StatusCode = 404, false);
    }


问:
insert data from a table and insert into another table in different database
I have 2 database that link together. I need to retrieve data from that table and insert those column into a table in different database based on their Unique id number.

```<code><?php

$handle  =  mysql_connect("localhost", "root", "") or die(mysql_error());

  mysql_query("USE shop",$handle);
  $query = "SELECT ModelCode,Class FROM shopfloor_pro WHERE CommNo = '0985560712'";
  $result = mysql_query($query);

  while ($data = mysql_fetch_object($result)){
      $variable1 = $data->ModelCode;
      $variable2 = $data->Class;

      mysql_query("USE vt",$handle);
      $sql = "INSERT INTO track SET
              t_model_code = '$variable1',
t_class = '$variable2' WHERE t_comm_no = '0985560712'";
       if (!mysql_query($sql)) {
       echo '<p>Error adding data into database: ' . mysql_error() . '</p>';
      }
      mysql_query("USE paintshop",$handle);

  }

?>
</code>```

this is the data that i want to retrieve

this is where i want to put the data

When i run the code it shows
"Error adding data into database: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE t_comm_no = '0985560712'' at line 3"

答:
You can most likely do this in a single query - but as pointed out the mysql api has been deprecated a long time ago and totally removed from PHP 7+.

To do the query in a single operation you might try like this:

```<code>insert into `vt`.`track` (`t_model_code`,`t_class` )
    select `ModelCode`,`Class` from `shop`.`shopfloor_pro` where `CommNo`='0985560712'
</code>```

Body:
I have 2 database that link together. I need to retrieve data from that table and insert those column into a table in different database based on their Unique id number.

<?php

$handle  =  mysql_connect("localhost", "root", "") or die(mysql_error());

  mysql_query("USE shop",$handle);
  $query = "SELECT ModelCode,Class FROM shopfloor_pro WHERE CommNo = '0985560712'";
  $result = mysql_query($query);

  while ($data = mysql_fetch_object($result)){
      $variable1 = $data->ModelCode;
      $variable2 = $data->Class;

      mysql_query("USE vt",$handle);
      $sql = "INSERT INTO track SET
              t_model_code = '$variable1',
t_class = '$variable2' WHERE t_comm_no = '0985560712'";
       if (!mysql_query($sql)) {
       echo '
Error adding data into database: ' . mysql_error() . '
';
      }
      mysql_query("USE paintshop",$handle);

  }

?>

this is the data that i want to retrieve

this is where i want to put the data

When i run the code it shows
"Error adding data into database: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE t_comm_no = '0985560712'' at line 3"

Body:
You can most likely do this in a single query - but as pointed out the mysql api has been deprecated a long time ago and totally removed from PHP 7+.

To do the query in a single operation you might try like this:

insert into `vt`.`track` (`t_model_code`,`t_class` )
    select `ModelCode`,`Class` from `shop`.`shopfloor_pro` where `CommNo`='0985560712'


问:
How to show or hide image in HTML
In the following HTML/JS code, if I enter a valid e-mail id a command button and a tick mark should appear. But command button works fine. Tick mark is not appearing. Any one please help.</p>

```<code><html>
<head>

</head>
<body>
<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>
  <img id "img1" src="valid.jpg" width=100px style="display:none"/>

</form>

<script>
const signUpForm = document.getElementById('signUpForm');
const emailField = document.getElementById('emailField');
const flag1 = document.getElementById('okButton');
const img1 = document.getElementById('img1');

emailField.addEventListener('keyup', function (event) {
  isValidEmail = emailField.checkValidity();

  if ( isValidEmail ) {
        flag1.style="display:inline";
        img1.style="display:block"";
  } else {
        flag1.style="display:none";
        img1.style="display:none";
 }
});

okButton.addEventListener('click', function (event) {
  signUpForm.submit();
});
</script>

</body>
</html>
</code>```

答:
```<code><html>
</head>
<body>
<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>
  <!--You Missed Equlas to sign in id -->
  <img id ="img1" src="valid.jpg" width=100px style="display:none"/>

</form>

<script>
const signUpForm = document.getElementById('signUpForm');
const emailField = document.getElementById('emailField');
const flag1 = document.getElementById('okButton');
const img1 = document.getElementById('img1');

emailField.addEventListener('keyup', function (event) {
  isValidEmail = emailField.checkValidity();

  if ( isValidEmail ) {
        flag1.style="display:inline";
        img1.style="display:block";
  } else {
        flag1.style="display:none";
        img1.style="display:none";
 }
});

okButton.addEventListener('click', function (event) {
  signUpForm.submit();
});
</script>

</body>
</html>```
</code>```

Title: How to show or hide image in HTML

Body:
In the following HTML/JS code, if I enter a valid e-mail id a command button and a tick mark should appear. But command button works fine. Tick mark is not appearing. Any one please help.

<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>

</form>


问:
Remove highlight on press in tablayout

How to disable this highlight on pressing the tab. I have been searching for half an hour and couldn't figure it out. I am using tablayout.

答:
Add the below line to your XML:</p>

```<code>app:tabRippleColor="@android:color/transparent"
</code>```

Title: Remove highlight on press in tablayout

Body:
Add the below line to your XML:

app:tabRippleColor="@android:color/transparent"


问:
How to take user input using getter and setter
I  have created a getter and setter class as book and from that i am accessing setbookName,setbookPrice,setAuthorName similar get methods too but i am not able to take inputs from user please check my code     </p>

```<code>Scanner sc=new Scanner(System.in);
try
{
    System.out.println("Enter book name:");
    String bookName=sc.nextLine();
    System.out.println("Enter book price:");
    String bookPrice=sc.nextLine();
    System.out.println("Enter author name:");
    String authorName=sc.nextLine();
}
catch(Exception e)
{
    System.out.println("I/O Exception");
}
book b=new book();
b.setBookName(bookName);          //here i am facing error
b.setBookPrice(bookPrice);
b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}
</code>```

<p>// book class</p>

```<code>    class book
   {

     private String bookName;
    private String authorName;
    private String bookPrice;

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(String bookPrice) {
        this.bookPrice = bookPrice;
    }
</code>```

答:
Book Class

```<code>public class Book {
private String BookName;
private String AuthorName;
private double BookPrice;
public String getBookName() {
    return this.BookName;
}
public void setBookName(String bookName) {
    this.BookName = bookName;
}
public String getAuthorName() {
    return AuthorName;
}
public void setAuthorName(String authorName) {
    this.AuthorName = authorName;
}
public double getBookPrice() {
    return this.BookPrice;
}
public void setBookPrice(String bookPrice) {
    try {
        this.BookPrice =Double.valueOf(bookPrice);
    } catch (Exception e) {
        e.printStackTrace();
    }
}}
</code>```

Main class

```<code>public class App {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    String bookName=null;//i think your error in hear
    String bookPrice=null;
    String authorName=null;
    try
    {
        System.out.println("Enter book name:");
        bookName=sc.nextLine();
        System.out.println("Enter book price:");
        bookPrice=sc.nextLine();
        System.out.println("Enter author name:");
        authorName=sc.nextLine();
    }
    catch(Exception e)
    {
        System.out.println("I/O Exception");
    }
    Book b=new Book();
    b.setBookName(bookName);
    b.setBookPrice(bookPrice);
    b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
    sc.close();
}}
</code>```

this work for me

Body:
I  have created a getter and setter class as book and from that i am accessing setbookName,setbookPrice,setAuthorName similar get methods too but i am not able to take inputs from user please check my code

Scanner sc=new Scanner(System.in);
try
{
    System.out.println("Enter book name:");
    String bookName=sc.nextLine();
    System.out.println("Enter book price:");
    String bookPrice=sc.nextLine();
    System.out.println("Enter author name:");
    String authorName=sc.nextLine();
}
catch(Exception e)
{
    System.out.println("I/O Exception");
}
book b=new book();
b.setBookName(bookName);          //here i am facing error
b.setBookPrice(bookPrice);
b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}

// book class

    class book
   {

     private String bookName;
    private String authorName;
    private String bookPrice;

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(String bookPrice) {
        this.bookPrice = bookPrice;
    }

Body:
Book Class

public class Book {
private String BookName;
private String AuthorName;
private double BookPrice;
public String getBookName() {
    return this.BookName;
}
public void setBookName(String bookName) {
    this.BookName = bookName;
}
public String getAuthorName() {
    return AuthorName;
}
public void setAuthorName(String authorName) {
    this.AuthorName = authorName;
}
public double getBookPrice() {
    return this.BookPrice;
}
public void setBookPrice(String bookPrice) {
    try {
        this.BookPrice =Double.valueOf(bookPrice);
    } catch (Exception e) {
        e.printStackTrace();
    }
}}

Main class

public class App {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    String bookName=null;//i think your error in hear
    String bookPrice=null;
    String authorName=null;
    try
    {
        System.out.println("Enter book name:");
        bookName=sc.nextLine();
        System.out.println("Enter book price:");
        bookPrice=sc.nextLine();
        System.out.println("Enter author name:");
        authorName=sc.nextLine();
    }
    catch(Exception e)
    {
        System.out.println("I/O Exception");
    }
    Book b=new Book();
    b.setBookName(bookName);
    b.setBookPrice(bookPrice);
    b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
    sc.close();
}}

this work for me


问:
Help with OnTouch
I am trying to create a few circles when the user touches, and if they touch again depending where they touch another one would show... but when I use the ontouch event.. it crashes... I am new by the way, how can I fix it?

```<code>public class GameView extends View{

    private final float x;
    private final float y;
    private final int r;
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public GameView(Context context, float x, float y, int r) {
        super(context);
        mPaint.setColor(0xFFFF0000);
        this.x = x;
        this.y = y;
        this.r = r;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(x, y, r, mPaint);
    }
</code>```

}

```<code>public class GameActivity extends Activity {
/** Called when the activity is first created. */
GameView gm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

    main.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(final View v, MotionEvent e) {
             final float x = e.getX();
             final float y = e.getY();
              final Handler handler = new Handler()
              {
                public void handleMessage(Message msg) {

                         gm.postInvalidate();

                  }
                };
                Thread graphicThread = new Thread()
                {
                    public void run() {

                        try {

                            //Do the drop
                               FrameLayout flView = (FrameLayout) v;
                              flView.addView(new GameView(getParent(), x,y,25));

                                 Thread.sleep(1000);

                                 handler.sendMessage(handler.obtainMessage());
                            }
                         catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                    };
                     boolean isRunning=true;
                    graphicThread.start();
                    return true;

                    }

    });

  }
}
</code>```

答:
It could be anything really, but one thing you never do is instantiate your gm. When you do this

```<code> gm.postInvalidate();
</code>```

You probably get a nullpointerexception. This isn't enough:

```<code>GameView gm;
</code>```

You need to actually call

```<code>gm = new GameView(/*insert stuff here*/);
</code>```

Title: Help with OnTouch

Body:
I am trying to create a few circles when the user touches, and if they touch again depending where they touch another one would show... but when I use the ontouch event.. it crashes... I am new by the way, how can I fix it?

public class GameView extends View{

    private final float x;
    private final float y;
    private final int r;
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public GameView(Context context, float x, float y, int r) {
        super(context);
        mPaint.setColor(0xFFFF0000);
        this.x = x;
        this.y = y;
        this.r = r;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(x, y, r, mPaint);
    }

}

public class GameActivity extends Activity {
/** Called when the activity is first created. */
GameView gm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

    main.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(final View v, MotionEvent e) {
             final float x = e.getX();
             final float y = e.getY();
              final Handler handler = new Handler()
              {
                public void handleMessage(Message msg) {

                         gm.postInvalidate();

                  }
                };
                Thread graphicThread = new Thread()
                {
                    public void run() {

                        try {

                            //Do the drop
                               FrameLayout flView = (FrameLayout) v;
                              flView.addView(new GameView(getParent(), x,y,25));

                                 Thread.sleep(1000);

                                 handler.sendMessage(handler.obtainMessage());
                            }
                         catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                    };
                     boolean isRunning=true;
                    graphicThread.start();
                    return true;

                    }

    });

  }
}

Body:
It could be anything really, but one thing you never do is instantiate your gm. When you do this

 gm.postInvalidate();

You probably get a nullpointerexception. This isn't enough:

GameView gm;

You need to actually call

gm = new GameView(/*insert stuff here*/);


问:
Create new repo and have all the 'old" repo files in the new one
I have an existing repository that almost hit the 2G limits.
I need to try for the first try to shrink it as much as I can in the way that I will make the old deleted files history to be deleted and therefor I will have some more free space in the repository.

I want to have my first try doing that on a copy of the old repository that I will have in a new repository that I created.

Since I do not know GIT very well and I afraid to damaged the existing repository I asking for any help that you can send to me in order to see how all the setups that needs to be done actually goes and as a side affect I will see how much free space I will have due this process.

I tried to follow this guide: https://confluence.atlassian.com/bitbucket/reduce-repository-size-321848262.html but I really afraid doing that by my self with no help.
Thanks again for your help.

I crated a copy of the "old" repository and backed it up in other folder.

答:
You can do a tarball export and initialize the new repository there </p>

```<code>cd old_repo #Wherever your git repository is
mkdir ../new_repo

#The following line copies over the files from your existing repository with
#.git files and repository history etc

git archive master | tar -x -C ../new_repo

cd ../new_repo

# Delete any files you want

git init .
git add -A
git commit -a

# Create a new git repository on atlassian or github
git remote add origin <new_repo_url_from_atlassian_or_github>
git push -u origin master # or any other branch
</code>```

Body:
You can do a tarball export and initialize the new repository there

cd old_repo #Wherever your git repository is
mkdir ../new_repo

#The following line copies over the files from your existing repository with
#.git files and repository history etc

git archive master | tar -x -C ../new_repo

cd ../new_repo

# Delete any files you want

git init .
git add -A
git commit -a

# Create a new git repository on atlassian or github
git remote add origin <new_repo_url_from_atlassian_or_github>
git push -u origin master # or any other branch