问:
Changing color of body report, depending on value in table
I have report in SQL Server 2008.

Report has a parameter, parameter values:

```<code>organization1
organization2
organization3
organization4
</code>```

To display a list of parameter with values, I used "Available Values" "Get values from a query".

If value of organization1 parameter in "Value" column is greater than
20, then report body and background of tables should be in red color.

If selected parameter organization1 background of tables and report body should be in red color.

If selected parameter organization2 background of tables and report body  should not be in red color.

If selected parameter organization3 background of tables  and report body  should be in red color.

If selected parameter organization4 background of tables and report body  should not be in red color.

The expression below does not work for selected parameter.

```<code>=IIF(Fields!AVID.Value, "summ_work">20 and
First(Parameters!ReportParameter1.Value, "test")="Organization1","Red","Transparent")
</code>```

How can I fix it?

答:
You're going to need something like this for the BackGround expression in the report.

```<code>=Switch(Sum(Fields!value.Value, "DataSet1") > 20 And Parameters!Organization.Value = "Organization1", "Red",
    Parameters!Organization.Value = "Organization1", "Red",
    Parameters!Organization.Value = "Organization2", "White",
    Parameters!Organization.Value = "Organization3", "Red",
    Parameters!Organization.Value = "Organization4", "White",
    True, "Yellow")
</code>```

That last line of the Switch is a catch all that will turn the background Yellow. Do what you want with that, or remove it entirely if you don't think the situation will happen where someone passes a parameter value other than what you have in the list.

I went with White as the "should not be in red" color, change that to something else if you like.

Body:
I have report in SQL Server 2008.

Report has a parameter, parameter values:

organization1
organization2
organization3
organization4

To display a list of parameter with values, I used "Available Values" "Get values from a query".

If value of organization1 parameter in "Value" column is greater than
20, then report body and background of tables should be in red color.

If selected parameter organization1 background of tables and report body should be in red color.

If selected parameter organization2 background of tables and report body  should not be in red color.

If selected parameter organization3 background of tables  and report body  should be in red color.

If selected parameter organization4 background of tables and report body  should not be in red color.

The expression below does not work for selected parameter.

=IIF(Fields!AVID.Value, "summ_work">20 and
First(Parameters!ReportParameter1.Value, "test")="Organization1","Red","Transparent")

How can I fix it?

Body:
You're going to need something like this for the BackGround expression in the report.

=Switch(Sum(Fields!value.Value, "DataSet1") > 20 And Parameters!Organization.Value = "Organization1", "Red",
    Parameters!Organization.Value = "Organization1", "Red",
    Parameters!Organization.Value = "Organization2", "White",
    Parameters!Organization.Value = "Organization3", "Red",
    Parameters!Organization.Value = "Organization4", "White",
    True, "Yellow")

That last line of the Switch is a catch all that will turn the background Yellow. Do what you want with that, or remove it entirely if you don't think the situation will happen where someone passes a parameter value other than what you have in the list.

I went with White as the "should not be in red" color, change that to something else if you like.


来源: stackexchange

问:
How to resolve an ImportError working with a graphene django basic setup through tutorial?
I have started working through the graphene_django tutorial for a basic setup using Django and GraphQL.

However, I am unable to progress any further due to an import error:

```<code>ImportError at /graphql
Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema.
Request Method: GET
Request URL:    http://127.0.0.1:8000/graphql
Django Version: 1.11.2
Exception Type: ImportError
Exception Value:
Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema.
Exception Location: /home/mackie/Code/graphene_django_tutorial/env/local/lib/python2.7/site-packages/graphene_django/settings.py in import_from_string, line 78
Python Executable:  /home/mackie/Code/graphene_django_tutorial/env/bin/python
Python Version: 2.7.12
Python Path:
['/home/mackie/Code/graphene_django_tutorial/cookbook',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-tk',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-old',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/mackie/Code/graphene_django_tutorial/env/local/lib/python2.7/site-packages',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/site-packages']
Server time:    Sun, 4 Jun 2017 16:29:46 +0000
</code>```

You can see the current state of the code here in a minimal repo.

I think that my problem has something to do with how I'm running the server: python3 manage.py runserver. Or maybe how I am importing. But I don't know how to do any more debugging from here.

Everything is exactly as stated in the tutorial and nothing seems especially incorrect to me. I'm using Linux with virtualenv as well if that matters.

Let me know if you need any more information I'll be carefully monitoring the thread.

EDIT: Appologies! I had run it with python3 and python 2.7, neither had worked. Here is the trace:

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/graphql

Django Version: 1.10.6
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'graphene_django',
 'ingredients']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
  62.             self = cls(**initkwargs)

File "/usr/local/lib/python2.7/dist-packages/graphene_django/views.py" in __init__
  70.             schema = graphene_settings.SCHEMA

File "/usr/local/lib/python2.7/dist-packages/graphene_django/settings.py" in __getattr__
  116.             val = perform_import(val, attr)

File "/usr/local/lib/python2.7/dist-packages/graphene_django/settings.py" in perform_import
  60.         return import_from_string(val, setting_name)

File "/usr/local/lib/python2.7/dist-packages/graphene_django/settings.py" in import_from_string
  78.         raise ImportError(msg)

Exception Type: ImportError at /graphql
Exception Value: Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema.
</code>```

答:
```<code>GRAPHENE = {
    'SCHEMA': 'cookbook.schema.schema'
}
</code>```

For cookbook.schema to be importable, you would need to place schema.py in the inner cookbook directory (the one that contains settings.py). At the moment, you have it in the outer cookbook directory (the one that contains manage.py). To import it from the outer directory, you would want 'schema.schema' in the setting.

There is similar confusion when the tutorial says to add 'ingredients' to the INSTALLED_APPS setting (suggests it should be in the outer cookbook directory), but the code includes imports like from cookbook.ingredients.models import ... (suggests that ingredients should be in the inner cookbook directory).

You could try moving both the schema.py and the ingredients directory into the inner cookbook directory, and change the entry in INSTALLED_APPS to 'cookbook.ingredients', as in this repo.

ContentLicense: CC BY-SA 3.0

Body:
I have started working through the graphene_django tutorial for a basic setup using Django and GraphQL.

However, I am unable to progress any further due to an import error:

ImportError at /graphql
Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema.
Request Method: GET
Request URL:    http://127.0.0.1:8000/graphql
Django Version: 1.11.2
Exception Type: ImportError
Exception Value:
Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema.
Exception Location: /home/mackie/Code/graphene_django_tutorial/env/local/lib/python2.7/site-packages/graphene_django/settings.py in import_from_string, line 78
Python Executable:  /home/mackie/Code/graphene_django_tutorial/env/bin/python
Python Version: 2.7.12
Python Path:
['/home/mackie/Code/graphene_django_tutorial/cookbook',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-tk',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-old',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/mackie/Code/graphene_django_tutorial/env/local/lib/python2.7/site-packages',
 '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/site-packages']
Server time:    Sun, 4 Jun 2017 16:29:46 +0000

You can see the current state of the code here in a minimal repo.

I think that my problem has something to do with how I'm running the server: python3 manage.py runserver. Or maybe how I am importing. But I don't know how to do any more debugging from here.

Everything is exactly as stated in the tutorial and nothing seems especially incorrect to me. I'm using Linux with virtualenv as well if that matters.

Let me know if you need any more information I'll be carefully monitoring the thread.

EDIT: Appologies! I had run it with python3 and python 2.7, neither had worked. Here is the trace:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/graphql

Django Version: 1.10.6
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'graphene_django',
 'ingredients']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
  62.             self = cls(**initkwargs)

File "/usr/local/lib/python2.7/dist-packages/graphene_django/views.py" in __init__
  70.             schema = graphene_settings.SCHEMA

File "/usr/local/lib/python2.7/dist-packages/graphene_django/settings.py" in __getattr__
  116.             val = perform_import(val, attr)

File "/usr/local/lib/python2.7/dist-packages/graphene_django/settings.py" in perform_import
  60.         return import_from_string(val, setting_name)

File "/usr/local/lib/python2.7/dist-packages/graphene_django/settings.py" in import_from_string
  78.         raise ImportError(msg)

Exception Type: ImportError at /graphql
Exception Value: Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema.

Body:
GRAPHENE = {
    'SCHEMA': 'cookbook.schema.schema'
}

For cookbook.schema to be importable, you would need to place schema.py in the inner cookbook directory (the one that contains settings.py). At the moment, you have it in the outer cookbook directory (the one that contains manage.py). To import it from the outer directory, you would want 'schema.schema' in the setting.

There is similar confusion when the tutorial says to add 'ingredients' to the INSTALLED_APPS setting (suggests it should be in the outer cookbook directory), but the code includes imports like from cookbook.ingredients.models import ... (suggests that ingredients should be in the inner cookbook directory).

You could try moving both the schema.py and the ingredients directory into the inner cookbook directory, and change the entry in INSTALLED_APPS to 'cookbook.ingredients', as in this repo.


问:
How to implement an API key on PHP software?
I am distributing a PHP created plugin like a Wordpress plugin but I want to implement an API key for it and users would need to enter an API key to unlock it for it to work.

How can that be done?  And yes I already know it could be easily bypassed since PHP is not compiled but atleast it will deter some people with no PHP knowledge.

Thanks..

答:
If you don't care about people removing your check then you really only need to add a if statement that validates if the configured license key is valid or not.

I noticed you mentioned your license keys were simply SHA1 hashes. You could easily append an extra 4 characters to the hash, which you could use as checksum.

For instance:

```<code>function generate_key()
{
  $serial = sha1(uniqid(rand(), true));
  $checksum = substr(md5($serial), 0, 4);
  return $serial . $checksum;
}

