问:
pass userData from callback-begin to callback-end
How to appropriately cache userData that is generated from user's callbackBegin() and send it to user's callbackEnd().

Simple version  (No userData - demo)

I want to create a complex database that support callback.  For MCVE, let's say it is MyArray.

Here is a simple array class that supports callback but no userData.

```<code>#include <iostream>
template<class Derived>class MyArray{           //library - I design it.
    public: void push_back(int s){
        static_cast<Derived*>(this)->callbackBegin(s);
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s);
    }
    //other fields / functions
};
class Callback : public MyArray<Callback>{      //user's class
    public: void callbackBegin(int s){
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s){
        std::cout<<"callbackEnd"<<std::endl;
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd
    return 0;
}
</code>```

It works correctly.

The next step : I want to pass some userData from Callback::callbackBegin() to Callback::callbackEnd().

For example, userData is a clock time when Callback::callbackBegin() is called.

My poor solution (void*& userdata : demo)

Here is my attempt to implement it :-

```<code>#include <iostream>
#include <time.h>
template<class Derived>class MyArray{
    public: void push_back(int s){
        void* userData=nullptr;                                 //#
        static_cast<Derived*>(this)->callbackBegin(s,userData); //# ugly
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s,userData);   //# ugly
    }
};
class Callback : public MyArray<Callback>{
    public: void callbackBegin(int s,void*& userData){          //#
        userData=new clock_t(clock());                          //# danger
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s,void*& userData){            //#
        clock_t* userDataTyped=static_cast<clock_t*>(userData);
        clock_t clock2=clock();
        clock_t different=clock2 - (*userDataTyped);
        std::cout<<"callbackEnd time(second)="
                 <<((float)different)/CLOCKS_PER_SEC<<std::endl;
        delete userDataTyped;                                   //# danger
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd time(second)=8.5e-05
    return 0;
}
</code>```

