问:
ODBC Connection String error - C#
Attempting a simple ODBC connection to QuickBooks 2017 and have been unable to connect.

This is my current(among many other attempts) connection string.
connection string

This is OdbcException was unhandled error
unhandled

Error Message:
"An unhandled exception of type 'System.Data.Odbc.OdbcException' occurred in System.Data.dll

Additional information: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"

Any input on where I'm going wrong is appreciated.  Thank you.

答:
here is a good site , where you can find help

Long story short,

Example of simple DSN

```<code>sConnectString = "DSN=Quickbooks Data;OLE DB Services=-2;"
</code>```

Example of a DSNless connection string

```<code>sConnectString = "Driver={QODBC Driver for QuickBooks};DFQ=C:\Users\Public\Documents\Intuit\QuickBooks\Sample Company Files\QuickBooks Enterprise Solutions 14.0\sample_service-based business.qbw;OpenMode=M;OLE DB Services=-2;"
</code>```

Example of using current ADO syntax

```<code>sConnectString = "Provider=MSDASQL.1;Persist Security Info=False;Data Source=QuickBooks Data;OLE DB Services=-2;"
</code>```

Standard syntax

```<code>"DRIVER={QODBC Driver for QuickBooks};SERVER=QODBC;DFQ=.;OLE DB Services=-2;OptimizerOn=No;"
</code>```

Title: ODBC Connection String error - C#

Body:
here is a good site , where you can find help

Long story short,

Example of simple DSN

sConnectString = "DSN=Quickbooks Data;OLE DB Services=-2;"

Example of a DSNless connection string

sConnectString = "Driver={QODBC Driver for QuickBooks};DFQ=C:\Users\Public\Documents\Intuit\QuickBooks\Sample Company Files\QuickBooks Enterprise Solutions 14.0\sample_service-based business.qbw;OpenMode=M;OLE DB Services=-2;"

Example of using current ADO syntax

sConnectString = "Provider=MSDASQL.1;Persist Security Info=False;Data Source=QuickBooks Data;OLE DB Services=-2;"

Standard syntax

"DRIVER={QODBC Driver for QuickBooks};SERVER=QODBC;DFQ=.;OLE DB Services=-2;OptimizerOn=No;"


来源: stackexchange

问:
Remove specific XML nodes using Clojure
I have the following XML structure:

```<code>(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")
</code>```

where I want to remove any Item, if it has a Type B or C. The result should be something like:

```<code><ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>
</code>```

I've found it pretty trivial to query such structures using data.xml and data.xml.zip, e.g:

;; lein try org.clojure/data.xml org.clojure/data.zip
(def xmldoc (clojure.data.xml/parse-str xmlstr))
(def zipxml (clojure.zip/xml-zip xmldoc))

(clojure.data.zip.xml/xml-> zipxml :Items :Item [:Type "A"] :Note clojure.data.zip.xml/text)
;; => ("AA" "AA")
```

but didn't find similar declarative features for removing/editing children.

答:
The Clojure standard APIs provide convenient functions for manipulating XML and other tree structures. Removing (leaf) nodes can be done on depth-first traversal using clojure.walk:

```<code>(require '[clojure.xml :as xml]
         '[clojure.walk :as walk])

(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")

(def xmldoc (xml/parse (java.io.ByteArrayInputStream. (.getBytes xmlstr))))

(defn tag-matches [item tag]
  (= (:tag item) tag))

(defn content-matches [item to-match]
  ((into #{} to-match)
   (apply str (:content item))))

(defn match-criteria [item to-match]
  (some #(and (tag-matches % :Type)
              (content-matches % to-match))
        (:content item)))

(defn mk-xml-walker [& to-remove]
  (fn [form]
    (if (and (vector? form)
             (some #(tag-matches % :Item) form))
      (filter (complement #(match-criteria % to-remove)) form)
      form)))

(xml/emit (walk/postwalk (mk-xml-walker "B" "C") xmldoc))
</code>```

For magical one-liners, you may also want to check out Specter which provides a very concise syntax for manipulating nested data structures, like XML.

ContentLicense: CC BY-SA 3.0

Title: Remove specific XML nodes using Clojure

Body:
I have the following XML structure:

(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")

where I want to remove any Item, if it has a Type B or C. The result should be something like:

<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>

I've found it pretty trivial to query such structures using data.xml and data.xml.zip, e.g:

;; lein try org.clojure/data.xml org.clojure/data.zip
(def xmldoc (clojure.data.xml/parse-str xmlstr))
(def zipxml (clojure.zip/xml-zip xmldoc))

(clojure.data.zip.xml/xml-> zipxml :Items :Item [:Type "A"] :Note clojure.data.zip.xml/text)
;; => ("AA" "AA")

but didn't find similar declarative features for removing/editing children.

Body:
The Clojure standard APIs provide convenient functions for manipulating XML and other tree structures. Removing (leaf) nodes can be done on depth-first traversal using clojure.walk:

(require '[clojure.xml :as xml]
         '[clojure.walk :as walk])

(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")

(def xmldoc (xml/parse (java.io.ByteArrayInputStream. (.getBytes xmlstr))))

(defn tag-matches [item tag]
  (= (:tag item) tag))

(defn content-matches [item to-match]
  ((into #{} to-match)
   (apply str (:content item))))

(defn match-criteria [item to-match]
  (some #(and (tag-matches % :Type)
              (content-matches % to-match))
        (:content item)))

(defn mk-xml-walker [& to-remove]
  (fn [form]
    (if (and (vector? form)
             (some #(tag-matches % :Item) form))
      (filter (complement #(match-criteria % to-remove)) form)
      form)))

(xml/emit (walk/postwalk (mk-xml-walker "B" "C") xmldoc))

For magical one-liners, you may also want to check out Specter which provides a very concise syntax for manipulating nested data structures, like XML.


问:
Kafka + AWS lambda
Is it possible to integrate AWS Lambda with Apache Kafka ?
I want to put a consumer in a lambda function. When a consumer receive a message the lambda function execute.</p>

答:
Continuing the point by Arafat. We have successfully built an infrastructure to consume from Kafka using AWS Lambdas. Here are some gotcha's:

Make sure to consistently batch and commit while reading when consuming.

If you are storing the batches to s3, make sure to clean your file descriptors.

If you are forwarding the batches to another service make sure to clean the variables. Variable caching in AWS Lambda might result in memory overflows.

A good idea is to check how much time you have left while from the context object in the Lambda and give yourself some wiggle room to do something with the buffer you populated in your consumer which might not be read to a file unless you call close().

We are using Apache Airflow for scheduling. I hear cloudwatch can do that too.

Title: Kafka + AWS lambda


问:
SetText in a new activity
i get a an intent with a string i a new activity, i would like to disply the string inside a TextView, i tried to declare my TextView inside the onCreate but it crash. how i can do for disply the variable "requestbuff"?

```<code>public class RequestDetail extends MainActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Intent intent = getIntent();
        String requestbuff =  intent.getExtras().getString("Requête");
        TextView details = (TextView)findViewById(R.id.detailreq);
        details.setText(requestbuff);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_req);
    }
}
</code>```

答:
This will work fine. Put setContentView at the beginning of the method so the view is created. After that you can use findViewById()  </p>

```<code>public class RequestDetail extends MainActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail_req);
    Intent intent = getIntent();
    String requestbuff =  intent.getExtras().getString("Requête");
    TextView details = (TextView)findViewById(R.id.detailreq);
    details.setText(requestbuff);
}
}
</code>```

Title: SetText in a new activity

Body:
i get a an intent with a string i a new activity, i would like to disply the string inside a TextView, i tried to declare my TextView inside the onCreate but it crash. how i can do for disply the variable "requestbuff"?

public class RequestDetail extends MainActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Intent intent = getIntent();
        String requestbuff =  intent.getExtras().getString("Requête");
        TextView details = (TextView)findViewById(R.id.detailreq);
        details.setText(requestbuff);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_req);
    }
}

Body:
This will work fine. Put setContentView at the beginning of the method so the view is created. After that you can use findViewById()

public class RequestDetail extends MainActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail_req);
    Intent intent = getIntent();
    String requestbuff =  intent.getExtras().getString("Requête");
    TextView details = (TextView)findViewById(R.id.detailreq);
    details.setText(requestbuff);
}
}


问:
Show echo in previous php file
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

```<code><input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">
</code>```

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

答:
Put this in your overview.php</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function(){
  $('.btn-danger').on('click', function(e){

    $.ajax({
      url: 'mailinfo.php',
      success: function(data, status) {
          $('body').html('<p><em>success!</em></p>');
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
      }
    }); // end ajax call
  });
</script>
</code>```

Title: Show echo in previous php file

Body:
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

<input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