function verify_key($key)
{
  $serial = substr($key, 0, 40);
  $checksum = substr($key, -4);
  return md5($serial, 0, 4) == $checksum;
}
</code>```

This is a very simple example, but it is simply instructional.

Essentially you would validate whether the license key is valid on the host's server instead of pinging a script on your server.

The drawback of this is that anyone would be able to generate a valid key by opening the source code and finding validate_key.

You could have it call an external script to do the verify_key, but is it really worth the effort? Also, you will be sacrificing page load time to verify the key.

I recall vBulletin having a very easy to crack licensing system, but they had a hidden 1x1 image in a few sections which pinged a script on their domain. Using the logs, they were able to determine which domains were hosting illegal copies of their software and they simply sent a lawyer's letter to the admin.

If you wanted a more robust solution, I would suggest maybe looking into Zend Guard, but you seem not to care about people cracking your software so personally I would just go as simple as possible.

ContentLicense: CC BY-SA 2.5

Body:
If you don't care about people removing your check then you really only need to add a if statement that validates if the configured license key is valid or not.

I noticed you mentioned your license keys were simply SHA1 hashes. You could easily append an extra 4 characters to the hash, which you could use as checksum.

For instance:

function generate_key()
{
  $serial = sha1(uniqid(rand(), true));
  $checksum = substr(md5($serial), 0, 4);
  return $serial . $checksum;
}

function verify_key($key)
{
  $serial = substr($key, 0, 40);
  $checksum = substr($key, -4);
  return md5($serial, 0, 4) == $checksum;
}

This is a very simple example, but it is simply instructional.

Essentially you would validate whether the license key is valid on the host's server instead of pinging a script on your server.

The drawback of this is that anyone would be able to generate a valid key by opening the source code and finding validate_key.

You could have it call an external script to do the verify_key, but is it really worth the effort? Also, you will be sacrificing page load time to verify the key.

I recall vBulletin having a very easy to crack licensing system, but they had a hidden 1x1 image in a few sections which pinged a script on their domain. Using the logs, they were able to determine which domains were hosting illegal copies of their software and they simply sent a lawyer's letter to the admin.

If you wanted a more robust solution, I would suggest maybe looking into Zend Guard, but you seem not to care about people cracking your software so personally I would just go as simple as possible.


问:
app:transformClassesWithJarMergingForDebug'. > com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry
Please need your help...

this my app build.gradle

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.wiimii"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:9.2.1'
    compile 'com.google.firebase:firebase-messaging:9.2.1'
    testCompile 'junit:junit:4.12'
    compile files('libs/httpcore-4.2.3.jar')
    compile files('libs/httpclient-4.0.3.jar')
    compile files('libs/httpmime-4.3.jar')
}
apply plugin: 'com.google.gms.google-services'```

When i press on "build apk" i get this error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/http/annotation/Immutable.class

答:
```<code>**Finally this the way I fix the problem:**
</code>```

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.wiimii"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
//this I adding to fix the http... jar file
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
//necessary
    configurations {
        all*.exclude group: 'com.android.support', module: 'support-v4'
    }
}

dependencies {
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
//also need this for deal with com.android.support.test
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:9.2.1'
    compile 'com.google.firebase:firebase-messaging:9.2.1'
    testCompile 'junit:junit:4.12'
    compile files('libs/httpcore-4.3.3.jar')
    compile files('libs/httpclient-4.3.6.jar')
    compile files('libs/httpmime-4.3.6.jar')
//add this jar file manually to libs directory
    compile files('libs/android-support-v4.jar')

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

Body:
Please need your help...

this my app build.gradle

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.wiimii"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:9.2.1'
    compile 'com.google.firebase:firebase-messaging:9.2.1'
    testCompile 'junit:junit:4.12'
    compile files('libs/httpcore-4.2.3.jar')
    compile files('libs/httpclient-4.0.3.jar')
    compile files('libs/httpmime-4.3.jar')
}
apply plugin: 'com.google.gms.google-services'

When i press on "build apk" i get this error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/http/annotation/Immutable.class

Body:
**Finally this the way I fix the problem:**

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.wiimii"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
//this I adding to fix the http... jar file
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
//necessary
    configurations {
        all*.exclude group: 'com.android.support', module: 'support-v4'
    }
}

dependencies {
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
//also need this for deal with com.android.support.test
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:9.2.1'
    compile 'com.google.firebase:firebase-messaging:9.2.1'
    testCompile 'junit:junit:4.12'
    compile files('libs/httpcore-4.3.3.jar')
    compile files('libs/httpclient-4.3.6.jar')
    compile files('libs/httpmime-4.3.6.jar')
//add this jar file manually to libs directory
    compile files('libs/android-support-v4.jar')

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


问:
How to retrieve second item of HashSet<Tuple<string, int>>
I've a  HashSet<Tuple<string, int>> In the second item I've numbers (1,18,5,46).

I'd like to get biggest number of in these items.

I'm new in programming so please forgive me for question.

I've just found a way and want to share:
int max = students.Max(kvp => kvp.Item2);

答:
You can do this</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var students = new List<Tuple<string, int>>();

        students.Add(new Tuple<string, int>("test", 10));
        students.Add(new Tuple<string, int>("test", 10));

        Console.Write(students.Max(t => t.Item2));
    }
}
</code>```

Body:
You can do this

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var students = new List<Tuple<string, int>>();

        students.Add(new Tuple<string, int>("test", 10));
        students.Add(new Tuple<string, int>("test", 10));

        Console.Write(students.Max(t => t.Item2));
    }
}


问:
Why g++ not link static programs?
I installed Ubuntu 17.04
them:

```<code>apt-get install libsdl2-dev`
</code>```

and all extras
when I compiled program by:

```<code>g++ -o prg main.cpp -lSDL2 -lSDL2_gfx -lSDL2_image
</code>```

application work only in terminal by

```<code>./prg
</code>```

but in Ubuntu interface i see window "there is no program to open files shared library" what i must do?

答:
In Ubuntu 17.04 the GCC toolchains have been configured - for the first time
in Ubuntu - to generate PIE (Position Independent Executable) code by default.

If you compile your program in verbose mode - g++ -v ... - and capture the output,
there you will see:

```<code>Configured with: ... --enable-default-pie ...
</code>```

which is not so on earlier releases.

This means that programs are now relocatable binaries, as shared libraries
have always been. You can check this definitively with the file command on your prg:

```<code>$ file prg
prg: ELF 64-bit LSB shared object, x86-64,...
</code>```

As a result, the graphical file manager is no longer able to
distinguish programs from shared libraries just by examining them and when asked to open a program
you have built yourself thinks that you want to open a shared library, which it doesn't know how to do. Perhaps
in future the file manager will be enabled to tell the difference between
a shared library and a PIE program, but until then you will have to run your
programs by opening a terminal for the purpose.

I do not know the motivation for this toolchain change but I would
speculate that it is because PIEs can benefit from ASLR - Address Space Layout Randomization - an established exploit-mitigation defense that has been enabled in Ubuntu, and Linux generally, for a long time but from which
program executables are exempt, unless compiled as PIE.

Later

What i must to do to [build a] static application?

If you wish to make a non-PIE program that the file-manager can recognize as
a program and run, then add -no-pie to your linkage options.

```<code>$ g++ -no-pie -o prg main.cpp -lSDL2 -lSDL2_gfx -lSDL2_image
</code>```