It also works correctly, but I believe it is a bad design (at various #) :-

new/delete in 2 places : potential memory leaking.

Strong pointer is preferred, but I don't know how to.

static_cast<clock_t*>(userData) is code-smell, at least for me.

(minor issue) an extra ugly parameter void*&

Question: What are design patterns / C++ magic to avoid such issues, while make MyArray concise, easy to use, maintainable (i.e. not much worse than the Simple version)?

Other notes:

In real cases, <5% of user's callback classes need userData.

Thus, I feel very reluctant to add void&* as an extra parameter.

Clarify: (edited) The minority cases usually need different types of userData e.g. Callback1 need clock_t,  Callback2 need std::string, etc.

Proposed solution should restrain from using std::function<> or virtual function, because the performance is a major concern here.

Thank.

答:
You can use a smart pointer to avoid manually deleting your userData

```<code>std::unique_ptr<clock_t> userData;
</code>```

pass it as a reference to your callbacks

```<code>void callbackBegin(int s, std::unique_ptr<clock_t> &userData)
</code>```

and initialize it this way

```<code>userData = std::make_unique<clock_t>(clock())
</code>```

Body:
How to appropriately cache userData that is generated from user's callbackBegin() and send it to user's callbackEnd().

Simple version  (No userData - demo)

I want to create a complex database that support callback.  For MCVE, let's say it is MyArray.

Here is a simple array class that supports callback but no userData.

#include <iostream>
template<class Derived>class MyArray{           //library - I design it.
    public: void push_back(int s){
        static_cast<Derived*>(this)->callbackBegin(s);
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s);
    }
    //other fields / functions
};
class Callback : public MyArray<Callback>{      //user's class
    public: void callbackBegin(int s){
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s){
        std::cout<<"callbackEnd"<<std::endl;
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd
    return 0;
}

It works correctly.

The next step : I want to pass some userData from Callback::callbackBegin() to Callback::callbackEnd().

For example, userData is a clock time when Callback::callbackBegin() is called.

My poor solution (void*& userdata : demo)

Here is my attempt to implement it :-

#include <iostream>
#include <time.h>
template<class Derived>class MyArray{
    public: void push_back(int s){
        void* userData=nullptr;                                 //#
        static_cast<Derived*>(this)->callbackBegin(s,userData); //# ugly
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s,userData);   //# ugly
    }
};
class Callback : public MyArray<Callback>{
    public: void callbackBegin(int s,void*& userData){          //#
        userData=new clock_t(clock());                          //# danger
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s,void*& userData){            //#
        clock_t* userDataTyped=static_cast<clock_t*>(userData);
        clock_t clock2=clock();
        clock_t different=clock2 - (*userDataTyped);
        std::cout<<"callbackEnd time(second)="
                 <<((float)different)/CLOCKS_PER_SEC<<std::endl;
        delete userDataTyped;                                   //# danger
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd time(second)=8.5e-05
    return 0;
}

It also works correctly, but I believe it is a bad design (at various #) :-

new/delete in 2 places : potential memory leaking.

Strong pointer is preferred, but I don't know how to.

static_cast<clock_t*>(userData) is code-smell, at least for me.

(minor issue) an extra ugly parameter void*&

Question: What are design patterns / C++ magic to avoid such issues, while make MyArray concise, easy to use, maintainable (i.e. not much worse than the Simple version)?

Other notes:

In real cases, <5% of user's callback classes need userData.

Thus, I feel very reluctant to add void&* as an extra parameter.

Clarify: (edited) The minority cases usually need different types of userData e.g. Callback1 need clock_t,  Callback2 need std::string, etc.

Proposed solution should restrain from using std::function<> or virtual function, because the performance is a major concern here.

Thank.

Body:
You can use a smart pointer to avoid manually deleting your userData

std::unique_ptr<clock_t> userData;

pass it as a reference to your callbacks

void callbackBegin(int s, std::unique_ptr<clock_t> &userData)

and initialize it this way

userData = std::make_unique<clock_t>(clock())


来源: stackexchange

问:
Notifications for successful automated builds to each team member
We are just integrating Visual Studio Team Services as our new workflow and setting up automated builds on commits to master. Currently the individual who commits to master and instigates a new build will get a notification email when the build fails or succeeds.

We thought we would all get a notification but it does not appear that way. We have looked at notification settings in VSTS but have so far not found any setting that would allow all of us to be notified on build completion. Is there a setting we are missing or is this a feature that is not currently supported?

答:
Notifications

The VSTS Build Succeeded notification can be customized to report only on certain statuses using the Filter Criteria options, by creating the subscription for a team or group the notification will be sent to all members of the group:

If you need more advanced filters, consider routing your notification to an alternate email address and point that to IFTTT or Microsoft Flow. Or using the Build notification step in Microsoft Flow directly.

Visual Studio CD tools

The VSTS CD Tools integrate build notification directly into Visual Studio. This results in a toast notification whenever you have Visual Studio open:

Catlight

Another great tool to get build notifications is Catlight, it runs from the task tray and will even notify you when Visual studio isn't open:

Siren of Shame

And a 4th option is Siren of Shame, which also offers integration with a USB emergency light that will start blinking when the build fails:

ContentLicense: CC BY-SA 3.0


问:
How to enable scrolling in slides for a jupyter notebook?
How do I enable vertical scrolling once I've launched the slideshow in a jupyter notebook ?

If the slides are larger than the window, then they are cut and we cannot see what at the bottom.

I created the slides by simply clicking on the "basic" slides auto generated by jupyter.

Fyi my version is 4.2.3

Thanks

答:
After trying multiple solutions posted elsewhere, I found that jupyter2slides seems to solve this issue. It creates static html files that can be vertically scrolled.

Step 1: Clone the git repo using git clone https://github.com/datitran/jupyter2slides.git

Step 2: Copy your notebook (.ipynb) in jupyter2slides/static directory.

Step 3: Execute python create_slides.py --file static/your_notebook.ipynb from jupyter2slides directory.


问:
change array with objects into new array with objects
Hi I have this array with objects,

```<code>[
    {
         "QuestionID":1350,
         "Answers":[
                {
                     "AnswerId":"1350_1",
                     "selected":true
                },
                {
                     "AnswerId":"1350_2",
                     "selected":false
                },
                {
                     "AnswerId":"1350_3",
                     "selected":false
                }
         ]
    },
    {
         "QuestionID":1349,
         "Answers":[
                {
                     "AnswerId":"1349_1",
                     "selected":false
                },
                {
                     "AnswerId":"1349_2",
                     "selected":true
                },
                {
                     "AnswerId":"1349_3",
                     "selected":false
                }
         ]
    }
]
</code>```

but it should be changed to this, where answerID is the selected answers ID

```<code>[
    {
        "QuestionID": 1350,
        "AnswerId": "1350_1"
    },
    {
        “QuestionID”: 1349,
        “AnswerId”: "1349_2"
    }
]
</code>```

答:
Try this

```<code>arr.map( s => (s.AnswerId = s.Answers.find( p => p.selected ).AnswerId, delete s.Answers, s) )
</code>```

Explanation

Use map to iterate

Iterate answer for each question and find one with selected == true

Delete the answers key

Demo

var input = [{
    "QuestionID": 1350,
    "Answers": [{
        "AnswerId": "1350_1",
        "selected": true
      },
      {
        "AnswerId": "1350_2",
        "selected": false
      },
      {
        "AnswerId": "1350_3",
        "selected": false
      }
    ]
  },
  {
    "QuestionID": 1349,
    "Answers": [{
        "AnswerId": "1349_1",
        "selected": false
      },
      {
        "AnswerId": "1349_2",
        "selected": true
      },
      {
        "AnswerId": "1349_3",
        "selected": false
      }
    ]
  }
];

var output = input.map(s => (s.AnswerId = s.Answers.find(p => p.selected).AnswerId, delete s.Answers, s));

console.log(output);```

Body:
Hi I have this array with objects,

[
    {
         "QuestionID":1350,
         "Answers":[
                {
                     "AnswerId":"1350_1",
                     "selected":true
                },
                {
                     "AnswerId":"1350_2",
                     "selected":false
                },
                {
                     "AnswerId":"1350_3",
                     "selected":false
                }
         ]
    },
    {
         "QuestionID":1349,
         "Answers":[
                {
                     "AnswerId":"1349_1",
                     "selected":false
                },
                {
                     "AnswerId":"1349_2",
                     "selected":true
                },
                {
                     "AnswerId":"1349_3",
                     "selected":false
                }
         ]
    }
]

but it should be changed to this, where answerID is the selected answers ID

[
    {
        "QuestionID": 1350,
        "AnswerId": "1350_1"
    },
    {
        “QuestionID”: 1349,
        “AnswerId”: "1349_2"
    }
]

Body:
Try this

arr.map( s => (s.AnswerId = s.Answers.find( p => p.selected ).AnswerId, delete s.Answers, s) )

Explanation

Use map to iterate

Iterate answer for each question and find one with selected == true

Delete the answers key

Demo

var input = [{
    "QuestionID": 1350,
    "Answers": [{
        "AnswerId": "1350_1",
        "selected": true
      },
      {
        "AnswerId": "1350_2",
        "selected": false
      },
      {
        "AnswerId": "1350_3",
        "selected": false
      }
    ]
  },
  {
    "QuestionID": 1349,
    "Answers": [{
        "AnswerId": "1349_1",
        "selected": false
      },
      {
        "AnswerId": "1349_2",
        "selected": true
      },
      {
        "AnswerId": "1349_3",
        "selected": false
      }
    ]
  }
];

var output = input.map(s => (s.AnswerId = s.Answers.find(p => p.selected).AnswerId, delete s.Answers, s));

console.log(output);


问:
OpenAPI reuse part of definition without defining a new one
Suppose that I have this definition in a yaml OpenApi definition

```<code>definitions:
  User:
    description: "User"
    type: "object"
    properties:
      firstname:
        type: "string"
      lastname:
        type: "string"
      password:
        type: "string"
      email:
        type: "string"
      username:
        type: "string"
</code>```

If in a parameters specification I need specific fields of a definition how can I refer them without defining another model as below?

```<code>definitions:
  UserLogin:
    description: "User"
    type: "object"
    properties:
      password:
        type: "string"
      email:
        type: "string"
</code>```

答:
In your question, you are using definitions keyword what hints that your question is about OpenAPI v2 aka. Swagger. For OpenAPI v3, definitions provided below should be defined inside appropriate Components Object sections.

In order to achieve this, you have to use Composition with keyword allOf. There is a great example that relates to your question here. First, you have to define a smaller object and then include it into the definition of a larger as follows:

```<code>definitions:
  UserLogin:
    description: User Login
    type: object
    properties:
      password:
        type: string
      email:
        type: string
  User:
    allOf:
    - $ref: '#/definitions/UserLogin'
    - description: User
      type: object
      properties:
        firstname:
          type: string
        lastname:
          type: string
        username:
          type: string
</code>```

It is worth noting that:

Some lighter implementations may not support allOf keyword.

Using composition may increase or decrease the readability of the documentation, depending on the complexity and choice of words used to name the schemas.

Body:
Suppose that I have this definition in a yaml OpenApi definition

definitions:
  User:
    description: "User"
    type: "object"
    properties:
      firstname:
        type: "string"
      lastname:
        type: "string"
      password:
        type: "string"
      email:
        type: "string"
      username:
        type: "string"

If in a parameters specification I need specific fields of a definition how can I refer them without defining another model as below?

definitions:
  UserLogin:
    description: "User"
    type: "object"
    properties:
      password:
        type: "string"
      email:
        type: "string"

Body:
In your question, you are using definitions keyword what hints that your question is about OpenAPI v2 aka. Swagger. For OpenAPI v3, definitions provided below should be defined inside appropriate Components Object sections.

In order to achieve this, you have to use Composition with keyword allOf. There is a great example that relates to your question here. First, you have to define a smaller object and then include it into the definition of a larger as follows:

definitions:
  UserLogin:
    description: User Login
    type: object
    properties:
      password:
        type: string
      email:
        type: string
  User:
    allOf:
    - $ref: '#/definitions/UserLogin'
    - description: User
      type: object
      properties:
        firstname:
          type: string
        lastname:
          type: string
        username:
          type: string

It is worth noting that:

Some lighter implementations may not support allOf keyword.

Using composition may increase or decrease the readability of the documentation, depending on the complexity and choice of words used to name the schemas.


问:
jekyll serve only updates sass when I save the main file
I have a jekyll project that looks like this:

```<code>- assets
-- css
--- main.scss
-- sass
--- base
---- _root.scss
--- vendor
---- normalize.scss
</code>```

main.scss includes the files

```<code>---
---
@charset "utf-8";

@import 'vendor/normalize';

@import 'base/root';
</code>```

Here are the config.yml-settings that might be relevant

```<code># Sass settings
sass:
  add_charset: true
  sass_dir: assets/sass
  style: :compressed

# Build settings
exclude:
  - Gemfile
  - Gemfile.lock
  - package.json
  - README.md
  - CNAME
  - node_modules
  - assets/sass
</code>```

The sass works and gets generated into the right folders, but it seems like  sass only listens to updates of main.scss when I run jekyll serve I have tried putting all files in /assets/sass/ and also putting all files in assets/css/, but none of these things work either.

答: I moved the files from /assets/css/ to /_css and removed the setting sass_dir: from config.yml, this worked, not sure why, but it seems that jekyll only listens to sass changes in that folder. Hopefully this is heplpful for someone!

Body:
I have a jekyll project that looks like this:

- assets
-- css
--- main.scss
-- sass
--- base
---- _root.scss
--- vendor
---- normalize.scss

main.scss includes the files

---
---
@charset "utf-8";

@import 'vendor/normalize';

@import 'base/root';

Here are the config.yml-settings that might be relevant

# Sass settings
sass:
  add_charset: true
  sass_dir: assets/sass
  style: :compressed

# Build settings
exclude:
  - Gemfile
  - Gemfile.lock
  - package.json
  - README.md
  - CNAME
  - node_modules
  - assets/sass

The sass works and gets generated into the right folders, but it seems like  sass only listens to updates of main.scss when I run jekyll serve I have tried putting all files in /assets/sass/ and also putting all files in assets/css/, but none of these things work either.


问:
Highcharts 'bindAxis' for one chart only
I'm trying to integrate a MariMekko / Market type of chart in my application. I found an interesting implementation here:

http://jsfiddle.net/h2np93k1/39/

This code constructs a treemap and adds axis to it. That is done by this snippet:

```<code>Highcharts.seriesTypes.treemap.prototype.bindAxes = function() {
    Highcharts.Series.prototype.bindAxes.call(this);
};
</code>```

However, if I understand correctly, this will cause all my treemap charts to have axis. I don't want this, I'd like to keep the axis only for my marimekko maps.

What whould be the best way to accomplish this?  Is there an easy way to extend a charttype for example?

答:
The easy way to do it is to wrap a core function and add conditional statement that checks options and applies the modification when needed.

In this case I added isMariMekko flag in the series. If it's true the modified code executes. It's false the original function launches:

```<code>  Highcharts.wrap(Highcharts.seriesTypes.treemap.prototype, 'bindAxes', function(proceed) {
    if (this.options.isMariMekko) {
      var treeAxis = {
        min: 0,
        dataMin: 0,
        max: 100,
        dataMax: 0
      };

      Highcharts.Series.prototype.bindAxes.call(this);
      Highcharts.extend(this.yAxis.options, treeAxis);
      Highcharts.extend(this.xAxis.options, treeAxis);

    } else {
      proceed.apply(this); // default action
    }

  });
</code>```

Docs reference about wrapping: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts

Body:
I'm trying to integrate a MariMekko / Market type of chart in my application. I found an interesting implementation here:

http://jsfiddle.net/h2np93k1/39/

This code constructs a treemap and adds axis to it. That is done by this snippet:

Highcharts.seriesTypes.treemap.prototype.bindAxes = function() {
    Highcharts.Series.prototype.bindAxes.call(this);
};

However, if I understand correctly, this will cause all my treemap charts to have axis. I don't want this, I'd like to keep the axis only for my marimekko maps.

What whould be the best way to accomplish this?  Is there an easy way to extend a charttype for example?

Body:
The easy way to do it is to wrap a core function and add conditional statement that checks options and applies the modification when needed.

In this case I added isMariMekko flag in the series. If it's true the modified code executes. It's false the original function launches:

  Highcharts.wrap(Highcharts.seriesTypes.treemap.prototype, 'bindAxes', function(proceed) {
    if (this.options.isMariMekko) {
      var treeAxis = {
        min: 0,
        dataMin: 0,
        max: 100,
        dataMax: 0
      };

      Highcharts.Series.prototype.bindAxes.call(this);
      Highcharts.extend(this.yAxis.options, treeAxis);
      Highcharts.extend(this.xAxis.options, treeAxis);

    } else {
      proceed.apply(this); // default action
    }

  });

Docs reference about wrapping: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts


问:
How to check if a dictionary is empty?
I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything aside from the display the message. Any ideas why ?

```<code>def isEmpty(self, dictionary):
    for element in dictionary:
        if element:
            return True
        return False

def onMessage(self, socket, message):
    if self.isEmpty(self.users) == False:
        socket.send("Nobody is online, please use REGISTER command" \
                 " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))
</code>```

答:
You can also use get(). Initially I believed it to only check if key existed.

```<code>>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
</code>```

What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.

ContentLicense: CC BY-SA 4.0

Title: How to check if a dictionary is empty?

Body:
I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything aside from the display the message. Any ideas why ?

def isEmpty(self, dictionary):
    for element in dictionary:
        if element:
            return True
        return False

def onMessage(self, socket, message):
    if self.isEmpty(self.users) == False:
        socket.send("Nobody is online, please use REGISTER command" \
                 " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))

Body:
You can also use get(). Initially I believed it to only check if key existed.

>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True

What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.


问:
Converting String to bit before inserting into the database
Can anyone help in converting string value in C# to bit equivalent in Sql.  I'm trying to bulkcopy the values of a datatable into Sql table.  All the values I've in the datatable are in string format.  When I try to bulkcopy to SQL table I'm getting an error for bit datatype columns.Can anyone please post the C# code to convert string to bit type before I bulkcopy to SQL table.

Thanks,
Vix

答:
```<code>int a = Convert.ToInt32( row.ItemArray[5]);
bool b;
b = Convert.ToBoolean(a);
switch (a)
{
    case 1:
        b = true;
        break;
    case 0:
        b = false;
        break;
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
Remove duplicate rows in mysqldb in a specific way
I want to delete the duplicate rows in my mysqldb table, where 4 columns value is the same. How can i do it if I have got an auto_increment column too?

```<code>ALTER IGNORE TABLE test
ADD UNIQUE INDEX idx_name (col1, col2, col3, col4);
</code>```

How can i implement this part of code to do this in Python?

```<code>connection = MySQLdb.connect(host='localhost',
            user='admin',
            passwd='',
            db='database1',
            use_unicode=True,
            charset="utf8")
 cursor = connection.cursor()
</code>```

答:
assuming your auto increment column is named  id
You could use a not in clause

```<code>  delete from  my_table
  where id not IN (
   select max(id)
   from  my_table
   group by col1, col2, col3, col4
   )
</code>```

id this way you delete all the row that have more then on istance for the same col1, col2, col3, col4 and you let in db the row with max(id) for each of this

Body:
I want to delete the duplicate rows in my mysqldb table, where 4 columns value is the same. How can i do it if I have got an auto_increment column too?

ALTER IGNORE TABLE test
ADD UNIQUE INDEX idx_name (col1, col2, col3, col4);

How can i implement this part of code to do this in Python?

connection = MySQLdb.connect(host='localhost',
            user='admin',
            passwd='',
            db='database1',
            use_unicode=True,
            charset="utf8")
 cursor = connection.cursor()

Body:
assuming your auto increment column is named  id
You could use a not in clause

  delete from  my_table
  where id not IN (
   select max(id)
   from  my_table
   group by col1, col2, col3, col4
   )

id this way you delete all the row that have more then on istance for the same col1, col2, col3, col4 and you let in db the row with max(id) for each of this


问:
Factory Model in C#
I have a bunch of MDI child nodes that are all created in the same way and to reduce redundant code I'd like to be able to call a method, pass it a string (name of child node), have it create the node and add it to the parent.

I can do all the stuff except create the class from a string of a class name, how can I do this?

答:
I'm currently using this in one of my applications to new up a class

```<code>public static IMobileAdapter CreateAdapter(Type AdapterType)
{
  return (IMobileAdapter)System.Activator.CreateInstance(AdapterType);
}
</code>```

It's returning an instance of a class that implements IMobileAdapter, but you could use it equally easily with a string:

```<code>public static IMyClassInterface CreateClass(string MyClassType)
{
  return (IMyClassInterface)System.Activator.CreateInstance(Type.GetType(MyClassType));
}
</code>```

Call it using code similar to the following:

```<code>IMyClassInterface myInst = CreateClass("MyNamespace.MyClass, MyAssembly");
</code>```

Of course, the class it creates must implement the interface IMyClassInterface in this case, but with a class factory, you'd likely have all your classes implementing the same interface anyway.

Edit:

In reference to your comment, for the purpose of this discussion, think of the term "assembly" as the set of files within your vb/cs project. I'm assuming that you're doing this all within a single project [assembly] and not spreading over multiple projects.

In your case as your classes will be extending the Form object, you would do something like this.

```<code>Form myInst = CreateClass("MyExtendedForm");
</code>```

Or

```<code>Form myInst = CreateClass(Type.GetType("MyExtendedForm"));
</code>```

Depending on whether you get the type within your CreateClass method or outside it.  You would need to cast your instance to the correct type in order to access any custom members.  Consider this:

```<code>class MyCustomForm : Form
{
    public int myCustomField{ get; set; }
}
</code>```

I've got a custom form that extends Form adding the myCustomField property.  I want to instantiate this using Activator.CreateInstance():

```<code>public static Form CreateClass(string InstanceName)
{
    return (Form)System.Activator.CreateInstance(Type.GetType(InstanceName));
}
</code>```

I then call it using:

```<code>Form myInst = CreateClass("MyCustomForm");
</code>```

So now I have my custom form stored in myInst.  However, to access the custom property [myCustomField], you would need to cast your instance to the correct form:

```<code>int someVal = ((Type.GetType("MyCustomForm"))myInst).myCustomField;
</code>```

OwnerDisplayName: Malfist

Title: Factory Model in C#

LastEditorDisplayName: chris

Body:
I'm currently using this in one of my applications to new up a class

public static IMobileAdapter CreateAdapter(Type AdapterType)
{
  return (IMobileAdapter)System.Activator.CreateInstance(AdapterType);
}

It's returning an instance of a class that implements IMobileAdapter, but you could use it equally easily with a string:

public static IMyClassInterface CreateClass(string MyClassType)
{
  return (IMyClassInterface)System.Activator.CreateInstance(Type.GetType(MyClassType));
}

Call it using code similar to the following:

IMyClassInterface myInst = CreateClass("MyNamespace.MyClass, MyAssembly");

Of course, the class it creates must implement the interface IMyClassInterface in this case, but with a class factory, you'd likely have all your classes implementing the same interface anyway.

Edit:

In reference to your comment, for the purpose of this discussion, think of the term "assembly" as the set of files within your vb/cs project. I'm assuming that you're doing this all within a single project [assembly] and not spreading over multiple projects.

In your case as your classes will be extending the Form object, you would do something like this.

Form myInst = CreateClass("MyExtendedForm");

Or

Form myInst = CreateClass(Type.GetType("MyExtendedForm"));

Depending on whether you get the type within your CreateClass method or outside it.  You would need to cast your instance to the correct type in order to access any custom members.  Consider this:

class MyCustomForm : Form
{
    public int myCustomField{ get; set; }
}

I've got a custom form that extends Form adding the myCustomField property.  I want to instantiate this using Activator.CreateInstance():

public static Form CreateClass(string InstanceName)
{
    return (Form)System.Activator.CreateInstance(Type.GetType(InstanceName));
}

I then call it using:

Form myInst = CreateClass("MyCustomForm");

So now I have my custom form stored in myInst.  However, to access the custom property [myCustomField], you would need to cast your instance to the correct form:

int someVal = ((Type.GetType("MyCustomForm"))myInst).myCustomField;

OwnerDisplayName: balabaster

LastEditorDisplayName: balabaster


问:
Generic class with array
I want to create a custom generic class for my Java project and this is how far I got - I found the code as an example on how to create generic arrays.

```<code>public class RegisterSet<T> {
   private T[] register;
   public <T> RegisterSet(int size) {
      register = (T[])Array.newInstance(T, size);
   }
}
</code>```

Now, I get the error Incompatible types - found: T[], required: T[] which makes absolutely no sense to me - how can I fix this?

答:
It makes perfect sense, because you've got two different type parameters called T. However, fixing it is rather hard as I can't see how you expect your code to compile at all. Consider this bit:

```<code>Array.newInstance(T, size);
</code>```

T is the name of a type parameter... you can't use it as an argument to a method.

Note that due to type erasure, if you want to be able to create an array of the right type, you'll need to specify the relevant Class instance. For example:

```<code>public class RegisterSet<T> {
   private T[] register;
   public RegisterSet(Class<T> clazz, int size) {
      register = (T[])Array.newInstance(clazz, size);
   }
}
</code>```

... but I'm not sure which Array class you're trying to use here.

Title: Generic class with array

Body:
I want to create a custom generic class for my Java project and this is how far I got - I found the code as an example on how to create generic arrays.

public class RegisterSet<T> {
   private T[] register;
   public <T> RegisterSet(int size) {
      register = (T[])Array.newInstance(T, size);
   }
}

Now, I get the error Incompatible types - found: T[], required: T[] which makes absolutely no sense to me - how can I fix this?

Body:
It makes perfect sense, because you've got two different type parameters called T. However, fixing it is rather hard as I can't see how you expect your code to compile at all. Consider this bit:

Array.newInstance(T, size);

T is the name of a type parameter... you can't use it as an argument to a method.

Note that due to type erasure, if you want to be able to create an array of the right type, you'll need to specify the relevant Class instance. For example:

public class RegisterSet<T> {
   private T[] register;
   public RegisterSet(Class<T> clazz, int size) {
      register = (T[])Array.newInstance(clazz, size);
   }
}

... but I'm not sure which Array class you're trying to use here.


问:
Is there an event for when the title attribute shows the tooltip?
So, let's say I have this span with a title attribute:

Span```
</div>
</div>
</p>

<p>This shows the tooltip just fine, but I'd like to attach some kind of event listener for when the title shows with either JavaScript or JQuery. e.g. something like (obviously <code>"title"</code> isn't a valid event):</p>

```document.getElementById("mySpan").addEventListener("title", function () {
    console.log("Tooltip shown");
});
```

<hr>

<p>I know that I could create my own tooltip with JavaScript and a <code>mouseover</code> event like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById("mySpan").addEventListener("mouseover", function (event) {
    console.log("Tooltip shown");
    document.getElementById("myTooltip").style.display = 'block';
    document.getElementById("myTooltip").style.top = (event.clientY + 5) + 'px';
    document.getElementById("myTooltip").style.left = (event.clientX + 5) + 'px';
});

document.getElementById("mySpan").addEventListener("mouseout", function () {
    document.getElementById("myTooltip").style.display = 'none';
});</code>```

#myTooltip {
    position: absolute;
    background-color: lightgray;
    padding: 2px 4px;
    font-size: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="mySpan">Span</span>
<span id="myTooltip" style="display: none;">Tooltip</span></code>```

But this means I have to recreate the style of the title attribute from scratch, which changes from browser to browser, and from OS to OS, and I'd really rather not change the standard tooltip that the user is used to seeing.

So, in summary, is it possible to attach some sort of event listener for when the title attribute displays?

答:
Disclaimer: this isn't actually an event listener.

It's not the greatest of solutions, but it works. All it does is start a setTimeout for 0.5s (that was based on trial and error, couldn't find it in any docs) on mouseover, and cancel it when you mouseout. It works for me, but it might not work if the delay changes based on the browser / OS.

var titleShowTimeout;
document.getElementById("mySpan").addEventListener("mouseover", function (event) {
    titleShowTimeout = setTimeout(function () {
        console.log("Tooltip shown");
    }, 500);
});

document.getElementById("mySpan").addEventListener("mouseout", function () {
    clearTimeout(titleShowTimeout);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span title="Tooltip" id="mySpan">Span</span></code>```

Body:
So, let's say I have this span with a title attribute:

Span

This shows the tooltip just fine, but I'd like to attach some kind of event listener for when the title shows with either JavaScript or JQuery. e.g. something like (obviously "title" isn't a valid event):

document.getElementById("mySpan").addEventListener("title", function () {
    console.log("Tooltip shown");
});

I know that I could create my own tooltip with JavaScript and a mouseover event like this:

document.getElementById("mySpan").addEventListener("mouseover", function (event) {
    console.log("Tooltip shown");
    document.getElementById("myTooltip").style.display = 'block';
    document.getElementById("myTooltip").style.top = (event.clientY + 5) + 'px';
    document.getElementById("myTooltip").style.left = (event.clientX + 5) + 'px';
});

document.getElementById("mySpan").addEventListener("mouseout", function () {
    document.getElementById("myTooltip").style.display = 'none';
});

#myTooltip {
    position: absolute;
    background-color: lightgray;
    padding: 2px 4px;
    font-size: 10px;
}

Span
Tooltip

But this means I have to recreate the style of the title attribute from scratch, which changes from browser to browser, and from OS to OS, and I'd really rather not change the standard tooltip that the user is used to seeing.

So, in summary, is it possible to attach some sort of event listener for when the title attribute displays?

Body:
Disclaimer: this isn't actually an event listener.

It's not the greatest of solutions, but it works. All it does is start a setTimeout for 0.5s (that was based on trial and error, couldn't find it in any docs) on mouseover, and cancel it when you mouseout. It works for me, but it might not work if the delay changes based on the browser / OS.

var titleShowTimeout;
document.getElementById("mySpan").addEventListener("mouseover", function (event) {
    titleShowTimeout = setTimeout(function () {
        console.log("Tooltip shown");
    }, 500);
});

document.getElementById("mySpan").addEventListener("mouseout", function () {
    clearTimeout(titleShowTimeout);
});

<span title="Tooltip" id="mySpan">Span</span>


问:
R - Pivot like data
Using R and tidyverse library I am trying to achieve pivot like result. Here it sample data set:

```<code>zz <- "   Date          ParAB ParCD
1         2017-05-27    A     C
2         2017-05-27    B     D
3         2017-05-27    A     D
4         2017-05-27    B     C
5         2017-05-27    B     C
6         2017-05-28    A     D
7         2017-05-28    A     C
8         2017-05-28    A     C
9         2017-05-28    A     D"

Data <- read.table(text=zz, header = TRUE)}
</code>```

I would like transform the data to look like this with number of occurrences per day:

```<code>Date           A        B        C       D
2017-05-27     2        3        3       2
2017-05-28     2        0        1       1
</code>```

I tired spread function that works great on ParAB column.

```<code>Data %>%
  group_by(Date, ParAB, ParCD) %>%
  summarise(occr = n()) %>%
  spread(ParAB, occr, fill = 0) %>%
  mutate(occrCD = A+B)
</code>```

so the result is:

```<code># A tibble: 4 x 5
# Groups:   Date [2]
    Date        ParCD     A     B   occrCD
  <fctr>        <fctr> <dbl> <dbl>  <dbl>
1 2017-05-27      C     1     2      3
2 2017-05-27      D     1     1      2
3 2017-05-28      C     2     0      2
4 2017-05-28      D     2     0      2
</code>```

and then when I try spread second time it does not work as intended. The data for column A (and B) is not added for particular day for C and D rows. As result I get wrong data.

Code with both steps:

```<code>Data %>%
  group_by(Date, ParAB, ParCD) %>%
  summarise(occr = n()) %>%
  spread(ParAB, occr, fill = 0) %>% # first spread - result as expected
  mutate(occrCD = A+B) %>%
  spread(ParCD, occrCD, fill = 0) %>% # second spread, lost sum for A and B
  group_by(Date) %>%
  summarise_all(sum)
</code>```

and the result that is not what I wanted. The error is visible as A+B should be equal for C +D but for 2017-05-28 it is not. :(

```<code># A tibble: 2 x 5
        Date     A     B     C     D
      <fctr> <dbl> <dbl> <dbl> <dbl>
1 2017-05-27     2     3     3     2
2 2017-05-28     2     0     2     2
</code>```

I am sure is pretty trivial, but as I am quite new your help highly appreciated.

M

答:
No reason to spread twice if you put all your parameters in one column.

```<code>library(dplyr)
library(tidyr)

zz <- "   Date          ParAB ParCD
1         2017-05-27    A     C
2         2017-05-27    B     D
3         2017-05-27    A     D
4         2017-05-27    B     C
5         2017-05-27    B     C
6         2017-05-28    A     D
7         2017-05-28    A     C
8         2017-05-28    A     C
9         2017-05-28    A     D"

Data <- read.table(text=zz, header = TRUE, stringsAsFactors = F)

Data %>%
  gather(v1,value,-Date) %>%
  count(Date, value) %>%
  spread(value, n, fill = 0)

# # A tibble: 2 x 5
#         Date     A     B     C     D
# *      <chr> <dbl> <dbl> <dbl> <dbl>
# 1 2017-05-27     2     3     3     2
# 2 2017-05-28     4     0     2     2
</code>```

Title: R - Pivot like data

Body:
Using R and tidyverse library I am trying to achieve pivot like result. Here it sample data set:

zz <- "   Date          ParAB ParCD
1         2017-05-27    A     C
2         2017-05-27    B     D
3         2017-05-27    A     D
4         2017-05-27    B     C
5         2017-05-27    B     C
6         2017-05-28    A     D
7         2017-05-28    A     C
8         2017-05-28    A     C
9         2017-05-28    A     D"

Data <- read.table(text=zz, header = TRUE)}

I would like transform the data to look like this with number of occurrences per day:

Date           A        B        C       D
2017-05-27     2        3        3       2
2017-05-28     2        0        1       1

I tired spread function that works great on ParAB column.

Data %>%
  group_by(Date, ParAB, ParCD) %>%
  summarise(occr = n()) %>%
  spread(ParAB, occr, fill = 0) %>%
  mutate(occrCD = A+B)

so the result is:

# A tibble: 4 x 5
# Groups:   Date [2]
    Date        ParCD     A     B   occrCD
  <fctr>        <fctr> <dbl> <dbl>  <dbl>
1 2017-05-27      C     1     2      3
2 2017-05-27      D     1     1      2
3 2017-05-28      C     2     0      2
4 2017-05-28      D     2     0      2

and then when I try spread second time it does not work as intended. The data for column A (and B) is not added for particular day for C and D rows. As result I get wrong data.

Code with both steps:

Data %>%
  group_by(Date, ParAB, ParCD) %>%
  summarise(occr = n()) %>%
  spread(ParAB, occr, fill = 0) %>% # first spread - result as expected
  mutate(occrCD = A+B) %>%
  spread(ParCD, occrCD, fill = 0) %>% # second spread, lost sum for A and B
  group_by(Date) %>%
  summarise_all(sum)

and the result that is not what I wanted. The error is visible as A+B should be equal for C +D but for 2017-05-28 it is not. :(

# A tibble: 2 x 5
        Date     A     B     C     D
      <fctr> <dbl> <dbl> <dbl> <dbl>
1 2017-05-27     2     3     3     2
2 2017-05-28     2     0     2     2

I am sure is pretty trivial, but as I am quite new your help highly appreciated.

M

Body:
No reason to spread twice if you put all your parameters in one column.

library(dplyr)
library(tidyr)

zz <- "   Date          ParAB ParCD
1         2017-05-27    A     C
2         2017-05-27    B     D
3         2017-05-27    A     D
4         2017-05-27    B     C
5         2017-05-27    B     C
6         2017-05-28    A     D
7         2017-05-28    A     C
8         2017-05-28    A     C
9         2017-05-28    A     D"

Data <- read.table(text=zz, header = TRUE, stringsAsFactors = F)

Data %>%
  gather(v1,value,-Date) %>%
  count(Date, value) %>%
  spread(value, n, fill = 0)

# # A tibble: 2 x 5
#         Date     A     B     C     D
# *      <chr> <dbl> <dbl> <dbl> <dbl>
# 1 2017-05-27     2     3     3     2
# 2 2017-05-28     4     0     2     2


问:
Data properties dependency in Protege
Could someone please provide examples of what kind (if any) dependecies between Data Properties we can declare in Protege?
Basically what I am trying to do is to declare simple rules, that e.g one Data Property (year) can or can not be before the other one ( like Birth Year <= Death Year). Is that possible to be done using Data Properties?</p>

答:
The only dependencies that can be expressed between DataProperties are subproperty and disjointness properties. SWRLTab in Protege can be used to express rules. Assuming the following ontology:

```<code>ObjectProperty: hasDeathCertificate
  Domain: Person
  Range: DeathCertificate
DataProperty: dateOfBirth
  Domain: Person
Range: xsd:dateTime
DataProperty: dateOfDeath
  Domain: DeathCertificate
  Range: xsd:dateTime
Class: DeathCertificate
Class: Person
</code>```

the following SWRL rule can be specified to ensure that the date of death on a DeathCertificate is after the date birth of the person.

```<code>Person(?p)^dateOfBirth(?p, ?birth)^DeathCertificate(?d)^dateOfDeath(?p, ?death)
^swrlb:greaterThan(?death, ?birth)->hasDeathCertificate(?p, ?d)
</code>```

Good luck!

Title: Data properties dependency in Protege

Body:
The only dependencies that can be expressed between DataProperties are subproperty and disjointness properties. SWRLTab in Protege can be used to express rules. Assuming the following ontology:

ObjectProperty: hasDeathCertificate
  Domain: Person
  Range: DeathCertificate
DataProperty: dateOfBirth
  Domain: Person
Range: xsd:dateTime
DataProperty: dateOfDeath
  Domain: DeathCertificate
  Range: xsd:dateTime
Class: DeathCertificate
Class: Person

the following SWRL rule can be specified to ensure that the date of death on a DeathCertificate is after the date birth of the person.

Person(?p)^dateOfBirth(?p, ?birth)^DeathCertificate(?d)^dateOfDeath(?p, ?death)
^swrlb:greaterThan(?death, ?birth)->hasDeathCertificate(?p, ?d)

Good luck!


问:
Why doesn't the access modifier matter in unity3D
Unity has a set of methods that you can use to implement behavior like Start, Awake, Update this methods have no access modifier which means that they are private in C# classes.

From what I know there's no way in C# to call a private method of another class without using reflection.

```<code>public class TestClass : MonoBehaviour {
    private void Start () {
       // How is unity able to call this method if it's private and I'm not calling it anywhere
    }

    void Update () {
    }
}
</code>```

So my question is how is unity able to call them if they are private? And why aren't they just protected virtual so you can use override ?

答:
Unity itself is written in C++ and uses C# only for user-created scripts. Somewhere in documentation there is mentioned that all this "magic" methods (like Start(), Update() etc are called from C++ side by registering scripts which have this "magic" methods. For this methods it doesn't matter which access modified you use public or protected they will be called anyway.

As for why those methods are not protected virtual I can say that less of this methods you have - the better performance you get. If script doesn't have an Update() method, Unity doesn't have to register this script inside it's scripting system and doesn't have to call it each frame.

MonoBehaviour-derived script have huge overhead in compare of regular C# classes. This is because Unity have to manage all resources (graphics, gameObjects, physics, etc) itself except C# memory (it uses mono garbage collection for this purpose). So it's a good practice to use as less MonoBahaviour-derived classes as possible prefering regular C# classes.

Update: here is a good explanation from comments.

Body:
Unity has a set of methods that you can use to implement behavior like Start, Awake, Update this methods have no access modifier which means that they are private in C# classes.

From what I know there's no way in C# to call a private method of another class without using reflection.

public class TestClass : MonoBehaviour {
    private void Start () {
       // How is unity able to call this method if it's private and I'm not calling it anywhere
    }

    void Update () {
    }
}

So my question is how is unity able to call them if they are private? And why aren't they just protected virtual so you can use override ?


问:
Unfortunately app has stopped after transferring app
I have received  *.apk file developed in Android Studio by a friend of mine. This app works fine on his Emulator and on his phone, but not on mine (Samsung Galaxy S4). I get "Unfortunately app has stopped" on my phone.

I can't put any code here because it is a huge application and there is no error reported in Android Studio. I was thinking that it might be a problem with the version that was set in the "New Project" page, but there it was shown that the selected version works for 100% of the phones.

I have also checked these methods, but with no success.

So the only thing that comes to mind right now is that it is something to do with development options and permissions in the Android OS, but I don't know which option should I play with.

Now the question is... is there anyone who can help me with this crash? I know it is a very loose question, but I hope that there are people who dealt with this here.

答:
I had the same problem when I sent my friend apk file directly from my device through shareit after I run it. The app will just close because the APK is generated and installed on debug mode, so it will only run on device that is connected to android studio.
Ask your friend to send  .apk file that is generated from Build> Build APK. There should be no problem, If that did not work ask him to send from "Generate Signed APK" option. </p>


问:
Why max size of SurfaceView(Android) for play video is 1024x1024?
I use SurfaceView for play video. I use Samsung Galaxy Tab to test. I set size:

```<code>LinearLayout.LayoutParams videoViewParams = new   LinearLayout.LayoutParams(m_mainView.getPictureWidth(), m_mainView.getPictureHeight());
mPreview = (SurfaceView) videoView.findViewById(R.id.surface);
mPreview.setLayoutParams(videoViewParams);
</code>```

When mainView.getPictureWidth() or mainView.getPictureHeight() is higer then 1024 - i get message in logcat:

01-12 11:49:15.839: ERROR/SurfaceFlinger(2491): LayerBuffer init temp buff failed with w=1210, h=922, exp max=1024x1024 on 0

and i see only black screen.

Why?
In my application I use video scaling, and sometimes I need to get a video of a size greater than 1024.

答:
I still have 2 ideas:

1)Make a zoom limit for all devices (Set the maximum size of video as a maximum size of one side of the screen). But in this case sometimes zoom in general will not or he will be very small.

2)Catch this log about error and show the user a dialogue that in such a zoom video to play will not work. But how to catch this log?