Body:
Put this in your overview.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function(){
  $('.btn-danger').on('click', function(e){

    $.ajax({
      url: 'mailinfo.php',
      success: function(data, status) {
          $('body').html('<p><em>success!</em></p>');
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
      }
    }); // end ajax call
  });
</script>


问:
Cakephp 3 - Save associated belongsToMany (joinTable)
i have a question about saving a new entity with an association which is a belongsToMany relation. Just a quick introduction. I have something like a settings table and a setting_values table. The user is connected to the settings by a joinTable called users_settings. So in summary:

settings:
id | name

setting_values:
id | setting_id | name | value |

users_settings:
id | user_id | setting_id | setting_value_id

Now before the user is added I want to patch the entity of the user with all settings and the first setting_value for each setting. So that users_settings has now all settings connected to the user with the first value. But I can't get the patch or the newEntity to be work. All models are baked so this should be fine. Here's my code

```<code>$settings = $this->Settings->find('all', [
            'contain' => [
                'SettingValues'
            ]
        ]);

$settingsData = [];

foreach ($settings as $setting) {
    $settingsData[] = [
        'setting_id' => $setting->id,
        'setting_value_id' => $setting->setting_values[0]->id,
    ];
}

$data = [
    'users_settings' => $settingsData
];

$user = $this->Users->patchEntity($user, $data, [
    'associated' => [
        'Settings.UsersSettings'
    ]
]);
</code>```

This is the result in the $user entity. As you can see nothing is corretly marshaled:

```<code>users_settings => [
    (int) 0 => [
        setting_id => (int) 1,
        setting_value_id => (int) 1
    ],
    (int) 1 => [
        setting_id => (int) 2,
        setting_value_id => (int) 5
    ]
]
</code>```

Can someone give me an advice on this. Thanks

答:
That's not how belongsToMany association data should be structured, you have to supply the target, not the join table. Additional join table data can be supplied via the special _joinData key, ie the data should look like:

```<code>$data = [
    'settings' => [
        [
            'id' => 1,
            '_joinData' => [
                'setting_value_id' => 1
            ]
        ],
        [
            'id' => 2,
            '_joinData' => [
                'setting_value_id' => 5
            ]
        ]
    ]
];
</code>```

That would populate the join table like:

```<code>+----+---------+------------+------------------+
| id | user_id | setting_id | setting_value_id |
+----+---------+------------+------------------+
| 1  | 1       | 1          | 1                |
| 2  | 1       | 2          | 5                |
+----+---------+------------+------------------+
</code>```

And if you (need to) use the associated option, then make sure to specify the _joinData key too:

```<code>$user = $this->Users->patchEntity($user, $data, [
    'associated' => [
        'Settings._joinData'
    ]
]);
</code>```

See also

Cookbook > Database Access & ORM > Saving Data > Saving BelongsToMany Associations

Cookbook > Database Access & ORM > Saving Data > Saving Data To The Join Table

Body:
i have a question about saving a new entity with an association which is a belongsToMany relation. Just a quick introduction. I have something like a settings table and a setting_values table. The user is connected to the settings by a joinTable called users_settings. So in summary:

settings:
id | name

setting_values:
id | setting_id | name | value |

users_settings:
id | user_id | setting_id | setting_value_id

Now before the user is added I want to patch the entity of the user with all settings and the first setting_value for each setting. So that users_settings has now all settings connected to the user with the first value. But I can't get the patch or the newEntity to be work. All models are baked so this should be fine. Here's my code

$settings = $this->Settings->find('all', [
            'contain' => [
                'SettingValues'
            ]
        ]);

$settingsData = [];

foreach ($settings as $setting) {
    $settingsData[] = [
        'setting_id' => $setting->id,
        'setting_value_id' => $setting->setting_values[0]->id,
    ];
}

$data = [
    'users_settings' => $settingsData
];

$user = $this->Users->patchEntity($user, $data, [
    'associated' => [
        'Settings.UsersSettings'
    ]
]);

This is the result in the $user entity. As you can see nothing is corretly marshaled:

users_settings => [
    (int) 0 => [
        setting_id => (int) 1,
        setting_value_id => (int) 1
    ],
    (int) 1 => [
        setting_id => (int) 2,
        setting_value_id => (int) 5
    ]
]

Can someone give me an advice on this. Thanks

Body:
That's not how belongsToMany association data should be structured, you have to supply the target, not the join table. Additional join table data can be supplied via the special _joinData key, ie the data should look like:

$data = [
    'settings' => [
        [
            'id' => 1,
            '_joinData' => [
                'setting_value_id' => 1
            ]
        ],
        [
            'id' => 2,
            '_joinData' => [
                'setting_value_id' => 5
            ]
        ]
    ]
];

That would populate the join table like:

+----+---------+------------+------------------+
| id | user_id | setting_id | setting_value_id |
+----+---------+------------+------------------+
| 1  | 1       | 1          | 1                |
| 2  | 1       | 2          | 5                |
+----+---------+------------+------------------+

And if you (need to) use the associated option, then make sure to specify the _joinData key too:

$user = $this->Users->patchEntity($user, $data, [
    'associated' => [
        'Settings._joinData'
    ]
]);

See also

Cookbook > Database Access & ORM > Saving Data > Saving BelongsToMany Associations

Cookbook > Database Access & ORM > Saving Data > Saving Data To The Join Table


问:
How to exit function with signal on Windows?
I have the following code written in Python 2.7 on Windows. I want to check for updates for the current python script and update it, if there is an update, with a new version through ftp server preserving the filename and then executing the new python script after terminating the current through the os.kill with SIGNTERM.

I went with the exit function approach but I read that in Windows this only works with the atexit library and default python exit methods. So I used a combination of the atexit.register() and the signal handler.

```<code>***necessary libraries***

filematch = 'test.py'
version = '0.0'
checkdir = os.path.abspath(".")
dircontent = os.listdir(checkdir)
r = StringIO()

def exithandler():
    try:
        try:
            if filematch in dircontent:
                os.remove(checkdir + '\\' + filematch)
        except Exception as e:
            print e

        ftp = FTP(ip address)
        ftp.login(username, password)
        ftp.cwd('/Test')

        for filename in ftp.nlst(filematch):
            fhandle = open(filename, 'wb')
            ftp.retrbinary('RETR ' + filename, fhandle.write)
            fhandle.close()

        subprocess.Popen([sys.executable, "test.py"])
        print 'Test file successfully updated.'
    except Exception as e:
        print e

ftp = FTP(ip address)
ftp.login(username, password)
ftp.cwd('/Test')

ftp.retrbinary('RETR version.txt', r.write)

if(r.getvalue() != version):
    atexit.register(exithandler)
    somepid = os.getpid()
    signal.signal(SIGTERM, lambda signum, stack_frame: exit(1))
    os.kill(somepid, signal.SIGTERM)

print 'Successfully replaced and started the file'
</code>```

Using the:

```<code>signal.signal(SIGTERM, lambda signum, stack_frame: exit(1))
</code>```

I get:

Traceback (most recent call last):
  File "C:\Users\STiX\Desktop\Python Keylogger\test.py", line 50, in <module>
    signal.signal(SIGTERM, lambda signum, stack_frame: exit(1))
NameError: name 'SIGTERM' is not defined
```

But I get the job done without a problem except if I use the current code in a more complex script where the script give me the same error but terminates right away for some reason.

On the other hand though, if I use it the correct way, signal.SIGTERM, the process goes straight to termination and the exit function never executed. Why is that?

How can I make this work on Windows and get the outcome that I described above successfully?

答:
What you are trying to do seems a bit complicated (and dangerous from an infosec-perspective ;-). I would suggest to handle the reload-file-when-updated part of the functionality be adding a controller class that imports the python script you have now as a module and, starts it and the reloads it when it is updated (based on a function return or other technique) - look this way for inspiration - https://stackoverflow.com/a/1517072/1010991

Edit - what about exe?

Another hacky technique for manipulating the file of the currently running program would be the shell ping trick. It can be used from all programming languages. The trick is to send a shell command that is not executed before after the calling process has terminated. Use ping to cause the delay and chain the other commands with &. For your use case it could be something like this:

```<code>import subprocess
subprocess.Popen("ping -n 2 -w 2000 1.1.1.1 > Nul & del hack.py & rename hack_temp.py hack.py & hack.py ", shell=True)
</code>```

Edit 2 - Alternative solution to original question

Since python does not block write access to the currently running script an alternative concept to solve the original question would be:

```<code>import subprocess
print "hello"
a = open(__file__,"r")
running_script_as_string = a.read()
b = open(__file__,"w")
b.write(running_script_as_string)
b.write("\nprint 'updated version of hack'")
b.close()
subprocess.Popen("python hack.py")
</code>```

Body:
I have the following code written in Python 2.7 on Windows. I want to check for updates for the current python script and update it, if there is an update, with a new version through ftp server preserving the filename and then executing the new python script after terminating the current through the os.kill with SIGNTERM.

I went with the exit function approach but I read that in Windows this only works with the atexit library and default python exit methods. So I used a combination of the atexit.register() and the signal handler.

***necessary libraries***

filematch = 'test.py'
version = '0.0'
checkdir = os.path.abspath(".")
dircontent = os.listdir(checkdir)
r = StringIO()

def exithandler():
    try:
        try:
            if filematch in dircontent:
                os.remove(checkdir + '\\' + filematch)
        except Exception as e:
            print e

        ftp = FTP(ip address)
        ftp.login(username, password)
        ftp.cwd('/Test')

        for filename in ftp.nlst(filematch):
            fhandle = open(filename, 'wb')
            ftp.retrbinary('RETR ' + filename, fhandle.write)
            fhandle.close()

        subprocess.Popen([sys.executable, "test.py"])
        print 'Test file successfully updated.'
    except Exception as e:
        print e

ftp = FTP(ip address)
ftp.login(username, password)
ftp.cwd('/Test')

ftp.retrbinary('RETR version.txt', r.write)

if(r.getvalue() != version):
    atexit.register(exithandler)
    somepid = os.getpid()
    signal.signal(SIGTERM, lambda signum, stack_frame: exit(1))
    os.kill(somepid, signal.SIGTERM)

print 'Successfully replaced and started the file'

Using the:

signal.signal(SIGTERM, lambda signum, stack_frame: exit(1))

I get:

Traceback (most recent call last):
  File "C:\Users\STiX\Desktop\Python Keylogger\test.py", line 50, in <module>
    signal.signal(SIGTERM, lambda signum, stack_frame: exit(1))
NameError: name 'SIGTERM' is not defined

But I get the job done without a problem except if I use the current code in a more complex script where the script give me the same error but terminates right away for some reason.

On the other hand though, if I use it the correct way, signal.SIGTERM, the process goes straight to termination and the exit function never executed. Why is that?

How can I make this work on Windows and get the outcome that I described above successfully?

Body:
What you are trying to do seems a bit complicated (and dangerous from an infosec-perspective ;-). I would suggest to handle the reload-file-when-updated part of the functionality be adding a controller class that imports the python script you have now as a module and, starts it and the reloads it when it is updated (based on a function return or other technique) - look this way for inspiration - https://stackoverflow.com/a/1517072/1010991

Edit - what about exe?

Another hacky technique for manipulating the file of the currently running program would be the shell ping trick. It can be used from all programming languages. The trick is to send a shell command that is not executed before after the calling process has terminated. Use ping to cause the delay and chain the other commands with &. For your use case it could be something like this:

import subprocess
subprocess.Popen("ping -n 2 -w 2000 1.1.1.1 > Nul & del hack.py & rename hack_temp.py hack.py & hack.py ", shell=True)

Edit 2 - Alternative solution to original question

Since python does not block write access to the currently running script an alternative concept to solve the original question would be:

import subprocess
print "hello"
a = open(__file__,"r")
running_script_as_string = a.read()
b = open(__file__,"w")
b.write(running_script_as_string)
b.write("\nprint 'updated version of hack'")
b.close()
subprocess.Popen("python hack.py")


问:
How to deal with big numbers in javascript
I'm looking for a Mathematical solution that deals with really (long, big, huge, storms) numbers. I haven't found anything yet, But I don't wanna think that this problem hasn't be solve at this time. I'm looking for an easy Number solution, like Microsoft Excel Precision (30 decimals), or a BigInteger (Java) solution. in Javascript of course.</p>

答: There is also Silent Matt's library for Big Integers. It does not handle decimals.</p>

ContentLicense: CC BY-SA 2.5


问:
Access parent window's Grid from User Control
In my MainWindow VM i open the Views from my UserControls like this.
Usercontrol1 is the name of the View made in Xaml.
In my ViewModel of my MainWindow:

```<code>   private static Grid _myMainGrid;

    public static Grid MyMainGrid
    {
        get { return _myMainGrid; }
        set { _myMainGrid = value; }
    }

    private void OpenUserControl(UserControl myUS)
    {
        if (MyMainGrid.Children.Count > 0)
        {
            MyMainGrid.Children.RemoveAt(0);
        }
        Grid.SetColumn(myUS, 1);
        Grid.SetRow(myUS, 0);
        MyMainGrid.Children.Add(myUS);
    }
    private void FindGrid(object obj)
    {
        var myGrd = obj as Grid;
        if (myGrd != null)
        {
            MyMainGrid = myGrd;
        }
    }
</code>```

The command binding to the Button executes this.

```<code>private void ExecuteCMD_OpenUserControl1(object obj)
    {
        FindGrid(obj);
        Usercontrol1 _ucItem = new Usercontrol1();
        OpenUserControl(_ucItem);
    }
</code>```

Now i want to open Usercontrol2 replacing Usercontrol1 in MyMainGrid from my MainWindow by pressing a button in Usercontrol1. So i have to access the parent Window.

Tried using this methode but can't get it to work in my case.

答:
Let's say you have two children; it's trivial to generalize this to any number of children. Fortunately you've already got viewmodels and views, so we're most of the way there. It's just a matter of wiring it all together in a way that works well with WPF.

Here's a set of skeletal viewmodels. Main, and two children. MainViewModel creates its two child instances. ChildOneViewModel has a Next button command, bound to a Button in ChildOneView.xaml.

When the user clicks that button, we want to switch the active view to child two. Rather than have dependencies going in all directions, ChildOneViewModel is ignorant of what "next" really means; its parent, MainViewModel, is in charge of that. Everybody knows about his children; you've found that in programming, making a class know about its siblings or its parent creates problems.

So all ChildOneViewModel does is expose an event so MainViewModel knows when the button is clicked, and can take any action it likes when that happens. This is cool because what if we could be going to one of two different "next" pages, depending on what the user did in ChildOne? If we move that responsibility to the parent, everything becomes simpler. Easier to write, easier to reuse in a different context.

```<code>#region MainViewModel Class
public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        ChildOne = new ChildOneViewModel();
        ChildTwo = new ChildTwoViewModel();

        ActiveChild = ChildOne;

        ChildOne.NextButtonClicked += (s, e) => ActiveChild = ChildTwo;
    }

    #region ActiveChild Property
    private INotifyPropertyChanged _activeChild = default(INotifyPropertyChanged);
    public INotifyPropertyChanged ActiveChild
    {
        get { return _activeChild; }
        set
        {
            if (value != _activeChild)
            {
                _activeChild = value;
                OnPropertyChanged();
            }
        }
    }
    #endregion ActiveChild Property

    public ChildOneViewModel ChildOne { get; private set; }
    public ChildTwoViewModel ChildTwo { get; private set; }
}
#endregion MainViewModel Class