or if you compile first and link second, then:

```<code>$ g++ -o main.o -c main.cpp
$ g++ -no-pie -o prg main.o -lSDL2 -lSDL2_gfx -lSDL2_image
</code>```

Be aware, however, that a non-PIE program is not the same thing as
a statically linked program, and that your commandline would never
have produced a statically linked program. You have not indicated any
reason why you would want a statically linked program, and probably don't.

Title: Why g++ not link static programs?

Body:
I installed Ubuntu 17.04
them:

apt-get install libsdl2-dev`

and all extras
when I compiled program by:

g++ -o prg main.cpp -lSDL2 -lSDL2_gfx -lSDL2_image

application work only in terminal by

./prg

but in Ubuntu interface i see window "there is no program to open files shared library" what i must do?

Body:
In Ubuntu 17.04 the GCC toolchains have been configured - for the first time
in Ubuntu - to generate PIE (Position Independent Executable) code by default.

If you compile your program in verbose mode - g++ -v ... - and capture the output,
there you will see:

Configured with: ... --enable-default-pie ...

which is not so on earlier releases.

This means that programs are now relocatable binaries, as shared libraries
have always been. You can check this definitively with the file command on your prg:

$ file prg
prg: ELF 64-bit LSB shared object, x86-64,...

As a result, the graphical file manager is no longer able to
distinguish programs from shared libraries just by examining them and when asked to open a program
you have built yourself thinks that you want to open a shared library, which it doesn't know how to do. Perhaps
in future the file manager will be enabled to tell the difference between
a shared library and a PIE program, but until then you will have to run your
programs by opening a terminal for the purpose.

I do not know the motivation for this toolchain change but I would
speculate that it is because PIEs can benefit from ASLR - Address Space Layout Randomization - an established exploit-mitigation defense that has been enabled in Ubuntu, and Linux generally, for a long time but from which
program executables are exempt, unless compiled as PIE.

Later

What i must to do to [build a] static application?

If you wish to make a non-PIE program that the file-manager can recognize as
a program and run, then add -no-pie to your linkage options.

$ g++ -no-pie -o prg main.cpp -lSDL2 -lSDL2_gfx -lSDL2_image

or if you compile first and link second, then:

$ g++ -o main.o -c main.cpp
$ g++ -no-pie -o prg main.o -lSDL2 -lSDL2_gfx -lSDL2_image

Be aware, however, that a non-PIE program is not the same thing as
a statically linked program, and that your commandline would never
have produced a statically linked program. You have not indicated any
reason why you would want a statically linked program, and probably don't.


问:
Use npm speaker as output for GridFS download stream - NodeJS
I am creating a music streaming service using the MEAN stack. So far, I have written code that uploads an mp3 file to my MongoDB database, using GridFS, and I can also download that file to the root folder of my site.

However, I do not want the download stream to write to a file, rather stream to a player/the speakers so that the file is not on the user's system, simply streams from the server.

I have been looking at the npm speaker module, and have attempted to implement it as below:

```<code>var assert = require('assert');
var fs = require('fs');
var mongodb = require('mongodb');
var Speaker = require('speaker');

var uri = 'mongodb://localhost:27017/test';

var speaker = new Speaker({
    channels: 2,          // 2 channels
    bitDepth: 16,         // 16-bit samples
    sampleRate: 44100     // 44,100 Hz sample rate
});

mongodb.MongoClient.connect(uri, function(error, db) {
    assert.ifError(error);

    var bucket = new mongodb.GridFSBucket(db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });

    bucket.openDownloadStreamByName('testmp3.mp3').pipe(speaker)

});
</code>```

I'm not sure if I need to implement a buffer to do this. The npm speaker moudule, as far as I am aware, is a writable stream, and so I should be able to pipe to it.

The solution I have above, produces about 30 seconds of static noise, before quitting with the "Process finished with exit code 132 (interrupted by signal 4: SIGILL)" error.

I am new to NodeJS etc so any help on this would be very much appreciated.

Thanks

答:
You need a decoder to decode mp3 files.</p>

```<code>const lame = require('lame');
// create the Encoder instance
let decoder = new lame.Decoder({
    // pcm output
    channels: 2,        // 2 channels (left and right)
    bitDepth: 16,       // 16-bit samples
    sampleRate: 44100,  // 44,100 Hz sample rate

    // mp3 input
    bitRate: 128,
    outSampleRate: 44100,
    mode: lame.STEREO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO
});

// Create the Speaker instance
let speaker = new Speaker({
    channels: 2,          // 2 channels
    bitDepth: 16,         // 16-bit samples
    sampleRate: 44100     // 44,100 Hz sample rate
});

bucket.openDownloadStreamByName('testmp3.mp3').pipe(decoder);
decoder.pipe(speaker);
</code>```

Body:
I am creating a music streaming service using the MEAN stack. So far, I have written code that uploads an mp3 file to my MongoDB database, using GridFS, and I can also download that file to the root folder of my site.

However, I do not want the download stream to write to a file, rather stream to a player/the speakers so that the file is not on the user's system, simply streams from the server.

I have been looking at the npm speaker module, and have attempted to implement it as below:

var assert = require('assert');
var fs = require('fs');
var mongodb = require('mongodb');
var Speaker = require('speaker');

var uri = 'mongodb://localhost:27017/test';

var speaker = new Speaker({
    channels: 2,          // 2 channels
    bitDepth: 16,         // 16-bit samples
    sampleRate: 44100     // 44,100 Hz sample rate
});

mongodb.MongoClient.connect(uri, function(error, db) {
    assert.ifError(error);

    var bucket = new mongodb.GridFSBucket(db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });

    bucket.openDownloadStreamByName('testmp3.mp3').pipe(speaker)

});

I'm not sure if I need to implement a buffer to do this. The npm speaker moudule, as far as I am aware, is a writable stream, and so I should be able to pipe to it.

The solution I have above, produces about 30 seconds of static noise, before quitting with the "Process finished with exit code 132 (interrupted by signal 4: SIGILL)" error.

I am new to NodeJS etc so any help on this would be very much appreciated.

Thanks

Body:
You need a decoder to decode mp3 files.

const lame = require('lame');
// create the Encoder instance
let decoder = new lame.Decoder({
    // pcm output
    channels: 2,        // 2 channels (left and right)
    bitDepth: 16,       // 16-bit samples
    sampleRate: 44100,  // 44,100 Hz sample rate

    // mp3 input
    bitRate: 128,
    outSampleRate: 44100,
    mode: lame.STEREO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO
});

// Create the Speaker instance
let speaker = new Speaker({
    channels: 2,          // 2 channels
    bitDepth: 16,         // 16-bit samples
    sampleRate: 44100     // 44,100 Hz sample rate
});

bucket.openDownloadStreamByName('testmp3.mp3').pipe(decoder);
decoder.pipe(speaker);


问:
Remove rows based on groupby of multiple columns resulting in lowest value only
I have the following data in a pandas dataframe in Python. I would like to group the data based on the Name and Property column, and keep only the lowest value within the Date.

Before:

```<code>  Name  Property                         Date
0   X1      Cash  621 days 00:00:00.000000000
1   X1      Cash  256 days 00:00:00.000000000
2   X1      Cash  101 days 00:00:00.000000000
3   X1  Overflow  352 days 00:00:00.000000000
4   X1  Overflow  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000
</code>```

Repeat for X2/X3 etc.

After:

```<code>  Name  Property                         Date
2   X1      Cash  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000
</code>```

I am attempting to play around with the syntax but unable to get it right:

```<code>df1 = df1[df1.groupby(['Name', 'Property'])['Date'].min()]
</code>```

答:
If you call reset intex on the groupby.min() result, you'll have your desired output:

```<code>df.groupby(['Name', 'Property'])['Date'].min().reset_index()
Out:
  Name  Property     Date
0   X1      Cash 101 days
1   X1  Overflow  53 days
</code>```

You can also use nsmallest:

```<code>df.groupby(['Name', 'Property'])['Date'].nsmallest(1)
Out:
Name  Property
X1    Cash      2   101 days
      Overflow  5    53 days
Name: Date, dtype: timedelta64[ns]
</code>```

You can reset the index and drop the original index if you want:

```<code>df.groupby(['Name', 'Property'])['Date'].nsmallest(1).reset_index(level=[0, 1])
Out:
  Name  Property     Date
2   X1      Cash 101 days
5   X1  Overflow  53 days
</code>```

If you have additional columns you want to keep, you have several options.

```<code>df['additional column'] = np.arange(6)

df
Out:
  Name  Property     Date  additional column
