问:
Design-time Error finding the Resource Dictionary - Inconsistent between projects
TLDR;

Screens newly referencing an external ResourceDictionary file in VS2015 style correctly at run-time, but not at design-time. What gives?

At work, we have a WinForms product which houses many WinForms screens with one developer actively adding new ones, as well as a handful of WPF screens with me adding new ones. Noticing a lot repetitious code/styling in existing WPF screens, I created a single project to house this - to be referenced by all existing/future WPF screens.

Project: WpfHelper

Platform target: Any CPU

Target framework: .NET Framework 4.6

WpfHelper.dll deployed to ...\Trunk\Project\Externals

...\Trunk\Utilities\WpfHelper\WpfHelper\Resources\GlobalResources.xaml

Build Action: Page

ResourceDictionary containing generic styles

I have referenced ...\Trunk\Project\Externals\WpfHelper.dll in six projects, adding the following code to each of their resource files:

```<code><ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/WpfHelper;Component/Resources/GlobalResources.xaml" />
</ResourceDictionary.MergedDictionaries>
</code>```

All screens are located in ...\Trunk\Project\Plugins.

```<code>╔══════════╦═════════════════╦═════════════════╦══════════════════╦════════════════════════════════════════════════╗
║          ║ Resource Works? ║ Platform Target ║ Target Framework ║ Reference File Path                            ║
╠══════════╬═════════════════╬═════════════════╬══════════════════╬════════════════════════════════════════════════╣
║ Project1 ║ Succeeded       ║ Any CPU         ║ .NET 4.6         ║ ...\Project1\Project1\Resources\Resources.xaml ║
║ Project2 ║ Succeeded       ║ x86             ║ .NET 4.6         ║ ...\Project2\Project2\Resources\Resources.xaml ║
║ Project3 ║ Succeeded       ║ Any CPU         ║ .NET 4.6         ║ ...\Project3\Project3\Resources\Resources.xaml ║
║ Project4 ║ Failed          ║ x86             ║ .NET 4.6         ║ ...\Project4\Project4\Resources\Resources.xaml ║
║ Project5 ║ Failed          ║ x86             ║ .NET 4.6         ║ ...\Project5\Project5\Resources\Resources.xaml ║
║ Project6 ║ Failed          ║ Any CPU         ║ .NET 4.6         ║ ...\Project6\Project6\Resources\Resources.xaml ║
╚══════════╩═════════════════╩═════════════════╩══════════════════╩════════════════════════════════════════════════╝
</code>```

Recent Changes

Just recently I upgraded Visual Studios 2013 to 2015. Around the same time, the other screen developer upgraded all existing screen project's target frameworks to .NET Framework 4.6 from .NET Framework 3.5/4.0.

Successful Projects

I referenced WpfHelper.dll prior to the Recent Changes.

Styles applied correctly at Design-time and Run-time.

Failed Projects

I referenced WpfHelper.dll after the Recent Changes.

Styles applied correctly at Run-time only.

During Design-time, the error is thrown:

An error occurred while finding the resource dictionary "pack://application,,,/WpfHelper;component/Resources/GlobalResources.xaml".

Where the local Resources.xaml are used, the subsequent error is thrown:

Value cannot be null.
  Parameter name: item

What I have tried:

After reading an extensive list of articles and Q&A's:

Design Time WPF XAML Resource Dictionaries

How to load a ResourceDictionary at Design Time in WPF

Error finding resource dictionary in separate assembly

Problems loading merged resource dictionaries in .NET 4.0

Pack URIs in Windows Presentation Foundation

VS2013: An error occurred while finding the resource dictionary

An error occurred while finding the resource dictionary

Error finding merged resource dictionary in another assembly

Trouble referencing a Resource Dictionary that contains a Merged Dictionary

WPF VS2013: An error occurred while finding the resource dictionary

App runs normally but has “errors” during design time: “does not exist in namespace” and “an error occured when finding the resource dictionary”

Resource Dictionary as Linked File

Visual Studio 2015 XAML Resource Dictionary Error

I tried all the following to no avail:

Change project Platform target to "Any CPU"

Change project Target framework from/to .NET Framework 4.6

Ensure all Resource.xaml files had the same Build Action (Page), etc.

Checked each project's AssemblyInfo.cs file. Failing projects included (and I removed) the following:

```<code>[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
</code>```

Manually cleared the temp folder in AppsData, Cleaned & Rebuilt projects.

Re-opened projects.

Rebooted.

Right-click copied WpfHelper.dll references from working projects and pasted into references of failing projects.

Added the WpfHelper.Resources.GlobalResources.xaml as a Linked file to the failed projects.

Nagged every co-worker.

Added the full pack URI for sub-dictionaries used in GlobalResources.xaml.

Killed the designer and rebuilt the project.

I'm out of ideas and lost in research. I've templated one of the working solutions and used that for creating new screens - that creates new screens which successfully display at design-time. It's something about these pre-existing screens. How can I get the failed projects to correctly display styled resources at design-time?

答:
I have worked out a solution to this problem that takes little effort to implement.

First add a code behind file for the resource dictionary, GlobalResources.xaml.cs:

```<code>namespace YourNamespaceHere
{
    partial class GlobalResources : ResourceDictionary
    {
        public GlobalResources()
        {
            InitializeComponent();
        }
    }
}
</code>```

