问:
How to write CUDA code to print out the CUDA capable devices?
How to write the CUDA code to print out the CUDA capable devices on the computer.</p>

答:
This is directly from the nvidia developer site:

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

int main() {
  int nDevices;

  cudaGetDeviceCount(&nDevices);
  for (int i = 0; i < nDevices; i++) {
    cudaDeviceProp prop;
    cudaGetDeviceProperties(&prop, i);
    printf("Device Number: %d\n", i);
    printf("  Device name: %s\n", prop.name);
    printf("  Memory Clock Rate (KHz): %d\n",
           prop.memoryClockRate);
    printf("  Memory Bus Width (bits): %d\n",
           prop.memoryBusWidth);
    printf("  Peak Memory Bandwidth (GB/s): %f\n\n",
           2.0*prop.memoryClockRate*(prop.memoryBusWidth/8)/1.0e6);
  }
}
</code>```

From their documentation:

http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#device-enumeration

```<code>int deviceCount;
cudaGetDeviceCount (&deviceCount);
int device;
for (device = 0; device < deviceCount; ++device) {
    cudaDeviceProp deviceProp;
    cudaGetDeviceProperties (&deviceProp, device);
    printf ("Device %d has compute capability %d.%d.\n", device,
        deviceProp.major, deviceProp.minor);
}
</code>```

Note

Devices are enumerated from 1...

Body:
This is directly from the nvidia developer site:

#include <stdio.h>

int main() {
  int nDevices;

  cudaGetDeviceCount(&nDevices);
  for (int i = 0; i < nDevices; i++) {
    cudaDeviceProp prop;
    cudaGetDeviceProperties(&prop, i);
    printf("Device Number: %d\n", i);
    printf("  Device name: %s\n", prop.name);
    printf("  Memory Clock Rate (KHz): %d\n",
           prop.memoryClockRate);
    printf("  Memory Bus Width (bits): %d\n",
           prop.memoryBusWidth);
    printf("  Peak Memory Bandwidth (GB/s): %f\n\n",
           2.0*prop.memoryClockRate*(prop.memoryBusWidth/8)/1.0e6);
  }
}

From their documentation:

http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#device-enumeration

int deviceCount;
cudaGetDeviceCount (&deviceCount);
int device;
for (device = 0; device < deviceCount; ++device) {
    cudaDeviceProp deviceProp;
    cudaGetDeviceProperties (&deviceProp, device);
    printf ("Device %d has compute capability %d.%d.\n", device,
        deviceProp.major, deviceProp.minor);
}

Note

Devices are enumerated from 1...


来源: stackexchange

问:
How to check if a table exists in a given schema
Postgres 8.4 and greater databases contain common tables in public schema and company specific tables in company schema.

company schema names always start with 'company' and end with the company number.

So there may be schemas like:

```<code>public
company1
company2
company3
...
companynn
</code>```

An application always works with a single company.

The search_path is specified accordingly in odbc or npgsql connection string, like:

```<code>search_path='company3,public'
</code>```

How would you check if a given table exists in a specified companyn schema?

eg:

```<code>select isSpecific('company3','tablenotincompany3schema')
</code>```

should return false, and

```<code>select isSpecific('company3','tableincompany3schema')
</code>```

should return true.

In any case, the function should check only companyn schema passed, not other schemas.

If a given table exists in both public and the passed schema, the function should return true.

It should work for Postgres 8.4 or later.

答:
For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

```<code>/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Postgres 8.4 and greater databases contain common tables in public schema and company specific tables in company schema.

company schema names always start with 'company' and end with the company number.

So there may be schemas like:

public
company1
company2
company3
...
companynn

An application always works with a single company.

The search_path is specified accordingly in odbc or npgsql connection string, like:

search_path='company3,public'

How would you check if a given table exists in a specified companyn schema?

eg:

select isSpecific('company3','tablenotincompany3schema')

should return false, and

select isSpecific('company3','tableincompany3schema')

should return true.

In any case, the function should check only companyn schema passed, not other schemas.

If a given table exists in both public and the passed schema, the function should return true.

It should work for Postgres 8.4 or later.

Body:
For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

ContentLicense: CC BY-SA 3.0


问:
Obj-C, need to create an oject to hold strings / numbers and then update with calculations?
I need to create an array or a dictionary to hold a string and a value, I'm producing a pie chart. I need to loop through the rows from my database query and add a string and a price to an object.

I then need to add up the total price of all the items and change the value in the objects so they are less than 1.

I'm not explaining this very well...

This is what I'm replacing with dynamic data.

```<code>BNPieChart* chart = [[BNPieChart alloc] initWithFrame:myImageRect];
[chart addSlicePortion:0.1 withName:@"Orange 10%"];
[chart addSlicePortion:0.2 withName:@"Fandango 10%"];
[chart addSlicePortion:0.1 withName:@"Blue 10%"];
[chart addSlicePortion:0.1 withName:@"Cerulean 10%"];
[chart addSlicePortion:0.3 withName:@"Green 10%"];
[chart addSlicePortion:0.1 withName:@"Yellow 10%"];
[chart addSlicePortion:0.1 withName:@"Pink 10%"];
</code>```

Notice that when you add the slice values they total 1.

I've tried using a dictionary but the price doesn't seem to fit as a value or a key.

```<code>NSMutableDictionary *dictData = [[[NSMutableDictionary alloc] init] autorelease];

if(error_code == SQLITE_OK) {

    while(sqlite3_step(statementTMP) == SQLITE_ROW)
    {
        // HERE you need to put the data into an array so you can
        // perform calculations on it after the array is filled

        // get price and category string

        [dictData setObject:accumPrice forKey:category];
        i ++;
    }
}
</code>```

Suggestions ?

答:
You will need to use a NSNumber to store int,float,double etc inside of a dictionary.

```<code>NSMutableDictionary *dictData = [[[NSMutableDictionary alloc] init] autorelease];

if(error_code == SQLITE_OK) {

    while(sqlite3_step(statementTMP) == SQLITE_ROW)
    {
        // HERE you need to put the data into an array so you can
        // perform calculations on it after the array is filled

        // get price and category string

        [dictData setObject:[NSNumber numberWithFloat:accumPrice] forKey:category];
        i ++;
    }
}
</code>```

NSNumber Class Refernce

ContentLicense: CC BY-SA 2.5

Body:
I need to create an array or a dictionary to hold a string and a value, I'm producing a pie chart. I need to loop through the rows from my database query and add a string and a price to an object.

I then need to add up the total price of all the items and change the value in the objects so they are less than 1.

I'm not explaining this very well...

This is what I'm replacing with dynamic data.

BNPieChart* chart = [[BNPieChart alloc] initWithFrame:myImageRect];
[chart addSlicePortion:0.1 withName:@"Orange 10%"];
[chart addSlicePortion:0.2 withName:@"Fandango 10%"];
[chart addSlicePortion:0.1 withName:@"Blue 10%"];
[chart addSlicePortion:0.1 withName:@"Cerulean 10%"];
[chart addSlicePortion:0.3 withName:@"Green 10%"];
[chart addSlicePortion:0.1 withName:@"Yellow 10%"];
[chart addSlicePortion:0.1 withName:@"Pink 10%"];

Notice that when you add the slice values they total 1.

I've tried using a dictionary but the price doesn't seem to fit as a value or a key.

NSMutableDictionary *dictData = [[[NSMutableDictionary alloc] init] autorelease];

if(error_code == SQLITE_OK) {

    while(sqlite3_step(statementTMP) == SQLITE_ROW)
    {
        // HERE you need to put the data into an array so you can
        // perform calculations on it after the array is filled

        // get price and category string

        [dictData setObject:accumPrice forKey:category];
        i ++;
    }
}

Suggestions ?

Body:
You will need to use a NSNumber to store int,float,double etc inside of a dictionary.

NSMutableDictionary *dictData = [[[NSMutableDictionary alloc] init] autorelease];

if(error_code == SQLITE_OK) {

    while(sqlite3_step(statementTMP) == SQLITE_ROW)
    {
        // HERE you need to put the data into an array so you can
        // perform calculations on it after the array is filled

        // get price and category string

        [dictData setObject:[NSNumber numberWithFloat:accumPrice] forKey:category];
        i ++;
    }
}

NSNumber Class Refernce


问:
C++ - Is there a way for a template class specialization to contain code from the general template?
Given a C++ class:

```<code>template<typename T>
class A {
public:
    int a;
    T x;
    int getA() {return a;}
};
</code>```

Is it possible for a template specialization to 'inherit' (without actual C++ inheritance) members like a and getA() from A? Furthermore, when writing code that does a lot of template specializations for classes, should I type the same code many times (which kinda defeats the whole purpose of templates), or restructure the class so that it accommodates for the specializations (e.g. by encapsulating another template class member inside so that specializations are limited to that class only)?

答:
If you don't want additional classes then you can trick a little bit like in:

```<code>template <class T>
class A {
public:
        void f() { cout << "here" << endl; }
};

template <> class A<char> : private A<A<char> >  {
public:
        using A<A<char> >::f;
};
</code>```