0   X1      Cash 621 days                  0
1   X1      Cash 256 days                  1
2   X1      Cash 101 days                  2
3   X1  Overflow 352 days                  3
4   X1  Overflow 101 days                  4
5   X1  Overflow  53 days                  5
</code>```

The first one, as @piRSquared mentioned, is to use loc with the indexes of the returning rows:

```<code>df.loc[df.groupby(['Name', 'Property'])['Date'].idxmin()]
</code>```

A second one would be to merge the original DataFrame and the aggregated one:

```<code>df.merge(df.groupby(['Name', 'Property'])['Date'].min().reset_index())
</code>```

Both yield:

```<code>  Name  Property     Date  additional column
0   X1      Cash 101 days                  2
1   X1  Overflow  53 days                  5
</code>```

Based on the use case, one may outperform the other.

Body:
I have the following data in a pandas dataframe in Python. I would like to group the data based on the Name and Property column, and keep only the lowest value within the Date.

Before:

  Name  Property                         Date
0   X1      Cash  621 days 00:00:00.000000000
1   X1      Cash  256 days 00:00:00.000000000
2   X1      Cash  101 days 00:00:00.000000000
3   X1  Overflow  352 days 00:00:00.000000000
4   X1  Overflow  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000

Repeat for X2/X3 etc.

After:

  Name  Property                         Date
2   X1      Cash  101 days 00:00:00.000000000
5   X1  Overflow   53 days 00:00:00.000000000

I am attempting to play around with the syntax but unable to get it right:

df1 = df1[df1.groupby(['Name', 'Property'])['Date'].min()]

Body:
If you call reset intex on the groupby.min() result, you'll have your desired output:

df.groupby(['Name', 'Property'])['Date'].min().reset_index()
Out:
  Name  Property     Date
0   X1      Cash 101 days
1   X1  Overflow  53 days

You can also use nsmallest:

df.groupby(['Name', 'Property'])['Date'].nsmallest(1)
Out:
Name  Property
X1    Cash      2   101 days
      Overflow  5    53 days
Name: Date, dtype: timedelta64[ns]

You can reset the index and drop the original index if you want:

df.groupby(['Name', 'Property'])['Date'].nsmallest(1).reset_index(level=[0, 1])
Out:
  Name  Property     Date
2   X1      Cash 101 days
5   X1  Overflow  53 days

If you have additional columns you want to keep, you have several options.

df['additional column'] = np.arange(6)

df
Out:
  Name  Property     Date  additional column
0   X1      Cash 621 days                  0
1   X1      Cash 256 days                  1
2   X1      Cash 101 days                  2
3   X1  Overflow 352 days                  3
4   X1  Overflow 101 days                  4
5   X1  Overflow  53 days                  5

The first one, as @piRSquared mentioned, is to use loc with the indexes of the returning rows:

df.loc[df.groupby(['Name', 'Property'])['Date'].idxmin()]

A second one would be to merge the original DataFrame and the aggregated one:

df.merge(df.groupby(['Name', 'Property'])['Date'].min().reset_index())

Both yield:

  Name  Property     Date  additional column
0   X1      Cash 101 days                  2
1   X1  Overflow  53 days                  5

Based on the use case, one may outperform the other.


问:
PHP: get subarray of subarray data from array by key from JSON file
I have a JSON file as seen below and i already have i want to create a final array that has the movie name as the key and the actors are the value that the key stores

JSON file

```<code>{
    "movies": [{
            "title": "Diner",
            "cast": [
                "Steve Guttenberg",
                "Daniel Stern",
                "Mickey Rourke",
                "Kevin Bacon",
                "Tim Daly",
                "Ellen Barkin",
                "Paul Reiser",
                "Kathryn Dowling",
                "Michael Tucker",
                "Jessica James",
                "Colette Blonigan",
                "Kelle Kipp",
                "Clement Fowler",
                "Claudia Cron"
            ]
        },
        {
            "title": "Footloose",
            "cast": [
                "Kevin Bacon",
                "Lori Singer",
                "Dianne Wiest",
                "John Lithgow",
                "Sarah Jessica Parker",
                "Chris Penn",
                "Frances Lee McCain",
                "Jim Youngs",
                "John Laughlin",
                "Lynne Marta",
                "Douglas Dirkson"
            ]
        }
    ]
}
</code>```

Ideal output

```<code>Array(
["Diner"]=>Array(Steve Guttenberg","Daniel Stern","Mickey Rourke","Kevin Bacon","Tim Daly","Ellen Barkin","Paul Reiser","Kathryn Dowling","Michael Tucker","Jessica James","Colette Blonigan","Kelle Kipp","Clement Fowler","Claudia Cron")
["Footloose"]=>Array("Kevin Bacon","Lori Singer","Dianne Wiest","John Lithgow","Sarah Jessica Parker","Chris Penn","Frances Lee McCain","Jim Youngs","John Laughlin","Lynne Marta","Douglas Dirkson")
</code>```

)

My code so far

```<code>$movies = json_decode(file_get_contents("movies.json"),true);

$actors = array();
foreach($movies as $movie){
  $key = "cast";
  echo $movie->$key;
}
</code>```

But when i run my current code php gives me a notice "Trying to get property of non-object" Can someone explain why this is happening and how to fix it? the error is on this line:

```<code>echo $movie->$key;
</code>```

thanks in advance!

答:
First your json is object that has movies property. So you must get movies when decode by getting movies property.
Then if second parameter of json_decode is true, it returns associated array and not object. If you want to get object, call like this:

```<code>$json = json_decode(file_get_contents("movies.json"));
$movies = $json->movies;
</code>```

And finally you want to get array with name is title and value is cast.

You can use following code:

```<code>$json = json_decode(file_get_contents("movies.json"));
$movies = $json->movies;

$actors = array();
foreach($movies as $movie){
    $title = $movie->title;
    $actors[$title] = $movie->cast;
}

print_r($actors); //to see ideal output
</code>```

Body:
I have a JSON file as seen below and i already have i want to create a final array that has the movie name as the key and the actors are the value that the key stores

JSON file

{
    "movies": [{
            "title": "Diner",
            "cast": [
                "Steve Guttenberg",
                "Daniel Stern",
                "Mickey Rourke",
                "Kevin Bacon",
                "Tim Daly",
                "Ellen Barkin",
                "Paul Reiser",
                "Kathryn Dowling",
                "Michael Tucker",
                "Jessica James",
                "Colette Blonigan",
                "Kelle Kipp",
                "Clement Fowler",
                "Claudia Cron"
            ]
        },
        {
            "title": "Footloose",
            "cast": [
                "Kevin Bacon",
                "Lori Singer",
                "Dianne Wiest",
                "John Lithgow",
                "Sarah Jessica Parker",
                "Chris Penn",
                "Frances Lee McCain",
                "Jim Youngs",
                "John Laughlin",
                "Lynne Marta",
                "Douglas Dirkson"
            ]
        }
    ]
}

Ideal output

Array(
["Diner"]=>Array(Steve Guttenberg","Daniel Stern","Mickey Rourke","Kevin Bacon","Tim Daly","Ellen Barkin","Paul Reiser","Kathryn Dowling","Michael Tucker","Jessica James","Colette Blonigan","Kelle Kipp","Clement Fowler","Claudia Cron")
["Footloose"]=>Array("Kevin Bacon","Lori Singer","Dianne Wiest","John Lithgow","Sarah Jessica Parker","Chris Penn","Frances Lee McCain","Jim Youngs","John Laughlin","Lynne Marta","Douglas Dirkson")

)

My code so far

$movies = json_decode(file_get_contents("movies.json"),true);

$actors = array();
foreach($movies as $movie){
  $key = "cast";
  echo $movie->$key;
}

But when i run my current code php gives me a notice "Trying to get property of non-object" Can someone explain why this is happening and how to fix it? the error is on this line:

echo $movie->$key;

thanks in advance!

Body:
First your json is object that has movies property. So you must get movies when decode by getting movies property.
Then if second parameter of json_decode is true, it returns associated array and not object. If you want to get object, call like this:

$json = json_decode(file_get_contents("movies.json"));
$movies = $json->movies;

And finally you want to get array with name is title and value is cast.

You can use following code:

$json = json_decode(file_get_contents("movies.json"));
$movies = $json->movies;

$actors = array();
foreach($movies as $movie){
    $title = $movie->title;
    $actors[$title] = $movie->cast;
}

print_r($actors); //to see ideal output


问:
Find the index of two minimum values in array
I have an array that contains numbers.

I got the two minimum values (can be the same number) of this array in O(N) but i cant figure out how to get the index of this two values.

For example: in {1,2,3,1,5} the answer will be index 0 and index 3. this is the code i'm using:

```<code>    public static void minMin(int arr[]){
    int min1 = weights[0], min2 = weights[1];
      if(min1 > min2){
       int temp = min1;
       min1 = min2;
       min2 = temp;
      }
      for (int i = 2; i < weights.length; i++) {
       if(weights[i] < min1){
        int temp = min1;
        min1 = weights[i];
        min2 = temp;
       }else if(weights[i] < min2){
        min2 = weights[i];
       }
      }
}
</code>```

答:
Ghostcat already gave the answer, you just didnt understand:

I have only one index because its one for loop and i need the index's of two elements..

Just create more variables:

```<code>public static void main(String[] args) {

    minMin(new int[] { 1, 2, 3, 1, 5 });
}

// Careful: this code only works for arr.lengh > 1
public static void minMin(int arr[]) {

    int min1 = arr[0];
    int min2 = arr[1];

    int index1 = 0;
    int index2 = 1;

    if (min1 > min2) {
        int temp = min1;
        min1 = min2;
        min2 = temp;

        index1 = 1;
        index2 = 0;
    }

    for (int i = 2; i < arr.length; i++) {
        if (arr[i] < min1) {
            int temp = min1;
            min1 = arr[i];
            min2 = temp;
            index2 = index1;
            index1 = i;
        } else if (arr[i] < min2) {
            min2 = arr[i];
            index2 = i;
        }
    }

    System.out.println("Smallest: " + min1 + ", index " + index1);
    System.out.println("2nd smallest: " + min2 + ", index " + index2);
}
</code>```

Output:

```<code>Smallest: 1, index 0
2nd smallest: 1, index 3
</code>```

Body:
I have an array that contains numbers.

I got the two minimum values (can be the same number) of this array in O(N) but i cant figure out how to get the index of this two values.

For example: in {1,2,3,1,5} the answer will be index 0 and index 3. this is the code i'm using:

    public static void minMin(int arr[]){
    int min1 = weights[0], min2 = weights[1];
      if(min1 > min2){
       int temp = min1;
       min1 = min2;
       min2 = temp;
      }
      for (int i = 2; i < weights.length; i++) {
       if(weights[i] < min1){
        int temp = min1;
        min1 = weights[i];
        min2 = temp;
       }else if(weights[i] < min2){
        min2 = weights[i];
       }
      }
}

Body:
Ghostcat already gave the answer, you just didnt understand:

I have only one index because its one for loop and i need the index's of two elements..

Just create more variables:

public static void main(String[] args) {

    minMin(new int[] { 1, 2, 3, 1, 5 });
}

// Careful: this code only works for arr.lengh > 1
public static void minMin(int arr[]) {

    int min1 = arr[0];
    int min2 = arr[1];

    int index1 = 0;
    int index2 = 1;

    if (min1 > min2) {
        int temp = min1;
        min1 = min2;
        min2 = temp;

        index1 = 1;
        index2 = 0;
    }

    for (int i = 2; i < arr.length; i++) {
        if (arr[i] < min1) {
            int temp = min1;
            min1 = arr[i];
            min2 = temp;
            index2 = index1;
            index1 = i;
        } else if (arr[i] < min2) {
            min2 = arr[i];
            index2 = i;
        }
    }

    System.out.println("Smallest: " + min1 + ", index " + index1);
    System.out.println("2nd smallest: " + min2 + ", index " + index2);
}

Output:

Smallest: 1, index 0
2nd smallest: 1, index 3


问:
Determining Qt stylesheet options programmatically?
Is it possible to look up stylesheet values at runtime in Qt?

I'm working on a custom button derived from QPushButton that has some stylesheet properties set. I'd like to be able to look up some stylesheet settings like border width, margin, padding-top, padding-left, padding-right, etc.  Is this at all possible to do without calling widget->getStyleSheet() and parsing out the values myself?

答: Don't think so, you might be able to find something by stepping through the drawing code. But the parsing and the application of stylesheets is pretty optimised and uses a lot of preprocessing. I don't even think that you can get to the stylesheet of a widget if it was actually set in a parent.</p>


问:
What is the idiom for passing command line arguments to TensorFlow?
Previous versions of TensorFlow used tf.app.flags for command like flags:

```<code>flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
</code>```

but recent versions now have just

```<code>import argparse
#...
FLAGS = None
</code>```

wherever such code once appeared, importing argparse but not using it anywhere (that I can find).

The previous heavy use of tf.app.flags seemed like an endorsement of the gflags architecture as a kind of idiom for TensorFlow projects. Is it's removal an indication that another approach is now idiomatic and should be used in its place? If so, what approach, and is there a simple suggested migration path?

答:
According to a commit 8018346 of TF, the maintainer of TF, vrv,  replied:

Yup! tf.flags is something that is used within Google but has a bunch of problems, we suggest using argparse when possible.

As for the migration, you can checkout the same commit which did exactly the task.

Body:
Previous versions of TensorFlow used tf.app.flags for command like flags:

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')

but recent versions now have just

import argparse
#...
FLAGS = None

wherever such code once appeared, importing argparse but not using it anywhere (that I can find).

The previous heavy use of tf.app.flags seemed like an endorsement of the gflags architecture as a kind of idiom for TensorFlow projects. Is it's removal an indication that another approach is now idiomatic and should be used in its place? If so, what approach, and is there a simple suggested migration path?


问:
Can't see image view when running app
I have following XML

```<code><ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/error_btn"
        android:layout_above="@+id/et_register_email"
        android:layout_toRightOf="@+id/et_register_fullName"
        android:layout_toEndOf="@+id/et_register_fullName"
        android:id="@+id/error_name"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"/>
</code>```

When I'm running my application this ImageView is not visible....

答: Substitute app:srcCompat="@drawable/error_btn" with android:background="@drawable/error_btn"

Title: Can't see image view when running app

Body:
I have following XML

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/error_btn"
        android:layout_above="@+id/et_register_email"
        android:layout_toRightOf="@+id/et_register_fullName"
        android:layout_toEndOf="@+id/et_register_fullName"
        android:id="@+id/error_name"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"/>

When I'm running my application this ImageView is not visible....


问:
Repeated code for validating request in each controller
I have bunch of Rest controllers. for example:

```<code>@RequestMapping(path="/{groupId}",method=RequestMethod.PUT)
public void update(@RequestBody GroupDto groupDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
    updateGroupDtoValidator.validate(groupDto, result);
    if (result.hasErrors()) {
        throw new ValidationException();
    }
    groupService.update(groupId, groupDto, principal.getName());
}
</code>```

In each method controller I have to repeat making a call to validate and checking the result for errors. IS there any better way ? Is it possible to configure @Validated somehow to validate the input data from the client ?

Update1 I have several validators. For example, I have UpdateGroupDtoValidator which validates a GroupDto object when it's passed to the Update Rest endpoint. I have another validator CreateGroupDtoValidator which validates GroupDto when dto is passed to the Create Rest endpoint.

答:
Arian is right.But if you need to validate not for all method and controllers (you can contoler what should be validated and where) you can do it via spring aspects like this
https://www.abtosoftware.com/blog/form-validation-using-aspect-oriented-programming-aop-in-spring-framework</p>

Body:
I have bunch of Rest controllers. for example:

@RequestMapping(path="/{groupId}",method=RequestMethod.PUT)
public void update(@RequestBody GroupDto groupDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
    updateGroupDtoValidator.validate(groupDto, result);
    if (result.hasErrors()) {
        throw new ValidationException();
    }
    groupService.update(groupId, groupDto, principal.getName());
}

In each method controller I have to repeat making a call to validate and checking the result for errors. IS there any better way ? Is it possible to configure @Validated somehow to validate the input data from the client ?

Update1 I have several validators. For example, I have UpdateGroupDtoValidator which validates a GroupDto object when it's passed to the Update Rest endpoint. I have another validator CreateGroupDtoValidator which validates GroupDto when dto is passed to the Create Rest endpoint.


问:
Bad Argument, Invalid Subscription Key when trying to add key from Azure
I am trying to set up my LUIS app in luis.ai (because it seems like I can't set it up in Azure directly?). Anyway, I have created a Language Understanding Intelligent Service (LUIS) (preview) resource, but when I enter one of the keys from that resource into "My Keys" in luis.ai, I get this error: "Bad Argument, Invalid Subscription Key"

Also, I just tried to publish an app with the bootstrap key and got the following errors:

{ "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }

答:
As provided in comments, the solution is to use a correct end-point. This is not clear anywhere, but for the luis.ai portal, I have to use WestUS endpoint.

If I change to useing eu.luis.ai, I have to use the WestEU end-point.


答:
This is untested, but try something like this. (Note access $movies like an array, not an object as passed true as the second param to json_decode())

```<code>$movies = json_decode(file_get_contents("movies.json"), true);

$actors = array();
foreach($movies['movies'] as $movie){
  $actors[$movie['title']] = $movie['cast'];
}
</code>```

Title: PHP: get subarray of subarray data from array by key from JSON file

Body:
This is untested, but try something like this. (Note access $movies like an array, not an object as passed true as the second param to json_decode())

$movies = json_decode(file_get_contents("movies.json"), true);

$actors = array();
foreach($movies['movies'] as $movie){
  $actors[$movie['title']] = $movie['cast'];
}


问:
Tomcat 8 Unicode filename war file deploy issue
On Linux(openSUSE) machine I'm trying to deploy on Tomcat 8 application(war file) that contains a files with names with Unicode characters.

Inside of the war file the name looks like:

```<code>бжк-природний-1496336830201.xml
</code>```

but after deploy the file looks like:

```<code>???-?????????????-1496336830201.xml
</code>```

How to tell Tomcat to properly deploy the file names ?

UPDATED

This is a sample war file with Unicode file name inside: war file

What is wrong with the file name of the file inside in this war ?

UPDATED

I have installed unzip-rcc as it was suggested here https://superuser.com/questions/1215670/opensuse-unzip-unicode-issue and now unzip(console command) on the WAR file is working fine but Tomcat still deploy the files with the same issue.

答:
The filename is indeed in UTF-8 in the zip .war file.

```<code>try (ZipFile zipFile = new ZipFile(path, StandardCharsets.UTF_8)) {
    zipFile.stream()
        .forEachOrdered(entry -> System.out.printf("- %s%n", entry.getName()));
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

However the zip does not has added the encoding (as bytes[] extra information).

Three solutions would be imaginable:

One short solution might be to run TomCat under a UTF-8 locale.

The best would be to have maven build a war with UTF-8 encoding. (<onfiguration><encoding>UTF-8</encoding></configuration>)

Repairing the war by converting it.

With the first two solutions I have no experience. A quick search didn't yield anything ("encoding" is a bit ubiquitous).

The repair code is simple:

```<code>Path path = Paths.get(".../api.war").toAbsolutePath().normalize();
Path path2 = Paths.get(".../api2.war").toAbsolutePath().normalize();

URI uri = URI.create("jar:file://" + path.toString());
Map<String,String> env = new HashMap<String,String>();
env.put("create", "false");
env.put("encoding", "UTF-8");

URI uri2 = URI.create("jar:file://" + path2.toString());
Map<String,String> env2 = new HashMap<String,String>();
env2.put("create", "true");
env2.put("encoding", "UTF-8");

try (FileSystem zipFS = FileSystems.newFileSystem(uri, env);
     FileSystem zipFS2 = FileSystems.newFileSystem(uri2, env2)) {

    Files.walkFileTree(zipFS.getPath("/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
            System.out.println("* File: " + file);
            Path file2 = zipFS2.getPath(file.toString());
            Files.createDirectories(file2.getParent());
            Files.copy(file, file2);
            return FileVisitResult.CONTINUE;
        }
    });

} catch(IOException e) {
    e.printStackTrace();
}
</code>```

Body:
On Linux(openSUSE) machine I'm trying to deploy on Tomcat 8 application(war file) that contains a files with names with Unicode characters.

Inside of the war file the name looks like:

бжк-природний-1496336830201.xml

but after deploy the file looks like:

???-?????????????-1496336830201.xml

How to tell Tomcat to properly deploy the file names ?

UPDATED

This is a sample war file with Unicode file name inside: war file

What is wrong with the file name of the file inside in this war ?

UPDATED

I have installed unzip-rcc as it was suggested here https://superuser.com/questions/1215670/opensuse-unzip-unicode-issue and now unzip(console command) on the WAR file is working fine but Tomcat still deploy the files with the same issue.

Body:
The filename is indeed in UTF-8 in the zip .war file.

try (ZipFile zipFile = new ZipFile(path, StandardCharsets.UTF_8)) {
    zipFile.stream()
        .forEachOrdered(entry -> System.out.printf("- %s%n", entry.getName()));
} catch (IOException e) {
    e.printStackTrace();
}

However the zip does not has added the encoding (as bytes[] extra information).

Three solutions would be imaginable:

One short solution might be to run TomCat under a UTF-8 locale.

The best would be to have maven build a war with UTF-8 encoding. (<onfiguration><encoding>UTF-8</encoding></configuration>)

Repairing the war by converting it.

With the first two solutions I have no experience. A quick search didn't yield anything ("encoding" is a bit ubiquitous).

The repair code is simple:

Path path = Paths.get(".../api.war").toAbsolutePath().normalize();
Path path2 = Paths.get(".../api2.war").toAbsolutePath().normalize();

URI uri = URI.create("jar:file://" + path.toString());
Map<String,String> env = new HashMap<String,String>();
env.put("create", "false");
env.put("encoding", "UTF-8");

URI uri2 = URI.create("jar:file://" + path2.toString());
Map<String,String> env2 = new HashMap<String,String>();
env2.put("create", "true");
env2.put("encoding", "UTF-8");

try (FileSystem zipFS = FileSystems.newFileSystem(uri, env);
     FileSystem zipFS2 = FileSystems.newFileSystem(uri2, env2)) {

    Files.walkFileTree(zipFS.getPath("/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
            System.out.println("* File: " + file);
            Path file2 = zipFS2.getPath(file.toString());
            Files.createDirectories(file2.getParent());
            Files.copy(file, file2);
            return FileVisitResult.CONTINUE;
        }
    });

} catch(IOException e) {
    e.printStackTrace();
}


问:
Django formset with manytomany through intermediate model
I want to save data to an intermediary model and do some calculations in the model (by overriding model save). The problem I have is with formsets not able to save to the intermediary model.

The intermediary model is created only when there is M2M relationship (that's understood I guess).

I have 4 models like so:

```<code>Category(models.Model):
    name = models.CharField(..)

Tax(models.Model):
   name = models.CharField(..)
   rate = models.DecimalField(..)

CategoryItem(models.Model):
    category = models.ForeignKey(Category)
    taxes = models.ManyToManyField(Tax, through='CategoryItemTax', through_fields=('item', 'tax'))
    quantity = models.DecimalField(..)
    price = models.DecimalField(..)

# intermediary model below
CategoryItemTax(models.Model):
    category = models.ForeignKey(Category)
    tax = models.ForeignKey(Tax)
    item = models.ForeignKey(CategoryItem)
    rate = models.DecimalField(..) #derived from tax object in the model
    total_tax = models.DecimalField(..) #calculated in model save
</code>```

My I have a Category model form with CategoryItem formset. My views.py as below:

```<code>class FormsetMixin(object):
    object = None

    def post(self, request, *args, **kwargs):
        if getattr(self, 'is_update_view', False):
            self.object = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        formset_class = self.get_formset_class()
        formset = self.get_formset(formset_class)
        if form.is_valid() and formset.is_valid():
            return self.form_valid(form, formset)
        else:
            return self.form_invalid(form, formset)

    # THE SAVE METHOD
    def form_valid(self, form, formset):
        self.object = form.save()
        formset.instance = self.object
        instances = formset.save(commit=False)
        for i in instances:
            CategoryItemTax.objects.create(category=self.object, item=i, tax=i)
            CategoryItemTax.save()

class CategoryCreateView(FormsetMixin, CreateView):
    template_name='..'
    model = Category
    form_class = CategoryForm
    formset_class = CategoryItemFormSet
</code>```

Forms.py as below

```<code>class CategoryForm(forms.ModelForm):

    class Meta:
        model = Category

class CategoryItemForm(forms.ModelForm)
    class Meta:
        model = CategoryItem

CategoryItemFormSet = inlineformset_factory(Category, CategoryItem, form=CategoryItemForm, extra=1)
</code>```

Unfortunately I get the below error:

```<code>Cannot set values on a ManyToManyField which specifies an intermediary model.
Use category.CategoryItemTax's Manager instead
</code>```

答:
Edit your view like this,

```<code>def form_valid(self, form, formset):
    self.object = form.save()
    formset.instance = self.object
    instances = formset.save(commit=False)
    for each in instances:
        each.category = self.object
        each.save()
        item = CategoryItemTax.objects.create(category=self.object, item=each)
        item.save()
</code>```

Many to many related objects must be saved first inorder to associate with another instance.

Body:
I want to save data to an intermediary model and do some calculations in the model (by overriding model save). The problem I have is with formsets not able to save to the intermediary model.

The intermediary model is created only when there is M2M relationship (that's understood I guess).

I have 4 models like so:

Category(models.Model):
    name = models.CharField(..)

Tax(models.Model):
   name = models.CharField(..)
   rate = models.DecimalField(..)

CategoryItem(models.Model):
    category = models.ForeignKey(Category)
    taxes = models.ManyToManyField(Tax, through='CategoryItemTax', through_fields=('item', 'tax'))
    quantity = models.DecimalField(..)
    price = models.DecimalField(..)

# intermediary model below
CategoryItemTax(models.Model):
    category = models.ForeignKey(Category)
    tax = models.ForeignKey(Tax)
    item = models.ForeignKey(CategoryItem)
    rate = models.DecimalField(..) #derived from tax object in the model
    total_tax = models.DecimalField(..) #calculated in model save

My I have a Category model form with CategoryItem formset. My views.py as below:

class FormsetMixin(object):
    object = None

    def post(self, request, *args, **kwargs):
        if getattr(self, 'is_update_view', False):
            self.object = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        formset_class = self.get_formset_class()
        formset = self.get_formset(formset_class)
        if form.is_valid() and formset.is_valid():
            return self.form_valid(form, formset)
        else:
            return self.form_invalid(form, formset)

    # THE SAVE METHOD
    def form_valid(self, form, formset):
        self.object = form.save()
        formset.instance = self.object
        instances = formset.save(commit=False)
        for i in instances:
            CategoryItemTax.objects.create(category=self.object, item=i, tax=i)
            CategoryItemTax.save()

class CategoryCreateView(FormsetMixin, CreateView):
    template_name='..'
    model = Category
    form_class = CategoryForm
    formset_class = CategoryItemFormSet

Forms.py as below

class CategoryForm(forms.ModelForm):

    class Meta:
        model = Category

class CategoryItemForm(forms.ModelForm)
    class Meta:
        model = CategoryItem

CategoryItemFormSet = inlineformset_factory(Category, CategoryItem, form=CategoryItemForm, extra=1)

Unfortunately I get the below error:

Cannot set values on a ManyToManyField which specifies an intermediary model.
Use category.CategoryItemTax's Manager instead

Body:
Edit your view like this,

def form_valid(self, form, formset):
    self.object = form.save()
    formset.instance = self.object
    instances = formset.save(commit=False)
    for each in instances:
        each.category = self.object
        each.save()
        item = CategoryItemTax.objects.create(category=self.object, item=each)
        item.save()

Many to many related objects must be saved first inorder to associate with another instance.


问:
How to move background in cocos 2d
Hi i want to develop  game like 'Doodle jump'.But i have some problem with the following features-

1.How to move background scene/image.

2.How to detect collision between object.Is it needed a physics engine like box2d or i should just use manual collision.

3.what should be the size of the background image.

4.In fact i have no idea how does background move .So i need a explanation from someone.

答:
In the folder of cocos2d,  you could get many demos of  tilemap.
TileMapTest.h
TileMapTest.m</p>

Title: How to move background in cocos 2d


问:
AVAudioRecorder never records
I am using an AVAudioRecorder to record human voice. My code is as follows:

```<code>// Property of Class
var recorder:AVAudioRecorder?

func recordButtonTapped() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setActive(true)
        if audioSession.recordPermission() != .granted {
            audioSession.requestRecordPermission({ (success) in
                self.startRecording()
            })
        }
        else {
            self.startRecording()
        }

    } catch {
        print("Unable To Set Category")
    }
}

func startRecording() {
    // libraryPathWith(media) just gets the path to the documents directory
    // Like so: Documents/MediaLibrary/Audio/<mediaID>.<mediaExtension>
    if let path = MMFileManager.libraryPathWith(media: self.media) {
        isRecording = true
        do {
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            recorder = try AVAudioRecorder(url: path, settings: settings)

            recorder?.delegate = self

            if recorder!.prepareToRecord() {
                recorder?.record()
            }
        }
        catch {
            isRecording = false
        }
    }
}

func stopRecording() {
    self.recordingLabel.text = "Recording Complete"
    self.recordingLabel.textColor = UIColor.white
    if let rec = recorder {
        rec.stop()
        recorder = nil
    }
    isRecording = false
}
</code>```

AVAudioRecorderDelegate

```<code>func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    print("RECORDED AUDIO SUCCESSFULLY \(flag)")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
    print("AUDIO RECORDER ERROR \(error?.localizedDescription)")
}
</code>```

After I call stop on the AVAudioRecorder the audioRecorderEncodeErrorDidOccur function never gets called, but the audioRecorderDidFinishRecording function does but the flag is always false. It prints out "RECORDED AUDIO SUCCESSFULLY false"

QUESTION

When I record using the code above I does save a file to my documents directory at the location specified. But this file is not something that I can play. It writes a text file, not an audio file as I specify the extension to be .aac.

Why does the AVAudioRecorder not record audio? And how do I get it to do so?

答:
If you've verified your url has the "aac" extension, then I suspect the you simply forgot to call stop() on your recorder.  This results in an un-finalized file.

Also print your errors in the catch block.

```<code>do{
    try throwingFunc()
} catch {
    print(error)
}
</code>```

Title: AVAudioRecorder never records

Body:
I am using an AVAudioRecorder to record human voice. My code is as follows:

// Property of Class
var recorder:AVAudioRecorder?

func recordButtonTapped() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setActive(true)
        if audioSession.recordPermission() != .granted {
            audioSession.requestRecordPermission({ (success) in
                self.startRecording()
            })
        }
        else {
            self.startRecording()
        }

    } catch {
        print("Unable To Set Category")
    }
}

func startRecording() {
    // libraryPathWith(media) just gets the path to the documents directory
    // Like so: Documents/MediaLibrary/Audio/<mediaID>.<mediaExtension>
    if let path = MMFileManager.libraryPathWith(media: self.media) {
        isRecording = true
        do {
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            recorder = try AVAudioRecorder(url: path, settings: settings)

            recorder?.delegate = self

            if recorder!.prepareToRecord() {
                recorder?.record()
            }
        }
        catch {
            isRecording = false
        }
    }
}

func stopRecording() {
    self.recordingLabel.text = "Recording Complete"
    self.recordingLabel.textColor = UIColor.white
    if let rec = recorder {
        rec.stop()
        recorder = nil
    }
    isRecording = false
}

AVAudioRecorderDelegate

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    print("RECORDED AUDIO SUCCESSFULLY \(flag)")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
    print("AUDIO RECORDER ERROR \(error?.localizedDescription)")
}

After I call stop on the AVAudioRecorder the audioRecorderEncodeErrorDidOccur function never gets called, but the audioRecorderDidFinishRecording function does but the flag is always false. It prints out "RECORDED AUDIO SUCCESSFULLY false"

QUESTION

When I record using the code above I does save a file to my documents directory at the location specified. But this file is not something that I can play. It writes a text file, not an audio file as I specify the extension to be .aac.

Why does the AVAudioRecorder not record audio? And how do I get it to do so?

Body:
If you've verified your url has the "aac" extension, then I suspect the you simply forgot to call stop() on your recorder.  This results in an un-finalized file.

Also print your errors in the catch block.

do{
    try throwingFunc()
} catch {
    print(error)
}


问:
Tap GMSPolygon Swift
I have some GMSPolygon in my map:

```<code> let españa = GMSMutablePath()
    españa.add(CLLocationCoordinate2D(latitude: 42.11, longitude: -9.37))
    españa.add(CLLocationCoordinate2D(latitude: 43.94, longitude: -9.55))
    españa.add(CLLocationCoordinate2D(latitude: 43.60, longitude: -1.89))
    españa.add(CLLocationCoordinate2D(latitude: 42.02, longitude: 3.72))
    españa.add(CLLocationCoordinate2D(latitude: 36.16, longitude: -2.65))
    españa.add(CLLocationCoordinate2D(latitude: 37.10, longitude: -7.28))
    españa.add(CLLocationCoordinate2D(latitude: 42.08, longitude: -6.61))
</code>```

```<code>    let polygonEspaña = GMSPolygon(path: españa)
    polygonEspaña.fillColor = UIColor(red : 0, green: 0, blue: 0, alpha: 0.05);
    polygonEspaña.strokeColor = .black
    polygonEspaña.strokeWidth = 2
    polygonEspaña.map = myMapView
    polygonEspaña.isTappable = true
</code>```

I want tap them to make some functions.

I implemented this method:

```<code>import UIKit
import GoogleMaps

class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
}
</code>```

When I tap them nothing happen.

```<code>// ###### Click Country

private func myMapView(_ myMapView: GMSMapView, didTap overlay: GMSOverlay) {
    print("User Tapped Layer: \(overlay)")
}
</code>```

I think that i have a issue in my GMSMapViewDelegate but i can´t fix it, how could i do that?

EDIT: I Already have this also.

```<code>// ##### MAPA

    let mapCenter = GMSCameraPosition.camera(withLatitude: 48.23,
                                             longitude: 16.35,
                                             zoom: 3)

    myMapView.camera = mapCenter
    myMapView.setMinZoom(1, maxZoom: 8)

    myMapView.delegate = self

    // #### Estilo de mapa

    do {
        if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
            myMapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
        } else {
            NSLog("Unable to finde style.json")
        }
    } catch {
        NSLog("One or more of the map styles failed to load. \(error)")
    }
</code>```

Thanks

答:
Finally it works.

I had a problem with my slide menu:

```<code>RevealViewController
</code>```

I don´t know why with the RevealViewController, functions from:

```<code>GSMapViewDelegate
</code>```

does not work

Now when i tap in my polygon i receive a text in the console.

But i have the full information about my Polygon, i need the name of it.

For example, if i click in Spain, i want to receive "Your are tapped in Spain".

Thanks

Title: Tap GMSPolygon Swift

Body:
I have some GMSPolygon in my map:

 let españa = GMSMutablePath()
    españa.add(CLLocationCoordinate2D(latitude: 42.11, longitude: -9.37))
    españa.add(CLLocationCoordinate2D(latitude: 43.94, longitude: -9.55))
    españa.add(CLLocationCoordinate2D(latitude: 43.60, longitude: -1.89))
    españa.add(CLLocationCoordinate2D(latitude: 42.02, longitude: 3.72))
    españa.add(CLLocationCoordinate2D(latitude: 36.16, longitude: -2.65))
    españa.add(CLLocationCoordinate2D(latitude: 37.10, longitude: -7.28))
    españa.add(CLLocationCoordinate2D(latitude: 42.08, longitude: -6.61))

    let polygonEspaña = GMSPolygon(path: españa)
    polygonEspaña.fillColor = UIColor(red : 0, green: 0, blue: 0, alpha: 0.05);
    polygonEspaña.strokeColor = .black
    polygonEspaña.strokeWidth = 2
    polygonEspaña.map = myMapView
    polygonEspaña.isTappable = true

I want tap them to make some functions.

I implemented this method:

import UIKit
import GoogleMaps

class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
}