Then set the x:Class property to the ResourceDictionary tag in GlobalResources.xaml:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Class="YourNamespaceHere.GlobalResources">
</code>```

You are now able to create an instance of the resource dictionary like this:

```<code>new YourNamespaceHere.GlobalResources()
</code>```

In the WPF user control where you are using the resource dictionary, add the following to the constructor i UserControl1.xaml.cs:

```<code>public UserControl1()
{
    if (DesignerProperties.GetIsInDesignMode(this))
        this.Resources.MergedDictionaries.Add(new YourNamespaceHere.GlobalResources());

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

Now the WinForms designer for the control where UserControl1 is used, will no longer complain about not finding your dll containing the resource dictionary. Used resources will also be displayed in the designer.

To make sure the WPF designer will show content from the resource dictionary that is used in UserControl1, you still need the following in your UserControl1.xaml:

```<code><UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MyDll;component/GlobalResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
</code>```

MyDll is the name of the assembly containing the resource dictionary. In this example GlobalResources.xaml and GlobalResources.xaml.cs are expected to be placed at the root level of the assembly (not in a folder).

Body:
TLDR;

Screens newly referencing an external ResourceDictionary file in VS2015 style correctly at run-time, but not at design-time. What gives?

At work, we have a WinForms product which houses many WinForms screens with one developer actively adding new ones, as well as a handful of WPF screens with me adding new ones. Noticing a lot repetitious code/styling in existing WPF screens, I created a single project to house this - to be referenced by all existing/future WPF screens.

Project: WpfHelper

Platform target: Any CPU

Target framework: .NET Framework 4.6

WpfHelper.dll deployed to ...\Trunk\Project\Externals

...\Trunk\Utilities\WpfHelper\WpfHelper\Resources\GlobalResources.xaml

Build Action: Page

ResourceDictionary containing generic styles

I have referenced ...\Trunk\Project\Externals\WpfHelper.dll in six projects, adding the following code to each of their resource files:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/WpfHelper;Component/Resources/GlobalResources.xaml" />
</ResourceDictionary.MergedDictionaries>

All screens are located in ...\Trunk\Project\Plugins.

╔══════════╦═════════════════╦═════════════════╦══════════════════╦════════════════════════════════════════════════╗
║          ║ Resource Works? ║ Platform Target ║ Target Framework ║ Reference File Path                            ║
╠══════════╬═════════════════╬═════════════════╬══════════════════╬════════════════════════════════════════════════╣
║ Project1 ║ Succeeded       ║ Any CPU         ║ .NET 4.6         ║ ...\Project1\Project1\Resources\Resources.xaml ║
║ Project2 ║ Succeeded       ║ x86             ║ .NET 4.6         ║ ...\Project2\Project2\Resources\Resources.xaml ║
║ Project3 ║ Succeeded       ║ Any CPU         ║ .NET 4.6         ║ ...\Project3\Project3\Resources\Resources.xaml ║
║ Project4 ║ Failed          ║ x86             ║ .NET 4.6         ║ ...\Project4\Project4\Resources\Resources.xaml ║
║ Project5 ║ Failed          ║ x86             ║ .NET 4.6         ║ ...\Project5\Project5\Resources\Resources.xaml ║
║ Project6 ║ Failed          ║ Any CPU         ║ .NET 4.6         ║ ...\Project6\Project6\Resources\Resources.xaml ║
╚══════════╩═════════════════╩═════════════════╩══════════════════╩════════════════════════════════════════════════╝

Recent Changes

Just recently I upgraded Visual Studios 2013 to 2015. Around the same time, the other screen developer upgraded all existing screen project's target frameworks to .NET Framework 4.6 from .NET Framework 3.5/4.0.

Successful Projects

I referenced WpfHelper.dll prior to the Recent Changes.

Styles applied correctly at Design-time and Run-time.

Failed Projects

I referenced WpfHelper.dll after the Recent Changes.

Styles applied correctly at Run-time only.

During Design-time, the error is thrown:

An error occurred while finding the resource dictionary "pack://application,,,/WpfHelper;component/Resources/GlobalResources.xaml".

Where the local Resources.xaml are used, the subsequent error is thrown:

Value cannot be null.
  Parameter name: item

What I have tried:

After reading an extensive list of articles and Q&A's:

Design Time WPF XAML Resource Dictionaries

How to load a ResourceDictionary at Design Time in WPF

Error finding resource dictionary in separate assembly

Problems loading merged resource dictionaries in .NET 4.0

Pack URIs in Windows Presentation Foundation

VS2013: An error occurred while finding the resource dictionary

An error occurred while finding the resource dictionary

Error finding merged resource dictionary in another assembly

Trouble referencing a Resource Dictionary that contains a Merged Dictionary

WPF VS2013: An error occurred while finding the resource dictionary

App runs normally but has “errors” during design time: “does not exist in namespace” and “an error occured when finding the resource dictionary”

Resource Dictionary as Linked File

Visual Studio 2015 XAML Resource Dictionary Error

I tried all the following to no avail:

Change project Platform target to "Any CPU"

Change project Target framework from/to .NET Framework 4.6

Ensure all Resource.xaml files had the same Build Action (Page), etc.

Checked each project's AssemblyInfo.cs file. Failing projects included (and I removed) the following:

[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

Manually cleared the temp folder in AppsData, Cleaned & Rebuilt projects.

Re-opened projects.

Rebooted.

Right-click copied WpfHelper.dll references from working projects and pasted into references of failing projects.

Added the WpfHelper.Resources.GlobalResources.xaml as a Linked file to the failed projects.

Nagged every co-worker.

Added the full pack URI for sub-dictionaries used in GlobalResources.xaml.

Killed the designer and rebuilt the project.

I'm out of ideas and lost in research. I've templated one of the working solutions and used that for creating new screens - that creates new screens which successfully display at design-time. It's something about these pre-existing screens. How can I get the failed projects to correctly display styled resources at design-time?

Body:
I have worked out a solution to this problem that takes little effort to implement.

First add a code behind file for the resource dictionary, GlobalResources.xaml.cs:

namespace YourNamespaceHere
{
    partial class GlobalResources : ResourceDictionary
    {
        public GlobalResources()
        {
            InitializeComponent();
        }
    }
}

Then set the x:Class property to the ResourceDictionary tag in GlobalResources.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Class="YourNamespaceHere.GlobalResources">

You are now able to create an instance of the resource dictionary like this:

new YourNamespaceHere.GlobalResources()

In the WPF user control where you are using the resource dictionary, add the following to the constructor i UserControl1.xaml.cs:

public UserControl1()
{
    if (DesignerProperties.GetIsInDesignMode(this))
        this.Resources.MergedDictionaries.Add(new YourNamespaceHere.GlobalResources());

    InitializeComponent();
}

Now the WinForms designer for the control where UserControl1 is used, will no longer complain about not finding your dll containing the resource dictionary. Used resources will also be displayed in the designer.

To make sure the WPF designer will show content from the resource dictionary that is used in UserControl1, you still need the following in your UserControl1.xaml:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MyDll;component/GlobalResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

MyDll is the name of the assembly containing the resource dictionary. In this example GlobalResources.xaml and GlobalResources.xaml.cs are expected to be placed at the root level of the assembly (not in a folder).


来源: stackexchange

问:
Joins in dynamodb tables
can we perform joins on DynamoDB table? If yes then please provide any sample for node js. here is my sample query.

```<code>SELECT M.*,MH.*,MP.* FROM MERCHANT AS M JOIN MERCHANT_HIERARCHY AS MH ON M.MERCHANT_ID=MH.SUB_MERCHANT_IDJOIN MERCHANT ON MH.MERCHANT_ID=MP.MERCHANT_IDWHERE M.USERNAME='THIS' AND M.PASSWORD='THIS' AND M.STATUS='ACTIVE'
</code>```

if you are not unable to understand this query you can use any table for one to one and one to many join example.

答:
Amazon DynamoDB is NoSQL database, often commonly referred to as a Document Store because it can store complex fields as JSON objects.

It cannot be used with SQL

Tables cannot be joined

Fields can't be mapped between tables

There are exceptions. For example, Hive on Amazon EMR can connect to DynamoDB and run SQL against data in DynamoDB and can even join tables between DynamoDB and other data sources. However, this is not a model that would normally be used to access data in DynamoDB.

ContentLicense: CC BY-SA 3.0

Title: Joins in dynamodb tables

Body:
can we perform joins on DynamoDB table? If yes then please provide any sample for node js. here is my sample query.

SELECT M.*,MH.*,MP.* FROM MERCHANT AS M JOIN MERCHANT_HIERARCHY AS MH ON M.MERCHANT_ID=MH.SUB_MERCHANT_IDJOIN MERCHANT ON MH.MERCHANT_ID=MP.MERCHANT_IDWHERE M.USERNAME='THIS' AND M.PASSWORD='THIS' AND M.STATUS='ACTIVE'

if you are not unable to understand this query you can use any table for one to one and one to many join example.


问:
Why is the ternary operator used to define 1 and 0 in a macro?
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

```<code>#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
</code>```

Does the use of the ternary operator here make any difference?

Isn't

```<code>#define FOO (1 > 0)
</code>```

the same as

```<code>#define BAR ( (1 > 0) ? 1 : 0)
</code>```

?

I tried evaluating it by using

```<code>printf("%d", FOO == BAR);
</code>```

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

答:
There are linting tools that are of the opinion that the result of a comparison is boolean, and can't be used directly in arithmetic.

Not to name names or point any fingers, but PC-lint is such a linting tool.

I'm not saying they're right, but it's a possible explanation to why the code was written like that.

Body:
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )

Does the use of the ternary operator here make any difference?

Isn't

#define FOO (1 > 0)

the same as

#define BAR ( (1 > 0) ? 1 : 0)

?

I tried evaluating it by using

printf("%d", FOO == BAR);

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?


问:
What are new languages useful for - finding use cases for Offsider
One of my colleagues today demonstrated what I could call an interesting piece of Computer Science. He has created a "system" for lack of a better word called Offsider. After the presentation I was left with a niggling thought that this must have some sort of precedence.

It feels like an object based shell like python with instant pickling of the objects on creation in what feels like a php file based sessions. Can anyone draw any well established parallels to this ? What would be reasonable use cases for it ?

答:
i think it's another one of those esoteric programming languages so many are written but so little is written in most of them

they normally have some interesting feature but no one is quite sure how to build on that

ContentLicense: CC BY-SA 2.5


问:
ExtJs: How can I select first item of Radiogroup on button click event
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

```<code>Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});
</code>```

Above code is not working. I have also tried below code. But it also doesn't work:

```<code>var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));
</code>```

答:
Or you can use id of your first radio item to select him

here is the fiddle

handler: function() {
  var radio = Ext.getCmp('yourgroupitemid');
  radio.setValue(true);
}```

Body:
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});

Above code is not working. I have also tried below code. But it also doesn't work:

var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));


问:
Local postrges works, but can't seem to push to RAILS_ENV=production heroku
I have my app working just fine on my local environment at localhost:3000. It is pulling data from my local postgres db, however I don't appear to be updating the production environment.  My welcome page is viewable on my https://gcl.herokuapp.com page, but when I click the nav link to view another page I get an error, I'm assuming because that page calls on data from the db, which it cannot find.

I'm doing $ rails db:migrate RAILS_ENV=production

I get the following output in Terminal:

```<code>(0.2ms)  SELECT pg_try_advisory_lock(3666737882978712990);
ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".*
FROM "schema_migrations"
ActiveRecord::InternalMetadata Load (0.6ms)  SELECT
"ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", :environment], ["LIMIT", 1]]
(0.2ms)  BEGIN
SQL (1.9ms)  UPDATE "ar_internal_metadata" SET "value" = $1, "updated_at" = $2 WHERE "ar_internal_metadata"."key" = $3  [["value", "production"], ["updated_at", 2017-03-31 10:42:57 UTC], ["key", "environment"]]
(0.4ms)  COMMIT
(0.2ms)  SELECT pg_advisory_unlock(3666737882978712990)
</code>```

I have gem 'pg' in my Gemfile

My database.yml looks like:

```<code>default: &default
 adapter: postgresql
 pool: 5
 timeout: 5000

development:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000
test:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000

production:
 adapter: postgresql
 database: postgresql-rectangular-42683
 username: Simon
 password: *************

 pool: 5
 timeout: 5000`
</code>```

Any thoughts?  Been trying various things for about a day now :(

Simon

答:
Try this in the terminal:

```<code>heroku run rake db:create:all
</code>```

then run the migrations:

```<code>heroku run rake db:migrate
</code>```

Also, could you post the output of heroku logs

Body:
I have my app working just fine on my local environment at localhost:3000. It is pulling data from my local postgres db, however I don't appear to be updating the production environment.  My welcome page is viewable on my https://gcl.herokuapp.com page, but when I click the nav link to view another page I get an error, I'm assuming because that page calls on data from the db, which it cannot find.

I'm doing $ rails db:migrate RAILS_ENV=production

I get the following output in Terminal:

(0.2ms)  SELECT pg_try_advisory_lock(3666737882978712990);
ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".*
FROM "schema_migrations"
ActiveRecord::InternalMetadata Load (0.6ms)  SELECT
"ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", :environment], ["LIMIT", 1]]
(0.2ms)  BEGIN
SQL (1.9ms)  UPDATE "ar_internal_metadata" SET "value" = $1, "updated_at" = $2 WHERE "ar_internal_metadata"."key" = $3  [["value", "production"], ["updated_at", 2017-03-31 10:42:57 UTC], ["key", "environment"]]
(0.4ms)  COMMIT
(0.2ms)  SELECT pg_advisory_unlock(3666737882978712990)

I have gem 'pg' in my Gemfile

My database.yml looks like:

default: &default
 adapter: postgresql
 pool: 5
 timeout: 5000

development:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000
test:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000

production:
 adapter: postgresql
 database: postgresql-rectangular-42683
 username: Simon
 password: *************

 pool: 5
 timeout: 5000`

Any thoughts?  Been trying various things for about a day now :(

Simon

Body:
Try this in the terminal:

heroku run rake db:create:all

then run the migrations:

heroku run rake db:migrate

Also, could you post the output of heroku logs


问:
How to determine if a Python class attribute is read only/writeable?
I'm trying to use inspect.getmembers() to list all the writeable attributes of a class. Is there a way to query if a class attribute is readonly or writeable?

Edit: I'm using the first solution from https://stackoverflow.com/a/3818861/2746401 and get an error when trying to copy read-only attributes (e.g. __doc__). I want to filter our these read-only properties and only copy the writeable ones

答:
Most names will be settable by default. The exceptions are the data descriptor objects and classes that define the __setattr__ hook.

A data descriptor is any attribute of the class that has a __get__ method and at least either a __set__ or a __delete__ method. These methods are used when you try to set or delete the attribute on an instance of the class.

Data descriptors with a __set__ method may not be writeable, and it'll depend on the exact descriptor implementation what they'll allow. A property object is such a data descriptor; if the property has a fset attribute set to None it won't be writeable. If property().fset is not set to None but to a callable, then that callable determines if the attribute is writeable.

In addition, any data descriptor with only a __delete__ method can't be written either, the lack of a __set__ method results in a AttributeError when you try to set the attribute name on the instance.

A __setattr__ hook intercepts all attribute setting, and can prevent any such action to fail. There is a corresponding __delattr__ hook too, which matters if you want to count deleting attributes as writing.

In other words, this is really hard to determine, not in a generic way, once descriptors or a __setattr__ hook are involved.


问:
Show Text on ProgressBar in StatusStrip
I am new in windows programming. In C# I was working with using Visual Studio 2017. Now, Im stuck with a problem. The Problem is that, I am trying to display some text (the progress value) in ProgressBar in the StatusStrip but can't find a proper working way to do that. :-(

Can anyone please provide me some ideas or solution to this problem? I shall be glad and thankful to you !
 Your answers will be appreciated greatly. :-)

答:
ToolStripProgressBar component uses a ProgressBar to show the progress and the  control doesn't show text. To be able to render a text for control, you need to paint the value yourself. To do so, you can create a custom item deriving from ToolStripProgressBar. Then you can use NativeWindow to assign a custom code to WM_PAINT message of the control:

```<code>using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
public class MyToolStripProgressBar : ToolStripProgressBar
{
    public MyToolStripProgressBar() : base()
    {
        this.Control.HandleCreated += Control_HandleCreated;
    }
    private void Control_HandleCreated(object sender, EventArgs e)
    {
        var s = new ProgressBarHelper((ProgressBar)this.Control);
    }
}
public class ProgressBarHelper : NativeWindow
{
    ProgressBar c;
    public ProgressBarHelper(ProgressBar progressBar)
    {
        c = progressBar;
        this.AssignHandle(c.Handle);
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0xF /*WM_PAINT*/)
        {
            using (var g = c.CreateGraphics())
                TextRenderer.DrawText(g, c.Value.ToString(),
                   c.Font, c.ClientRectangle, c.ForeColor);
        }
    }
}
</code>```

Title: Show Text on ProgressBar in StatusStrip

Body:
ToolStripProgressBar component uses a ProgressBar to show the progress and the  control doesn't show text. To be able to render a text for control, you need to paint the value yourself. To do so, you can create a custom item deriving from ToolStripProgressBar. Then you can use NativeWindow to assign a custom code to WM_PAINT message of the control:

using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
public class MyToolStripProgressBar : ToolStripProgressBar
{
    public MyToolStripProgressBar() : base()
    {
        this.Control.HandleCreated += Control_HandleCreated;
    }
    private void Control_HandleCreated(object sender, EventArgs e)
    {
        var s = new ProgressBarHelper((ProgressBar)this.Control);
    }
}
public class ProgressBarHelper : NativeWindow
{
    ProgressBar c;
    public ProgressBarHelper(ProgressBar progressBar)
    {
        c = progressBar;
        this.AssignHandle(c.Handle);
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0xF /*WM_PAINT*/)
        {
            using (var g = c.CreateGraphics())
                TextRenderer.DrawText(g, c.Value.ToString(),
                   c.Font, c.ClientRectangle, c.ForeColor);
        }
    }
}


问:
sql query to get multiplication of two rows of two different tables and insert the answer to one of the two table
I have two tables tblemployee, tblEmpSalary. I want to take the MonthlySalary form the tblEmployee and multiply it with the attendance in the tblEmpSalary and insert the answer to the tblEmpSalary table totalsalary column. Anyone kindly help me please.

```<code>tblEmployee
>EmpId
>Empname
>MonthlySalary

tblEmpSalary
>SalaryId
>EmpId
>Month
>Year
>AttendanceOfCurrentMonth
>TotalSalaryOfMonth
</code>```

I want the TotalSalaryOfMonth to be the

multiplication of MonthlySalary and AttendanceOfCurrentMonth

for each specific employee

答:
I think you are looking for Update based on Join conditions.
This link already answers your question.

UPDATE A
SET TotalSalaryOfMonth = AttendanceOfCurrentMonth * MonthlySalary
FROM tblEmpSalary A
INNER JOIN tblEmployee B
    ON A.EmpId = B.EmpId

Body:
I have two tables tblemployee, tblEmpSalary. I want to take the MonthlySalary form the tblEmployee and multiply it with the attendance in the tblEmpSalary and insert the answer to the tblEmpSalary table totalsalary column. Anyone kindly help me please.

tblEmployee
>EmpId
>Empname
>MonthlySalary

tblEmpSalary
>SalaryId
>EmpId
>Month
>Year
>AttendanceOfCurrentMonth
>TotalSalaryOfMonth

I want the TotalSalaryOfMonth to be the

multiplication of MonthlySalary and AttendanceOfCurrentMonth

for each specific employee


问:
g++ fatal error when compiling Google Test
I am trying to compile some tests with Google Test. I am using the sample makefile that comes with GTEST, but from a different directory. I added some make targets to compile my tests and sources, but left the Google Test bits untouched, however compiling the Google Test Sources fails with this notification:

```<code>    g++ -isystem ~/stm32/googletest/googletest/include -I~/stm32/googletest/googletest -g -Wall -Wextra -pthread -c \
            ~/stm32/googletest/googletest/src/gtest-all.cc
/home/nuclear_kiwi/stm32/googletest/googletest/src/gtest-all.cc:42:24: Fatal Error: src/gtest.cc: File or directory not found
     #include "src/gtest.cc"