What do you think about this?

Body:
I use SurfaceView for play video. I use Samsung Galaxy Tab to test. I set size:

LinearLayout.LayoutParams videoViewParams = new   LinearLayout.LayoutParams(m_mainView.getPictureWidth(), m_mainView.getPictureHeight());
mPreview = (SurfaceView) videoView.findViewById(R.id.surface);
mPreview.setLayoutParams(videoViewParams);

When mainView.getPictureWidth() or mainView.getPictureHeight() is higer then 1024 - i get message in logcat:

01-12 11:49:15.839: ERROR/SurfaceFlinger(2491): LayerBuffer init temp buff failed with w=1210, h=922, exp max=1024x1024 on 0

and i see only black screen.

Why?
In my application I use video scaling, and sometimes I need to get a video of a size greater than 1024.


问:
How to fully remove svn.iml file that generate PhpStorm from .idea folder
In my projects I'm using BitBucket base on Git control version. My IDE is PhpStorm 2017.

My problem is when I remove myprojectsvn.iml file from .idea folder after some time I can see that file again.

Why is file always create If I've never used svn? For that file when I switch branch I got error like this:

Can not loading myprojectsvn.iml module

答:
You should remove it from the remote repository firstly. Then, you should add a .gitignore file to your project and add .idea and .iml files into it. By this way, you are saying git not to push that files into your remote repository. You can also add some other folders into .gitignore file out etc. Check the following link it will help you I guess.