#region ChildOneViewModel Class
public class ChildOneViewModel : ViewModelBase
{
    public event EventHandler NextButtonClicked;

    //  You already know how to implement a command, so I'll skip that.
    protected void NextButtonCommandMethod()
    {
        NextButtonClicked?.Invoke(this, EventArgs.Empty);
    }
}
#endregion ChildOneViewModel Class

#region ChildTwoViewModel Class
public class ChildTwoViewModel : ViewModelBase
{
}
#endregion ChildTwoViewModel Class
</code>```

And here's the XAML that translates all of that into actual UI at runtime:

```<code><Window.Resources>
    <!--
    These are "implicit datatemplates": They have no x:Key, so they'll be
    automatically used to display any content of the specified types.
    -->
    <DataTemplate DataType="{x:Type local:ChildOneViewModel}">
        <local:ChildOneView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type local:ChildTwoViewModel}">
        <local:ChildTwoView />
    </DataTemplate>
</Window.Resources>
<Grid>

    <!-- other stuff -->
    <UserControl
        Content="{Binding ActiveChild}"
        />
    <!-- other stuff -->
</code>```

You don't need OpenUserControl(), FindGrid(), any of that stuff.

Body:
In my MainWindow VM i open the Views from my UserControls like this.
Usercontrol1 is the name of the View made in Xaml.
In my ViewModel of my MainWindow:

   private static Grid _myMainGrid;

    public static Grid MyMainGrid
    {
        get { return _myMainGrid; }
        set { _myMainGrid = value; }
    }

    private void OpenUserControl(UserControl myUS)
    {
        if (MyMainGrid.Children.Count > 0)
        {
            MyMainGrid.Children.RemoveAt(0);
        }
        Grid.SetColumn(myUS, 1);
        Grid.SetRow(myUS, 0);
        MyMainGrid.Children.Add(myUS);
    }
    private void FindGrid(object obj)
    {
        var myGrd = obj as Grid;
        if (myGrd != null)
        {
            MyMainGrid = myGrd;
        }
    }

The command binding to the Button executes this.

private void ExecuteCMD_OpenUserControl1(object obj)
    {
        FindGrid(obj);
        Usercontrol1 _ucItem = new Usercontrol1();
        OpenUserControl(_ucItem);
    }

Now i want to open Usercontrol2 replacing Usercontrol1 in MyMainGrid from my MainWindow by pressing a button in Usercontrol1. So i have to access the parent Window.

Tried using this methode but can't get it to work in my case.

Body:
Let's say you have two children; it's trivial to generalize this to any number of children. Fortunately you've already got viewmodels and views, so we're most of the way there. It's just a matter of wiring it all together in a way that works well with WPF.

Here's a set of skeletal viewmodels. Main, and two children. MainViewModel creates its two child instances. ChildOneViewModel has a Next button command, bound to a Button in ChildOneView.xaml.

When the user clicks that button, we want to switch the active view to child two. Rather than have dependencies going in all directions, ChildOneViewModel is ignorant of what "next" really means; its parent, MainViewModel, is in charge of that. Everybody knows about his children; you've found that in programming, making a class know about its siblings or its parent creates problems.

So all ChildOneViewModel does is expose an event so MainViewModel knows when the button is clicked, and can take any action it likes when that happens. This is cool because what if we could be going to one of two different "next" pages, depending on what the user did in ChildOne? If we move that responsibility to the parent, everything becomes simpler. Easier to write, easier to reuse in a different context.

#region MainViewModel Class
public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        ChildOne = new ChildOneViewModel();
        ChildTwo = new ChildTwoViewModel();

        ActiveChild = ChildOne;

        ChildOne.NextButtonClicked += (s, e) => ActiveChild = ChildTwo;
    }

    #region ActiveChild Property
    private INotifyPropertyChanged _activeChild = default(INotifyPropertyChanged);
    public INotifyPropertyChanged ActiveChild
    {
        get { return _activeChild; }
        set
        {
            if (value != _activeChild)
            {
                _activeChild = value;
                OnPropertyChanged();
            }
        }
    }
    #endregion ActiveChild Property

    public ChildOneViewModel ChildOne { get; private set; }
    public ChildTwoViewModel ChildTwo { get; private set; }
}
#endregion MainViewModel Class

#region ChildOneViewModel Class
public class ChildOneViewModel : ViewModelBase
{
    public event EventHandler NextButtonClicked;

    //  You already know how to implement a command, so I'll skip that.
    protected void NextButtonCommandMethod()
    {
        NextButtonClicked?.Invoke(this, EventArgs.Empty);
    }
}
#endregion ChildOneViewModel Class

#region ChildTwoViewModel Class
public class ChildTwoViewModel : ViewModelBase
{
}
#endregion ChildTwoViewModel Class

And here's the XAML that translates all of that into actual UI at runtime:

<Window.Resources>
    <!--
    These are "implicit datatemplates": They have no x:Key, so they'll be
    automatically used to display any content of the specified types.
    -->
    <DataTemplate DataType="{x:Type local:ChildOneViewModel}">
        <local:ChildOneView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type local:ChildTwoViewModel}">
        <local:ChildTwoView />
    </DataTemplate>
</Window.Resources>
<Grid>

    <!-- other stuff -->
    <UserControl
        Content="{Binding ActiveChild}"
        />
    <!-- other stuff -->

You don't need OpenUserControl(), FindGrid(), any of that stuff.


问:
Name for pattern T | Array<T>
A common pattern that libraries use is accepting a type or an array of that type as an argument to a function. For example:

```<code>interface JQuery {
    add(selector: HTMLElement | HTMLElement[]): this;
}
</code>```

Is there a name for this pattern? I'd like to alias it to improve readability. My first guess is TypeOrArray<T> but this sounds clunky and may potentially be unintuitive.

Note: I've tagged this typescript since that's what I'm using and something idiomatic may be a better answer. However, this should apply to any language that makes use of generics.

答:
That syntax is typescript's way of allowing you to define multiple types for a single parameter.

In your case the selector can be either an HTMLElement or an Array of HTMLElement.

The same you can do for any type:

function example(parameter: number | string) {

}

example(5) // works

example('2') // works

example(new Date()) // fails
```