</code>```

Why does this fail, even though the source path is supplied in the call to the compiler?

答:
You need to change:

```<code>-I~/stm32/googletest/googletest
</code>```

to:

```<code>-I ~/stm32/googletest/googletest
</code>```

Bash only recognizes the tilde-prefix operator when the ~ occurs at the
beginning of a word. 3.4.3. Tilde expansion

Body:
I am trying to compile some tests with Google Test. I am using the sample makefile that comes with GTEST, but from a different directory. I added some make targets to compile my tests and sources, but left the Google Test bits untouched, however compiling the Google Test Sources fails with this notification:

    g++ -isystem ~/stm32/googletest/googletest/include -I~/stm32/googletest/googletest -g -Wall -Wextra -pthread -c \
            ~/stm32/googletest/googletest/src/gtest-all.cc
/home/nuclear_kiwi/stm32/googletest/googletest/src/gtest-all.cc:42:24: Fatal Error: src/gtest.cc: File or directory not found
     #include "src/gtest.cc"

Why does this fail, even though the source path is supplied in the call to the compiler?

Body:
You need to change:

-I~/stm32/googletest/googletest

to:

-I ~/stm32/googletest/googletest

Bash only recognizes the tilde-prefix operator when the ~ occurs at the
beginning of a word. 3.4.3. Tilde expansion


问:
weak linking in shared object not working as expected
I'm trying to use the cmocka unit test framework which suggests to use weak linking to be able to select a user-defined implementation over the actual implementation of a function. In my environment I have a shared object which I want to unit test. I've implemented the unit tests in a separate file which I compile and link to the shared object. My problem is that calling a function bar in the shared object which in turn calls a function foo in that shared object always leads to the real implementation of foo and not the custom one. I've created a simplified implementation of the shared object and of the unit test.

The shared library, a.c:

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

void foo(void); __attribute__((weak))
void bar(void); __attribute__((weak))

void foo(void) {
    printf("called real foo\n");
}

void bar(void) {
    printf("called real bar calling\n");
    foo();
}
</code>```

The unit test, b.c:

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

bool orig_foo;
bool orig_bar;

void __wrap_foo(void) {
    printf("in foo wrapper\n");
    if (orig_foo)
            __real_foo();
    else
            printf("called wrapped foo\n");
}

void __wrap_bar() {
    printf("in bar wrapper\n");
    if (orig_bar)
            __real_bar();
    else
            printf("called wrapped bar\n");
}

int main(void) {

    orig_bar = true;
    orig_foo = false;

    printf("calling foo from main\n");
    foo();

    printf("\n");

    printf("calling bar from main\n");
    bar();

    return 0;
}
</code>```

And finally, the Makefile:

```<code>all: a.out

a.out: b.c a.so
    gcc -Wall b.c a.so -Wl,--wrap=foo -Wl,--wrap=bar

a.so: a.c
    gcc -Wall -c a.c -shared -o a.so

clean:
    rm -f a.so a.out
</code>```

Running a.out produces the following output:

```<code># ./a.out
calling foo from main
in foo wrapper
called wrapped foo

calling bar from main
in bar wrapper
called real bar
called real foo
</code>```

From main, the direct call to foo results in __wrap_foo being called, as expected.

Next, I call bar from main which correctly results in __wrap_bar being called, where I redirect the call to the real implementation of bar (__real_bar). bar then calls foo but the real implementation is used, not the wrapped one. Why isn't the wrapped implementation of foo called in this case? It looks like the issue is related to from where the function call originates.

In function bar, if I replaced the called to foo with __wrap_foo I do get the expected behaviour however I don't think that this is an elegant solution.

I've managed to bypass this problem using normal linking and dlopen(3) and friends however I'm curious as to why weak linking isn't working in my case.

答:
One error is that attribute syntax is not correct. Correct ones:

```<code>void foo(void) __attribute__((weak));
void bar(void) __attribute__((weak));
</code>```

An alternative solution would be the standard Linux function interposition:

```<code>// a.c
#include <stdio.h>

void foo(void) {
    printf("called real foo\n");
}

void bar(void) {
    printf("called real bar calling\n");
    foo();
}
</code>```

```<code>// b.c

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdbool.h>

bool orig_foo;
bool orig_bar;

void foo(void) {
    printf("in foo wrapper\n");

    static void(*__real_foo)(void);
    if(!__real_foo)
        __real_foo = dlsym(RTLD_NEXT, "foo");

    if (orig_foo)
            __real_foo();
    else
            printf("called wrapped foo\n");
}

void bar() {
    printf("in bar wrapper\n");

    static void(*__real_bar)(void);
    if(!__real_bar)
        __real_bar = dlsym(RTLD_NEXT, "bar");

    if (orig_bar)
            __real_bar();
    else
            printf("called wrapped bar\n");
}

int main(void) {

    orig_bar = true;
    orig_foo = false;

    printf("calling foo from main\n");
    foo();

    printf("\n");

    printf("calling bar from main\n");
    bar();

    return 0;
}
</code>```

```<code>$ gcc -o a.so -shared -Wall -Wextra -fPIC a.c
$ gcc -o b -Wall -Wextra b.c -L. -l:a.so -Wl,-rpath='$ORIGIN' -ldl
$ ./b
calling foo from main
in foo wrapper
called wrapped foo

calling bar from main
in bar wrapper
called real bar calling
in foo wrapper
called wrapped foo
</code>```

Body:
I'm trying to use the cmocka unit test framework which suggests to use weak linking to be able to select a user-defined implementation over the actual implementation of a function. In my environment I have a shared object which I want to unit test. I've implemented the unit tests in a separate file which I compile and link to the shared object. My problem is that calling a function bar in the shared object which in turn calls a function foo in that shared object always leads to the real implementation of foo and not the custom one. I've created a simplified implementation of the shared object and of the unit test.

The shared library, a.c:

#include <stdio.h>

void foo(void); __attribute__((weak))
void bar(void); __attribute__((weak))

void foo(void) {
    printf("called real foo\n");
}

void bar(void) {
    printf("called real bar calling\n");
    foo();
}

The unit test, b.c:

#include <stdio.h>
#include <stdbool.h>

bool orig_foo;
bool orig_bar;

void __wrap_foo(void) {
    printf("in foo wrapper\n");
    if (orig_foo)
            __real_foo();
    else
            printf("called wrapped foo\n");
}

void __wrap_bar() {
    printf("in bar wrapper\n");
    if (orig_bar)
            __real_bar();
    else
            printf("called wrapped bar\n");
}

int main(void) {

    orig_bar = true;
    orig_foo = false;

    printf("calling foo from main\n");
    foo();

    printf("\n");

    printf("calling bar from main\n");
    bar();

    return 0;
}

And finally, the Makefile:

all: a.out

a.out: b.c a.so
    gcc -Wall b.c a.so -Wl,--wrap=foo -Wl,--wrap=bar

a.so: a.c
    gcc -Wall -c a.c -shared -o a.so

clean:
    rm -f a.so a.out

Running a.out produces the following output:

# ./a.out
calling foo from main
in foo wrapper
called wrapped foo

calling bar from main
in bar wrapper
called real bar
called real foo

From main, the direct call to foo results in __wrap_foo being called, as expected.

Next, I call bar from main which correctly results in __wrap_bar being called, where I redirect the call to the real implementation of bar (__real_bar). bar then calls foo but the real implementation is used, not the wrapped one. Why isn't the wrapped implementation of foo called in this case? It looks like the issue is related to from where the function call originates.

In function bar, if I replaced the called to foo with __wrap_foo I do get the expected behaviour however I don't think that this is an elegant solution.

I've managed to bypass this problem using normal linking and dlopen(3) and friends however I'm curious as to why weak linking isn't working in my case.

Body:
One error is that attribute syntax is not correct. Correct ones:

void foo(void) __attribute__((weak));
void bar(void) __attribute__((weak));

An alternative solution would be the standard Linux function interposition:

// a.c
#include <stdio.h>

void foo(void) {
    printf("called real foo\n");
}

void bar(void) {
    printf("called real bar calling\n");
    foo();
}

// b.c

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdbool.h>

bool orig_foo;
bool orig_bar;

void foo(void) {
    printf("in foo wrapper\n");

    static void(*__real_foo)(void);
    if(!__real_foo)
        __real_foo = dlsym(RTLD_NEXT, "foo");

    if (orig_foo)
            __real_foo();
    else
            printf("called wrapped foo\n");
}

void bar() {
    printf("in bar wrapper\n");

    static void(*__real_bar)(void);
    if(!__real_bar)
        __real_bar = dlsym(RTLD_NEXT, "bar");

    if (orig_bar)
            __real_bar();
    else
            printf("called wrapped bar\n");
}

int main(void) {

    orig_bar = true;
    orig_foo = false;

    printf("calling foo from main\n");
    foo();

    printf("\n");

    printf("calling bar from main\n");
    bar();

    return 0;
}

$ gcc -o a.so -shared -Wall -Wextra -fPIC a.c
$ gcc -o b -Wall -Wextra b.c -L. -l:a.so -Wl,-rpath='$ORIGIN' -ldl
$ ./b
calling foo from main
in foo wrapper
called wrapped foo

calling bar from main
in bar wrapper
called real bar calling
in foo wrapper
called wrapped foo


问:
How can I put an icon and an input text on the same line?
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

```<code>----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------
</code>```

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

答:
Try this ...</p>

```<code><div style="display: table;">
<div style="display: table-row; width:100%;">
    <div style="display: table-cell;">
    <img src="img.png" width="16" height="11" alt="img"/>
    </div>
    <div style="display: table-cell; width:100%;">
    <input type="text" style="width:100%;"/>
    </div>