help.github.com/articles/ignoring-files


问:
Create a table in postgreSQL using Node-red
I wanted to create a table and insert data from a CSV file in Node-red postgreSQL. Is there any possibility to do it like PG Create?
script I used script to create message shown in the debug as Debug message

Thanks in Advance

Update: Using msg.payload instead of msg.topic it worked which solved my problem

答:
Using msg.payload instead of msg.topic it worked which solved my problem

removing template node and connecting function directly to postgres node

In the function node I wrote
msg.payload = "CREATE TABLE ...";


问:
Strange unit version error - Is DUnitX depending on DUnit or the other way around?
I was using Delphi xe4 to compile https://github.com/hprose/hprose-delphi/blob/master/Test/HproseTest.dpr

And got the following error which I spent tens of minutes and still couldn't figure out why.

I've tried deleting all 'DUnitX*.dcu" and compile again, with no luck.

What puzzled me is that, why the unit TextTestRunner from DUnit (born first) relies on a unit from DUnitX which was born later?

Any hint? Thanks.

```<code>[dcc32 Fatal Error] HproseTest.dpr(37): F2051 Unit TextTestRunner was compiled with a different version of DUnitX.TestFramework.ITestListener
</code>```

And here is the screenshot I made for making the problem description clear:

答: I downloaded the repository and it was compiling on the first try but i only have Delph XE8. But i found out that there is a unit called TestFramework.pas in DUnit and DUnitX. While TextTestRunner relies on DUnit, it can only find DUnitX's unit. So, I think you should check your Delphi librarypath.</p>