Of course one would like to be able to write template <> class A<char> : private A<char> and obtain a specialization that inherits from the generic case, but it is not possible, so I used a trick to instanciate the generic case with some type (here something like CRTP but one can use any other type).

Another trick would be to use a second type and a default value.

Body:
Given a C++ class:

template<typename T>
class A {
public:
    int a;
    T x;
    int getA() {return a;}
};

Is it possible for a template specialization to 'inherit' (without actual C++ inheritance) members like a and getA() from A? Furthermore, when writing code that does a lot of template specializations for classes, should I type the same code many times (which kinda defeats the whole purpose of templates), or restructure the class so that it accommodates for the specializations (e.g. by encapsulating another template class member inside so that specializations are limited to that class only)?

Body:
If you don't want additional classes then you can trick a little bit like in:

template <class T>
class A {
public:
        void f() { cout << "here" << endl; }
};

template <> class A<char> : private A<A<char> >  {
public:
        using A<A<char> >::f;
};

Of course one would like to be able to write template <> class A<char> : private A<char> and obtain a specialization that inherits from the generic case, but it is not possible, so I used a trick to instanciate the generic case with some type (here something like CRTP but one can use any other type).

Another trick would be to use a second type and a default value.


问:
PHP session_start cookie doesn't save session id
On my server i am starting a new session by calling a static class function.
The problem is that the session id is not being saved in the session cookie, furthermore it seems that no session cookie is being saved at the client (eg. chrome doesn't display a cookie for the website).
Printing out $_COOKIE results in array(0) { }. Same with $_SESSION.

Here is the static class function which starts a new session:

```<code><?php
class Session
{
    private function __construct() { }

    public static function sec_session_start()
    {
        $session_name = 'sec_session_id';
        $secure = TRUE;                     // https only
        $httponly = true;                   // javascript can't access session id

        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams['lifetime'],
            '/',
            'www.example-domain.de',
            $secure,
            $httponly);

        session_name($session_name);
        session_start();
        session_regenerate_id();
    }
}
?>
</code>```

And at the top of every page i am starting the session with

```<code>Session::sec_session_start();
</code>```

For example when i am at the login page of my website and print out var_dump($_COOKIE) it says array(0) { } instead of array(2) { ["PHPSESSID"]=> string(26) "..." ["sec_session_id"]=> string(26) "..." }.

The php ini looks as follows
php ini

答:
Make sure your website supports https.

session.cookie_secure specifies whether cookies should only be sent
  over secure connections.

http://php.net/manual/en/session.configuration.php#ini.session.cookie-secure

If it doesn't, just set the $secure to false.

Hope this will help.

Body:
On my server i am starting a new session by calling a static class function.
The problem is that the session id is not being saved in the session cookie, furthermore it seems that no session cookie is being saved at the client (eg. chrome doesn't display a cookie for the website).
Printing out $_COOKIE results in array(0) { }. Same with $_SESSION.

Here is the static class function which starts a new session:

<?php
class Session
{
    private function __construct() { }

    public static function sec_session_start()
    {
        $session_name = 'sec_session_id';
        $secure = TRUE;                     // https only
        $httponly = true;                   // javascript can't access session id

        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams['lifetime'],
            '/',
            'www.example-domain.de',
            $secure,
            $httponly);

        session_name($session_name);
        session_start();
        session_regenerate_id();
    }
}
?>

And at the top of every page i am starting the session with

Session::sec_session_start();

For example when i am at the login page of my website and print out var_dump($_COOKIE) it says array(0) { } instead of array(2) { ["PHPSESSID"]=> string(26) "..." ["sec_session_id"]=> string(26) "..." }.

The php ini looks as follows
php ini


问:
Camera permission not automatically granted
I try to access camera using Camera.open()
But it throws exception Fail to connect to camera service.

I checked camera permission in Settings->Apps->MyApp->Permission->Camera and it's not granted.
I have already added camera permission in android manifest.

```<code><uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera2" android:required="true"/>
</code>```

Why is it not automatically granted at the first time ?
What is the best practice to handle this ?

答:
First check if the user grant the permission:

```<code>if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
    == PackageManager.PERMISSION_DENIED)
</code>```

Then, you could use this to request to the user:

```<code>ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);
</code>```

And in marshmallow and later, it appears the dialog

After requesting the permission alert will display to ask permission contains allow and deny options. After clicking action we can get result of the request with the following method.

```<code>@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == MY_CAMERA_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}
</code>```

If you don't believe me, I have taken the answer from here.

Body:
I try to access camera using Camera.open()
But it throws exception Fail to connect to camera service.

I checked camera permission in Settings->Apps->MyApp->Permission->Camera and it's not granted.
I have already added camera permission in android manifest.

<uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera2" android:required="true"/>

Why is it not automatically granted at the first time ?
What is the best practice to handle this ?

Body:
First check if the user grant the permission:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
    == PackageManager.PERMISSION_DENIED)

Then, you could use this to request to the user:

ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);

And in marshmallow and later, it appears the dialog

After requesting the permission alert will display to ask permission contains allow and deny options. After clicking action we can get result of the request with the following method.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == MY_CAMERA_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}

If you don't believe me, I have taken the answer from here.


问:
SWFObject is undefined
I'm getting the following error in my Flash Builder project. This is my file structure

Flex Project

src

lib

bin

html-template

```<code>Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Timestamp: Wed, 19 Jan 2011 13:29:11 UTC

Message: Invalid character
Line: 1
Char: 1
Code: 0
URI: file:///D:/branches/v0.0/flash/bin/swfobject.js

Message: 'swfobject' is undefined
Line: 50
Char: 13
Code: 0
URI: file:///D:/branches/v0.0/flash/bin/something.html
</code>```

Now, if I move swfObject.js into the bin folder. On debug it starts working fine. But when I do a debug again. Builder automatically deletes the Swfobject.js and the error is back again.

Any solution?

答: shouldn't you move swfobject.js to the html-template directory? I think on each compile the bin folder is deleted and recreated with the content of the html template, plus the new swf file.</p>

Title: SWFObject is undefined

Body:
I'm getting the following error in my Flash Builder project. This is my file structure

Flex Project

src

lib

bin

html-template

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Timestamp: Wed, 19 Jan 2011 13:29:11 UTC

Message: Invalid character
Line: 1
Char: 1
Code: 0
URI: file:///D:/branches/v0.0/flash/bin/swfobject.js

Message: 'swfobject' is undefined
Line: 50
Char: 13
Code: 0
URI: file:///D:/branches/v0.0/flash/bin/something.html

Now, if I move swfObject.js into the bin folder. On debug it starts working fine. But when I do a debug again. Builder automatically deletes the Swfobject.js and the error is back again.

Any solution?


问:
pip install error: ModuleNotFoundError No module named 'setuptools'
When I run pip install virtualenvwrapper-win in a PowerShell console I get the error:

PS C:\Windows\system32> pip install virtualenvwrapper-win
  Collecting virtualenvwrapper-win
    Using cached virtualenvwrapper-win-1.2.1.zip
      Complete output from command python setup.py egg_info:
      Traceback (most recent call last):
        File "", line 1, in
      ModuleNotFoundError: No module named 'setuptools'

Command "python setup.py egg_info" failed with error code 1 in

I've tried doing pip install setuptools and also tried uninstalling and reinstalling and update but the error persists.

pip and python executables have been added to environment variables.

答:
virtualenvwrapper-win is only intended for the DOS cmd.exe.  From the README:

These scripts should work on any version of Windows (Windows XP, Windows Vista, Windows 7/8/10).

However, they only work in the regular command prompt. They will not work in Powershell. There are other virtualenvwrapper projects out there for Powershell.