</div>
</div>
</code>```

Body:
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

Body:
Try this ...

<div style="display: table;">
<div style="display: table-row; width:100%;">
    <div style="display: table-cell;">
    <img src="img.png" width="16" height="11" alt="img"/>
    </div>
    <div style="display: table-cell; width:100%;">
    <input type="text" style="width:100%;"/>
    </div>
</div>
</div>


问:
Angular 2 map.set is not a function
I am trying to added some values to my map. For example I have the following,

My AddressBook class

```<code>export class AddressBook {
  constructor(
    public social: Map<string, string> = new Map<string, string>(),

  ) {
  }
}
</code>```

here is what the server is returning,

```<code>{
 social: {
 twitter: "twitterId",
 facebook: "facebookId",
 linkedIn: "linkedinId",
 pinterest: "pinterestId"
 }
}
</code>```

This is my method to add to my social map

```<code>this.addressBook.social.set('Google+','GooglePlusId');
</code>```

But I get the following error

```<code>caused by: this.addressBook.social.set is not a function
</code>```

Here is how i retrieve the data from the server

```<code> return this.http.get(this.addressBookURL+address_book_id)
      .map(res => <AddressBook> res.json())
      .catch(this.handleError);

this.addressBookService.getAddressBookFromId(address_book_id)
      .subscribe((res) => {
          this.addressBook = res;

        },
        error => {
          console.log(<any>error);
        });
</code>```

Not sure how to solve this. If anyone can point me the right direction that would be much appreciated. Thanks

答:
I guess that you don't pass the right argument to the AddressBook constructor.
Actually I guess you are doing this:

```<code>let addressBook= new AdresseBook({
 twitter: "twitterId",
 facebook: "facebookId",
 linkedIn: "linkedinId",
 pinterest: "pinterestId"
 } as any);
</code>```

while you should pass a Map Object...

```<code>let map = new Map();
let obj = {
  twitter: "twitterId",
  facebook: "facebookId",
  linkedIn: "linkedinId",
  pinterest: "pinterestId"
};
Object.keys(obj).forEach(key => {
  map.set(key, obj[key]);
});
let addressBook = new AdresseBook(map);
</code>```

Edit: and I'm right (I'm always right), you cannot expect a plain object to be a Map :

```<code> return this.http.get(this.addressBookURL+address_book_id)
      .map(res => <AddressBook> res.json()) //here you are just telling the compiler
                                            // that resp.json() is an AdresseBook, but
                                            // it's not right, it's a plain Object
      .catch(this.handleError);
</code>```

This should work :

```<code> return this.http.get(this.addressBookURL+address_book_id)
      .map(res => {
        let map = new Map();
        let social = res.json().social;
        Object.keys(social).forEach(key => {
          map.set(key, social[key]);
        });
        return new AdresseBook(map);
      })
      .catch(this.handleError);
</code>```

Title: Angular 2 map.set is not a function

Body:
I am trying to added some values to my map. For example I have the following,

My AddressBook class

export class AddressBook {
  constructor(
    public social: Map<string, string> = new Map<string, string>(),

  ) {
  }
}

here is what the server is returning,

{
 social: {
 twitter: "twitterId",
 facebook: "facebookId",
 linkedIn: "linkedinId",
 pinterest: "pinterestId"
 }
}

This is my method to add to my social map

this.addressBook.social.set('Google+','GooglePlusId');

But I get the following error

caused by: this.addressBook.social.set is not a function

Here is how i retrieve the data from the server

 return this.http.get(this.addressBookURL+address_book_id)
      .map(res => <AddressBook> res.json())
      .catch(this.handleError);

this.addressBookService.getAddressBookFromId(address_book_id)
      .subscribe((res) => {
          this.addressBook = res;

        },
        error => {
          console.log(<any>error);
        });

Not sure how to solve this. If anyone can point me the right direction that would be much appreciated. Thanks

Body:
I guess that you don't pass the right argument to the AddressBook constructor.
Actually I guess you are doing this:

let addressBook= new AdresseBook({
 twitter: "twitterId",
 facebook: "facebookId",
 linkedIn: "linkedinId",
 pinterest: "pinterestId"
 } as any);

while you should pass a Map Object...

let map = new Map();
let obj = {
  twitter: "twitterId",
  facebook: "facebookId",
  linkedIn: "linkedinId",
  pinterest: "pinterestId"
};
Object.keys(obj).forEach(key => {
  map.set(key, obj[key]);
});
let addressBook = new AdresseBook(map);

Edit: and I'm right (I'm always right), you cannot expect a plain object to be a Map :

 return this.http.get(this.addressBookURL+address_book_id)
      .map(res => <AddressBook> res.json()) //here you are just telling the compiler
                                            // that resp.json() is an AdresseBook, but
                                            // it's not right, it's a plain Object
      .catch(this.handleError);

This should work :

 return this.http.get(this.addressBookURL+address_book_id)
      .map(res => {
        let map = new Map();
        let social = res.json().social;
        Object.keys(social).forEach(key => {
          map.set(key, social[key]);
        });
        return new AdresseBook(map);
      })
      .catch(this.handleError);


问:
Explode array from mysql and assign to variables PHP
OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )

What I'm trying to do is explode at the : and then assign the exploded values to variables

At most there are 4 bits of data separated by : so a max of 4 variables

Here is the code I have so far

```<code>$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);

do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4;
}while($result = mysql_fetch_assoc($query));
</code>```

It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:

The output however does NOT display the final
Advanced

it only displays
Novice
Novice/Intermediate
Intermediate/Advanced

Anyone help me please I am pulling hair out badly here .

I have also tried adding another $var5 but that doesnt help

答:
I forgot to add $var5 to the list()

```<code> $query = mysql_query("SELECT * FROM venues WHERE id ='30'",$dbc);
 $result = mysql_fetch_assoc($query);

 do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4,$var5) = $eventtype;
 //print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4.'<br>'.$var5;
 }while($result = mysql_fetch_assoc($query));
</code>```

Working fine now :)

Body:
OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )

What I'm trying to do is explode at the : and then assign the exploded values to variables

At most there are 4 bits of data separated by : so a max of 4 variables

Here is the code I have so far

$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);

do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'
'.$var2.'
'.$var3.'
'.$var4;
}while($result = mysql_fetch_assoc($query));

It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:

The output however does NOT display the final
Advanced

it only displays
Novice
Novice/Intermediate
Intermediate/Advanced

Anyone help me please I am pulling hair out badly here .

I have also tried adding another $var5 but that doesnt help

Body:
I forgot to add $var5 to the list()

 $query = mysql_query("SELECT * FROM venues WHERE id ='30'",$dbc);
 $result = mysql_fetch_assoc($query);

 do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4,$var5) = $eventtype;
 //print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4.'<br>'.$var5;
 }while($result = mysql_fetch_assoc($query));

Working fine now :)


问:
AHK Add Checkboxes dynamically
I was wondering if anyone had any source for adding a Checkbox to a GUI dynamically? Basically i have a Loader that download AHK Scripts but i need to add a new Checkbox for every downloaded Script in my Gui that activates the Script if a condution is given like game xxx.exe is running

you can find the script Here: https://github.com/happymaj00r/HappyLoader

答:
I'd advice you to use a ListView for that. Using the Checked option you can have Checkboxes in every row. This way all the nasty scrollbar stuff is being handles for you automatically.

```<code>Gui, Add, ListView, r10 AltSubmit Checked v#HSList Hdr gListViewChecks, |Column
Gui, Add, Button, gButton, Add Row
Gui, Show,, Dynamically Add Checkboxes
Return

Button:
    LV_Add(Checked, "", "Another Row")
Return

ListViewChecks:
    If (A_GuiEvent == "I") {
        If (ErrorLevel == "C")
            ToolTip, % "Row " . A_EventInfo . " is checked."
        Else If (ErrorLevel == "c")
            ToolTip, % "Row " . A_EventInfo . " is unchecked."
    }
Return

GuiClose:
    ExitApp