Body:
I was using Delphi xe4 to compile https://github.com/hprose/hprose-delphi/blob/master/Test/HproseTest.dpr

And got the following error which I spent tens of minutes and still couldn't figure out why.

I've tried deleting all 'DUnitX*.dcu" and compile again, with no luck.

What puzzled me is that, why the unit TextTestRunner from DUnit (born first) relies on a unit from DUnitX which was born later?

Any hint? Thanks.

[dcc32 Fatal Error] HproseTest.dpr(37): F2051 Unit TextTestRunner was compiled with a different version of DUnitX.TestFramework.ITestListener

And here is the screenshot I made for making the problem description clear:


问:
Is it possible to force an XMLHttpRequest not to send cookies in chromium?
Is it possible to force chrome not to send the cookie header on an XMLHttpRequest. I see that Firefox has an anon parameter, but is there something similar on chrome/webkit?</p>

答:
Unfortunately, there is no straightforward way in webextensions at the moment (both in Firefox and Chrome). Let us look at the alternatives:

Use fetch instead of XMLHttpRequest

Modify request headers using the webRequest API

Option 1 has the charm that it does not involve hacks, but the downside is that fetch is currently still missing some functionality that exists in XMLHttpRequest. Whether that is a problem, depends on your concrete example.

Option 2 requires permission to use the webRequest API, which requires additional permissions. Also it looks more complicated than it should be. Still, it is the only way that I got working and which can be used on today's browsers (Nov 2017).

But let us look at both options in detail.

Option 1: fetch API and its limitations

When you mention anonymous requests in Firefox, I'm sure you mean code like this:

```<code>let xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
           .createInstance(Components.interfaces.nsIXMLHttpRequest);
xhr.open('GET', 'http://www.example.com');
xhr.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_ANONYMOUS;
xhr.send();
</code>```

With XMLHttpRequest in Chrome it is not possible, but the closest thing that you can get today is to avoid sending cookies by using the fetch API, which has a similar option called credentials, which lets you control whether cookies should be included ('include') or not ('omit'):

```<code>fetch('http://www.example.com', { credentials: 'omit' }).then(...);
</code>```

This will make a GET request without setting any cookies.

There are still some limitations in terms of functionality in comparison to XMLHttpRequest. The most pressing issue from my perspective is that you cannot abort requests started with fetch, nor do you have control over timeouts.

There is a new standard to support abortable fetch (see AbortController API), but it is currently only implemented on Firefox 57 and Edge (in Nov 2017). It will soon arrive in Chrome, but if you need the functionality now, it might not be an option to wait until all browsers support it.

Still, once AbortController is there, I assume it will become the preferred way to avoid sending cookies.

Option 2: webRequest API and removing the 'Cookie' header manually

If you need a working solution now, and you have permission in the extension to access the webRequest API, you can install a onBeforeSendHeaders listener and manually remove the Cookie header.

To get an idea, this is how it could look like:

```<code>chrome.webRequest.onBeforeSendHeaders.addListener((details) => {
  return {
    requestHeaders: details.requestHeaders.filter(x => x.name.toLowerCase() !== 'cookie');
  };
}, { urls: ['<all_urls>'] }, ['requestHeaders', 'blocking']);
</code>```

But you have to be careful that you do not accidentally modify unrelated requests. In a real implementation, you should verify whether the details.requestId matches. To get access to the request id, I used another onBeforeRequestListener and verified whether the URL of the request seems to match. When the request is done, all listeners are removed again. (For more details, see How to get the requestId of a new request?.)

From what I see, it works but it is not a very elegant solution.

Summary:

fetch API:

(+) Straightforward solution via crendentials: 'omit'

(+) New standard which is intended to replace XMLHttpRequest

(-) Current browsers do not yet support all features (timeouts, cancellation)

webRequest API:

(+) works on today's browsers (tested on Chrome)

(-) very complex solution for a simple problem

(-) requires extra permissions to use it

Body:
Unfortunately, there is no straightforward way in webextensions at the moment (both in Firefox and Chrome). Let us look at the alternatives:

Use fetch instead of XMLHttpRequest

Modify request headers using the webRequest API

Option 1 has the charm that it does not involve hacks, but the downside is that fetch is currently still missing some functionality that exists in XMLHttpRequest. Whether that is a problem, depends on your concrete example.

Option 2 requires permission to use the webRequest API, which requires additional permissions. Also it looks more complicated than it should be. Still, it is the only way that I got working and which can be used on today's browsers (Nov 2017).

But let us look at both options in detail.

Option 1: fetch API and its limitations

When you mention anonymous requests in Firefox, I'm sure you mean code like this:

let xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
           .createInstance(Components.interfaces.nsIXMLHttpRequest);
xhr.open('GET', 'http://www.example.com');
xhr.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_ANONYMOUS;
xhr.send();

With XMLHttpRequest in Chrome it is not possible, but the closest thing that you can get today is to avoid sending cookies by using the fetch API, which has a similar option called credentials, which lets you control whether cookies should be included ('include') or not ('omit'):

fetch('http://www.example.com', { credentials: 'omit' }).then(...);

This will make a GET request without setting any cookies.

There are still some limitations in terms of functionality in comparison to XMLHttpRequest. The most pressing issue from my perspective is that you cannot abort requests started with fetch, nor do you have control over timeouts.

There is a new standard to support abortable fetch (see AbortController API), but it is currently only implemented on Firefox 57 and Edge (in Nov 2017). It will soon arrive in Chrome, but if you need the functionality now, it might not be an option to wait until all browsers support it.

Still, once AbortController is there, I assume it will become the preferred way to avoid sending cookies.