问:
Django File upload - Path to file
I am uploading a file using the model.FileField method, but I am at a loss on how to actually return the path of the uploaded file (I can't recreate the path as there can be duplicate files and the imagename changes)

Views.py

```<code>if form.is_valid():

        newdoc = Invoices(docfile = request.FILES['docfile'])
        newdoc.save()
</code>```

Models.py

```<code>class Invoices(models.Model):
    docfile = models.FileField(upload_to='invoices/')
    timestamp = models.DateTimeField(auto_now_add=True)
    username = models.CharField(max_length=20, default="default_user")
</code>```

I found some references to document.uploaded_file path etc, but they throw an error - no property document. Is it possible using the method above to get the actual path to the saved file including the possibly changed filename?

答: You can get the full filesystem path to your file accessing newdoc.docfile.path - in a template you'll definitely want to use the {{ newdoc.docfile.url }} attribute. For more information see documentation on FileField.

Title: Django File upload - Path to file

Body:
I am uploading a file using the model.FileField method, but I am at a loss on how to actually return the path of the uploaded file (I can't recreate the path as there can be duplicate files and the imagename changes)

Views.py

if form.is_valid():

        newdoc = Invoices(docfile = request.FILES['docfile'])
        newdoc.save()

Models.py

class Invoices(models.Model):
    docfile = models.FileField(upload_to='invoices/')
    timestamp = models.DateTimeField(auto_now_add=True)
    username = models.CharField(max_length=20, default="default_user")

I found some references to document.uploaded_file path etc, but they throw an error - no property document. Is it possible using the method above to get the actual path to the saved file including the possibly changed filename?


问:
Image is not showing up in Whatsapp link
I want to display the image when I paste the link of webpage to whatsapp. But somehow it's not showing up there. I've been able to show the description but image is not showing till yet. I have tried all the snippets on so but couldn't be succeeded somehow. Any help will be appreciated. Thanks.

Code:

```<code>    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>

    <meta name="description" content="description of my website">
    <meta property="og:title" content="title of my page heading" />
    <meta property="og:url" content="http://www.example.com/example.php" />
    <meta property="og:description" content="desc">

    <meta property="og:image" itemprop="image" content="http://urlOfmyimage.jpg">
   <meta itemprop="width" content="256">
    <meta itemprop="height" content="256">
    <meta property="og:type" content="article" />
</code>```

答:
thanks to your question, I did some research and solved it.

you need an image less than 50 or 100 kb.

```<code><meta  property="og:type" content="...">
<meta  property="og:url" content="...">
<meta  property="og:title" content="...">
<meta  property="og:image" content="...jpg">
<meta  property="og:description" content="...">
<meta  property="og:site_name" content="...">
</code>```

Body:
I want to display the image when I paste the link of webpage to whatsapp. But somehow it's not showing up there. I've been able to show the description but image is not showing till yet. I have tried all the snippets on so but couldn't be succeeded somehow. Any help will be appreciated. Thanks.

Code:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>

    <meta name="description" content="description of my website">
    <meta property="og:title" content="title of my page heading" />
    <meta property="og:url" content="http://www.example.com/example.php" />
    <meta property="og:description" content="desc">

    <meta property="og:image" itemprop="image" content="http://urlOfmyimage.jpg">
   <meta itemprop="width" content="256">
    <meta itemprop="height" content="256">
    <meta property="og:type" content="article" />

Body:
thanks to your question, I did some research and solved it.

you need an image less than 50 or 100 kb.

<meta  property="og:type" content="...">
<meta  property="og:url" content="...">
<meta  property="og:title" content="...">
<meta  property="og:image" content="...jpg">
<meta  property="og:description" content="...">
<meta  property="og:site_name" content="...">


问:
How to not lose elements with same values from a TreeMap?
```<code>class CompoundKey implements Comparable<CompoundKey>{
        String key;
        Integer count;

        public CompoundKey(String key, Integer count){
            this.key = key;
            this.count = count;
        }

        @Override
        public int compareTo(@Nonnull CompoundKey other) {
            return (other.count.compareTo(this.count));
        }
    }

    public static void main(String[] args) {

        Map<CompoundKey, Integer> map = new TreeMap<>();
        map.put(new CompoundKey("a", 3), 3);
        map.put(new CompoundKey("b", 1), 1);
        map.put(new CompoundKey("c", 8), 8);
        map.put(new CompoundKey("d", 3), 3);
        map.put(new CompoundKey("e", 9), 9);

        for (CompoundKey key : map.keySet()) {
            System.out.println(key.key + "->" + map.get(key));
        }
    }
</code>```

This will print out as below:

```<code>e->9
c->8
a->3
b->1
</code>```

In the print out, the 'd->3' is missing. The purpose of this implementation is to create a map sorted by value when element is inserted (I don't need an implementation that will sort the map after all are inserted).

Is there some minor modification of my code to not lose the element with duplicate values? In the case of two duplicate values, the sorting order can be random.

答:
Be sure to factor in the String as part of your Comparable.  For instance (your exact logic may want to vary):

```<code>public int compareTo(CompoundKey other) {
    return other.count.compareTo(this.count) + other.key.compareTo(this.key);
}
</code>```

Because it only looks at numbers right now, it will only ever count numerals as being the natural order.  You need to include key as a part of this.

Body:
class CompoundKey implements Comparable<CompoundKey>{
        String key;
        Integer count;

        public CompoundKey(String key, Integer count){
            this.key = key;
            this.count = count;
        }

        @Override
        public int compareTo(@Nonnull CompoundKey other) {
            return (other.count.compareTo(this.count));
        }
    }

    public static void main(String[] args) {

        Map<CompoundKey, Integer> map = new TreeMap<>();
        map.put(new CompoundKey("a", 3), 3);
        map.put(new CompoundKey("b", 1), 1);
        map.put(new CompoundKey("c", 8), 8);
        map.put(new CompoundKey("d", 3), 3);
        map.put(new CompoundKey("e", 9), 9);

        for (CompoundKey key : map.keySet()) {
            System.out.println(key.key + "->" + map.get(key));
        }
    }

This will print out as below:

e->9
c->8
a->3
b->1

In the print out, the 'd->3' is missing. The purpose of this implementation is to create a map sorted by value when element is inserted (I don't need an implementation that will sort the map after all are inserted).

Is there some minor modification of my code to not lose the element with duplicate values? In the case of two duplicate values, the sorting order can be random.

Body:
Be sure to factor in the String as part of your Comparable.  For instance (your exact logic may want to vary):

public int compareTo(CompoundKey other) {
    return other.count.compareTo(this.count) + other.key.compareTo(this.key);
}

Because it only looks at numbers right now, it will only ever count numerals as being the natural order.  You need to include key as a part of this.


问:
Error when referring to many multiple named ranges in Range property
I have around 236 named ranges (columns) for a large table of data. I get this error when trying to split up the long code-line of delimited named ranges:

Run-time error '1004' Application-defined or object-defined error

E.g.:

```<code>Worksheets("Sheet1").Range("foo1,foo2" _
    & "foo3,foo4" _
    & "..." _
    & "foo235,foo236")
</code>```

I am trying to filter and unfilter columns based on specific criteria (named ranges). Everything seems to work fine (for smaller strings that only span 1 line in length) until I have to split the code into multiple lines since it reaches the end of the window..

Code -

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$B$3" Then
        Worksheets("Sheet1").Range("Fruit," _
            & "Months,Colour").EntireColumn.Hidden = Target.Value = "CustomView"
    End If

    If Target.Address = "$B$3" Then
        Worksheets("Sheet1").Range("Colour,Number" _
            & "Months").EntireColumn.Hidden = Target.Value = "Custom2View"
    End If
End Sub
</code>```

This code doesn't seem to work. I think it has something to do with the quotes and how excel reads it but i haven't been able to find a fix yet.

New code being tested based on suggestions in comments results in an error Run-time error '1004' Application-defined or object-defined error

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

Dim arr, i As Long, rng As Range

If Target.Address = "$B$3" Then
    arr = Split("foo1,foo2,foo3,...,foo266,foo267", ",")
 Set rng = Worksheets("Database").Range(arr(0))
 For i = 1 To UBound(arr)
 Set rng = Application.Union(rng, Worksheets("Database").Range(arr(i)))
 Next i
 rng.EntireColumn.Hidden = (Target.Value = "CustomView")
End If

End Sub
</code>```

答:
You can use Application.Union to build up a range and then hide/show that range in one shot.

EDIT: based on your second shared file I think you need something like this.  Your previous code was not checking the value of the "view name" cell and was applying all of the views, leaving you with the last one...

Eg:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    Dim arr, q As Long, rng As Range, sht As Worksheet

    Set sht = Worksheets("Database")

    If Target.Address = "$B$3" Then

        'unhide all columns forst
        sht.UsedRange.EntireColumn.Hidden = False

        Select Case Target.Value
            Case "CustomView"
                arr = Split("A,B,C_,X,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM," & _
                  "AN,AO,AP,AQ,AR,AS,AT,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG," & _
                  "BH,BI,BJ,BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA," & _
                  "CB,CC,CD,CE,CF,CG,CH,CI,CJ,CK,CL,CU,CV,CW,CX,CY,CZ,DA,DB,DC", ",")
            Case "XX100View"
                arr = Split("D,E,F,G,X,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO," & _
                   "AP,AQ,AR,AS,AT,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG,BH,BI,BJ," & _
                   "BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA,CB,CC,CD,CE," & _
                   "CF,CG,CH,CI,CJ,CK,CL,CU,CV,CW,CX,CY,CZ,DA,DB,DC", ",")
            Case "OtherView"
                arr = Split("A,B,D,E,F,G,H,I,X,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM," & _
                    "AN,AO,AP,AQ,AR,AS,AT,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG,BH," & _
                    "BI,BJ,BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA,CB," & _
                    "CC,CD,CE,CF,CG,CH,CI,CJ,CK,CL,CU,CV,CW,CX,CY,CZ,DA,DB,DC", ",")
        End Select

        If Not IsEmpty(arr) Then
            Set rng = sht.Range(arr(0))
            For q = 1 To UBound(arr)
                Set rng = Application.Union(rng, sht.Range(arr(q)))
            Next q
            rng.EntireColumn.Hidden = True '<<edited
        End If 'got a view

    End If 'is view name cell
End Sub
</code>```

PS - your range names don't need to include all of your data: a single cell would be fine, since you use EntireColumn to expand it to the entire sheet height anyway.

Body:
I have around 236 named ranges (columns) for a large table of data. I get this error when trying to split up the long code-line of delimited named ranges:

Run-time error '1004' Application-defined or object-defined error

E.g.:

Worksheets("Sheet1").Range("foo1,foo2" _
    & "foo3,foo4" _
    & "..." _
    & "foo235,foo236")

I am trying to filter and unfilter columns based on specific criteria (named ranges). Everything seems to work fine (for smaller strings that only span 1 line in length) until I have to split the code into multiple lines since it reaches the end of the window..

Code -

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$B$3" Then
        Worksheets("Sheet1").Range("Fruit," _
            & "Months,Colour").EntireColumn.Hidden = Target.Value = "CustomView"
    End If

    If Target.Address = "$B$3" Then
        Worksheets("Sheet1").Range("Colour,Number" _
            & "Months").EntireColumn.Hidden = Target.Value = "Custom2View"
    End If
End Sub

This code doesn't seem to work. I think it has something to do with the quotes and how excel reads it but i haven't been able to find a fix yet.

New code being tested based on suggestions in comments results in an error Run-time error '1004' Application-defined or object-defined error

Private Sub Worksheet_Change(ByVal Target As Range)

Dim arr, i As Long, rng As Range

If Target.Address = "$B$3" Then
    arr = Split("foo1,foo2,foo3,...,foo266,foo267", ",")
 Set rng = Worksheets("Database").Range(arr(0))
 For i = 1 To UBound(arr)
 Set rng = Application.Union(rng, Worksheets("Database").Range(arr(i)))
 Next i
 rng.EntireColumn.Hidden = (Target.Value = "CustomView")
End If

End Sub

Body:
You can use Application.Union to build up a range and then hide/show that range in one shot.

EDIT: based on your second shared file I think you need something like this.  Your previous code was not checking the value of the "view name" cell and was applying all of the views, leaving you with the last one...

Eg:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim arr, q As Long, rng As Range, sht As Worksheet

    Set sht = Worksheets("Database")

    If Target.Address = "$B$3" Then

        'unhide all columns forst
        sht.UsedRange.EntireColumn.Hidden = False

        Select Case Target.Value
            Case "CustomView"
                arr = Split("A,B,C_,X,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM," & _
                  "AN,AO,AP,AQ,AR,AS,AT,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG," & _
                  "BH,BI,BJ,BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA," & _
                  "CB,CC,CD,CE,CF,CG,CH,CI,CJ,CK,CL,CU,CV,CW,CX,CY,CZ,DA,DB,DC", ",")
            Case "XX100View"
                arr = Split("D,E,F,G,X,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO," & _
                   "AP,AQ,AR,AS,AT,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG,BH,BI,BJ," & _
                   "BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA,CB,CC,CD,CE," & _
                   "CF,CG,CH,CI,CJ,CK,CL,CU,CV,CW,CX,CY,CZ,DA,DB,DC", ",")
            Case "OtherView"
                arr = Split("A,B,D,E,F,G,H,I,X,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM," & _
                    "AN,AO,AP,AQ,AR,AS,AT,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG,BH," & _
                    "BI,BJ,BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA,CB," & _
                    "CC,CD,CE,CF,CG,CH,CI,CJ,CK,CL,CU,CV,CW,CX,CY,CZ,DA,DB,DC", ",")
        End Select

        If Not IsEmpty(arr) Then
            Set rng = sht.Range(arr(0))
            For q = 1 To UBound(arr)
                Set rng = Application.Union(rng, sht.Range(arr(q)))
            Next q
            rng.EntireColumn.Hidden = True '<<edited
        End If 'got a view

    End If 'is view name cell
End Sub

PS - your range names don't need to include all of your data: a single cell would be fine, since you use EntireColumn to expand it to the entire sheet height anyway.


问:
Angular2 passing data over services(two Components)
I am trying to pass data between two components via services. I am not sure how can I consume data via services from another component. I am getting the data from the 2. Component via getData() methode and saving it into the data variable. I can print it within the method but not outside from the method and also I tried to pass it to the first component. What is wrong with my code?

1. Component file

```<code>import {Component, OnInit} from '@angular/core';
import {PassProfileDataService} from '../common/PassProfileDataService';

@Component({

    selector: "profile",
    templateUrl: `client/components/profile/profile.component.html`

})

export class ProfileComponent implements OnInit{
public data;

constructor(private _sharedService: PassProfileDataService){}

ngOnInit() {

this.data = this._sharedService.dataStringSource)
  }

}
</code>```

2. Component file

```<code>import {Component} from '@angular/core';
import {PassProfileDataService} from '../common/PassProfileDataService';

@Component({

    selector: "search",
    templateUrl: `client/components/search/search.component.html`

})
export class ProfileComponent{

constructor(private _sharedService: PassProfileDataService){}

this._sharedService.getData(data[0].values)
ngOnInit() {

  }

}
</code>```

3. SharedService

```<code>import {Component, Injectable} from '@angular/core'

@Injectable()
export class PassProfileDataService {

  public dataStringSource;

  // Service message commands
  getData(data: String) {
    this.dataStringSource  data;

  };

}
</code>```

答:
Make a service that holds the data while you switch components. Below is an example.

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class TransfereService {

  constructor(
    private router:Router,
    private companyServiceService:CompanyServiceService
  ) { }

  private data;

  setData(data){
    this.data = data;
  }

  getData(){
    let temp = this.data;
    this.clearData();
    return temp;
  }

  clearData(){
    this.data = undefined;
  }

}
</code>```

Now Consider 2 components Sender and Reciever.

Senders code: This code sets the data to the service and navigates to the receiver.

```<code>import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class SenderComponent implements OnInit {
  constructor(
    private transfereService:TransfereService,
    private router:Router) {}

  somefunction(data){
   this.transfereService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}
</code>```

Reciever's Code: This code fetches the data from service and clears the data as well.

```<code>import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {
 data = this.transfereService.getData();
 constructor(
   private transfereService:TransfereService,
   private router:Router) {
      if(this.data){
        // do whatever needed
      }
      else{
        this.router.navigateByUrl('/sender');
      }
   }
}
</code>```

Body:
I am trying to pass data between two components via services. I am not sure how can I consume data via services from another component. I am getting the data from the 2. Component via getData() methode and saving it into the data variable. I can print it within the method but not outside from the method and also I tried to pass it to the first component. What is wrong with my code?

1. Component file

import {Component, OnInit} from '@angular/core';
import {PassProfileDataService} from '../common/PassProfileDataService';

@Component({

    selector: "profile",
    templateUrl: `client/components/profile/profile.component.html`

})

export class ProfileComponent implements OnInit{
public data;

constructor(private _sharedService: PassProfileDataService){}

ngOnInit() {

this.data = this._sharedService.dataStringSource)
  }

}

2. Component file

import {Component} from '@angular/core';
import {PassProfileDataService} from '../common/PassProfileDataService';

@Component({

    selector: "search",
    templateUrl: `client/components/search/search.component.html`

})
export class ProfileComponent{

constructor(private _sharedService: PassProfileDataService){}

this._sharedService.getData(data[0].values)
ngOnInit() {

  }

}

3. SharedService

import {Component, Injectable} from '@angular/core'

@Injectable()
export class PassProfileDataService {

  public dataStringSource;

  // Service message commands
  getData(data: String) {
    this.dataStringSource  data;

  };

}

Body:
Make a service that holds the data while you switch components. Below is an example.

import { Injectable } from '@angular/core';

@Injectable()
export class TransfereService {

  constructor(
    private router:Router,
    private companyServiceService:CompanyServiceService
  ) { }

  private data;

  setData(data){
    this.data = data;
  }

  getData(){
    let temp = this.data;
    this.clearData();
    return temp;
  }

  clearData(){
    this.data = undefined;
  }

}

Now Consider 2 components Sender and Reciever.

Senders code: This code sets the data to the service and navigates to the receiver.

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class SenderComponent implements OnInit {
  constructor(
    private transfereService:TransfereService,
    private router:Router) {}

  somefunction(data){
   this.transfereService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}

Reciever's Code: This code fetches the data from service and clears the data as well.

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {
 data = this.transfereService.getData();
 constructor(
   private transfereService:TransfereService,
   private router:Router) {
      if(this.data){
        // do whatever needed
      }
      else{
        this.router.navigateByUrl('/sender');
      }
   }
}


问:
What SQL standard is Spark SQL?
I have a hard time finding what SQL commands/syntax is available in Spark SQL. I usually end up finding a variety of Scala function calls.

What standard does Spark SQL comply to? Where can I find an official comprehensive list of the SQL supported by Spark?

To be clear, I am looking for the Spark SQL equivalent of this List of PostgreSQL Commands

答:
This is not complete but Databricks has this... https://docs.databricks.com/spark/latest/spark-sql/index.html

That is the only pseudo official Spark SQL guide on the net.

Title: What SQL standard is Spark SQL?


问:
SQL how can I have sql return one row instead of multiple per distinct ID?
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

```<code>ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50
</code>```

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

```<code>SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID
</code>```

that worked fine.  I would get

```<code>01 2016-08-21
02 2016-10-01
</code>```

I soon realized that I also need PERCENT column.

```<code>SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT
</code>```

but now, I'm getting the multiple rows for ID 01 which is wrong...

```<code>01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50
</code>```

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

```<code>01  2016-08-21  1111  52
02  2016-10-01  1111  50
</code>```

答:
The reason PERCENT defeats the group by is because PERCENT is different between rows and you are removing duplicates with GROUP BY.  PERCENT makes the row different...  You can instead subquery to re-acquire the row from the table that has the same ID and MIN(DATE)

```<code>SELECT dT.ID
      ,dT.DATE
      ,(SELECT T.PERCENT
          FROM TABLE T
         WHERE T.ID = dT.ID AND T.DATE = dT.DATE
       ) AS Percent
  FROM (
         SELECT ID, MIN(DATE) AS DATE
           FROM TABLE
          WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
            AND   CODE = 1111
         GROUP BY ID
       ) AS dT
</code>```

Body:
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID

that worked fine.  I would get

01 2016-08-21
02 2016-10-01

I soon realized that I also need PERCENT column.

SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT

but now, I'm getting the multiple rows for ID 01 which is wrong...

01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

01  2016-08-21  1111  52
02  2016-10-01  1111  50

Body:
The reason PERCENT defeats the group by is because PERCENT is different between rows and you are removing duplicates with GROUP BY.  PERCENT makes the row different...  You can instead subquery to re-acquire the row from the table that has the same ID and MIN(DATE)

SELECT dT.ID
      ,dT.DATE
      ,(SELECT T.PERCENT
          FROM TABLE T
         WHERE T.ID = dT.ID AND T.DATE = dT.DATE
       ) AS Percent
  FROM (
         SELECT ID, MIN(DATE) AS DATE
           FROM TABLE
          WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
            AND   CODE = 1111
         GROUP BY ID
       ) AS dT


问:
Timezone in symfony
I'm trying to run new symfony project by symfony new name_project 2.7.21. Unfortunately, I keep having the error for incorrect time zone. I changed it in my C:\xampp\php\php.ini file. Do I have to change it somewhere else? Many thanks for your help</p>

答:
Hey so I spent a lot of time chasing this down so here's what worked.  To find the real php.ini that you need to change go to Terminal and run the following:
php -i | grep "php.ini"

You'll get a path like this: Configuration File (php.ini) Path => /etc

When you go to that directory you may find that you, in fact, have no php.ini file at all but instead have something named php.ini.default !!!

Copy that bad boy in Terminal like so: sudo cp php.ini.default php.ini

Then open up your new php.ini file and edit the date.timezone = "Europe/Paris"

IMPORTANT!!!  RESTART YOUR LOCAL SERVER!

Then go back to Terminal and run Symfony's complaining-ass validator like so: php my_project_name/bin/symfony_requirements

Title: Timezone in symfony


问:
python domain name split name and extension
How would you split a domain name that will return name and extension</p>

答:
Wow, there are a lot of bad answers here. You can only do this if you know what's on the public suffix list. If you are using split or a regex or something else, you're doing this wrong.

Luckily, this is python, and there's a library for this: https://pypi.python.org/pypi/tldextract

From their readme:

```<code>>>> import tldextract
>>> tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
</code>```

ExtractResult is a namedtuple. Makes it pretty easy.

The advantage of using a library like this is that they will keep up with the additions to the public suffix list so you don't have to.

Body:
Wow, there are a lot of bad answers here. You can only do this if you know what's on the public suffix list. If you are using split or a regex or something else, you're doing this wrong.

Luckily, this is python, and there's a library for this: https://pypi.python.org/pypi/tldextract

From their readme:

>>> import tldextract
>>> tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')

ExtractResult is a namedtuple. Makes it pretty easy.

The advantage of using a library like this is that they will keep up with the additions to the public suffix list so you don't have to.


问:
Change Magento Template
I have been asked by a customer to edit there ecommerce website, the cms system they use is Magento, how would i go about changing the category page html coding as i need to change a h2 to a h1. Were is it stored on the FTP so i can download edit html and then reupload. i have tried to go to /public_html/app/design/frontend/base/mylightbulb/template/catalog/category and the view.phtml does not contain the html i am after

Thanks

答: Magento's template is quite complicated (but flexible), but one way to find out where the HTML for a 'block' is located is by enabling Template Path Hints.</p>

Title: Change Magento Template


问:
Replace string with output of command, different each time
I have many files and I want to replace the class names with a UUID. I figured out this

```<code>sed -i -r "s/ Class \w(\w|\d)+/ Class C$(python -c 'import uuid;print(uuid.uuid4().hex)')/"
</code>```

It works fine when the pattern only occurs once in each file. However if the pattern occurs more than once, each occurence is replaced by the same number.

Class1.vb

```<code>Public Class Class1
    Public ReadOnly Property P As String = "hello"
End Class

Public Class Class2
    Public ReadOnly Property P As String = "hello"
End Class
</code>```

$ sed -r "s/ Class \w(\w|\d)+/ Class C$(echo $RANDOM)/" Class1.vb
Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class

Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class
```

I expect the two classes to have different names. How do I fix my script?

答:
```<code>$ awk '{gsub(/Class [[:alnum:]]+/, "Class C" int(9999*rand()))} 1' Class1.vb
Public Class C2377
    Public ReadOnly Property P As String = "hello"
End Class

Public Class C5854
    Public ReadOnly Property P As String = "hello"
End Class
</code>```

The above will give you the same random numbers in the same order each time.  If you want different random numbers each time you run the program, use:

```<code>awk -v s=$RANDOM 'BEGIN{srand(s)} {gsub(/Class [[:alnum:]]+/, "Class C" int(9999*rand()))} 1' Class1.vb
</code>```

How it works

gsub(/Class [[:alnum:]]+/, "Class C" int(9999*rand()))

This looks for occurrences of the regex Class [[:alnum:]]+ and replaces each one with the concatenation of the string Class C and a four-digit random number calculated from int(9999*rand()).  A new random number is generated for each line.

1

This is awk's cryptic shorthand for print-the-current-line.

Body:
I have many files and I want to replace the class names with a UUID. I figured out this

sed -i -r "s/ Class \w(\w|\d)+/ Class C$(python -c 'import uuid;print(uuid.uuid4().hex)')/"

It works fine when the pattern only occurs once in each file. However if the pattern occurs more than once, each occurence is replaced by the same number.

Class1.vb

Public Class Class1
    Public ReadOnly Property P As String = "hello"
End Class

Public Class Class2
    Public ReadOnly Property P As String = "hello"
End Class

$ sed -r "s/ Class \w(\w|\d)+/ Class C$(echo $RANDOM)/" Class1.vb
Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class

Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class

I expect the two classes to have different names. How do I fix my script?

Body:
$ awk '{gsub(/Class [[:alnum:]]+/, "Class C" int(9999*rand()))} 1' Class1.vb
Public Class C2377
    Public ReadOnly Property P As String = "hello"
End Class

Public Class C5854
    Public ReadOnly Property P As String = "hello"
End Class

The above will give you the same random numbers in the same order each time.  If you want different random numbers each time you run the program, use:

awk -v s=$RANDOM 'BEGIN{srand(s)} {gsub(/Class [[:alnum:]]+/, "Class C" int(9999*rand()))} 1' Class1.vb

How it works

gsub(/Class [[:alnum:]]+/, "Class C" int(9999*rand()))

This looks for occurrences of the regex Class [[:alnum:]]+ and replaces each one with the concatenation of the string Class C and a four-digit random number calculated from int(9999*rand()).  A new random number is generated for each line.

1

This is awk's cryptic shorthand for print-the-current-line.


问:
Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:25.0.1

Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:25.0.1

  Error:(23, 24) Failed to resolve: com.android.support.test.espresso:espresso-core:2.0

Here is my gradle file

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.example.jignesh.myapplication"
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
I honestly don't understand why this is not automatically catered for when you create a new project...
Solution is to add

```<code> maven {
            url "https://maven.google.com"
        }
</code>```

under allprojects => repositories in project level build.gradle

Body:
Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:25.0.1

  Error:(23, 24) Failed to resolve: com.android.support.test.espresso:espresso-core:2.0

Here is my gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.example.jignesh.myapplication"
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
}

Body:
I honestly don't understand why this is not automatically catered for when you create a new project...
Solution is to add

 maven {
            url "https://maven.google.com"
        }

under allprojects => repositories in project level build.gradle


问:
No output displayed from for loop
I'm trying to write a for loop to repeat (c) and (d) 100 times. I want to print the estimates of TRS-TRS0 at each iteration of the for loop. It should stop algorithm if it is small (say 1/10000). Finally I want it to create a plot in which each of these values is displayed.

I think I have everything here, but when I run it I don't see anything happen. Am I missing something?

```<code>for (i in 1:100){
  #c)
  fit1 = loess(res~x2, data=data.frame(res,x1,x2))
  f2=predict(fit1,newdata=data.frame(res,x1,x2))
  res=data$y-mean(data$y) -f2
  #d)
  fit2 = loess(res~x1, data=data.frame(res,x1,x2))
  f1=predict(fit2,newdata=data.frame(res,x1,x2))
  res=data$y - mean(data$y)-f1

  TSR=sum((data$y-mean(data$y)-f1-f2)^2);TSR
  if (abs(TSR-TSR0) > delta) TSR0=TSR else break
  #continue
  if (abs(TSR-TSR0) < delta) break
  TSR0=TSR
  val=TSR-TSR0;val
  x11(); plot(x1,f1); plot(x2,f2)
}
</code>```

To reproduce, here is the created data:

```<code>set.seed(3)
x1=runif(300);x2=runif(300)
error=rnorm(300,mean=0,sd=3)
z1=-2+3*x1; z2=2*sin(2*pi*x2)
data=data.frame(x1,x2,y=z1+z2+error)
#fit the model
TSR0=0
f10=0;f20=0
res=data$y-mean(data$y) -f10 -f20;
delta=.0001
</code>```

答:
The confusion is that when you execute just a name as a statement (e.g. in your statement TSR) it normally prints the value of that object to the console. However, inside a loop this default printing is suppressed. You will need to print it explicitly with print(TSR).

We can see this behaviour in a simpler example. First try this

```<code>for (i in 1:100) i
</code>```

then try this

```<code>for (i in 1:100) print(i)
</code>```

That explains why you don't see anything printed. But why no plot? Because the loop exits on a break before getting there. This will always happen because you first set TSR0 = TSR, then you break if TSR - TSR0 (which now equals zero by definition) is less than delta.  I think you need to set TSR0 = TSR only after testing the difference between them, not before.

Title: No output displayed from for loop

Body:
I'm trying to write a for loop to repeat (c) and (d) 100 times. I want to print the estimates of TRS-TRS0 at each iteration of the for loop. It should stop algorithm if it is small (say 1/10000). Finally I want it to create a plot in which each of these values is displayed.

I think I have everything here, but when I run it I don't see anything happen. Am I missing something?

for (i in 1:100){
  #c)
  fit1 = loess(res~x2, data=data.frame(res,x1,x2))
  f2=predict(fit1,newdata=data.frame(res,x1,x2))
  res=data$y-mean(data$y) -f2
  #d)
  fit2 = loess(res~x1, data=data.frame(res,x1,x2))
  f1=predict(fit2,newdata=data.frame(res,x1,x2))
  res=data$y - mean(data$y)-f1

  TSR=sum((data$y-mean(data$y)-f1-f2)^2);TSR
  if (abs(TSR-TSR0) > delta) TSR0=TSR else break
  #continue
  if (abs(TSR-TSR0) < delta) break
  TSR0=TSR
  val=TSR-TSR0;val
  x11(); plot(x1,f1); plot(x2,f2)
}

To reproduce, here is the created data:

set.seed(3)
x1=runif(300);x2=runif(300)
error=rnorm(300,mean=0,sd=3)
z1=-2+3*x1; z2=2*sin(2*pi*x2)
data=data.frame(x1,x2,y=z1+z2+error)
#fit the model
TSR0=0
f10=0;f20=0
res=data$y-mean(data$y) -f10 -f20;
delta=.0001

Body:
The confusion is that when you execute just a name as a statement (e.g. in your statement TSR) it normally prints the value of that object to the console. However, inside a loop this default printing is suppressed. You will need to print it explicitly with print(TSR).

We can see this behaviour in a simpler example. First try this

for (i in 1:100) i

then try this

for (i in 1:100) print(i)

That explains why you don't see anything printed. But why no plot? Because the loop exits on a break before getting there. This will always happen because you first set TSR0 = TSR, then you break if TSR - TSR0 (which now equals zero by definition) is less than delta.  I think you need to set TSR0 = TSR only after testing the difference between them, not before.


问:
how do i pass arrays in java
I am trying to compare to arrays defined in the main method and need to pass them to the compareAnswers method how do I do this?

here is my code:

```<code>/**********************************************
 *
 * Daniel Wilson
 *
 * CIS129
 *
 * November 15 2017
 *
 * Compaires test answers against correct answers
 *
 * ********************************************/

import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CIS129_DanielWilson_PC6 {

public static void main(String args[]) {

  final int SIZE = 20;
  String[] givenAnswers = new String[SIZE];
  String[] correctAnswers =      { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B",  "C", "D", "A", "D", "C    ", "C", "B", "D", "A"};
  String answers = compareAnswers();

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);

  try{
    System.out.println(Arrays.toString(correctAnswers));
    for (int i = 0; i<SIZE; i++) {
    System.out.println("please enter your answer for question " + (i+1));
      givenAnswers[i] = reader.readLine();
    }
  }catch (IOException e){
            System.out.println("Error reading from user");
      }
}
public static String compareAnswers(){

List<String> tempList = new ArrayList<String>();
for(int i = 0; i < correctAnswers.length; i++)
{
    boolean foundString = false;
    for(int j = 0; j < givenAnswers.length; j++)
    {
        if(givenAnswers[j].equals(correctAnswers[i]))
        {
            foundString = true;
            break;
        }
    }
    if(!foundString)
        tempList.add(givenAnswers[i]);
}
String ammountRight[] = tempList.toArray(new String[0]);
for(int i = 0; i < ammountRight.length; i++)
{
    System.out.println(ammountRight[i]);
  }
 }
}
</code>```

I understand I need to pass by reference but my professor didn't cover that in much detail. any help is appreciated.

答:
how do i pass arrays in java?

java only has call by value;
but java can just pass a reference by copying the reference where needed.

e.g.

```<code>public class Main{
     public static void main(String[] args){
            String[] arr = new String[size];
            // fill your array!

            Main.foo(arr);

     public static void foo(String[] a){
          // do something with your array.
          // if you change a value of the array,
          // the array in main will be changed too.
     }
}
</code>```

Title: how do i pass arrays in java

Body:
I am trying to compare to arrays defined in the main method and need to pass them to the compareAnswers method how do I do this?

here is my code:

/**********************************************
 *
 * Daniel Wilson
 *
 * CIS129
 *
 * November 15 2017
 *
 * Compaires test answers against correct answers
 *
 * ********************************************/

import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CIS129_DanielWilson_PC6 {

public static void main(String args[]) {

  final int SIZE = 20;
  String[] givenAnswers = new String[SIZE];
  String[] correctAnswers =      { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B",  "C", "D", "A", "D", "C    ", "C", "B", "D", "A"};
  String answers = compareAnswers();

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);

  try{
    System.out.println(Arrays.toString(correctAnswers));
    for (int i = 0; i<SIZE; i++) {
    System.out.println("please enter your answer for question " + (i+1));
      givenAnswers[i] = reader.readLine();
    }
  }catch (IOException e){
            System.out.println("Error reading from user");
      }
}
public static String compareAnswers(){

List<String> tempList = new ArrayList<String>();
for(int i = 0; i < correctAnswers.length; i++)
{
    boolean foundString = false;
    for(int j = 0; j < givenAnswers.length; j++)
    {
        if(givenAnswers[j].equals(correctAnswers[i]))
        {
            foundString = true;
            break;
        }
    }
    if(!foundString)
        tempList.add(givenAnswers[i]);
}
String ammountRight[] = tempList.toArray(new String[0]);
for(int i = 0; i < ammountRight.length; i++)
{
    System.out.println(ammountRight[i]);
  }
 }
}

I understand I need to pass by reference but my professor didn't cover that in much detail. any help is appreciated.

Body:
how do i pass arrays in java?

java only has call by value;
but java can just pass a reference by copying the reference where needed.

e.g.

public class Main{
     public static void main(String[] args){
            String[] arr = new String[size];
            // fill your array!

            Main.foo(arr);

     public static void foo(String[] a){
          // do something with your array.
          // if you change a value of the array,
          // the array in main will be changed too.
     }
}


问:
How to ignore unused imports in Python3
We are building a library, and part of that is a module that provides different database interfaces on different systems.

```<code>class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    def __init__():
        pass

class DbInterface2(object):
    """Uses SQLAlchemy, and is useful on system B."""
    def __init__():
        pass
</code>```

We'd like to skip imports that aren't used. For instance, on a system that has MySQLdb, we will use DbInterface1 and should not require SQLAlchemy to be installed. That is, on system A, we would use it like this:

```<code>from ourlibrary.dbinterfaces import DbInterface1

...
</code>```

Obviously, this will not work:

```<code>import MySQLdb
import sqlalchemy

class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    def __init__():
        pass

class DbInterface2(object):
    """Uses SQLAlchemy, and is useful on system B."""
    def __init__():
        pass
</code>```

We assumed that moving the imports into the classes that use them would work, since the library client won't import something it's not using, but it still has failed dependencies.

```<code>class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    import MySQLdb

    def __init__():
        pass

class DbInterface2(object):
    """Uses SQLAlchemy, and is useful on system B."""
    import sqlalchemy

    def __init__():
        pass
</code>```

What is the correct way to do this? Is it even possible?

答:
Why don't you wrap your imports in a try-except block?

```<code>try:
    import MySQLdb
except ImportError:
    pass
try:
    import sqlalchemy
except ImportError:
    pass
</code>```

This should allow to run your script even if neither module is installed.

You can modify the above method to track if the imported modules exist in order to verify if a class can be used on a certain system.

```<code>try:
    import MySQLdb
except ImportError:
    module_MySQLdb = False
else:
    module_MySQLdb = True
</code>```

Then you could store that information in a class variable and check it before instantiating the class.

```<code>class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    is_avaliable = module_MySQLdb
    def __init__(self):
        pass

if DbInterface1.is_avaliable:
    dbm = DbInterface1()
</code>```

Or you could use a dictionary (eg avaliable_modules = {'MySQLdb':module_MySQLdb}) and import it along with your class.

```<code>from ourlibrary.dbinterfaces import DbInterface1, avaliable_modules

if avaliable_modules['MySQLdb']:
    dbm = DbInterface1()
</code>```

Title: How to ignore unused imports in Python3

Body:
We are building a library, and part of that is a module that provides different database interfaces on different systems.

class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    def __init__():
        pass

class DbInterface2(object):
    """Uses SQLAlchemy, and is useful on system B."""
    def __init__():
        pass

We'd like to skip imports that aren't used. For instance, on a system that has MySQLdb, we will use DbInterface1 and should not require SQLAlchemy to be installed. That is, on system A, we would use it like this:

from ourlibrary.dbinterfaces import DbInterface1

...

Obviously, this will not work:

import MySQLdb
import sqlalchemy

class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    def __init__():
        pass

class DbInterface2(object):
    """Uses SQLAlchemy, and is useful on system B."""
    def __init__():
        pass

We assumed that moving the imports into the classes that use them would work, since the library client won't import something it's not using, but it still has failed dependencies.

class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    import MySQLdb

    def __init__():
        pass

class DbInterface2(object):
    """Uses SQLAlchemy, and is useful on system B."""
    import sqlalchemy

    def __init__():
        pass

What is the correct way to do this? Is it even possible?

Body:
Why don't you wrap your imports in a try-except block?

try:
    import MySQLdb
except ImportError:
    pass
try:
    import sqlalchemy
except ImportError:
    pass

This should allow to run your script even if neither module is installed.

You can modify the above method to track if the imported modules exist in order to verify if a class can be used on a certain system.

try:
    import MySQLdb
except ImportError:
    module_MySQLdb = False
else:
    module_MySQLdb = True

Then you could store that information in a class variable and check it before instantiating the class.

class DbInterface1(object):
    """Uses MySQLdb, and is useful on system A."""
    is_avaliable = module_MySQLdb
    def __init__(self):
        pass

if DbInterface1.is_avaliable:
    dbm = DbInterface1()

Or you could use a dictionary (eg avaliable_modules = {'MySQLdb':module_MySQLdb}) and import it along with your class.

from ourlibrary.dbinterfaces import DbInterface1, avaliable_modules

if avaliable_modules['MySQLdb']:
    dbm = DbInterface1()


问:
Pip Not Working On Raspberry Pi For Discord Bot
I wanted to run a discord bot from my raspberry pi so I could have it always running, so I transferred over the bot file.  BTW this bot was made in python.  I get an error saying no module named discord.  This is because I don't have discord installed.  Whenever I try to use pip3 install discord I get a message saying that it was successful, but was installed under Python 3.4.  I need it to be installed under Python 3.5 so that my bot's code will run properly.  If I try to use python3 -m pip install discord I get the error /usr/local/bin/python3: No module named pip.  When I run pip -V I get 3.4. I want to make the version 3.5 instead of 3.4, but even after running the get-pip.py file I still am on pip 3.4.  Any help?

答:
I had a similar problem on a different machine. what I did to have the python 3.6 interpreter as the default one for the python 3 command was this:

First, edit your .bashrc file to include the following line export PATH=/path/to/python/bin:$PATH(in this case, I will be using /home/pi/python). Then, download the python 3.6 usingwget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz. Unarchive it using tar -zxvf Python-3.6.3.tgz, and cding into the directory. Then, configure it by doing ./configure --prefix=$HOME/python(Or to the path you had used in .bashrc), and make it using make, and sudo make install. Afterwards, reboot the raspberry pi, and you should now be able to use python 3.6 with the python3 command


问:
Remove virtual environment with virtualenvwrapper-win
I'm trying out virtualenvwrapper-win (on Windows 7), everything works as it should, but when I try to remove virtual environments with rmvirtualenv command I am getting this output:

```<code>> rmvirtualenv env_py3
The directory is not empty.

Deleted C:\Users\User1\Envs\env_py3
</code>```

And the directory (env_py3) contains just one file: pip-selfcheck.json.
How do I fix it without deleting all the directories manually?

答: rmvirtualenv will deactivate the virtualenv for you. The problem you're describing (https://github.com/davidmarble/virtualenvwrapper-win/issues/78) has since been fixed.

Body:
I'm trying out virtualenvwrapper-win (on Windows 7), everything works as it should, but when I try to remove virtual environments with rmvirtualenv command I am getting this output:

> rmvirtualenv env_py3
The directory is not empty.

Deleted C:\Users\User1\Envs\env_py3

And the directory (env_py3) contains just one file: pip-selfcheck.json.
How do I fix it without deleting all the directories manually?


问:
Is it good practice to use exceptions for control flow in Ruby or Ruby on Rails?
I am reading Agile Web Development with Rails (4th ed.) and I have found the following code

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery

  private

  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end
end
</code>```

Since I am a Java developer, my understanding of that part of code is more or less the following:

```<code>private Cart currentCard(){
  try{
    return CartManager.get_cart_from_session(cartId)
  }catch(RecordNotFoundEx e){
    Cart c = CartManager.create_cart_and_add_to_session(new Cart())
    return c;
  }
}
</code>```

That what strikes me is that the exception handling is used to control normal application flow (lack of Cart is perfectly normal behaviour when user visits Depot application for the first time).

If one takes any Java book, they say that this is a very bad thing to do - and for a good reason: error handling shouldn't be used as a replacement for control statements, it's kind of misleading for those who read code.

Is there any good reason why such a practice is justified in Ruby (Rails)? Is this a common practice in Ruby?

答:
Rails is in no way consistent in its use of exceptions. find will raise an exception if no object is found, but for saving you can choose what behaviour you want. The most common form is this:

```<code>if something.save
  # formulate a reply
else
  # formulate an error reply, or redirect back to a form, or whatever
end
</code>```

i.e. save returns true or false. But there is also save! which raises an exception (adding an exclamation mark to the end of a method name is a Rubyism for showing that a method is "dangerous", or destructive, or simply that it has side-effects, the exact meaning depends on the context).

There is a valid reason for why find raises an exception, though: if a RecordNotFound exception bubbles up to the top level it will trigger the rendering of a 404 page. Since you usually don't catch these exceptions manually (it's rare that you see a rescue ActiveRecord::RecordNotFound in a Rails app), you get this feature for free. In some cases though, you want to do something when an object does not exist, and in those cases you have to catch the exception.

I don't think that the term "best practice" actually means anything, but it is my experience that exceptions aren't used for control of flow in Ruby anymore than in Java or any other language I have used. Given that Ruby doesn't have checked exceptions, you deal with exceptions much less in general.

In the end it's down to interpretation. Since the most common use case for find is retrieving an object to display it, and that the URL for that object will have been generated by the application, it may very well be an exceptional circumstance that the object cannot be found. It means that either the application is generating links to objects that don't exist, or that the user has manually edited the URL. It can also be the case that the object has been removed, but a link to it still exist in a cache, or via a search engine, I would say that that too is an exceptional circumstance.

That argument applies to find when used as in your example, i.e. with an ID. There are other forms of find (including the many find_by_* variants) that actually search, and those don't raise exceptions (and then there is where in Rails 3, which replaces many of the uses of find in Rails 2).

I don't mean to say that using exceptions as control of flow is a good thing to do, just that it's not necessarily wrong that find raises exceptions, and that your particular use case is not the common case.

Body:
I am reading Agile Web Development with Rails (4th ed.) and I have found the following code

class ApplicationController < ActionController::Base
  protect_from_forgery

  private

  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end
end

Since I am a Java developer, my understanding of that part of code is more or less the following:

private Cart currentCard(){
  try{
    return CartManager.get_cart_from_session(cartId)
  }catch(RecordNotFoundEx e){
    Cart c = CartManager.create_cart_and_add_to_session(new Cart())
    return c;
  }
}

That what strikes me is that the exception handling is used to control normal application flow (lack of Cart is perfectly normal behaviour when user visits Depot application for the first time).

If one takes any Java book, they say that this is a very bad thing to do - and for a good reason: error handling shouldn't be used as a replacement for control statements, it's kind of misleading for those who read code.

Is there any good reason why such a practice is justified in Ruby (Rails)? Is this a common practice in Ruby?

Body:
Rails is in no way consistent in its use of exceptions. find will raise an exception if no object is found, but for saving you can choose what behaviour you want. The most common form is this:

if something.save
  # formulate a reply
else
  # formulate an error reply, or redirect back to a form, or whatever
end

i.e. save returns true or false. But there is also save! which raises an exception (adding an exclamation mark to the end of a method name is a Rubyism for showing that a method is "dangerous", or destructive, or simply that it has side-effects, the exact meaning depends on the context).

There is a valid reason for why find raises an exception, though: if a RecordNotFound exception bubbles up to the top level it will trigger the rendering of a 404 page. Since you usually don't catch these exceptions manually (it's rare that you see a rescue ActiveRecord::RecordNotFound in a Rails app), you get this feature for free. In some cases though, you want to do something when an object does not exist, and in those cases you have to catch the exception.

I don't think that the term "best practice" actually means anything, but it is my experience that exceptions aren't used for control of flow in Ruby anymore than in Java or any other language I have used. Given that Ruby doesn't have checked exceptions, you deal with exceptions much less in general.

In the end it's down to interpretation. Since the most common use case for find is retrieving an object to display it, and that the URL for that object will have been generated by the application, it may very well be an exceptional circumstance that the object cannot be found. It means that either the application is generating links to objects that don't exist, or that the user has manually edited the URL. It can also be the case that the object has been removed, but a link to it still exist in a cache, or via a search engine, I would say that that too is an exceptional circumstance.

That argument applies to find when used as in your example, i.e. with an ID. There are other forms of find (including the many find_by_* variants) that actually search, and those don't raise exceptions (and then there is where in Rails 3, which replaces many of the uses of find in Rails 2).

I don't mean to say that using exceptions as control of flow is a good thing to do, just that it's not necessarily wrong that find raises exceptions, and that your particular use case is not the common case.


问:
Don't allow use of non existent keys on a given flow type
given this simple object: { id: 'x', value: 1 }, in TypeScript if you try to do:

```<code>type foo = {
    id: string,
    v: number,
};

const bar: foo = { id: 'something', v: 1111 };

// refrencing non existent key
if (bar.xyz) {
    console.log('xyz');
}
</code>```

you would get an error saying xyz does not exist on foo. How do you get the same result on Flowjs?

I've tried the following but flowjs isn't throwing any errors:

```<code>type foo = {|
    id: string,
    v: number,
|};

const bar: foo = { id: 'something', v: 1111 };

if (bar.xyz) { // no errors
    console.log('xyz');
}
</code>```

答:
Your problem is still exist as an open issue. https://github.com/facebook/flow/issues/106

As long as that issue is open, you can forcefully do type conversion bar.xyz to Boolean.

if (Boolean(bar.xyz))

You will get this error.

10: if (Boolean(bar.xyz)) {
                       ^ property xyz. Property not found in

10: if (Boolean(bar.xyz)) {
                  ^ object type

Body:
given this simple object: { id: 'x', value: 1 }, in TypeScript if you try to do:

type foo = {
    id: string,
    v: number,
};

const bar: foo = { id: 'something', v: 1111 };

// refrencing non existent key
if (bar.xyz) {
    console.log('xyz');
}

you would get an error saying xyz does not exist on foo. How do you get the same result on Flowjs?

I've tried the following but flowjs isn't throwing any errors:

type foo = {|
    id: string,
    v: number,
|};

const bar: foo = { id: 'something', v: 1111 };

if (bar.xyz) { // no errors
    console.log('xyz');
}


问:
Can't get div to show when unchecked
I am trying to use bootstrap toggle to create a switch to change between monthly and annual plans. I got the toggle to function in the sense it moves and looks right but I can not get the JS part to work. So it will only show the monthly div right now and will not switch to the annual div. Currently this is what I have

Toggle

```<code><div class="container">
   <div class="row">
     <div class="col-md-5"></div>
     <div class="col-md-4 selectCenter">
       <br>
       <input type="checkbox" checked  id="toggle" data-toggle="toggle" data-on="Monthly" data-off="Annual" data-style="ios" data-onstyle="primary" data-offstyle="primary">
     </div>
   </div>
</code>```

Monthly div

```<code><section class="se-section" id="monthly">
    <div class="container">
      <div class="row">
       <div class="col-md-4 col-sm-6">
         <h1>Monthly</h1>
       </div> <!-- end col-md-4 -->
      </div> <!-- end row -->
    </div> <!-- end container -->
  </section>
</code>```

Annual div

```<code><section class="se-section" id="annual">
    <div class="container">
      <div class="row">
       <div class="col-md-4 col-sm-6">
         <h1>Annual</h1>
       </div> <!-- end col-md-4 -->
      </div> <!-- end row -->
    </div> <!-- end container -->
  </section>
</code>```

Then my javascript

```<code>var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

if(toggle.checked){
  monthly.style.display = 'block';
  annual.style.display = 'none';
}
if(!toggle.checked){
  monthly.style.display = 'none';
  annual.style.display = 'block';
}
</code>```

答:
Your Javascript is actually only being executed once on page load.  So if you assigned one of them as 'checked' in the HTML to begin with, this would work.  However, nothing is checking whether or not these checkboxes are ticked or not afterwards.

Binding an event handler to an element will allow for this value to be checked again.  Most commonly, a button is used such as an 'Update' button but since you're using a checkbox, you can just tie one to a click event on the checkbox so it will be immediately evaluated whether or not it's checked.

So you need to tie that bit of code to an event such as a button click.  That can be done as such:

```<code>var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

toggle.addEventListener('click', function(){ //bind an anonymous function to a button click for the element referenced by 'toggle'
    if(toggle.checked){
        monthly.style.display = 'block';
        annual.style.display = 'none';
    }
    if(!toggle.checked){
        monthly.style.display = 'none';
        annual.style.display = 'block';
    }
});
</code>```

Now everytime someone clicks that checkbox, the value of the checkbox will be evaluated (checked or not) and will apply the proceeding effects to the style.

You can also abstract some of the details and create a named function that handles the checking and you can simply call the named function instead of an anonymous function upon the click event.

```<code>function checkTimeframe(){
    if(toggle.checked){
        monthly.style.display = 'block';
        annual.style.display = 'none';
    }
    if(!toggle.checked){
        monthly.style.display = 'none';
        annual.style.display = 'block';
    }
}
var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

toggle.addEventListener('click', checkTimeframe);
</code>```

Title: Can't get div to show when unchecked

Body:
I am trying to use bootstrap toggle to create a switch to change between monthly and annual plans. I got the toggle to function in the sense it moves and looks right but I can not get the JS part to work. So it will only show the monthly div right now and will not switch to the annual div. Currently this is what I have

Toggle

       <input type="checkbox" checked  id="toggle" data-toggle="toggle" data-on="Monthly" data-off="Annual" data-style="ios" data-onstyle="primary" data-offstyle="primary">

Monthly div

Monthly

Annual div

Annual

Then my javascript

var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

if(toggle.checked){
  monthly.style.display = 'block';
  annual.style.display = 'none';
}
if(!toggle.checked){
  monthly.style.display = 'none';
  annual.style.display = 'block';
}

Body:
Your Javascript is actually only being executed once on page load.  So if you assigned one of them as 'checked' in the HTML to begin with, this would work.  However, nothing is checking whether or not these checkboxes are ticked or not afterwards.

Binding an event handler to an element will allow for this value to be checked again.  Most commonly, a button is used such as an 'Update' button but since you're using a checkbox, you can just tie one to a click event on the checkbox so it will be immediately evaluated whether or not it's checked.

So you need to tie that bit of code to an event such as a button click.  That can be done as such:

var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

toggle.addEventListener('click', function(){ //bind an anonymous function to a button click for the element referenced by 'toggle'
    if(toggle.checked){
        monthly.style.display = 'block';
        annual.style.display = 'none';
    }
    if(!toggle.checked){
        monthly.style.display = 'none';
        annual.style.display = 'block';
    }
});

Now everytime someone clicks that checkbox, the value of the checkbox will be evaluated (checked or not) and will apply the proceeding effects to the style.

You can also abstract some of the details and create a named function that handles the checking and you can simply call the named function instead of an anonymous function upon the click event.

function checkTimeframe(){
    if(toggle.checked){
        monthly.style.display = 'block';
        annual.style.display = 'none';
    }
    if(!toggle.checked){
        monthly.style.display = 'none';
        annual.style.display = 'block';
    }
}
var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

toggle.addEventListener('click', checkTimeframe);


问:
Reverse a string in php without using any string function
In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().

Uninitialized string offset: -1 in
  D:\xampp\htdocs\PhpProject1\index.php on line xx

```<code>$string = "ZEESHAN";

$i =0;

while(($string[$i])!=null){

        $i++;

}

$i--;

while(($string[$i])!=null){

        echo $string[$i];

$i--;

}
</code>```

答:
```<code>//Program for reversing a string
<?php
class str_rev{
    public function Revese_Str($string){
        $reverse = '';
        $i=0;
        while(!empty($string[$i])){
          $reverse = $string[$i].$reverse;
          $i++;
        }
        return $reverse;
    }
}
$object = new str_rev();
echo $object->Revese_Str('Ayush Jain');
</code>```

Body:
In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().

Uninitialized string offset: -1 in
  D:\xampp\htdocs\PhpProject1\index.php on line xx

$string = "ZEESHAN";

$i =0;

while(($string[$i])!=null){

        $i++;

}

$i--;

while(($string[$i])!=null){

        echo $string[$i];

$i--;

}