</code>```

Title: AHK Add Checkboxes dynamically

Body:
I'd advice you to use a ListView for that. Using the Checked option you can have Checkboxes in every row. This way all the nasty scrollbar stuff is being handles for you automatically.

Gui, Add, ListView, r10 AltSubmit Checked v#HSList Hdr gListViewChecks, |Column
Gui, Add, Button, gButton, Add Row
Gui, Show,, Dynamically Add Checkboxes
Return

Button:
    LV_Add(Checked, "", "Another Row")
Return

ListViewChecks:
    If (A_GuiEvent == "I") {
        If (ErrorLevel == "C")
            ToolTip, % "Row " . A_EventInfo . " is checked."
        Else If (ErrorLevel == "c")
            ToolTip, % "Row " . A_EventInfo . " is unchecked."
    }
Return

GuiClose:
    ExitApp


问:
datatable plugin not display elements after clicking again on link to show
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid text-center">
      <div class="row content">
       <div class="col-lg-2 sidenav">
      <a href="#" id="link3" class="list-group-item">Vertical link #3</a>
        </div>
        <div class="col-lg-10 text-left">
          <div class="row">
            <div class="col-lg-12" id="content"></div>
          </div>
        </div>
      </div>
    </div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- link3 -->
<script src="link3.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
</html>
</code>```

link3.js

```<code>$(document).ready(function(){
var table = $('<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Note</th></tr></thead><tbody></tbody></table>').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("<tr><td>"+id+"</td><td>"+id2+"</td><td>"+id3+"</td><td>"+id4+"</td></tr>");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});
</code>```

test.json

```<code>[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]
</code>```

答:
Try out the below Code It will directly add JSON to data table:

$('.search-table').DataTable({"ajax": "test.json"});

Take Reference from https://datatables.net/reference/option/ajax

Body:
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

<!DOCTYPE html>

  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">

      Vertical link #3

link3.js