Option 2: webRequest API and removing the 'Cookie' header manually

If you need a working solution now, and you have permission in the extension to access the webRequest API, you can install a onBeforeSendHeaders listener and manually remove the Cookie header.

To get an idea, this is how it could look like:

chrome.webRequest.onBeforeSendHeaders.addListener((details) => {
  return {
    requestHeaders: details.requestHeaders.filter(x => x.name.toLowerCase() !== 'cookie');
  };
}, { urls: ['<all_urls>'] }, ['requestHeaders', 'blocking']);

But you have to be careful that you do not accidentally modify unrelated requests. In a real implementation, you should verify whether the details.requestId matches. To get access to the request id, I used another onBeforeRequestListener and verified whether the URL of the request seems to match. When the request is done, all listeners are removed again. (For more details, see How to get the requestId of a new request?.)

From what I see, it works but it is not a very elegant solution.

Summary:

fetch API:

(+) Straightforward solution via crendentials: 'omit'

(+) New standard which is intended to replace XMLHttpRequest

(-) Current browsers do not yet support all features (timeouts, cancellation)

webRequest API:

(+) works on today's browsers (tested on Chrome)

(-) very complex solution for a simple problem

(-) requires extra permissions to use it


问:
How self reference class in Python in class member variables (not known syntax)?
I am learned Python some years ago but I do not know how to reference class as self.

See my problem:

```<code>class SomeClassReference(object):
  def __init__(self, reference):
    self.reference = reference

class MyClass(object):
  # MyClass is not defined - how to solve it?
  a = SomeClassReference(reference = MyClass)
</code>```

Is it possible to do such self reference in Python what syntax I need to use to initialize class member with class. I use Python frequently but has no idea how to do it?

答:
class Point(object):
  ZERO = None
  def __init__(self, x, y):
    self.x = x
    self.y = y
Point.ZERO = Point(0,0)
```

ZERO in the class definition is not needed but I'm using it because my IDE is not able to find the class variable for code completion.

Body:
I am learned Python some years ago but I do not know how to reference class as self.

See my problem:

class SomeClassReference(object):
  def __init__(self, reference):
    self.reference = reference

class MyClass(object):
  # MyClass is not defined - how to solve it?
  a = SomeClassReference(reference = MyClass)

Is it possible to do such self reference in Python what syntax I need to use to initialize class member with class. I use Python frequently but has no idea how to do it?

Body:
class Point(object):
  ZERO = None
  def __init__(self, x, y):
    self.x = x
    self.y = y
Point.ZERO = Point(0,0)

ZERO in the class definition is not needed but I'm using it because my IDE is not able to find the class variable for code completion.


问:
PHP if a table table row exists
In PHP, is there a way of making the following statement to check if a row exists?

If "the table cases has a "passenger" field with the value of 4 WHERE case= '$case' {
code...
}

答:
not that elegantly, no. But you can run the query then compare the result:</p>

```<code>$case = mysql_real_escape_string($case); // make sure to escape values going in queries
if (($r = mysql_query("SELECT * FROM cases WHERE passenger=4 AND case='{$case}'")) !== false)
{
  if (mysql_num_rows($r))
  {
     // your code here.
  }
}
</code>```

Title: PHP if a table table row exists

Body:
not that elegantly, no. But you can run the query then compare the result:

$case = mysql_real_escape_string($case); // make sure to escape values going in queries
if (($r = mysql_query("SELECT * FROM cases WHERE passenger=4 AND case='{$case}'")) !== false)
{
  if (mysql_num_rows($r))
  {
     // your code here.
  }
}


问:
How to group by and return list in rx java
I'm trying to create group list based on certain conditions in Rxjava.

Below is my response:

```<code>{
   "dates":[
      {
         "date":18,
         "value":"1"
      },
      {
         "date":18,
         "value":"2"
      },
      {
         "date":18,
         "value":"3"
      },
      {
         "date":19,
         "value":"1"
      },
      {
         "date":19,
         "value":"2"
      },
      {
         "date":19,
         "value":"3"
      },
      {
         "date":19,
         "value":"4"
      }
   ]
}
</code>```

How can group by the values 18 [value 1, value 2, value 3, highestvalue= 3, lowestvalue = 1]
19[value 1, value 2, value 3, value 4,highestvalue= 4, lowestvalue = 1] using Rxjava

Note: I can create using for loop but the response will be fetched from the server and since it is returning observable thought of using rx java functionality.

Anyhelp will be really appreciated.

Thank you,
Shanthi

答:
Inspired by @Jon 's answer which works. Here's a full demo code for Rxjava2 and output.

Observable#collect() for Observable

Flowable#parallel() + Single#blockingGet() for Flowable

The output :

```<code>----------------------byCollect
[2017/11/16 20:42:43.548 CST][   1 -                           main] - flatMapSingle :  : 1
[2017/11/16 20:42:43.590 CST][   1 -                           main] - flatMapSingle :  : 2
[2017/11/16 20:42:43.591 CST][   1 -                           main] - flatMapSingle :  : 0
[2017/11/16 20:42:43.592 CST][   1 -                           main] - subscribe : onNext : {0=[3, 6, 9]}
[2017/11/16 20:42:43.593 CST][   1 -                           main] - subscribe : onNext : {1=[1, 4, 7]}
[2017/11/16 20:42:43.593 CST][   1 -                           main] - subscribe : onNext : {2=[2, 5, 8]}
[2017/11/16 20:42:43.597 CST][   1 -                           main] - subscribe : onComplete :
----------------------byParallelAndBlockingGet
[2017/11/16 20:42:43.629 CST][  13 -      RxComputationThreadPool-1] - flatMap :  : 1
[2017/11/16 20:42:43.629 CST][  15 -      RxComputationThreadPool-3] - flatMap :  : 0
[2017/11/16 20:42:43.629 CST][  14 -      RxComputationThreadPool-2] - flatMap :  : 2
[2017/11/16 20:42:43.632 CST][  15 -      RxComputationThreadPool-3] - subscribe : onNext : {0=[3, 6, 9]}
[2017/11/16 20:42:43.632 CST][  15 -      RxComputationThreadPool-3] - subscribe : onNext : {1=[1, 4, 7]}
[2017/11/16 20:42:43.633 CST][  15 -      RxComputationThreadPool-3] - subscribe : onNext : {2=[2, 5, 8]}
[2017/11/16 20:42:43.633 CST][  15 -      RxComputationThreadPool-3] - subscribe : onComplete :
</code>```

The source : Demo.java

```<code>import io.reactivex.*;
import io.reactivex.Observable;
import io.reactivex.schedulers.*;

import java.time.*;
import java.time.format.*;
import java.util.*;

/**
 *   List<Integer>              // [1..9]
 *   ->
 *   Map<Integer,List<Integer> //  {0: [3,6,9],  1: [1,4,7],  2: [2,5,8] }
 */
public class Demo {
    public static void main(String[] args) throws InterruptedException {
        byCollect();
        byParallelAndBlockingGet();
    }

    public static void byCollect() throws InterruptedException {
        System.out.println("----------------------byCollect");
        Observable.range(1, 9)
                .groupBy(i -> i % 3)
                .flatMapSingle(f -> {  // GroupedObservable<Integer, List<Integer>>

                    // Look output : all runs on same thread,
                    print("flatMapSingle : ", f.getKey());

                    // "onComplete" has not been triggered.
                    // blockingGet will block current thread.
                    //return Observable.just(Collections.singletonMap(f.getKey(), f.toList().blockingGet()))

                    return f.collect(
                            // (Callable<Map<Integer, List<Integer>>>)
                            () -> Collections.singletonMap(f.getKey(), new ArrayList<Integer>()),

                            // (BiConsumer<Map<Integer, List<Integer>>, Integer>)
                            (m, i) -> m.get(f.getKey()).add(i)
                    );

                })
                .subscribe(
                        i -> print("subscribe : onNext", i),
                        err -> print("subscribe : onError", err),
                        () -> print("subscribe : onComplete", "")
                )
        ;
    }

    public static void byParallelAndBlockingGet() throws InterruptedException {
        System.out.println("----------------------byParallelAndBlockingGet");
        Flowable.range(1, 9)
                .groupBy(i -> i % 3)
                .parallel()  // There's no `parallel` method on `Observable` class
                .runOn(Schedulers.computation())  // Important!!!
                .flatMap(f -> { // ParallelFlowable<GroupedFlowable<Integer, List<Integer>>
                    // Look output : runs on different thread each.
                    print("flatMap : ", f.getKey());
                    return Flowable.just(Collections.singletonMap(f.getKey(), f.toList().blockingGet()));
                })
                .sequential()
                .subscribe(
                        i -> print("subscribe : onNext", i),
                        err -> print("subscribe : onError", err),
                        () -> print("subscribe : onComplete", "")
                )
        ;
        Thread.sleep(500);
    }