Title: Name for pattern T | Array<T>

Body:
A common pattern that libraries use is accepting a type or an array of that type as an argument to a function. For example:

interface JQuery {
    add(selector: HTMLElement | HTMLElement[]): this;
}

Is there a name for this pattern? I'd like to alias it to improve readability. My first guess is TypeOrArray<T> but this sounds clunky and may potentially be unintuitive.

Note: I've tagged this typescript since that's what I'm using and something idiomatic may be a better answer. However, this should apply to any language that makes use of generics.


问:
count colored dots in image
First of all, sorry if this topic already exists (I think this is a common task, but couldn't find anything).

The point, is that I have an image who shows different dots of different colors. And I need an script to count how many red, green and yellow dots are.
The colors are pure red(ff0000), green(00ff00) and yellow(ffff00). Which makes this easier, and the shape is well defined.

My current approach is to select the round(dot) shape, select them and then once I have all dots away from background image, read its color to count them...

The point is that I'm so lost with this. I know that this can be done with OpenCV but don't know how (and couldn't find any nice tutorial).

Any idea?

答:
Since you already know the colors you are looking for, I would segment the image based on color. The steps I would follow are:

```<code>red_dot_count = 0
yellow_dot_count = 0
green_dot_count = 0
For each pixel in the image:
   if pixel color is red:
       floodfill using this pixel as seed pixel and target_color as black
       red_dot_count++
   if pixel color is green:
       floodfill using this pixel as seed pixel and target_color as black
       green_dot_count++
   if pixel is yellow:
       floodfill using this pixel as seed pixel and target_color as black
       yellow_dot_count++
</code>```

Your image would have to be a PNG image though as @Mark pointed out.

Also, this assumes that the colors in the red, green and yellow dots do not appear anywhere else in the image.

Title: count colored dots in image

Body:
Since you already know the colors you are looking for, I would segment the image based on color. The steps I would follow are:

red_dot_count = 0
yellow_dot_count = 0
green_dot_count = 0
For each pixel in the image:
   if pixel color is red:
       floodfill using this pixel as seed pixel and target_color as black
       red_dot_count++
   if pixel color is green:
       floodfill using this pixel as seed pixel and target_color as black
       green_dot_count++
   if pixel is yellow:
       floodfill using this pixel as seed pixel and target_color as black
       yellow_dot_count++

Your image would have to be a PNG image though as @Mark pointed out.

Also, this assumes that the colors in the red, green and yellow dots do not appear anywhere else in the image.


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
As the others indicate, letting end-users do this is not a good idea.  I suspect the requirement isn't really that the user really needs ad-hoc SQL, but rather a way to get and update data in ways not initially forseen. To allow queries, do as Joel suggests and keep a "read only" database, but use a reporting application such as Microsoft Reporting Services or Data Dynamics Active reports to allow users to design and run ad-hoc reports.  Both I believe have ways to present users with a filtered view on "their" data.

For the updates, it is more tricky- I don't know of existing tools to do this.  One option may be to design your application so that developers can quickly write plugins to expose new forms for updating data.  The plugin would need to expose a UI form, code for checking that the current user can execute it, and code for executing it.  Your application would load all plugins and expose the forms that a user has access to.

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: Daniel


问:
How to code the 2 lines, 4 buttons and white background in this Email only using HTML
Today I tried to practice, and use HTML to code a simple email design. But until now I have a few questions not clearly, please see the image sample, so may I ask some help:

The middle white background. How to code this part use HTML?

The two pink lines, I tried use
 for this, but I don't know why the color won't change and the middle space which from first line to image top is not correct, so is there any other way to code the line?

The 4 buttons, how to HTML the 4 buttons?  The image sample button pink background looks like use as a shape?

I know these can used CSS to reach the effect but currently want all things ONLY done in HTML, is this possible based on this sample?

Please let me know if any guy who know how to solve these problems.

答:
HTML:

```<code><head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
 <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
  <div class="mainDiv">
    <div class="lines"></div>
    <div class="title">MEMORIAL DAY</div>
    <div class="title2">SALE</div>
    <div class="lines"></div>
    <div class="text1">stock up blah blah</div>
    <div class="row">
      <div class="sm-col margin">
      <button type="button" class="btn btn-info">but1</button>
      <button type="button" class="btn btn-info">but2</button>
      </div>
        <div class="row">
      <div class="sm-col">
      <button type="button" class="btn btn-info">but1</button>
      <button type="button" class="btn btn-info">but2</button>
      </div>
    </div>
  </div>
</code>```

You need css to do the margins by the way. Really recommend Using it.
CSS:

```<code>.mainDiv {
  background-color: white;
  width: 350px;
  height: 500px;
  display: inline-block;
  text-align: center;
}

.lines {
  margin-top: 50px;
  display: inline-block;
  text-align: center;
  margin-bottom: 10px;
  height: 6px;
  width: 200px;
  background-color: pink;
}

.title {
  color: black;
  font-size: 25px;
}

.title2 {
  color: black;
  font-size: 60px;
}

.text1{
  font-size:17;
}
.margin{
  margin-bottom:30px;
}
</code>```

LINK TO JSFIDDLE :)))

Body:
HTML:

<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
 <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
  <div class="mainDiv">
    <div class="lines"></div>
    <div class="title">MEMORIAL DAY</div>
    <div class="title2">SALE</div>
    <div class="lines"></div>
    <div class="text1">stock up blah blah</div>
    <div class="row">
      <div class="sm-col margin">
      <button type="button" class="btn btn-info">but1</button>
      <button type="button" class="btn btn-info">but2</button>
      </div>
        <div class="row">
      <div class="sm-col">
      <button type="button" class="btn btn-info">but1</button>
      <button type="button" class="btn btn-info">but2</button>
      </div>
    </div>
  </div>

You need css to do the margins by the way. Really recommend Using it.
CSS:

.mainDiv {
  background-color: white;
  width: 350px;
  height: 500px;
  display: inline-block;
  text-align: center;
}

.lines {
  margin-top: 50px;
  display: inline-block;
  text-align: center;
  margin-bottom: 10px;
  height: 6px;
  width: 200px;
  background-color: pink;
}

.title {
  color: black;
  font-size: 25px;
}

.title2 {
  color: black;
  font-size: 60px;
}

.text1{
  font-size:17;
}
.margin{
  margin-bottom:30px;
}

LINK TO JSFIDDLE :)))


问:
In Xcode using Swift, how can one make a press on, release off, button?
How can one program a button that executes a set of commands when it is pressed and then stops the execution when it is released in Xcode? For example: when the button is pressed a light is turned on and when it is released the light turns off.</p>

答:
It is pretty simple using IBActions/Targets:

```<code>let btn = UIButton()
btn.addTarget(self, action: #selector(self.on(_:)), for: .touchDown)
btn.addTarget(self, action: #selector(self.off(_:)), for: .touchUpInside)
</code>```

You could also use storyboards to give the same effect

```<code>@IBAction func on(_ sender: UIButton?) -> Void {}
@IBAction func off(_ sender: UIButton?) -> Void {}
</code>```

Then when connecting your actions, connect on() for your onTouchDown and off() for your onTouchUpInside, etc..

Body:
It is pretty simple using IBActions/Targets:

let btn = UIButton()
btn.addTarget(self, action: #selector(self.on(_:)), for: .touchDown)
btn.addTarget(self, action: #selector(self.off(_:)), for: .touchUpInside)

You could also use storyboards to give the same effect

@IBAction func on(_ sender: UIButton?) -> Void {}
@IBAction func off(_ sender: UIButton?) -> Void {}

Then when connecting your actions, connect on() for your onTouchDown and off() for your onTouchUpInside, etc..


问:
How to Load config from ~/.aws/config
change log says
Load config from ~/.aws/config if AWS_SDK_LOAD_CONFIG is set.
Couldn't find any examples or documentation regarding how to load the config. Any help!

答:
There is documentation for this:

HERE: Loading Node Credentials Shared

HERE: Loading Node Credentials JSON File

HERE: Getting Started NodeJS

I would recommend installing the awscli tool to set this up and then run aws configure in your terminal. By default, anything you're running on your local host will assume the credentials listed in your config file unless specified to assume a different profile.

Example from the first link:

```<code>AWS.config.credentials = new AWS.SharedIniFileCredentials( { profile: 'work-account' } );
</code>```

If you are using the CLI to run your script:

```<code>AWS_PROFILE=work-account node script.js
</code>```

If you are using just the CLI tool and not JavaScript:

```<code>aws s3 ls --profile work-account
</code>```

Update:

config and credentials are made and referenced at the same time. When you run aws configure it makes two files. The credentials file containing AccessKey and SecretKey - and the config file containing the response type and region. It is NOT necessary to explicitly define or reference the config file.

Title: How to Load config from ~/.aws/config

Body:
There is documentation for this:

HERE: Loading Node Credentials Shared

HERE: Loading Node Credentials JSON File

HERE: Getting Started NodeJS

I would recommend installing the awscli tool to set this up and then run aws configure in your terminal. By default, anything you're running on your local host will assume the credentials listed in your config file unless specified to assume a different profile.

Example from the first link:

AWS.config.credentials = new AWS.SharedIniFileCredentials( { profile: 'work-account' } );

If you are using the CLI to run your script:

AWS_PROFILE=work-account node script.js

If you are using just the CLI tool and not JavaScript:

aws s3 ls --profile work-account

Update:

config and credentials are made and referenced at the same time. When you run aws configure it makes two files. The credentials file containing AccessKey and SecretKey - and the config file containing the response type and region. It is NOT necessary to explicitly define or reference the config file.


问:
how to get title of of row selected in UITableview
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

but how can i get that title of that row ?

thanks in advance

regards

答:
Assuming you're using a standard UITableViewCell, you can get the cell by using

```<code>UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
</code>```

then access the text property view properties via:

```<code>cell.textLabel.text
cell.detailTextLabel.text
</code>```

Body:
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

but how can i get that title of that row ?

thanks in advance

regards

Body:
Assuming you're using a standard UITableViewCell, you can get the cell by using

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

then access the text property view properties via:

cell.textLabel.text
cell.detailTextLabel.text


问:
Xamarin iOS UiPickerView tutorial
I'm trying to find just some basic instructions on using UiPickerView in Xamarin iOS. There are questions here on Stack Overflow that answer certain questions, but I'm looking for just a simple overview and hopefully walk-through of adding the UiPickerView to a ViewController, wiring up the data, and registering events. As a noob to Xamarin and iOS, I'm struggling to catalogue all the places the code for this type of control need to go.</p>

答:
I created a blog post to cover the basics of a UIPickerView. It can be confusing, basic idea:

Add the UIPickerView to your storyboard etc, give it a name.

Create a class that extends from UIPickerViewModel

Set the model of the picker, pickerExample.Model = new YourListPicker(YourList);

Title: Xamarin iOS UiPickerView tutorial


问:
Why this SFINAE snippet is not working in g++, but working in MSVC?
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

```<code>template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}
</code>```

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

```<code>In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'
</code>```

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

答:
This has absolutely nothing to do with whether default template arguments are part of a function template's signature.

The real problem is that T is a class template parameter, and when you instantiate the class template's definition, the implementation can immediately substitute it into your default template argument, decltype(std::declval<T>().size()) outside of template argument deduction, which causes a hard error if size is not present.

The fix is simple; simply make it depend on a parameter of the function template.

```<code>template <typename U, typename = decltype(std::declval<U>().size())>
static std::true_type check(U);
</code>```

(There are other problems with your implementation, such as it requires a move-constructible non-abstract T and doesn't require size() to be const-callable, but they aren't the cause of the error you are seeing.)

Body:
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same
::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

Body:
This has absolutely nothing to do with whether default template arguments are part of a function template's signature.

The real problem is that T is a class template parameter, and when you instantiate the class template's definition, the implementation can immediately substitute it into your default template argument, decltype(std::declval<T>().size()) outside of template argument deduction, which causes a hard error if size is not present.

The fix is simple; simply make it depend on a parameter of the function template.

template <typename U, typename = decltype(std::declval<U>().size())>
static std::true_type check(U);

(There are other problems with your implementation, such as it requires a move-constructible non-abstract T and doesn't require size() to be const-callable, but they aren't the cause of the error you are seeing.)


问:
Does `git diff` distinguish the part added into branch2 and the part removed from branch1?
When comparing the tip commits of two branches by git diff branch_1..branch_2,

does the output distinguish the part added into branch2 and the part removed from branch1?

does the output distinguish the part removed from branch2 and the part added  into branch1?

If not, is there some way to distinguish?

Thanks.

答:
There isn't really any notion of "removed from" or "added to" at this level (unlike git merge).  Git is merely comparing the two commits' files directly.

Given git diff branch_1..branch_2, Git first simply removes the .., leaving git diff branch_1 branch_2.  (This is different from almost every other Git command: the special treatment of .. in git diff is exclusive to git diff.)  Now that there are just two branch names or other commit specifiers, Git translates them to tree hash IDs, as if with:

```<code>git rev-parse branch_1^{tree}
</code>```

and:

```<code>git rev-parse branch_2^{tree}
</code>```

By this point, all notion of "branching" is gone entirely: all Git has, and needs, is the two trees.  It then compares the two trees, finding files with the same names and/or contents (depending on flags such as -M and -B), and then does an individualized diff of each file-pair (unless that's suppressed, e.g., --name-only or --name-status).

Body:
There isn't really any notion of "removed from" or "added to" at this level (unlike git merge).  Git is merely comparing the two commits' files directly.

Given git diff branch_1..branch_2, Git first simply removes the .., leaving git diff branch_1 branch_2.  (This is different from almost every other Git command: the special treatment of .. in git diff is exclusive to git diff.)  Now that there are just two branch names or other commit specifiers, Git translates them to tree hash IDs, as if with:

git rev-parse branch_1^{tree}

and:

git rev-parse branch_2^{tree}

By this point, all notion of "branching" is gone entirely: all Git has, and needs, is the two trees.  It then compares the two trees, finding files with the same names and/or contents (depending on flags such as -M and -B), and then does an individualized diff of each file-pair (unless that's suppressed, e.g., --name-only or --name-status).


问:
Printing square boxes in crystal report
Please guide me to print boxes like this in crystal reportReport.</p>

答:
It depends on the data you're displaying. If you want just boxes of consecutive numbers, maybe you can just create a bunch of text-boxes with solid borders and type the numbers in them. Crystal reports may not be the best tool for that.

If you want to display data in columns and rows, that would be a Cross-tab report.

Title: Printing square boxes in crystal report


问:
How to remove the top and bottom space on textview of Android
When I include the below XML to layout file, I can see the below image. If you see it, you could realize that the TextView has top and bottom space.

```<code><TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E1"
android:background="#ff00ff00"/>
</code>```

I wish to remove the space. How to remove it? What is it called?
If anyone has clue.. please let me know. Thanks in advance.

答: My way for fixing this is pretty hacky, but I managed to get the text to sit where I wanted by setting the height of the text view as static and fiddling with it until it just barely fit the text. In my case, the font style I was using had a height of 64sp so I set the height of my textview to 50sp and it worked okay. I also had to set foreground_gravity to bottom. </p>

Body:
When I include the below XML to layout file, I can see the below image. If you see it, you could realize that the TextView has top and bottom space.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E1"
android:background="#ff00ff00"/>

I wish to remove the space. How to remove it? What is it called?
If anyone has clue.. please let me know. Thanks in advance.


问:
Which PHP version is currently running 5.2.15 or 5.3.4?

           i often read official PHP website website.

on 9 Dec,2010 headlines was   PHP 5.2.15 Released! and

on 10 Dec,2010 headlines was  PHP 5.3.4 Released!

i m really confused that what means of two different headlines??
i think version order are may b wrong or what is this??please explain PHP GURU

please tell me what should i said when interviewer ask which version of php we works currently??

ONE MORE THING

so which version we need to use for safeside, is that 5.3.x or 5.2.x???

答: These are minor versions, some people need some  bug fixed but don't want to step to another major version.</p>


问:
LibGDX GUI Texture Packer won't open
I downloaded the LibGDX texture packer from here: https://github.com/crashinvaders/gdx-texture-packer-gui

but I can't figure out how to open it. I ran the gradlew and it said build successful but how do I open it? This isn't the command line version, but the GUI version but there's no jar to run.

答:
Download build of gdx-texture-packer-gui and run in your system.

If you're Window user you can download .exe file else if you're Mac user download .dmg file.

Title: LibGDX GUI Texture Packer won't open


问:
Height and width are not scaling while using SVG <use> tag
I am trying to achieve an opacity slider of width:250 and height:32, but the width and height are not scaling.I can achieve this easily in innerSVG, but as I might be using it in many places, with varied width, height and fill color as well, I need to do this using  tag. Can you help me out? This is my code:

```<code> <svg style='width:0px;height:0px'>
          <defs>
            <mask id='zcolorslider-mask'>
              <linearGradient id=zcolorslider-maskgrad x1='0' y1='0' x2='1' y2='0'>
                <stop offset='0' stop-color='#000000'> </stop>
                <stop offset='1' stop-color='#ffffff'> </stop>
              </linearGradient>
              <rect width=32 height=32 fill='url(#zcolorslider-maskgrad)'></rect>
            </mask>
          </defs>
          <g id='zcolorslider-opacitybar'>
            <rect width=32 height=32 fill=blue mask=url(#zcolorslider-mask)></rect>
          </g>
        </svg>

        <div class='colorslider'>
          <svg width=100% height=100% fill=pink viewBox='0 0 32 32'>
            <use width=100% height=100% xlink:href='#zcolorslider-opacitybar' />
          </svg>
        </div>
</code>```

Working url : colorslider

答:
Write your .colorslider like this:

```<code>    <div class='colorslider'>
      <svg width="100%" height="100%"
           viewBox="0 0 32 32" preserveAspectRatio="none">
        <use xlink:href='#zcolorslider-opacitybar' />
      </svg>
    </div>
</code>```

Take care to write valid html - use quotes around attribute values.

preserveAspectRatio governs the way your grafic is rendered inside the viewport. It has a default value of "xMidYMid meet", which means that the largest grafic that fits into the viewport without distorting the widht/height ratio is painted into the middle. You have to override it to scale your image unevenly.

Body:
I am trying to achieve an opacity slider of width:250 and height:32, but the width and height are not scaling.I can achieve this easily in innerSVG, but as I might be using it in many places, with varied width, height and fill color as well, I need to do this using  tag. Can you help me out? This is my code:

 <svg style='width:0px;height:0px'>
          <defs>
            <mask id='zcolorslider-mask'>
              <linearGradient id=zcolorslider-maskgrad x1='0' y1='0' x2='1' y2='0'>
                <stop offset='0' stop-color='#000000'> </stop>
                <stop offset='1' stop-color='#ffffff'> </stop>
              </linearGradient>
              <rect width=32 height=32 fill='url(#zcolorslider-maskgrad)'></rect>
            </mask>
          </defs>
          <g id='zcolorslider-opacitybar'>
            <rect width=32 height=32 fill=blue mask=url(#zcolorslider-mask)></rect>
          </g>
        </svg>

          <svg width=100% height=100% fill=pink viewBox='0 0 32 32'>
            <use width=100% height=100% xlink:href='#zcolorslider-opacitybar' />
          </svg>

Working url : colorslider

Body:
Write your .colorslider like this:

    <div class='colorslider'>
      <svg width="100%" height="100%"
           viewBox="0 0 32 32" preserveAspectRatio="none">
        <use xlink:href='#zcolorslider-opacitybar' />
      </svg>
    </div>

Take care to write valid html - use quotes around attribute values.

preserveAspectRatio governs the way your grafic is rendered inside the viewport. It has a default value of "xMidYMid meet", which means that the largest grafic that fits into the viewport without distorting the widht/height ratio is painted into the middle. You have to override it to scale your image unevenly.


问:
How can we use the helper from another app's module in Symfony1.4?
How can we use the helper from another app's module in Symfony1.4?

I want to reuse the same helper class without duplicating content.

答:
The easiest and recommended way would be moving this helper out of the apps, to the project lib/helper directory.

You can also use the fact that $moduleName parameter is not really validated nor escaped in sfApplicationConfiguration::getHelperDirs(), however moving it looks much cleaner than this dirty workaround:

```<code>sfContext::getInstance()->getConfiguration()->loadHelpers(['Test'], '../../other_app/modules/other_module');
</code>```

Body:
The easiest and recommended way would be moving this helper out of the apps, to the project lib/helper directory.

You can also use the fact that $moduleName parameter is not really validated nor escaped in sfApplicationConfiguration::getHelperDirs(), however moving it looks much cleaner than this dirty workaround:

sfContext::getInstance()->getConfiguration()->loadHelpers(['Test'], '../../other_app/modules/other_module');


问:
Adding SSL to Apache Server
We got our SSL certificate today, I'm trying to add the SSL certificate to the domain so that we can access the website through https however I'm running into problems.

We have an apache server running on windows.

The configuration works perfectly for port 80 however when I add port 443 to the config everything stops working.

The error I get when starting apache is

```<code>The requested operation has failed.
</code>```

I have added the following line

```<code>Listen 443
</code>```

below the line:

```<code>Listen 80
</code>```

I have added the following VirtualHost config

```<code><VirtualHost _default_:443>

    DocumentRoot "c:/path/to/website"

    ServerName example.com
    ServerAlias example.com www.example.com

    SSLEngine on

    SSLCertificateFile "c:/path/to/cert/cert.crt"

    SSLCertificateKeyFile "c:/path/to/cert/key.key"

    SSLCACertificateFile "c:/path/to/cert/bundle.ca-bundle"

</VirtualHost>
</code>```

However whenever I start the apache server after adding this, it doesn't start and I get an error.

I have commented out pieces of code and have narrowed the issue down to the Listen 443 line. Is there something I am not taking into consideration when adding this?

These are the last 3 lines in the error.log

```<code>[Thu Jun 08 18:15:31.909142 2017] [mpm_winnt:notice] [pid 66428:tid 712] AH00422: Parent: Received shutdown signal -- Shutting down the server.
[Thu Jun 08 18:15:47.209776 2017] [mpm_winnt:notice] [pid 67332:tid 620] AH00364: Child: All worker threads have exited.
[Thu Jun 08 18:15:48.067933 2017] [mpm_winnt:notice] [pid 66428:tid 712] AH00430: Parent: Child process exited successfully.
</code>```

Edit

This is the response from running httpd.exe -e debug

```<code>(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address [::]:443
(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address 0.0.0.0:443
AH00451: no listening sockets available, shutting down
AH00015: Unable to open logs
</code>```

答:
I don't know how your httpd.conf file looks like, maybe you deleted/changed accidentaly some value.

The very first thing you need to do is to restore your httpd.conf file and start the service without the SSL configuration. Once it works you can proceed with this steps:

In a new file separate all your SSL settings, maybe a new file called httpd-ssl.conf is a good name.

After that, at the end of your main httpd.conf add this lines to include the new file:

```<code># Secure (SSL/TLS) connections
Include conf/httpd-ssl.conf
</code>```

This as good practice to avoid changing/deleting accidentally something in the main config and limitate the source of possible errors, you'll know any error will be related to the new file included.

Your new conf/httpd-ssl.conf should look something like this (standard setup):

```<code># HTTPS port
Listen 443

<VirtualHost _default_:443>

#   General setup for the virtual host
DocumentRoot "C:/your_httpd_path/htdocs"
ServerName www.example.com:443
ServerAdmin admin@example.com
ErrorLog "C:/your_httpd_path/logs/error.log"
TransferLog "C:/your_httpd_path/logs/access.log"

#   SSL Engine Switch:
SSLEngine on

#   Server Certificates:

SSLCertificateFile "c:/path/to/cert/cert.crt"
SSLCertificateKeyFile "c:/path/to/cert/key.key"
SSLCACertificateFile "c:/path/to/cert/bundle.ca-bundle"

<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>

<Directory "C:/your_httpd_path/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

CustomLog "C:/your_httpd_path/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>
</code>```

Have you tried using httpd.exe -e debug? maybe we can find something useful in this mode.

UPDATE: Aha! you got an error! It could be a duplicated line somewhere with 443.

Could you check your files in notepad++ and search all the coincidences that match "443"? probably you already had 443 configured and you tried adding it again? You only need to have one line with:

```<code>Listen 443
</code>```

Or maybe already running in that port? Check with:

```<code>netstat -na | findstr "443"
</code>```

If you have something like:

```<code>TCP    [::]:443               [::]:0                 LISTENING
</code>```

Then something else is running on your 443 port. Anyway, you can change your httpd conf and set any other port like 4443 i.e. or kill the process which is taking 443 now.

Title: Adding SSL to Apache Server

Body:
We got our SSL certificate today, I'm trying to add the SSL certificate to the domain so that we can access the website through https however I'm running into problems.

We have an apache server running on windows.

The configuration works perfectly for port 80 however when I add port 443 to the config everything stops working.

The error I get when starting apache is

The requested operation has failed.

I have added the following line

Listen 443

below the line:

Listen 80

I have added the following VirtualHost config

<VirtualHost _default_:443>

    DocumentRoot "c:/path/to/website"

    ServerName example.com
    ServerAlias example.com www.example.com

    SSLEngine on

    SSLCertificateFile "c:/path/to/cert/cert.crt"

    SSLCertificateKeyFile "c:/path/to/cert/key.key"

    SSLCACertificateFile "c:/path/to/cert/bundle.ca-bundle"

</VirtualHost>

However whenever I start the apache server after adding this, it doesn't start and I get an error.

I have commented out pieces of code and have narrowed the issue down to the Listen 443 line. Is there something I am not taking into consideration when adding this?

These are the last 3 lines in the error.log

[Thu Jun 08 18:15:31.909142 2017] [mpm_winnt:notice] [pid 66428:tid 712] AH00422: Parent: Received shutdown signal -- Shutting down the server.
[Thu Jun 08 18:15:47.209776 2017] [mpm_winnt:notice] [pid 67332:tid 620] AH00364: Child: All worker threads have exited.
[Thu Jun 08 18:15:48.067933 2017] [mpm_winnt:notice] [pid 66428:tid 712] AH00430: Parent: Child process exited successfully.

Edit

This is the response from running httpd.exe -e debug

(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address [::]:443
(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address 0.0.0.0:443
AH00451: no listening sockets available, shutting down
AH00015: Unable to open logs

Body:
I don't know how your httpd.conf file looks like, maybe you deleted/changed accidentaly some value.

The very first thing you need to do is to restore your httpd.conf file and start the service without the SSL configuration. Once it works you can proceed with this steps:

In a new file separate all your SSL settings, maybe a new file called httpd-ssl.conf is a good name.

After that, at the end of your main httpd.conf add this lines to include the new file:

# Secure (SSL/TLS) connections
Include conf/httpd-ssl.conf

This as good practice to avoid changing/deleting accidentally something in the main config and limitate the source of possible errors, you'll know any error will be related to the new file included.

Your new conf/httpd-ssl.conf should look something like this (standard setup):

# HTTPS port
Listen 443

<VirtualHost _default_:443>

#   General setup for the virtual host
DocumentRoot "C:/your_httpd_path/htdocs"
ServerName www.example.com:443
ServerAdmin admin@example.com
ErrorLog "C:/your_httpd_path/logs/error.log"
TransferLog "C:/your_httpd_path/logs/access.log"

#   SSL Engine Switch:
SSLEngine on

#   Server Certificates:

SSLCertificateFile "c:/path/to/cert/cert.crt"
SSLCertificateKeyFile "c:/path/to/cert/key.key"
SSLCACertificateFile "c:/path/to/cert/bundle.ca-bundle"

<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>

<Directory "C:/your_httpd_path/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

CustomLog "C:/your_httpd_path/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>

Have you tried using httpd.exe -e debug? maybe we can find something useful in this mode.

UPDATE: Aha! you got an error! It could be a duplicated line somewhere with 443.

Could you check your files in notepad++ and search all the coincidences that match "443"? probably you already had 443 configured and you tried adding it again? You only need to have one line with:

Listen 443

Or maybe already running in that port? Check with:

netstat -na | findstr "443"

If you have something like:

TCP    [::]:443               [::]:0                 LISTENING

Then something else is running on your 443 port. Anyway, you can change your httpd conf and set any other port like 4443 i.e. or kill the process which is taking 443 now.


问:
Proper way to require libs in multiple files
I have two files - one with main code execution, and other just has a class in it.

For example:

File_1:

```<code>const _ = require('underscore'),
CoolClass = require('CoolClass');

_.map(//something)
</code>```

Files_2:

```<code>const _ = require('underscore');

class CoolClass(){
  constructor(){
    _.map(//something);
  }
}
</code>```

What's the proper way to require a library?

Should I require it in both files our should just require it in the main one and just pass it to constructor like:

```<code>let cool_stuff = new CoolClass(_);
</code>```

Or should I pass it when I require it, so:

```<code>const _ = require('underscore')(_);
</code>```

Thanks!

答:
Yes. In Node, you'd always include it in each file independent of one another.

The loading library (whether Node's native require or something else) will usually cache the module to avoid actually reloading it multiple times from the file system.

You do this so you have a variable that references the library in each file.

You can technically do your second option, but you usually only do that if you have to import and then initialize in some way an object from that library, then you'd pass the initialized object.

Something like underscore which is just import-and-use, you would just require in each.

Body:
I have two files - one with main code execution, and other just has a class in it.

For example:

File_1:

const _ = require('underscore'),
CoolClass = require('CoolClass');

_.map(//something)

Files_2:

const _ = require('underscore');

class CoolClass(){
  constructor(){
    _.map(//something);
  }
}

What's the proper way to require a library?

Should I require it in both files our should just require it in the main one and just pass it to constructor like:

let cool_stuff = new CoolClass(_);

Or should I pass it when I require it, so:

const _ = require('underscore')(_);

Thanks!


问:
-timestamp in Django
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

```<code>class Meta:
    ordering = ('-timestamp',)
</code>```

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

答:
You would have to present some more code, for example how you retrieve data from database. Here you have some ordering examples:

http://www.djangoproject.com/documentation/models/ordering/

Title: -timestamp in Django

Body:
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

class Meta:
    ordering = ('-timestamp',)

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.


答:
Your main issue is that you are adding many individual lines.  For the code to work the way you envision, you somehow have to add your shape as a single line.  To do this, change your sub from this:

```<code>Sub ArrayLoop(array1, array2, amountOfLine)
   Dim i As Long

   For i = 0 To amountOfLine
      With ActivePresentation.Slides(1).Shapes.AddLine(BeginX:=array1(i), BeginY:=array2(i), EndX:=array1(i + 1), EndY:=array2(i + 1)).Line
         .DashStyle = msoLineDashDotDot
         .ForeColor.RGB = RGB(50, 0, 128)
      End With
   Next
End Sub
</code>```

to this:

```<code>Sub ArrayLoop(array1, array2)
   'you will need a single array of points for the call.
   'whether you want to pass in 2 arrays and then merge them
   'or pass in a single merged array is up to you

   With ActivePresentation.Slides(1).Shapes.AddPolyline(<an array of points>).Line
      .DashStyle = msoLineDashDotDot
      .ForeColor.RGB = RGB(50, 0, 128)
   End With
End Sub
</code>```

You will need to tweak your array of points to get this to work.

Title: Merge a custom figure in powerpoint

Body:
I have custom that creates of map of the US in powerpoint.

Sub ArrayLoop(array1, array2, amountOfLine)

 Dim i As Long
 For i = 0 To amountOfLine
 With ActivePresentation.Slides(1).Shapes.AddLine(BeginX:=array1(i), BeginY:=array2(i), EndX:=array1(i + 1), EndY:=array2(i + 1)).Line
  .DashStyle = msoLineDashDotDot
  .ForeColor.RGB = RGB(50, 0, 128)
 End With
Next
End Sub

Sub TestArrayLoop()

 Dim USA1, USA2
 Dim amount As Integer

 USA1 = Array(316.0954, 321.021, 332.9831, 337.205, 337.205, 346.4698,
351.3953, 354.9135, 361.9501, 367.5793, 370.394, 371.8012, 374.6158, 376.7268,
375.3195, 376.7268, 383.0596, 385.1706, 378.8377, 376.0232, 378.1341,
378.8377, 368.9866, 364.061, 366.172, 371.0976, 373.9122, 382.356, 388.6888,
393.6144, 397.1327, 394.318, 393.6144, _
384.4669, 384.4669, 376.7268, 374.6158, 369.6902, 368.2829, 366.172,
366.172,
361.9501, 358.4318, 354.9135, 350.6917, 347.8771, 347.8771, 347.8771,
347.1734, 346.4698, 350.6917, 343.6551, 345.0624, 342.2478, 339.4332,
337.9087,
330.8721, 317.5027, 314.6881, 312.5772, 310.4662, 316.0954, 319.6137,
323.132, 325.2429, 327.3539, 328.7612, 335.7977, 339.4332, 337.205,
338.7296,
335.7977, 331.5757, 330.1685, 325.9465, 324.5393, 322.4283, 319.6137,
318.2064, 315.3918, 313.9845, 309.7626, 306.2443, 306.2443, 311.1698,
311.8735,
308.3553, 306.2443, 303.4297, 302.0224, 297.0969, 290.0603, 285.8384, 279.5055, 280.2092, 280.9128, 278.8019, 275.2836, 267.5435, 264.0252, 265.4325,
260.5069, 254.8777, 247.1376, 242.212, 237.2865, 223.917, 220.3988, 214.7696, 211.2513, 206.9121, 206.9121, 214.0659, 219.6951, 227.4353, 232.3609,
231.6572, 233.7682, 239.3974, 247.1376, 247.8412, 309.0589, 316.0954)

 USA2 = Array(247.1064, 248.5467, 254.3079, 263.6699, 267.9909, 265.1102, 260.7893, 260.0691, 258.6288, 251.4273, 252.1475, 259.349, 257.1885, 257.9087,
 260.0691, 262.9498, 257.9087, 255.028, 254.3079, 249.987, 247.8265, 244.9459, 247.1064, 251.4273, 246.3862, 243.5056, 240.625, 241.3451, 240.625,
 237.0242, 234.1435, 226.942, 223.3412, 218.3002, 215.4195, 200.2962, 206.7776, 208.218, 206.7776, 206.7776, 196.5754, 195.8553, 190.8142, 191.5343,
 190.094, 190.8142, 194.415, 198.1357, 206.0575, 208.9381, 217.58, 224.0613, 234.8637, 237.0242, 235.5839, 222.621, 221.9009, 213.9792, 213.9792, 207.4978,
 205.3373, 187.9335, 184.3327, 182.1723, 182.1723, 174.9708, 169.2095,
 167.7692, _
 164.8886, 158.4072, 154.0862, 150.4854, 149.7653, 156.9669, 163.4483, 155.5265, 152.6459, 156.2467, 152.6459, 147.6049, 141.1235, 133.9219, 144.0041,
147.6049, 151.9258, 156.2467, 159.8475, 158.4072, 158.4072, 162.0079, 160.5676, 160.5676, 157.687, 159.1273, 161.2878, 165.6087, 164.8886, 160.5676,
162.0079, 159.1273, 156.2467, 154.8064, 151.9258, 149.7653, 151.2056, 145.4444, 151.9258, 155.5265, 154.0862, 150.4854, 149.0452, 200.2962, 203.897,
201.0164, 215.4195, 219.0203, 224.7815, 229.1024, 237.0242, 242.0653, 245.6661, 245.6661, 247.1064)

 amount = UBound(USA1) - LBound(USA2) + 1
 amount = amount - 2
 ArrayLoop USA1, USA2, amount
 End Sub

This all works fine but the thing is that now I cant select the whole figure. So im looking for a way so I merge in it a figure which I can drag around the screen.

Any thoughts on how I can do this? Preferably in VBA

Body:
Your main issue is that you are adding many individual lines.  For the code to work the way you envision, you somehow have to add your shape as a single line.  To do this, change your sub from this:

Sub ArrayLoop(array1, array2, amountOfLine)
   Dim i As Long

   For i = 0 To amountOfLine
      With ActivePresentation.Slides(1).Shapes.AddLine(BeginX:=array1(i), BeginY:=array2(i), EndX:=array1(i + 1), EndY:=array2(i + 1)).Line
         .DashStyle = msoLineDashDotDot
         .ForeColor.RGB = RGB(50, 0, 128)
      End With
   Next
End Sub

to this:

Sub ArrayLoop(array1, array2)
   'you will need a single array of points for the call.
   'whether you want to pass in 2 arrays and then merge them
   'or pass in a single merged array is up to you

   With ActivePresentation.Slides(1).Shapes.AddPolyline(<an array of points>).Line
      .DashStyle = msoLineDashDotDot
      .ForeColor.RGB = RGB(50, 0, 128)
   End With
End Sub

You will need to tweak your array of points to get this to work.


答: You have two nested loops one with 10 and another with 16 iterations,so you got 160 lines printed</p>

Title: printf printing more lines in the for loop

Body:
I am having problem with an encryption algorithm in C, I'm encoding an AES criptography, I'm debugging one function, and this function is printing more lines than the for loop count. Below the entire code:

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

int main()
{
    unsigned char key[]   = {
                              0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                              0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
                             };

                              unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

    const unsigned char sbox[256] =
    {
//0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
        0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0
        0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1
        0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2
        0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3
        0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4
        0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5
        0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6
        0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7
        0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8
        0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9
        0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A
        0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B
        0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C
        0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D
        0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E
        0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
    }; //F

    const unsigned char Rcon[10] = {
    0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};

    unsigned char buf1, buf2, buf3, buf4, round, i;
    unsigned char rcon;

      for (round = 0; round < 10; round++){
    //add key + sbox
    for (i = 0; i <16; i++){
      state[i]=sbox[state[i] ^ key[i]];
    }
    for (i = 0; i<16; i++){
      printf("\n%d",state[i]);
    }
  }
}

The print function (as shown above):

   for (round = 0; round < 10; round++){
        //add key + sbox
        for (i = 0; i <16; i++){
          state[i]=sbox[state[i] ^ key[i]];
        }
        for (i = 0; i<16; i++){
          printf("\n%d",state[i]);
        }
      }

The output:

99
202
183
4
9
83
208
81
205
96
224
231
186
112
225
140
251
31
213
197
215
177
246
177
166
249
135
206
78
255
223
236
15
114
14
180
102
141
140
78
228
140
93
166
44
137
62
17
118
143
254
169
170
196
126
59
206
151
91
149
183
95
4
114
56
25
176
172
228
120
188
235
180
11
209
11
234
0
103
255
7
173
55
121
225
255
244
206
101
119
185
99
142
215
249
140
197
145
150
218
217
45
137
221
60
243
109
69
19
87
104
236
166
96
34
53
193
52
115
87
24
45
133
47
192
190
51
17
36
239
183
5
166
199
157
83
202
54
115
54
75
109
39
114
54
40
213
111
58
37
20
32
37
117
182
39
160
208
165
255

Someone knows what is happening?


问:
Why does Django think my query string is empty?
I've been having trouble with a query string in one of my views in Django. I've successfully handled query strings in other views, so I'm not sure what I did wrong here. I stripped things down to a really basic view, and I'm still not getting anything.

My URL:

localhost/query_view/?foo=foo
```

<p>My template:</p>

<pre class="lang-html prettyprint-override"><code><html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <p>{{ query_string }}</p>
    </body>
</html>
</code>```

My view:

def query_view(request):
    query_string = request.META['QUERY_STRING']
    return render(request, 'query_view.html', {'query_string': query_string})
```

I should expect foo=foo to be displayed on the page, right? Currently, I'm getting nothing.

Edit: Django version 1.9.4, Python version 3.4.3

答: I would put a debugger before the return to see what's actually in the request. But usually something like request.GET.get('foo') would get you what you want. Also, you can provide a default value if foo is actually empty. request.GET.get('foo', 'blah')

Body:
I've been having trouble with a query string in one of my views in Django. I've successfully handled query strings in other views, so I'm not sure what I did wrong here. I stripped things down to a really basic view, and I'm still not getting anything.

My URL:

localhost/query_view/?foo=foo

My template:

        <title>Title</title>

{{ query_string }}

My view:

def query_view(request):
    query_string = request.META['QUERY_STRING']
    return render(request, 'query_view.html', {'query_string': query_string})

I should expect foo=foo to be displayed on the page, right? Currently, I'm getting nothing.

Edit: Django version 1.9.4, Python version 3.4.3


问:
Extracting keywords from relevant topics using a trained MALLET Topic model
I'm attempting to use MALLET's TopicInferencer to infer keywords from arbitrary text using a trained model. So far my overall approach is as follows.

Train a ParallelTopicModel with a large set of known training data to create a collection of topics. I'm currently using a training file with 250,000 lines to create 5,000 topics.

Create an InstanceList from arbitrary text not in the trained model.

Use the trained model's topicInferencer.getSampledDistribution to generate a topic distribution of the unknown text against the model.

Sort the returned distribution and extract the IDs of the top n topics that closets match the unknown input text.

Extract the top keywords from each of the matching topics.

My code is as follows:

Generating the ParallelTopicModel

```<code>InstanceList instanceList = new InstanceList(makeSerialPipeList());
instanceList.addThruPipe(new SimpleFileLineIterator(trainingFile)); //training file with one entry per line (around 250,000 lines)

//should train a model with the end result being 5000 topics each with a collection of words
ParallelTopicModel parallelTopicModel = new ParallelTopicModel(
    5000, //number of topics, I think with a large sample size we should want a large collection of topics
    1.0D, //todo: alphaSum, really not sure what this does
    0.01D //todo: beta, really not sure what this does
);
parallelTopicModel.setOptimizeInterval(20); //todo: read about this
parallelTopicModel.addInstances(instanceList);
parallelTopicModel.setNumIterations(2000);
parallelTopicModel.estimate();
</code>```

My first group of questions are related to creating the ParallelTopicModel.

Since I'm using a fairly large training file I assume I want a large number of topics. My logic here is that the large the count of topics the more closely inferred keywords will match arbitrary input text.

I'm also unsure how the alphaSum beta value and number of iterations will affect the generated model.

On the other side I'm using the ParallelTopicModel to create an inferred topic distribution.

```<code>TopicInferencer topicInferencer = parallelTopicModel.getInferencer();
String document = //arbitrary text not in trained model
//following the format I found in SimpleFileLineIterator to create an Instance out of a document
Instance instance = new Instance(document, null, new URI("array:" + 1), null);
InstanceList instanceList = new InstanceList(serialPipes); //same SerialPipes used to create the InstanceList used for the ParallelTopicModel
instanceList.addThruPipe(instance);

//this should return the array of topicIDs and the match value
//[topicId] = 0.5 //match value
double[] topicDistribution =
topicInferencer.getSampledDistribution(instanceList.get(0), //extract text
    2000, //same iteration count used in the model
     1, //todo: thinning, not sure what this does
     5 //todo: burnIn, not sure what this does
);

//returns a sorted list of the top 5 topic IDs
//this should be the index of the largest values in the returned topicDistribution
List<Integer> topIndexes = topIndexes(topicDistribution, 5); //top 5 topic indexes

//list topics and sorted keywords
ArrayList<TreeSet<IDSorter>> sortedWords = parallelTopicModel.getSortedWords();

//loop over the top indexes
topIndexes.forEach(index -> {
    IDSorter idSorter = sortedWords.get(index).first(); //should hopefully be the first keyword in each topic
    //not sure what alphabet I should use here or if it really matters?
    //I passed in the alphabet from the original instance list as well as the one contained on our model
    Object result = parallelTopicModel.getAlphabet().lookupObject(idSorter.getID());
    double weight = idSorter.getWeight();

    String formattedResult = String.format("%s:%.0f", result, weight);
    //I should now have a relevant keyword and a weight in my result
});
</code>```

I have a similar set of questions here, first I'm not entirely sure if this overall approach is event correct.

I'm also not sure what Alphabet I should be using, the one from my InstanceList used to generate the ParallelTopicModel or the one obtained directly from the ParallelTopicModel.

I know this is a fairly involved question but any insight would be greatly appreciated!

答:
alphaSum and beta: These control how concentrated you want your estimated doc-topic and topic-word distributions. Smaller values encourage more concentrated distributions, and less movement. Larger values encourage flatter, more uniform distributions, with more movement. In physics terms, think "high energy" vs. "low energy".

1.0 for alphaSum is on the low end, 5.0 might be safer. 0.01 for beta is almost always fine. It doesn't matter a lot because you're using hyperparameter optimization (setOptimizeInterval). This will fit the alpha values based on the topics estimated. You might also want to set the burn-in period to something smaller than the default, like 25. This is the number of sweeps through the data before you start optimizing.

Number of topics: 5000 is a lot even for 250k text segments. I'd start with 500. With hyperparameter optimization you will get a few large, general topics and lots of small, specific topics. My guess is that with 5000 topics a large number of them -- at least half -- will be essentially empty. That's good in one way, because it means the model is adaptively choosing its topic limit. But it will also mean that you have topics with very little data support that will look like random words. It will also cause problems at inference time: if the model sees a document that doesn't really fit any "real" topic it can put it into an empty topic.

Inference: 2000 iterations is way too much for inferring topic distributions for new documents. 10 should be enough. Sampling topics for one document given a fixed, already-learned model is much easier than learning a model from scratch. The resulting distribution is the average over several sampling states. It will ignore burnin states at the beginning, and skip thinning states between saved samples after that.

The alphabet shouldn't matter. You can assume that the same id will result in the same string. If the training alphabet and the testing alphabet aren't compatible, inference wouldn't work.

Body:
I'm attempting to use MALLET's TopicInferencer to infer keywords from arbitrary text using a trained model. So far my overall approach is as follows.

Train a ParallelTopicModel with a large set of known training data to create a collection of topics. I'm currently using a training file with 250,000 lines to create 5,000 topics.

Create an InstanceList from arbitrary text not in the trained model.

Use the trained model's topicInferencer.getSampledDistribution to generate a topic distribution of the unknown text against the model.

Sort the returned distribution and extract the IDs of the top n topics that closets match the unknown input text.

Extract the top keywords from each of the matching topics.

My code is as follows:

Generating the ParallelTopicModel

InstanceList instanceList = new InstanceList(makeSerialPipeList());
instanceList.addThruPipe(new SimpleFileLineIterator(trainingFile)); //training file with one entry per line (around 250,000 lines)

//should train a model with the end result being 5000 topics each with a collection of words
ParallelTopicModel parallelTopicModel = new ParallelTopicModel(
    5000, //number of topics, I think with a large sample size we should want a large collection of topics
    1.0D, //todo: alphaSum, really not sure what this does
    0.01D //todo: beta, really not sure what this does
);
parallelTopicModel.setOptimizeInterval(20); //todo: read about this
parallelTopicModel.addInstances(instanceList);
parallelTopicModel.setNumIterations(2000);
parallelTopicModel.estimate();

My first group of questions are related to creating the ParallelTopicModel.

Since I'm using a fairly large training file I assume I want a large number of topics. My logic here is that the large the count of topics the more closely inferred keywords will match arbitrary input text.

I'm also unsure how the alphaSum beta value and number of iterations will affect the generated model.

On the other side I'm using the ParallelTopicModel to create an inferred topic distribution.

TopicInferencer topicInferencer = parallelTopicModel.getInferencer();
String document = //arbitrary text not in trained model
//following the format I found in SimpleFileLineIterator to create an Instance out of a document
Instance instance = new Instance(document, null, new URI("array:" + 1), null);
InstanceList instanceList = new InstanceList(serialPipes); //same SerialPipes used to create the InstanceList used for the ParallelTopicModel
instanceList.addThruPipe(instance);

//this should return the array of topicIDs and the match value
//[topicId] = 0.5 //match value
double[] topicDistribution =
topicInferencer.getSampledDistribution(instanceList.get(0), //extract text
    2000, //same iteration count used in the model
     1, //todo: thinning, not sure what this does
     5 //todo: burnIn, not sure what this does
);

//returns a sorted list of the top 5 topic IDs
//this should be the index of the largest values in the returned topicDistribution
List<Integer> topIndexes = topIndexes(topicDistribution, 5); //top 5 topic indexes

//list topics and sorted keywords
ArrayList<TreeSet<IDSorter>> sortedWords = parallelTopicModel.getSortedWords();

//loop over the top indexes
topIndexes.forEach(index -> {
    IDSorter idSorter = sortedWords.get(index).first(); //should hopefully be the first keyword in each topic
    //not sure what alphabet I should use here or if it really matters?
    //I passed in the alphabet from the original instance list as well as the one contained on our model
    Object result = parallelTopicModel.getAlphabet().lookupObject(idSorter.getID());
    double weight = idSorter.getWeight();

    String formattedResult = String.format("%s:%.0f", result, weight);
    //I should now have a relevant keyword and a weight in my result
});

I have a similar set of questions here, first I'm not entirely sure if this overall approach is event correct.

I'm also not sure what Alphabet I should be using, the one from my InstanceList used to generate the ParallelTopicModel or the one obtained directly from the ParallelTopicModel.

I know this is a fairly involved question but any insight would be greatly appreciated!