$(document).ready(function(){
var table = $('

Name	Age	Position	Note

').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("
"+id+"	"+id2+"	"+id3+"	"+id4+"
");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});

test.json

[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]


问:
Photo is never shown in Gallery in a new folder
I am trying to take a picture or select it from gallery, compress it and save it in a separate folder on my phone. The photo is taken and put into the imageview but I can't find it in gallery, even after couple of minutes. What might be the problem?

String mPhotoLocation;

```<code>private void takePhoto() {
    Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photoFile = null;
    try {
        photoFile = photoPath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Uri photoURI = FileProvider.getUriForFile(getContext(),
            getContext().getApplicationContext().getPackageName() + ".provider",
            photoFile);
    takePhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    startActivityForResult(takePhoto, REQUEST_CAMERA);
}
</code>```

Compressing the image

```<code>public String compressImage(String imageUri) {

    String filePath = getRealPathFromURI(imageUri);
    Bitmap scaledBitmap = null;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;

    options.inTempStorage = new byte[16 * 1024];

    try {
        bmp = BitmapFactory.decodeFile(filePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    ExifInterface exif;
    try {
        exif = new ExifInterface(filePath);

        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }
        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out;
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String photoName = "PHOTO_" + timestamp + "_";
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDirectory = new File(root, "/Test");
    if (!myDirectory.exists()) {
        myDirectory.mkdirs();
    }
    File f = new File(myDirectory.getAbsolutePath(), photoName);
    String filename = f.getAbsolutePath();
    mPhotoLocation = filename;
    try {
        out = new FileOutputStream(filename);
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return filename;
}

private String getRealPathFromURI(String contentURI) {
    Uri contentUri = Uri.parse(contentURI);
    Cursor cursor = getContext().getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}

public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;
    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }

    return inSampleSize;
}
</code>```

答:
Call this method After saving image

```<code>  public static void notifySystemGallery(Context context, File file) {
    if (file == null || !file.exists()) {
        Log.e(TAG, "notifySystemGallery: the file do not exist.");
        return;
    }

    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(),
                file.getName(), null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}
</code>```

Body:
I am trying to take a picture or select it from gallery, compress it and save it in a separate folder on my phone. The photo is taken and put into the imageview but I can't find it in gallery, even after couple of minutes. What might be the problem?

String mPhotoLocation;

private void takePhoto() {
    Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photoFile = null;
    try {
        photoFile = photoPath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Uri photoURI = FileProvider.getUriForFile(getContext(),
            getContext().getApplicationContext().getPackageName() + ".provider",
            photoFile);
    takePhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    startActivityForResult(takePhoto, REQUEST_CAMERA);
}

Compressing the image

public String compressImage(String imageUri) {

    String filePath = getRealPathFromURI(imageUri);
    Bitmap scaledBitmap = null;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;

    options.inTempStorage = new byte[16 * 1024];

    try {
        bmp = BitmapFactory.decodeFile(filePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    ExifInterface exif;
    try {
        exif = new ExifInterface(filePath);

        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }
        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out;
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String photoName = "PHOTO_" + timestamp + "_";
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDirectory = new File(root, "/Test");
    if (!myDirectory.exists()) {
        myDirectory.mkdirs();
    }
    File f = new File(myDirectory.getAbsolutePath(), photoName);
    String filename = f.getAbsolutePath();
    mPhotoLocation = filename;
    try {
        out = new FileOutputStream(filename);
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return filename;
}

private String getRealPathFromURI(String contentURI) {
    Uri contentUri = Uri.parse(contentURI);
    Cursor cursor = getContext().getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}

public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;
    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }

    return inSampleSize;
}

Body:
Call this method After saving image

  public static void notifySystemGallery(Context context, File file) {
    if (file == null || !file.exists()) {
        Log.e(TAG, "notifySystemGallery: the file do not exist.");
        return;
    }

    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(),
                file.getName(), null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}


问:
Show popover on button click using jquery
I am trying to display notification message by using popover, it is working but after loading a page if i click button first time it doesn't show the popover after that it works fine here is my code-

```<code><button type="button" id="bulk_actions_btn" class="btn btn-default has-spinner-two" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="Click any question mark icon to get help and tips with specific tasks"> Apply </button>
</code>```

Jquery

```<code>$(document).on('click','#bulk_actions_btn',function(){

   if(condition){
        $('[data-toggle="popover"]').popover(); //here if the condition is true then popover should be display.
    }else{
       //ajax
    }
});
</code>```

答:
you need to enable popover before it can be used. They are not enabled by default. So when you call popover() method, you are actually initializing the popover. You do that on click event and hence it doesnt work for the first time.
You should do that when document.ready is triggered like so -

```<code>$(document).ready(function(){
    $('[data-toggle="popover"]').popover();
});
</code>```

This will enable all bootstrap popovers in your code

Body:
I am trying to display notification message by using popover, it is working but after loading a page if i click button first time it doesn't show the popover after that it works fine here is my code-

<button type="button" id="bulk_actions_btn" class="btn btn-default has-spinner-two" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="Click any question mark icon to get help and tips with specific tasks"> Apply </button>

Jquery

$(document).on('click','#bulk_actions_btn',function(){

   if(condition){
        $('[data-toggle="popover"]').popover(); //here if the condition is true then popover should be display.
    }else{
       //ajax
    }
});

Body:
you need to enable popover before it can be used. They are not enabled by default. So when you call popover() method, you are actually initializing the popover. You do that on click event and hence it doesnt work for the first time.
You should do that when document.ready is triggered like so -

$(document).ready(function(){
    $('[data-toggle="popover"]').popover();
});

This will enable all bootstrap popovers in your code


问:
iPad - How to move Mulitple UIViews side-by-side
How to move multiple UIViews Side-by-Side just like an twitter application working in iPad. With full of effects animation and rotations.</p>

答:
You should take a look at the UIScrollView with paging enabled.

Make all your views and put them next to one another inside a UIScrollView. i.e.

```<code>// Get your views
MyView *v1 = [[[MyView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
MyView *v2 = [[[MyView alloc] initWithFrame:CGRectMake(320, 0, 320, 480)] autorelease];
MyView *v3 = [[[MyView alloc] initWithFrame:CGRectMake(640, 0, 320, 480)] autorelease];

// Make the UIScrollView
UIScrollView *scroll = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
[scroll setPagingEnabled:YES];
[[scroll addSubview:v1];
[[scroll addSubview:v2];
[[scroll addSubview:v3];
[scroll setContentSize:CGSizeMake(960, 480)];

// add the scroll view to your view
[[self view] addSubview:scroll];
</code>```

Now, the three views (v1, v2 and v3) are next to each other in a scroll view whose content is much wider the view. With paging enabled, they will scroll left and right but won't stop halfway through a view.

Body:
You should take a look at the UIScrollView with paging enabled.

Make all your views and put them next to one another inside a UIScrollView. i.e.

// Get your views
MyView *v1 = [[[MyView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
MyView *v2 = [[[MyView alloc] initWithFrame:CGRectMake(320, 0, 320, 480)] autorelease];
MyView *v3 = [[[MyView alloc] initWithFrame:CGRectMake(640, 0, 320, 480)] autorelease];

// Make the UIScrollView
UIScrollView *scroll = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
[scroll setPagingEnabled:YES];
[[scroll addSubview:v1];
[[scroll addSubview:v2];
[[scroll addSubview:v3];
[scroll setContentSize:CGSizeMake(960, 480)];

// add the scroll view to your view
[[self view] addSubview:scroll];

Now, the three views (v1, v2 and v3) are next to each other in a scroll view whose content is much wider the view. With paging enabled, they will scroll left and right but won't stop halfway through a view.


问:
Why does Visual Studio automatically changes the layout of my form?
I have a Windows form which consists of 3 files:

AbcFrm.cs

AbcFrm.Designer.cs

AbcFrm.resx

Whenever I do a little change to any properties of datagridview or add new events, the size of the controls grows larger to the right and bottom side and causes some part of the controls to go out of bounds.

I have compared the .Designer.cs file before and after I perform a minor property change (e.g. change a datagridview's tabStop property value from true to false) and discovered some lines/properties were added/changed automatically in the .Designer.cs file :

some controls' .Size value changes

some controls' .Location value changes

some controls' .Padding value changes

the form's .AutoScaleDimensions becomes larger

the form's .ClientSize becomes larger

Edit

I realize when I change the resolution from 150% to 125% and reopen the application, the controls are back in the correct place due to the windows form is now having a larger scaling size. My problem is similar to this question

The cause is that the code might have been edited in a computer with different resolution. However, the solution is not satisfying as it does not solves the problem, only identifying the cause.

How do I prevent this from happening? I'm using Visual Studio 2010 and my OS is Windows 10.

答:
My solution to this was to add the registry key LogPixels and rebooting the machine.  This key was previously not present on my machine.

```<code>[HKEY_CURRENT_USER\Control Panel\Desktop] "LogPixels"=dword:00000096
</code>```

I am on Windows 10 with a high resolution display.  I tried to toggle my display settings back to 100% but it had no effect.

This registry setting worked for me.

Body:
My solution to this was to add the registry key LogPixels and rebooting the machine.  This key was previously not present on my machine.

[HKEY_CURRENT_USER\Control Panel\Desktop] "LogPixels"=dword:00000096

I am on Windows 10 with a high resolution display.  I tried to toggle my display settings back to 100% but it had no effect.

This registry setting worked for me.


问:
php array_multisort use array name as argument
Sorry if this is duplicate, I have tried to look at previous posts, but maybe my limited understanding of php gets in the way.

This works to sort arrays 1 and 3 by array 2:

```<code><?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

array_multisort($ar[2],$ar[1],$ar[3]);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>
</code>```

output:

rock  A  one

 scissors  B  two

 paper  C  three

 game  D  four

Fine. But I want the list of arrays used as argument for array_multisort() to be specified by user input, so it can't be literal. Instead, I would like the program to decide the order of arrays in the list based on the user input and then name the resulting array of arrays $supar (superarray). But when using $supar as argument for array_multisort(), no sorting is carried out.

```<code><?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

$supar = array($ar[2],$ar[1],$ar[3]);
array_multisort($supar);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>
</code>```

Output:

game  D  four

 scissors  B  two

 rock  A  one

 paper  C  three

How should I do to make array_multisort() sort the arrays in $supar by a specified $ar array?

Thank you for your patience.

答:
You can't do that with just the PHP function. array_multisort() takes the different arrays separately as arguments and you can't just pass a different thing with the intended arguments inside.

What you could do is writing your own function to do that for you. Something like:

```<code>function my_multisort($supar) {
    array_multisort($supar[2], $supar[1], $supar[3]);
}

$supar = array(
    array("game","scissors","rock","paper"),
    array("D", "B", "A", "C"),
    array("four","two","one","three")
);

my_multisort($supar);
</code>```

EDIT

As @axiac correctly pointed out, this is basically a weird specific way of reinventing call_user_func_array(). You can simply build your array of arguments $supar as you need and then do

```<code>call_user_func_array('array_multisort', $supar);
</code>```

Body:
Sorry if this is duplicate, I have tried to look at previous posts, but maybe my limited understanding of php gets in the way.

This works to sort arrays 1 and 3 by array 2:

<?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

array_multisort($ar[2],$ar[1],$ar[3]);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>

output:

rock  A  one

 scissors  B  two

 paper  C  three

 game  D  four

Fine. But I want the list of arrays used as argument for array_multisort() to be specified by user input, so it can't be literal. Instead, I would like the program to decide the order of arrays in the list based on the user input and then name the resulting array of arrays $supar (superarray). But when using $supar as argument for array_multisort(), no sorting is carried out.

<?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

$supar = array($ar[2],$ar[1],$ar[3]);
array_multisort($supar);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>

Output:

game  D  four

 scissors  B  two

 rock  A  one

 paper  C  three

How should I do to make array_multisort() sort the arrays in $supar by a specified $ar array?

Thank you for your patience.

Body:
You can't do that with just the PHP function. array_multisort() takes the different arrays separately as arguments and you can't just pass a different thing with the intended arguments inside.

What you could do is writing your own function to do that for you. Something like:

function my_multisort($supar) {
    array_multisort($supar[2], $supar[1], $supar[3]);
}

$supar = array(
    array("game","scissors","rock","paper"),
    array("D", "B", "A", "C"),
    array("four","two","one","three")
);

my_multisort($supar);

EDIT

As @axiac correctly pointed out, this is basically a weird specific way of reinventing call_user_func_array(). You can simply build your array of arguments $supar as you need and then do

call_user_func_array('array_multisort', $supar);


问:
How to hide Logon Password in Teradata MLoad Script
I have written a Multiload script to Load Data in TeraData Database and the commands in the script is like:

```<code>.LOGTABLE Employee_log;
.LOGON 192.168.1.1/dbc,dbc;
.BEGIN MLOAD TABLES Employee_Stg;
.LAYOUT Employee;
.FIELD in_EmployeeNo * VARCHAR(10);
.FIELD in_FirstName * VARCHAR(30); ....
</code>```

But the password is clearly visible in the script. Is there a option to secure the password or any alternate way/command to logon and then run the script.

答:
You can create a logon file and run it in your MLOAD script using the following command

.RUN FILE logonfile.txt

In the logon file you can provide the statement that you used in your script    .LOGON 192.168.1.1/dbc,dbc;

Body:
I have written a Multiload script to Load Data in TeraData Database and the commands in the script is like:

.LOGTABLE Employee_log;
.LOGON 192.168.1.1/dbc,dbc;
.BEGIN MLOAD TABLES Employee_Stg;
.LAYOUT Employee;
.FIELD in_EmployeeNo * VARCHAR(10);
.FIELD in_FirstName * VARCHAR(30); ....

But the password is clearly visible in the script. Is there a option to secure the password or any alternate way/command to logon and then run the script.


问:
Local postrges works, but can't seem to push to RAILS_ENV=production heroku
I have my app working just fine on my local environment at localhost:3000. It is pulling data from my local postgres db, however I don't appear to be updating the production environment.  My welcome page is viewable on my https://gcl.herokuapp.com page, but when I click the nav link to view another page I get an error, I'm assuming because that page calls on data from the db, which it cannot find.

I'm doing $ rails db:migrate RAILS_ENV=production

I get the following output in Terminal:

```<code>(0.2ms)  SELECT pg_try_advisory_lock(3666737882978712990);
ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".*
FROM "schema_migrations"
ActiveRecord::InternalMetadata Load (0.6ms)  SELECT
"ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", :environment], ["LIMIT", 1]]
(0.2ms)  BEGIN
SQL (1.9ms)  UPDATE "ar_internal_metadata" SET "value" = $1, "updated_at" = $2 WHERE "ar_internal_metadata"."key" = $3  [["value", "production"], ["updated_at", 2017-03-31 10:42:57 UTC], ["key", "environment"]]
(0.4ms)  COMMIT
(0.2ms)  SELECT pg_advisory_unlock(3666737882978712990)
</code>```

I have gem 'pg' in my Gemfile

My database.yml looks like:

```<code>default: &default
 adapter: postgresql
 pool: 5
 timeout: 5000

development:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000
test:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000

production:
 adapter: postgresql
 database: postgresql-rectangular-42683
 username: Simon
 password: *************

 pool: 5
 timeout: 5000`
</code>```

Any thoughts?  Been trying various things for about a day now :(

Simon

答:
Haha, two mins later I've found what the problem was, and as usual it was a simple one.  I needed to run $ heroku run rake db:seed.

Although this only seems to have added the tables, as my rows still show as 0 of 10000

Also, my pages still don't load at https://gcl.herokuapp.com/articles but not 100% sure that's related to the db.

Body:
I have my app working just fine on my local environment at localhost:3000. It is pulling data from my local postgres db, however I don't appear to be updating the production environment.  My welcome page is viewable on my https://gcl.herokuapp.com page, but when I click the nav link to view another page I get an error, I'm assuming because that page calls on data from the db, which it cannot find.

I'm doing $ rails db:migrate RAILS_ENV=production

I get the following output in Terminal:

(0.2ms)  SELECT pg_try_advisory_lock(3666737882978712990);
ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".*
FROM "schema_migrations"
ActiveRecord::InternalMetadata Load (0.6ms)  SELECT
"ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", :environment], ["LIMIT", 1]]
(0.2ms)  BEGIN
SQL (1.9ms)  UPDATE "ar_internal_metadata" SET "value" = $1, "updated_at" = $2 WHERE "ar_internal_metadata"."key" = $3  [["value", "production"], ["updated_at", 2017-03-31 10:42:57 UTC], ["key", "environment"]]
(0.4ms)  COMMIT
(0.2ms)  SELECT pg_advisory_unlock(3666737882978712990)

I have gem 'pg' in my Gemfile

My database.yml looks like:

default: &default
 adapter: postgresql
 pool: 5
 timeout: 5000

development:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000
test:
 adapter: postgresql
 database: postgresql-rectangular-42683
 pool: 5
 timeout: 5000

production:
 adapter: postgresql
 database: postgresql-rectangular-42683
 username: Simon
 password: *************

 pool: 5
 timeout: 5000`

Any thoughts?  Been trying various things for about a day now :(

Simon


问:
ngRepeat - Sort object by specific keys first
I'm writing an AngularJS application (Angular 1) which requires a list of tables to be displayed on the page. However certain keys need to be displayed first like so:

```<code><div>baz (data)</div>
<div>bar (data)</div>
<div>foo (data)</div>
<div>baa (data)</div>
</code>```

I figured out I need to use the orderBy filter, however I can't seem to get that working. Does anyone know how I could achieve this?

JS:

```<code>angular.module("MyModule").controller("Test", function() {

    this.sort = ["baz", "bar"];

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

});
</code>```

HTML:

```<code><div ng-controller="Test as T">
    <div ng-repeat="(title, row) in T.data"> <!-- Not sure how I would go about sorting these keys by certain ones first -->
        {{ title }} ({{ row }})
    </div>
</div>
</code>```

答:
```<code><div ng-repeat="item in T.data | orderBy: customFilter
{{ item.$key }} ({{ item.value }}
</code>```

```<code>this.customFilter(obj){
switch(key){//key is actual value of cases like `baz`,`bar`
   case "baz":return 0;
   case "bar":return 1;
   case "foo":return 2;
   case "baa":return 3;
   default:return 99;
}
}
</code>```

Body:
I'm writing an AngularJS application (Angular 1) which requires a list of tables to be displayed on the page. However certain keys need to be displayed first like so:

baz (data)

bar (data)

foo (data)

baa (data)

I figured out I need to use the orderBy filter, however I can't seem to get that working. Does anyone know how I could achieve this?

JS:

angular.module("MyModule").controller("Test", function() {

    this.sort = ["baz", "bar"];

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

});

HTML:

        {{ title }} ({{ row }})

Body:
<div ng-repeat="item in T.data | orderBy: customFilter
{{ item.$key }} ({{ item.value }}

this.customFilter(obj){
switch(key){//key is actual value of cases like `baz`,`bar`
   case "baz":return 0;
   case "bar":return 1;
   case "foo":return 2;
   case "baa":return 3;
   default:return 99;
}
}


问:
How to stop Propagation on Double Click event
Consider this component:

```<code><Card onClick={openWindowHandler}>
  <Editable onDoubleClick={enableInputHandler} />
</Card>
</code>```

What I want to achieve is to stop event propagation, only when onDoubleClick event is dispatched, so the openWindowHandler function is not called. However, onClick will fire before onDoubleClick!

I can distinguish which event type was called by applying _.debounce function, but by that time, the event was already dispatched, so there is no way to call stopPropagation().

class App extends React.Component {
  delayedCallback = _.debounce(function (event) {
    if (event.type === 'dblclick') {
      // too late to call event.stopPropagation()
    } else {
      // continue
    }
  }, 250)

  handleClick = (event) => {
    event.persist()
    this.delayedCallback(event)
  }

  render () {
    return (
      <Card onClick={this.handleClick}>
        <Editable onDoubleClick={this.handleClick} />
      </Card>
    )
  }
}
```

Is there any way to do it?

EDIT:
The single click on <Editable /> element should be bubbled to parents causing openWindowHandler call.

答:
Example:</p>

```<code>// This will return a event
function clickHandlerModule() {
    var clickCount = 0;
    var timer = null;
    var delay = 250;
    return function(event) {
        clickCount++;
        if(clickCount === 1){
            timer = setTimeout(function(){
                console.log('SINGLE CLICK');
                clickCount = 0;
            }, delay);
        } else {
            clearTimeout(timer);
            console.log('DOUBLE CLICK');
            clickCount = 0;
        }
    }
}

class App extends React.Component {
  constructor() {
    super();
    this.clickHandler = clickHandlerModule()
  }
  render () {
    return (
      <Card onClick={this.clickHandler}>
        <Editable />
      </Card>
    )
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider this component:

<Card onClick={openWindowHandler}>
  <Editable onDoubleClick={enableInputHandler} />
</Card>

What I want to achieve is to stop event propagation, only when onDoubleClick event is dispatched, so the openWindowHandler function is not called. However, onClick will fire before onDoubleClick!

I can distinguish which event type was called by applying _.debounce function, but by that time, the event was already dispatched, so there is no way to call stopPropagation().

class App extends React.Component {
  delayedCallback = _.debounce(function (event) {
    if (event.type === 'dblclick') {
      // too late to call event.stopPropagation()
    } else {
      // continue
    }
  }, 250)

  handleClick = (event) => {
    event.persist()
    this.delayedCallback(event)
  }

  render () {
    return (
      <Card onClick={this.handleClick}>
        <Editable onDoubleClick={this.handleClick} />
      </Card>
    )
  }
}

Is there any way to do it?

EDIT:
The single click on <Editable /> element should be bubbled to parents causing openWindowHandler call.

Body:
Example:

// This will return a event
function clickHandlerModule() {
    var clickCount = 0;
    var timer = null;
    var delay = 250;
    return function(event) {
        clickCount++;
        if(clickCount === 1){
            timer = setTimeout(function(){
                console.log('SINGLE CLICK');
                clickCount = 0;
            }, delay);
        } else {
            clearTimeout(timer);
            console.log('DOUBLE CLICK');
            clickCount = 0;
        }
    }
}

class App extends React.Component {
  constructor() {
    super();
    this.clickHandler = clickHandlerModule()
  }
  render () {
    return (
      <Card onClick={this.clickHandler}>
        <Editable />
      </Card>
    )
  }
}


问:
RANDOM 0, 1, -1 IN VERILOG
I would like to generate random decimal number 0, 1 or -1 in verilog, that I can add it to my basic signal and get some noise on it with it.
I tried with

```<code>reg [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= {$random}%2;
</code>```

but it doesnt work the way I want.

Could someone give me advice what to do?

Thanks

答:
A simple solution in SystemVerilog is to use the randomize() method constraining the variable to the set of values you want. </p>

```<code>bit signed [1:0] SIGNAL_noise_ii;
...
randomize(SIGNAL_noise_ii) with {SIGNAL_noise_ii inside {-1,0,1};};
// alternatively specify a distribution
randomize(SIGNAL_noise_ii) with {SIGNAL_noise_ii dist  {-1:=25,0:=50,1:=25};};
</code>```

Title: RANDOM 0, 1, -1 IN VERILOG

Body:
I would like to generate random decimal number 0, 1 or -1 in verilog, that I can add it to my basic signal and get some noise on it with it.
I tried with

reg [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= {$random}%2;

but it doesnt work the way I want.

Could someone give me advice what to do?

Thanks

Body:
A simple solution in SystemVerilog is to use the randomize() method constraining the variable to the set of values you want.

bit signed [1:0] SIGNAL_noise_ii;
...
randomize(SIGNAL_noise_ii) with {SIGNAL_noise_ii inside {-1,0,1};};
// alternatively specify a distribution
randomize(SIGNAL_noise_ii) with {SIGNAL_noise_ii dist  {-1:=25,0:=50,1:=25};};