    public static void print(String step, Object data) {
        ZonedDateTime zdt = ZonedDateTime.now();
        String now = zdt.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS z"));
        System.out.printf("[%s][%4d - %30s] - %10s : %s%n",
                now,
                Thread.currentThread().getId(),
                Thread.currentThread().getName(),
                step,
                data
        );
    }
}
</code>```

Body:
I'm trying to create group list based on certain conditions in Rxjava.

Below is my response:

{
   "dates":[
      {
         "date":18,
         "value":"1"
      },
      {
         "date":18,
         "value":"2"
      },
      {
         "date":18,
         "value":"3"
      },
      {
         "date":19,
         "value":"1"
      },
      {
         "date":19,
         "value":"2"
      },
      {
         "date":19,
         "value":"3"
      },
      {
         "date":19,
         "value":"4"
      }
   ]
}

How can group by the values 18 [value 1, value 2, value 3, highestvalue= 3, lowestvalue = 1]
19[value 1, value 2, value 3, value 4,highestvalue= 4, lowestvalue = 1] using Rxjava

Note: I can create using for loop but the response will be fetched from the server and since it is returning observable thought of using rx java functionality.

Anyhelp will be really appreciated.

Thank you,
Shanthi

Body:
Inspired by @Jon 's answer which works. Here's a full demo code for Rxjava2 and output.

Observable#collect() for Observable

Flowable#parallel() + Single#blockingGet() for Flowable

The output :

----------------------byCollect
[2017/11/16 20:42:43.548 CST][   1 -                           main] - flatMapSingle :  : 1
[2017/11/16 20:42:43.590 CST][   1 -                           main] - flatMapSingle :  : 2
[2017/11/16 20:42:43.591 CST][   1 -                           main] - flatMapSingle :  : 0
[2017/11/16 20:42:43.592 CST][   1 -                           main] - subscribe : onNext : {0=[3, 6, 9]}
[2017/11/16 20:42:43.593 CST][   1 -                           main] - subscribe : onNext : {1=[1, 4, 7]}
[2017/11/16 20:42:43.593 CST][   1 -                           main] - subscribe : onNext : {2=[2, 5, 8]}
[2017/11/16 20:42:43.597 CST][   1 -                           main] - subscribe : onComplete :
----------------------byParallelAndBlockingGet
[2017/11/16 20:42:43.629 CST][  13 -      RxComputationThreadPool-1] - flatMap :  : 1
[2017/11/16 20:42:43.629 CST][  15 -      RxComputationThreadPool-3] - flatMap :  : 0
[2017/11/16 20:42:43.629 CST][  14 -      RxComputationThreadPool-2] - flatMap :  : 2
[2017/11/16 20:42:43.632 CST][  15 -      RxComputationThreadPool-3] - subscribe : onNext : {0=[3, 6, 9]}
[2017/11/16 20:42:43.632 CST][  15 -      RxComputationThreadPool-3] - subscribe : onNext : {1=[1, 4, 7]}
[2017/11/16 20:42:43.633 CST][  15 -      RxComputationThreadPool-3] - subscribe : onNext : {2=[2, 5, 8]}
[2017/11/16 20:42:43.633 CST][  15 -      RxComputationThreadPool-3] - subscribe : onComplete :

The source : Demo.java

import io.reactivex.*;
import io.reactivex.Observable;
import io.reactivex.schedulers.*;

import java.time.*;
import java.time.format.*;
import java.util.*;

/**
 *   List<Integer>              // [1..9]
 *   ->
 *   Map<Integer,List<Integer> //  {0: [3,6,9],  1: [1,4,7],  2: [2,5,8] }
 */
public class Demo {
    public static void main(String[] args) throws InterruptedException {
        byCollect();
        byParallelAndBlockingGet();
    }

    public static void byCollect() throws InterruptedException {
        System.out.println("----------------------byCollect");
        Observable.range(1, 9)
                .groupBy(i -> i % 3)
                .flatMapSingle(f -> {  // GroupedObservable<Integer, List<Integer>>

                    // Look output : all runs on same thread,
                    print("flatMapSingle : ", f.getKey());

                    // "onComplete" has not been triggered.
                    // blockingGet will block current thread.
                    //return Observable.just(Collections.singletonMap(f.getKey(), f.toList().blockingGet()))

                    return f.collect(
                            // (Callable<Map<Integer, List<Integer>>>)
                            () -> Collections.singletonMap(f.getKey(), new ArrayList<Integer>()),

                            // (BiConsumer<Map<Integer, List<Integer>>, Integer>)
                            (m, i) -> m.get(f.getKey()).add(i)
                    );

                })
                .subscribe(
                        i -> print("subscribe : onNext", i),
                        err -> print("subscribe : onError", err),
                        () -> print("subscribe : onComplete", "")
                )
        ;
    }

    public static void byParallelAndBlockingGet() throws InterruptedException {
        System.out.println("----------------------byParallelAndBlockingGet");
        Flowable.range(1, 9)
                .groupBy(i -> i % 3)
                .parallel()  // There's no `parallel` method on `Observable` class
                .runOn(Schedulers.computation())  // Important!!!
                .flatMap(f -> { // ParallelFlowable<GroupedFlowable<Integer, List<Integer>>
                    // Look output : runs on different thread each.
                    print("flatMap : ", f.getKey());
                    return Flowable.just(Collections.singletonMap(f.getKey(), f.toList().blockingGet()));
                })
                .sequential()
                .subscribe(
                        i -> print("subscribe : onNext", i),
                        err -> print("subscribe : onError", err),
                        () -> print("subscribe : onComplete", "")
                )
        ;
        Thread.sleep(500);
    }

    public static void print(String step, Object data) {
        ZonedDateTime zdt = ZonedDateTime.now();
        String now = zdt.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS z"));
        System.out.printf("[%s][%4d - %30s] - %10s : %s%n",
                now,
                Thread.currentThread().getId(),
                Thread.currentThread().getName(),
                step,
                data
        );
    }
}


问:
How to create an array of TextFields in JavaFX
I am converting an app written using Swing to JavaFX. I need an array of TextFields that I can manipulate collectively and as individual array members addressed by the array index. The following code works in Swing but I cannot find the equivalent in JavaFX, using TextField instead of JTextField. How can I achieve this in JavaFX?

```<code>private ArrayList<JTextField> fieldList= new ArrayList<JTextField>();

fieldList.add(fldCompletion);
fieldList.add(fldHrsToDate);
fieldList.add(fldHrsToComplete);

for(JTextField fl : fieldList) {
        fl.setText("");
        fl.setEnabled(true);    //FX equivalent is setDisable(false)
    }

fieldList.get(var).setText("");
</code>```

答:
This will do just fine</p>

```<code>TextField[] txt = new TextField[beanFields.length];
for (int i=0; i<=beanFields.length-1; i++) {
                TextField textField = new TextField();
                txt[i] = textField;
                textField.setPrefWidth(200);
                textField.setPrefHeight(32);
}
</code>```

Body:
I am converting an app written using Swing to JavaFX. I need an array of TextFields that I can manipulate collectively and as individual array members addressed by the array index. The following code works in Swing but I cannot find the equivalent in JavaFX, using TextField instead of JTextField. How can I achieve this in JavaFX?

private ArrayList<JTextField> fieldList= new ArrayList<JTextField>();

fieldList.add(fldCompletion);
fieldList.add(fldHrsToDate);
fieldList.add(fldHrsToComplete);

for(JTextField fl : fieldList) {
        fl.setText("");
        fl.setEnabled(true);    //FX equivalent is setDisable(false)
    }

fieldList.get(var).setText("");

Body:
This will do just fine

TextField[] txt = new TextField[beanFields.length];
for (int i=0; i<=beanFields.length-1; i++) {
                TextField textField = new TextField();
                txt[i] = textField;
                textField.setPrefWidth(200);
                textField.setPrefHeight(32);
}


问:
send a local email with codeIgniter
I try to send a local email with codeIgniter.

```<code>// envoi du mail
 public function envoiMail(){
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    );
    $sujet = $this->input->post('sujet');
    $message = $this->input->post('message');
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('xxxx@gmail.com', 'Name');
    $this->email->to('xxxx@yahoo.fr');
    $this->email->subject($sujet);
    $this->email->message($message);
    $this->email->send();
  if($this->email->send()){
      // mail transmis
       echo "ok";
  }else{
      // erreur de transmission
      echo"erreur d'envoi";
  }
 }
</code>```

when I test I get this error:  Message: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.

答:
```<code>$config = array(
                'protocol'  => 'smtp',
                'smtp_host' => 'ssl://smtp.googlemail.com',
                'smtp_port' => 465,
                'smtp_user' => 'yourmail@gmail.com',
                'smtp_pass' => 'your password',
                'mailtype'  => 'html',
                'charset'   => 'utf-8'
            );
</code>```

Try this....

Title: send a local email with codeIgniter

Body:
I try to send a local email with codeIgniter.

// envoi du mail
 public function envoiMail(){
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    );
    $sujet = $this->input->post('sujet');
    $message = $this->input->post('message');
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('xxxx@gmail.com', 'Name');
    $this->email->to('xxxx@yahoo.fr');
    $this->email->subject($sujet);
    $this->email->message($message);
    $this->email->send();
  if($this->email->send()){
      // mail transmis
       echo "ok";
  }else{
      // erreur de transmission
      echo"erreur d'envoi";
  }
 }

when I test I get this error:  Message: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.

Body:
$config = array(
                'protocol'  => 'smtp',
                'smtp_host' => 'ssl://smtp.googlemail.com',
                'smtp_port' => 465,
                'smtp_user' => 'yourmail@gmail.com',
                'smtp_pass' => 'your password',
                'mailtype'  => 'html',
                'charset'   => 'utf-8'
            );

Try this....


问:
I need to use a SELECT - JOIN sentence on a stored procedure PL/SQL
I had a problem with Oracle SQL. I need to use this PL/SQL sentence on a stored procedure:

```<code>select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
      from curso t
      inner join contrato c on t.ID_CURSO = c.curso_id_curso
      inner join PAQUETE_ACTIVIDADES p on
            c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
where id_curso=value;
</code>```

I need to show the data of this select query
How can I do that? I'm new at this
Thanks for your help

答:
This should work. A good practice is to have a specific notation for local PL/SQL variable, say here (l:local, i:id) l_i_value:

```<code>declare
  l_i_value integer := 14;
begin
    dbms_output.enable(1000000);
    for x in (
    select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
          from curso t
          inner join contrato c on t.ID_CURSO = c.curso_id_curso
          inner join PAQUETE_ACTIVIDADES p on
                c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
    where id_curso=l_i_value )
    loop
      dbms_output.put_line('---');
      dbms_output.put_line(x.ID_CURSO);
      dbms_output.put_line(x.DESCRIPCION);
   -- ...
    end loop;
end;
/
</code>```

Body:
I had a problem with Oracle SQL. I need to use this PL/SQL sentence on a stored procedure:

select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
      from curso t
      inner join contrato c on t.ID_CURSO = c.curso_id_curso
      inner join PAQUETE_ACTIVIDADES p on
            c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
where id_curso=value;

I need to show the data of this select query
How can I do that? I'm new at this
Thanks for your help

Body:
This should work. A good practice is to have a specific notation for local PL/SQL variable, say here (l:local, i:id) l_i_value:

declare
  l_i_value integer := 14;
begin
    dbms_output.enable(1000000);
    for x in (
    select t.ID_CURSO,p.DESCRIPCION,p.FECHA_INICIO,p.FECHA_FIN
          from curso t
          inner join contrato c on t.ID_CURSO = c.curso_id_curso
          inner join PAQUETE_ACTIVIDADES p on
                c.ID_PAQUETE_ACTIVIDADES_ID = p.ID_PAQUETE_ACTIVIDADES
    where id_curso=l_i_value )
    loop
      dbms_output.put_line('---');
      dbms_output.put_line(x.ID_CURSO);
      dbms_output.put_line(x.DESCRIPCION);
   -- ...
    end loop;
end;
/


问:
.Net compiler hooking
All my data objects implement an interface IFillable

```<code>Public Interface IFillable
    Sub Fill(ByVal Datareader As Data.IDataReader)