When I tap them nothing happen.

// ###### Click Country

private func myMapView(_ myMapView: GMSMapView, didTap overlay: GMSOverlay) {
    print("User Tapped Layer: \(overlay)")
}

I think that i have a issue in my GMSMapViewDelegate but i can´t fix it, how could i do that?

EDIT: I Already have this also.

// ##### MAPA

    let mapCenter = GMSCameraPosition.camera(withLatitude: 48.23,
                                             longitude: 16.35,
                                             zoom: 3)

    myMapView.camera = mapCenter
    myMapView.setMinZoom(1, maxZoom: 8)

    myMapView.delegate = self

    // #### Estilo de mapa

    do {
        if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
            myMapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
        } else {
            NSLog("Unable to finde style.json")
        }
    } catch {
        NSLog("One or more of the map styles failed to load. \(error)")
    }

Thanks

Body:
Finally it works.

I had a problem with my slide menu:

RevealViewController

I don´t know why with the RevealViewController, functions from:

GSMapViewDelegate

does not work

Now when i tap in my polygon i receive a text in the console.

But i have the full information about my Polygon, i need the name of it.

For example, if i click in Spain, i want to receive "Your are tapped in Spain".

Thanks


问:
Check if user is close to scrolling to bottom of element
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});
</code>```

答:
You can consider using https://developer.mozilla.org/en/docs/Web/API/Element/scrollHeight for checking with current scroll position

Example:

```<code>$("#exampleModalLong").on("scroll", function() {
var isEnd = this.scrollHeight - this.scrollTop === this.clientHeight;
if (isEnd) {
   alert('Bingo');
}
});
</code>```

Body:
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

JS:

$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});

Body:
You can consider using https://developer.mozilla.org/en/docs/Web/API/Element/scrollHeight for checking with current scroll position

Example:

$("#exampleModalLong").on("scroll", function() {
var isEnd = this.scrollHeight - this.scrollTop === this.clientHeight;
if (isEnd) {
   alert('Bingo');
}
});


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答: Each class' "max variables" count really is a function of what data makes sense for the class in question.  If there are truly X different values for a class and all data is related, that should be your structure.  It can be a bit tedious to create depending on the language being used, but I wouldn't say there is any "limit" that you shouldn't exceed.  It is dictated by the purpose.</p>

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

OwnerDisplayName: Mitchel Sellers


问:
Allowed memory size of 134217728 bytes exhausted
What i do wrong in this code? i tried to solve with "ini_set('memory_limit', '-1');" but didn't work. I think that my while is infinite loop. My column post have just 6 rows.</p>

```<code><?php
$user = $_SESSION['login_username'];
$db = mysqli_connect("localhost","stringdot","Ninja123","ddbase");
$query = "SELECT post FROM posts WHERE username = '$user' ORDER BY date_post DESC";
$result = mysqli_query($db,$query);
$result = mysqli_fetch_assoc($result);
$posts = array();

while($row = $result) {
    $posts = $row['post'];
}

print_r ($posts);

?>
</code>```

答:
The problem is born here

```<code>while($row = $result) {
</code>```

the condition $row = $result is an assignment

This assignment will always be true as it can put $result in $row

instead mysql_fetch_array($result) Each loop takes the next value, if the assignment is not successful

You can resolve it with this

```<code>while($row = mysql_fetch_array($result)) {
    $posts = $row['post'];
}
</code>```

Body:
What i do wrong in this code? i tried to solve with "ini_set('memory_limit', '-1');" but didn't work. I think that my while is infinite loop. My column post have just 6 rows.

<?php
$user = $_SESSION['login_username'];
$db = mysqli_connect("localhost","stringdot","Ninja123","ddbase");
$query = "SELECT post FROM posts WHERE username = '$user' ORDER BY date_post DESC";
$result = mysqli_query($db,$query);
$result = mysqli_fetch_assoc($result);
$posts = array();

while($row = $result) {
    $posts = $row['post'];
}

print_r ($posts);

?>

Body:
The problem is born here

while($row = $result) {

the condition $row = $result is an assignment

This assignment will always be true as it can put $result in $row

instead mysql_fetch_array($result) Each loop takes the next value, if the assignment is not successful

You can resolve it with this

while($row = mysql_fetch_array($result)) {
    $posts = $row['post'];
}


问:
Cannot find module '@tridnguyen/config' | Install npm grunt
Getting error while running grunt after installing npm.</p>

```<code>C:\Users\XXXX\git\projectname\cartridges>grunt
Loading "Gruntfile.js" tasks...ERROR
>> Error: Cannot find module '@tridnguyen/config'
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.
</code>```

答:
This error comes either git is not installed in your system or git is not set in PATH.

Expected root cause and solution:

Download git from https://git-scm.com/download/win if not installed

If installed but missed to set it in path then set following address of git in PATH.

```<code>;C:\Program Files\Git\bin;C:\Program Files\Git\cmd
</code>```

Reopen run the command prompt after closing it and then run the command again. npm install --save @tridnguyen/config

This time command should be executed successfully.

Also visit: http://www.clearfunda.com/ to find more knowledgeable stuffs.

Body:
Getting error while running grunt after installing npm.

C:\Users\XXXX\git\projectname\cartridges>grunt
Loading "Gruntfile.js" tasks...ERROR
>> Error: Cannot find module '@tridnguyen/config'
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.

Body:
This error comes either git is not installed in your system or git is not set in PATH.

Expected root cause and solution:

Download git from https://git-scm.com/download/win if not installed

If installed but missed to set it in path then set following address of git in PATH.

;C:\Program Files\Git\bin;C:\Program Files\Git\cmd

Reopen run the command prompt after closing it and then run the command again. npm install --save @tridnguyen/config

This time command should be executed successfully.

Also visit: http://www.clearfunda.com/ to find more knowledgeable stuffs.