End Interface
</code>```

In the objects themselves you will typically see something like

```<code>Public Class Supplier
    Implements IFillable

    Public Sub New()
    End Sub

    Public Sub New(ByVal SupplierID As Guid, ByVal CompanyID As Guid, ByVal Description As String)
        Me._SupplierID = SupplierID
        Me._CompanyID = CompanyID
        Me._Description = Description
    End Sub

    Public Property SupplierID As Guid
    Public Property CompanyID As Guid
    Public Property Description As String

    Public Sub Fill(ByVal Datareader As System.Data.IDataReader) Implements IFillable.Fill
        If Not Datareader.IsClosed Then
            Me._SupplierID = Datareader.GetGuid(Datareader.GetOrdinal("SupplierID"))
            Me._CompanyID = Datareader.GetGuid(Datareader.GetOrdinal("CompanyID"))
            Me._Description = Datareader.GetString(Datareader.GetOrdinal("Description"))
        End If
    End Sub

End Class
</code>```

Now here is the tricky bit. Given that all my property names WILL ALWAYS match my database column names what I want to do is using reflection generate the fill method at compile time and infer the types and column names for the datareader.

I am assuming I will need to structure this functionality as some sort of a tool/vs plugin? What I am looking for is guidance on the best way to go about this.

PS: BTW: Obviously I could easily do this using reflection at runtime but I dont want to take the performance hit for it (Although theoretically if I could cache the values somehow (static class?) it might not be too bad).

答:
I would recommend to use some code generation framework.
For VB/C#/.NET the most obvious choice should be T4:
some T4 introduction</p>

Title: .Net compiler hooking

Body:
All my data objects implement an interface IFillable

Public Interface IFillable
    Sub Fill(ByVal Datareader As Data.IDataReader)
End Interface

In the objects themselves you will typically see something like

Public Class Supplier
    Implements IFillable

    Public Sub New()
    End Sub

    Public Sub New(ByVal SupplierID As Guid, ByVal CompanyID As Guid, ByVal Description As String)
        Me._SupplierID = SupplierID
        Me._CompanyID = CompanyID
        Me._Description = Description
    End Sub

    Public Property SupplierID As Guid
    Public Property CompanyID As Guid
    Public Property Description As String

    Public Sub Fill(ByVal Datareader As System.Data.IDataReader) Implements IFillable.Fill
        If Not Datareader.IsClosed Then
            Me._SupplierID = Datareader.GetGuid(Datareader.GetOrdinal("SupplierID"))
            Me._CompanyID = Datareader.GetGuid(Datareader.GetOrdinal("CompanyID"))
            Me._Description = Datareader.GetString(Datareader.GetOrdinal("Description"))
        End If
    End Sub

End Class

Now here is the tricky bit. Given that all my property names WILL ALWAYS match my database column names what I want to do is using reflection generate the fill method at compile time and infer the types and column names for the datareader.

I am assuming I will need to structure this functionality as some sort of a tool/vs plugin? What I am looking for is guidance on the best way to go about this.

PS: BTW: Obviously I could easily do this using reflection at runtime but I dont want to take the performance hit for it (Although theoretically if I could cache the values somehow (static class?) it might not be too bad).


问:
Maximum concurrent connections in ms access
What are the maximum concurrent connections ms-access supports?</p>

答:
In my experience 10 concurrent users starts causing problems.
I'm sure there are examples w/ very small datasets working well w/ many users.

Access may be fine for some applications. There seems to be a lot of passion in this thread.

The key concept to understand here is that there is no server. EVERY QUERY will pull the ENTIRE table across the network.

If its a JOIN, EVERY QUERY will pull EVERY table involved across the network.
That's because the JOIN engine is located on your desktop.

It doesn't matter where the access file is. At best, it is located on the primary user's desktop machine. Everyone else has to utilize the network to access the data.

If you have a 100k table and you want id #1042, you will pull 100k * Record length worth of data across the network and then filter out everything but #1042. It can't cache, because your coworker may have changed the next record you want to look at.

I don't think its necessarily the number of concurrent users on an Access DB.
I think it's the number of people concurrently pulling sizable data chunks over the network each time they click a button.

Network load/Network latency will increase as table count grows, record counts grow,and user count grow. Possibly w/ a multiplicative effect.
Compound this when you have offsite data centers (encryption), vpn users(encryption), users on different continents, etc. etc. etc.


问:
Dropdown menu for editing categories doesn't work
I'm making a simple blog using springframework. I'm trying to make Categories for my posts/articles. When I create articles, I have the option to choose a Category and it works fine. However, when I try to edit an Article, the drop-down menu for choosing a Category is not working. It's just and empty field with a 'down arrow' sidebad and nothing happens when I click on it

```<code>//ARTICLE EDIT--------------------------------------------------
@GetMapping("/article/edit/{id}")
@PreAuthorize("isAuthenticated()")
public String edit(@PathVariable Integer id, Model model)
{
    if(!this.articleRepository.exists(id))
    {
        return "redirect:/";
    }
    Article article = this.articleRepository.findOne(id);

    if(!isUserAuthorOrAdmin(article))
    {
        return "redirect:/article/"+id;
    }

    List<Category> categories = this.categoryRepository.findAll();
    String tagString = article.getTags().stream().map(Tag::getName).collect(Collectors.joining(", "));

    model.addAttribute("view", "article/edit");
    model.addAttribute("article", article);
    model.addAttribute("category", categories);
    model.addAttribute("tags", tagString);

    return "base-layout";
}

@PostMapping("/article/edit/{id}")
@PreAuthorize("isAuthenticated()")
public String editProcess(@PathVariable Integer id, ArticleBindingModel articleBindingModel)
{
    if(!this.articleRepository.exists(id))
    {
        return "redirect:/";
    }
    Article article = this.articleRepository.findOne(id);
    Category category = this.categoryRepository.findOne(articleBindingModel.getCategoryId());
    HashSet<Tag> tags = this.findTagsFromString(articleBindingModel.getTagString());

    if(!isUserAuthorOrAdmin(article))
    {
        return "redirect:/article/"+id;
    }

    article.setContent(articleBindingModel.getContent());
    article.setTitle(articleBindingModel.getTitle());
    article.setCategory(category);
    article.setTags(tags);

    this.articleRepository.saveAndFlush(article);

    return "redirect:/article/" + article.getId();
}
</code>```

The html file is:

```<code><main>
    <div class="container body-content span=8 offset=2">
        <div class="well">
            <form class="form-horizontal" th:action="@{/article/edit/{id}(id=${article.id})}" method="POST">
                <fieldset>
                    <legend>Edit Post</legend>

                    <div class="form-group">
                        <label class="col-sm-4 control-label" for="article_title">Post Title</label>
                        <div class="col-sm-4 ">
                            <input type="text" class="form-control" id="article_title" placeholder="Post Title" name="title" th:value="${article.title}"/>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-4 control-label" for="article_content">Content</label>
                    <div class="col-sm-6">
                        <textarea class="form-control" rows="6" id="article_content" name="content" th:field="${article.content}"></textarea>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-4 control-label" for="article_tags">Tags</label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="article_tags" placeholder="Tags" name="tagString" th:value="${tags}"/>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-4 control-label" for="article_category">Category</label>
                    <div class="col-sm-6">
                        <select class="form-control" id="article_category" name="categoryId">
                            <option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}"  th:selected="${category.id == article.category.id}">
                            </option>
                        </select>
                    </div>
                 </div>

                <div class="form-group">
                    <div class="col-sm-4 col-sm-offset-4">
                        <a class="btn btn-default" th:href="@{/article/{id}(id = ${article.id})}">Cancel</a>
                        <input type="submit" class="btn btn-success" value="Edit"/>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>
</div>
</code>```

答:
You should use model attributes' names inside ${}. There is a mismatch between model.addAttribute("category", categories); and th:each="category : ${categories}".

Change model attribute name to "categories" and it should be fine

```<code>model.addAttribute("categories", categories);
</code>```

Body:
I'm making a simple blog using springframework. I'm trying to make Categories for my posts/articles. When I create articles, I have the option to choose a Category and it works fine. However, when I try to edit an Article, the drop-down menu for choosing a Category is not working. It's just and empty field with a 'down arrow' sidebad and nothing happens when I click on it

//ARTICLE EDIT--------------------------------------------------
@GetMapping("/article/edit/{id}")
@PreAuthorize("isAuthenticated()")
public String edit(@PathVariable Integer id, Model model)
{
    if(!this.articleRepository.exists(id))
    {
        return "redirect:/";
    }
    Article article = this.articleRepository.findOne(id);

    if(!isUserAuthorOrAdmin(article))
    {
        return "redirect:/article/"+id;
    }

    List<Category> categories = this.categoryRepository.findAll();
    String tagString = article.getTags().stream().map(Tag::getName).collect(Collectors.joining(", "));

    model.addAttribute("view", "article/edit");
    model.addAttribute("article", article);
    model.addAttribute("category", categories);
    model.addAttribute("tags", tagString);

    return "base-layout";
}

@PostMapping("/article/edit/{id}")
@PreAuthorize("isAuthenticated()")
public String editProcess(@PathVariable Integer id, ArticleBindingModel articleBindingModel)
{
    if(!this.articleRepository.exists(id))
    {
        return "redirect:/";
    }
    Article article = this.articleRepository.findOne(id);
    Category category = this.categoryRepository.findOne(articleBindingModel.getCategoryId());
    HashSet<Tag> tags = this.findTagsFromString(articleBindingModel.getTagString());

    if(!isUserAuthorOrAdmin(article))
    {
        return "redirect:/article/"+id;
    }

    article.setContent(articleBindingModel.getContent());
    article.setTitle(articleBindingModel.getTitle());
    article.setCategory(category);
    article.setTags(tags);

    this.articleRepository.saveAndFlush(article);

    return "redirect:/article/" + article.getId();
}

The html file is:

            <form class="form-horizontal" th:action="@{/article/edit/{id}(id=${article.id})}" method="POST">
                <fieldset>
                    <legend>Edit Post</legend>

                        Post Title

                            <input type="text" class="form-control" id="article_title" placeholder="Post Title" name="title" th:value="${article.title}"/>

                        Content

                        <textarea class="form-control" rows="6" id="article_content" name="content" th:field="${article.content}"></textarea>

                    Tags

                        <input type="text" class="form-control" id="article_tags" placeholder="Tags" name="tagString" th:value="${tags}"/>

                    Category

                        <select class="form-control" id="article_category" name="categoryId">
                            <option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}"  th:selected="${category.id == article.category.id}">
                            </option>
                        </select>

                        Cancel
                        <input type="submit" class="btn btn-success" value="Edit"/>

            </fieldset>
        </form>

Body:
You should use model attributes' names inside ${}. There is a mismatch between model.addAttribute("category", categories); and th:each="category : ${categories}".

Change model attribute name to "categories" and it should be fine

model.addAttribute("categories", categories);