问:
cordova-plugin-inappbrowser not opening links from APP to IOS Device default Browser
Search a lot, but not able to find the correct solution.

```<code>I am trying to open links from my app to default browser of my IOS device,
</code>```

but its not working. Its perfectly working with my android device.

My plugin is installed properly, ( i can see that in cordova plugin list on my app)

followed are the syntaxes, which i have tried:

window.open(this.href, '_system');

window.open(this.href, '_blank', {closebuttoncaption: 'Close', toolbar: 'yes', 'location=yes'});

window.open(this.href, '_blank', {closebuttoncaption: 'Close', toolbar: 'yes'});

window.open(this.href, '_system', 'location=yes')

same solution with cordova.InAppBrowser.open, this as starting syntax.

along with that tried with controller function also

link

$scope.openInExternalBrowser = function (path) {

var options = "closebuttoncaption=Close,toolbar=yes";
  if($ionicPlatform.is('ios') == true){

```<code>window.open(path, '_blank', {'closebuttoncaption': 'Close', 'toolbar':'yes', 'location=yes'});
</code>```

}else{
window.open(path, '_system', 'location=yes');
  }
}

So looking for some proper solution, which will work.

Thanks & Regards,

Sopo

答:
I simply use this for my project and confirm it's work</p>

```<code>cordova.InAppBrowser.open('https://google.com','_self')
</code>```

Body:
Search a lot, but not able to find the correct solution.

I am trying to open links from my app to default browser of my IOS device,

but its not working. Its perfectly working with my android device.

My plugin is installed properly, ( i can see that in cordova plugin list on my app)

followed are the syntaxes, which i have tried:

window.open(this.href, '_system');

window.open(this.href, '_blank', {closebuttoncaption: 'Close', toolbar: 'yes', 'location=yes'});

window.open(this.href, '_blank', {closebuttoncaption: 'Close', toolbar: 'yes'});

window.open(this.href, '_system', 'location=yes')

same solution with cordova.InAppBrowser.open, this as starting syntax.

along with that tried with controller function also

link

$scope.openInExternalBrowser = function (path) {

var options = "closebuttoncaption=Close,toolbar=yes";
  if($ionicPlatform.is('ios') == true){

window.open(path, '_blank', {'closebuttoncaption': 'Close', 'toolbar':'yes', 'location=yes'});

}else{
window.open(path, '_system', 'location=yes');
  }
}

So looking for some proper solution, which will work.

Thanks & Regards,

Sopo

Body:
I simply use this for my project and confirm it's work

cordova.InAppBrowser.open('https://google.com','_self')


来源: stackexchange

问:
UnsatisfiedLinkError - Unable to load library - Native library not found in resource path
I have the following error at runtime, while trying to run Tess4J:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302': Native library (win32-x86-64/libtesseract302.dll) not found in resource path ([myproject/target/classes/, ...some jars...])
</code>```

My questions are:

1) What exactly it tries to find and where?

2) Why is it apparently searches for myproject/target/classes/ directory? I set it nowhere.

3) Why is it ignores "native directory path" I set for tess4j.jar in user library descripto in Eclipse? My DLLs are there. If it didn't ignore the path, it would find DLLs.

4) Why is it apparently prepending DLL name with win32-x86-64/? I set this nowhere. Is this standard prefix of some API?

5) What is "resource path"? How to set it?

答:
A few days ago I ran into the same error message when trying to load a C++ DLL with JNA. It turned out that the cause was a missing DLL that my DLL depended on.

In my case it was the MS Visual Studio 2012 redistributable, which I then downloaded and installed on the machine and the problem was gone. Try using Dependency Walker to find any missing libraries and install them.

ContentLicense: CC BY-SA 3.0

Body:
I have the following error at runtime, while trying to run Tess4J:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302': Native library (win32-x86-64/libtesseract302.dll) not found in resource path ([myproject/target/classes/, ...some jars...])

My questions are:

1) What exactly it tries to find and where?

2) Why is it apparently searches for myproject/target/classes/ directory? I set it nowhere.

3) Why is it ignores "native directory path" I set for tess4j.jar in user library descripto in Eclipse? My DLLs are there. If it didn't ignore the path, it would find DLLs.

4) Why is it apparently prepending DLL name with win32-x86-64/? I set this nowhere. Is this standard prefix of some API?

5) What is "resource path"? How to set it?


问:
Jerky animation with jquery accordion, don't understand why
I'm using a number of jQueryUI accordions on a single page inside of AnythingSlider. It used to be that it was pretty smooth, but has gotten jerky.

Now, instead inserting a bunch of code, how about I just give the link and you can look. If it works fine for you, then, well, I just don't know. Of course, if there's more you'd like to have, let me know.

Click here

答: Seems to work fin, smooth and all.</p>

ContentLicense: CC BY-SA 2.5

Body: Seems to work fin, smooth and all.


问:
Unhandled content type error
Code to get Gson string:

```<code>String data = Jsoup.connect("http://localhost:9000/GetJson").get().data();
</code>```

"HTML" content from host:9000/GetJson :

```<code>{"Backend":"{\"onlineGames\":{},\"games\":{}}"}
</code>```

And I go this error message:

```<code>Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml
</code>```

Can somebody please show me where I were wrong :(

Thank you very much.

答:
```<code>    Document doc = Jsoup.connect(url).ignoreContentType(true).get();
</code>```

Title: Unhandled content type error

Body:
Code to get Gson string:

String data = Jsoup.connect("http://localhost:9000/GetJson").get().data();

"HTML" content from host:9000/GetJson :

{"Backend":"{\"onlineGames\":{},\"games\":{}}"}

And I go this error message:

Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml

Can somebody please show me where I were wrong :(

Thank you very much.


问:
Frequency of sequences in many files
Suppose that you have 50 files (in the same folder), and each one contains the character ">" at the beginning of your search. Like the examples:

```<code>File1.txt
>organism1
>organism2
>organism3
>organism4
>organism5

File2.txt
>organism3
>organism4
>organism5
>organism6
</code>```

My intention is to count the frequency of each organism in each file and generate a table.
At the moment I count each one file-by-file to generate the table:

```<code>Table 1.
          Frequency
organism1  1
organism2  1
organism3  2
organism4  2
organism5  2
organism6  1
</code>```

Until now, I can list all file in the folder but can't open them to make what I want.

```<code>    import sys
    from Bio import SeqIO
    import glob, os

    os.chdir(sys.argv[1])

    file_list = []

    for file in glob.glob("*.faa"):
            if file not in file_list:
                    file_list.append(file) # until here, perfect

for f in file_list:
        infile = open(f, 'r')
        fasta = SeqIO.parse(infile, 'fasta')
        seq = fasta.description  #.split("|")[2]
        print seq
</code>```

The problem is when I try to open the files in file_list.

```<code><generator object parse at 0x7f76867c7a00>
<generator object parse at 0x7f76867c7a50>
<generator object parse at 0x7f76867c7a00>
<generator object parse at 0x7f76867c7a50>
</code>```

答:
You're using SeqIO.parse() as if it were SeqIO.read() which won't work.  SeqIO.parse() returns a generator since it produces multiple results from the file:

```<code>import sys
import glob
import os
from Bio import SeqIO

os.chdir(sys.argv[1])

file_list = []

for file in glob.glob("*.faa"):
    if file not in file_list:
        file_list.append(file)

for file_name in file_list:
    for fasta in SeqIO.parse(file_name, 'fasta'):
        description = fasta.description
        print(description)
</code>```

This works in my environment, Python 3.6.0; Biopython 1.69.  In my environment, your code generates the error:

```<code>AttributeError: 'generator' object has no attribute 'description'
</code>```

instead of producing any output.  I see you're running Python 2.7 but which Biopython?

Why are you filtering duplicates from the result of your glob()?

Title: Frequency of sequences in many files

Body:
Suppose that you have 50 files (in the same folder), and each one contains the character ">" at the beginning of your search. Like the examples:

File1.txt
>organism1
>organism2
>organism3
>organism4
>organism5

File2.txt
>organism3
>organism4
>organism5
>organism6

My intention is to count the frequency of each organism in each file and generate a table.
At the moment I count each one file-by-file to generate the table:

Table 1.
          Frequency
organism1  1
organism2  1
organism3  2
organism4  2
organism5  2
organism6  1

Until now, I can list all file in the folder but can't open them to make what I want.

    import sys
    from Bio import SeqIO
    import glob, os

    os.chdir(sys.argv[1])

    file_list = []

    for file in glob.glob("*.faa"):
            if file not in file_list:
                    file_list.append(file) # until here, perfect

for f in file_list:
        infile = open(f, 'r')
        fasta = SeqIO.parse(infile, 'fasta')
        seq = fasta.description  #.split("|")[2]
        print seq

The problem is when I try to open the files in file_list.

<generator object parse at 0x7f76867c7a00>
<generator object parse at 0x7f76867c7a50>
<generator object parse at 0x7f76867c7a00>
<generator object parse at 0x7f76867c7a50>

Body:
You're using SeqIO.parse() as if it were SeqIO.read() which won't work.  SeqIO.parse() returns a generator since it produces multiple results from the file:

import sys
import glob
import os
from Bio import SeqIO

os.chdir(sys.argv[1])

file_list = []

for file in glob.glob("*.faa"):
    if file not in file_list:
        file_list.append(file)

for file_name in file_list:
    for fasta in SeqIO.parse(file_name, 'fasta'):
        description = fasta.description
        print(description)

This works in my environment, Python 3.6.0; Biopython 1.69.  In my environment, your code generates the error:

AttributeError: 'generator' object has no attribute 'description'

instead of producing any output.  I see you're running Python 2.7 but which Biopython?

Why are you filtering duplicates from the result of your glob()?


问:
My script is using .encode('utf-8') a lot. I feel like im doing something wrong
The problem i have with this script is that i have to keep calling .encode('utf-8') and this doesn't seem very zen to me. I must be doing something wrong.

```<code># -*- coding: utf-8 -*-

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

print save_file('http://stackoverflow.com/feeds', 'index.html')
</code>```

PS. If i remove any of them the script will break.

I tried putting # -*- coding: utf-8 -*- at the top of the file but that didn't fix it. i got this error.

```<code>C:\Python27>python rss2html.py
  File "rss2html.py", line 40
    save_file('http://stackoverflow.com/feeds', 'index.html')
            ^
SyntaxError: invalid syntax

C:\Python27>python rss2html.py
Traceback (most recent call last):
  File "rss2html.py", line 40, in <module>
    save_file('http://stackoverflow.com/feeds', 'index.html')
  File "rss2html.py", line 38, in save_file
    file_object.write(convert_feed(url=url))
  File "rss2html.py", line 32, in convert_feed
    print >> out, entry2html(title=title, link=link, description=description)
  File "rss2html.py", line 22, in entry2html
    return template.format(title=title, link=link, description=description)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 172: ordinal not in range(128)
</code>```

答:
So here is the newest version of the script no more flatten_unicode_keys(d)
no more StringIO and no more for loops I think this is way more pythonic then the past versions. Its also faster.

```<code># -*- coding: utf-8 -*-
"""Simple RSS to HTML converter."""

__version__ = "0.0.2"
__author__ = "Ricky L Wilson"

from bs4 import BeautifulSoup
from feedparser import parse as parse_feed

TEMPLATE = u"""
<h2 class='title'>{title}</h2>
<a class='link' href='{link}'>{title}</a>
<span class='description'>{summary}</span>
"""

def entry_to_html(**kwargs):
    """Formats feedparser entry."""
    return TEMPLATE.format(**kwargs).encode('utf-8')

def convert_feed(url):
    """Main loop."""
    html_fragments = [entry_to_html(**entry) for entry in parse_feed(url).entries]
    return BeautifulSoup("\n".join(html_fragments), 'lxml').prettify()

def save_file(url, filename):
    """Saves data to disc."""
    with open(filename, 'w') as file_object:
        file_object.write(convert_feed(url).encode('utf-8'))

if __name__ == '__main__':
    save_file('http://stackoverflow.com/feeds', 'index.html')
    with open('index.html') as fobj:
        print fobj.read()
</code>```

Body:
The problem i have with this script is that i have to keep calling .encode('utf-8') and this doesn't seem very zen to me. I must be doing something wrong.

# -*- coding: utf-8 -*-

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """

{title}

    {title}
    {description}
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

print save_file('http://stackoverflow.com/feeds', 'index.html')

PS. If i remove any of them the script will break.

I tried putting # -*- coding: utf-8 -*- at the top of the file but that didn't fix it. i got this error.

C:\Python27>python rss2html.py
  File "rss2html.py", line 40
    save_file('http://stackoverflow.com/feeds', 'index.html')
            ^
SyntaxError: invalid syntax

C:\Python27>python rss2html.py
Traceback (most recent call last):
  File "rss2html.py", line 40, in <module>
    save_file('http://stackoverflow.com/feeds', 'index.html')
  File "rss2html.py", line 38, in save_file
    file_object.write(convert_feed(url=url))
  File "rss2html.py", line 32, in convert_feed
    print >> out, entry2html(title=title, link=link, description=description)
  File "rss2html.py", line 22, in entry2html
    return template.format(title=title, link=link, description=description)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 172: ordinal not in range(128)

Body:
So here is the newest version of the script no more flatten_unicode_keys(d)
no more StringIO and no more for loops I think this is way more pythonic then the past versions. Its also faster.

# -*- coding: utf-8 -*-
"""Simple RSS to HTML converter."""

__version__ = "0.0.2"
__author__ = "Ricky L Wilson"

from bs4 import BeautifulSoup
from feedparser import parse as parse_feed

TEMPLATE = u"""
<h2 class='title'>{title}</h2>
<a class='link' href='{link}'>{title}</a>
<span class='description'>{summary}</span>
"""

def entry_to_html(**kwargs):
    """Formats feedparser entry."""
    return TEMPLATE.format(**kwargs).encode('utf-8')

def convert_feed(url):
    """Main loop."""
    html_fragments = [entry_to_html(**entry) for entry in parse_feed(url).entries]
    return BeautifulSoup("\n".join(html_fragments), 'lxml').prettify()

def save_file(url, filename):
    """Saves data to disc."""
    with open(filename, 'w') as file_object:
        file_object.write(convert_feed(url).encode('utf-8'))

if __name__ == '__main__':
    save_file('http://stackoverflow.com/feeds', 'index.html')
    with open('index.html') as fobj:
        print fobj.read()


问:
AlarmManager wouldn't wake up the phone
There is a code which supposed to trigger an action at a specified precise time using the AlarmManager (the next day at 7:00am):

```<code>val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, FooIntentService::class.java)
val pendingIntent = PendingIntent.getService(this, 0, intent, 0)

// Set alarm
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 0)

// Set tomorrow
calendar.add(Calendar.DATE, 1)

manager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
</code>```

I have tested this code to trigger event in up to 5 minutes from now, closing the app (close all apps) and putting it on sleep (pressing Hold button) - and it works. Yet when I set the time for tomorrow at 7:00am (which is way more then 5 minutes from now) - it would never trigger, until I have unblocked it (woke up manually). At the moment I woke it up - the action triggered right away.

Question: is the example code I have provided correct for setting planned event in my case?

答:
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

From documentation

Basically, the alarm is intended not exact to minimize wakeups and battery use. You can replace set with setExact then it should work as you required.

```<code>manager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent);
</code>```

Title: AlarmManager wouldn't wake up the phone

Body:
There is a code which supposed to trigger an action at a specified precise time using the AlarmManager (the next day at 7:00am):

val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, FooIntentService::class.java)
val pendingIntent = PendingIntent.getService(this, 0, intent, 0)

// Set alarm
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 0)

// Set tomorrow
calendar.add(Calendar.DATE, 1)

manager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

I have tested this code to trigger event in up to 5 minutes from now, closing the app (close all apps) and putting it on sleep (pressing Hold button) - and it works. Yet when I set the time for tomorrow at 7:00am (which is way more then 5 minutes from now) - it would never trigger, until I have unblocked it (woke up manually). At the moment I woke it up - the action triggered right away.

Question: is the example code I have provided correct for setting planned event in my case?

Body:
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

From documentation

Basically, the alarm is intended not exact to minimize wakeups and battery use. You can replace set with setExact then it should work as you required.

manager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent);


问:
Registry key Error: Java version has value '1.8', but '1.7' is required
While running

```<code>sencha app build production
</code>```

I am getting the following error:

Error: Registry key 'Software\JavaSoft\Java Runtime
  Environment'\CurrentVersion'

has value '1.8', but '1.7' is required. Error: could not find java.dll
  Error: Could not find Java SE Runtime Environment.

java -version , command is showing following:

java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)

Not able to find where path is going wrong. Any idea?

----------------------- EDIT ------------------------------------------------

Note: I am using Windows 7 (64 bit).

I have tried uninstalling the sencha touch cmd and reinstalling. But still same error.

I have uninstalled all the java version instances and reinstalled the latest one, Still the problem persist.

答:
Just Install Java SE Runtime Environment JRE 7 !

Now you see "java 7" & "java 8" in "Programs and Features" in the "Control Panel"

It worked for me.

Body:
While running

sencha app build production

I am getting the following error:

Error: Registry key 'Software\JavaSoft\Java Runtime
  Environment'\CurrentVersion'

has value '1.8', but '1.7' is required. Error: could not find java.dll
  Error: Could not find Java SE Runtime Environment.

java -version , command is showing following:

java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)

Not able to find where path is going wrong. Any idea?

----------------------- EDIT ------------------------------------------------

Note: I am using Windows 7 (64 bit).

I have tried uninstalling the sencha touch cmd and reinstalling. But still same error.

I have uninstalled all the java version instances and reinstalled the latest one, Still the problem persist.


问:
What is the most common waste of computing power in Javascript?
We've all seen people who do this:

```<code>jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}
</code>```

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

答:
You'll also see this:

```<code>$('#this').find('a').doSomeThing();
</code>```

Know what's a lot more efficient?  One selector that covers both will server you better...

```<code>$('#this a').doSomeThing();
</code>```

It seems obvious, but you'll see it all the time.

Body:
We've all seen people who do this:

jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

Body:
You'll also see this:

$('#this').find('a').doSomeThing();

Know what's a lot more efficient?  One selector that covers both will server you better...

$('#this a').doSomeThing();

It seems obvious, but you'll see it all the time.


问:
How Make Form Input With Auto Tag HTML

How to make form input like above? is it plugin? how to add to my own website?
i want every user make enter, the component auto add tag

答:
You can use something like TinyMCE

https://www.tinymce.com/
Docs : https://www.tinymce.com/docs/

Demo : https://www.tinymce.com/docs/demo/basic-example/

Your  will be replace by a TinyMCE box.

Title: How Make Form Input With Auto Tag HTML


问:
Powershell error when calling ps1 script from Command Prompt
I am using simple PowerShell file executing both in PowerShell and from a command prompt.

In PowerShell it's executing properly giving desired output, but when called from command prompt it's unable to connect to server and giving network not found.

filter.ps1:

```<code>param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try
{
    $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

    $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
    #write-host $SqlConnection.ConnectionString
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $SqlQuery
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $version = $DataSet.Tables[0].rows[0].Column1
    #Write-Host $version
    $DataSet.Tables[0] | out-file "C:\temp\version.csv"

    #switch case
    switch -Exact($version)
    {
    '8'  {$version=80}
    '9'  {$version=90}
    '10' {$version=100}
    '11' {$version=110}
    '12' {$version=120}
    '13' {$version=130}
    }

    #Write-Host $version
    $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"

    $pattern1=Select-String -Pattern "Final result:" -CaseSensitive -Path $filePath |Tee-Object D:\temp\pattern.txt
    $pattern2=Select-String -Pattern "Final result:" -CaseSensitive -Path $filePath

    if($pattern2)
    {
        Write-Host "string is not empty"
        $pattern3=Select-String -Pattern "Passed" -CaseSensitive -Path $filePath

        if($pattern3)
        {
        Write-Host "string is not empty"
        Out-File -FilePath $filePath1
         'Success'| Out-File -FilePath $filePath1
        }
        else
        {
         Out-File -FilePath $filePath1
         'failed'| Out-File -FilePath $filePath1
        }
    }
    else
    {
        Out-File -FilePath $filePath1
         'failed'| Out-File -FilePath $filePath1
    }
}

catch
{
    Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
    $errText =  $Error[0].ToString()

    if ($errText.Contains("network-related")) {Write-Host "Connection Error. Check server name, port, firewall."}
    Write-Host $errText
    continue
}
</code>```

Output from PowerShell Console:

```<code>PS D:\sysdba> d:\sysdba\filter.ps1 cx-siscsqltest\sqlinst
1
string is not empty
PS D:\sysdba>
</code>```

Output from Command Prompt:

```<code>H:\>powershell.exe -noexit "& ""d:\sysdba\filter.ps1"""
Fail
Connection Error. Check server name, port, firewall.
Exception calling "Fill" with "1" argument(s): "A network-related or instance-sp
ecific error occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name is correct an
d that SQL Server is configured to allow remote connections. (provider: Named Pi
pes Provider, error: 40 - Could not open a connection to SQL Server)"
PS H:\> d:
PS D:\> powershell "d:\sysdba\filter.ps1"
Fail
Connection Error. Check server name, port, firewall.
Exception calling "Fill" with "1" argument(s): "A network-related or instance-sp
ecific error occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name is correct an
d that SQL Server is configured to allow remote connections. (provider: Named Pi
pes Provider, error: 40 - Could not open a connection to SQL Server)"
PS D:\>
</code>```

答: In your commandline there is no parameter. The servername is empty</p>

Body:
I am using simple PowerShell file executing both in PowerShell and from a command prompt.

In PowerShell it's executing properly giving desired output, but when called from command prompt it's unable to connect to server and giving network not found.

filter.ps1:

param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try
{
    $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

    $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
    #write-host $SqlConnection.ConnectionString
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $SqlQuery
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $version = $DataSet.Tables[0].rows[0].Column1
    #Write-Host $version
    $DataSet.Tables[0] | out-file "C:\temp\version.csv"

    #switch case
    switch -Exact($version)
    {
    '8'  {$version=80}
    '9'  {$version=90}
    '10' {$version=100}
    '11' {$version=110}
    '12' {$version=120}
    '13' {$version=130}
    }

    #Write-Host $version
    $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"

    $pattern1=Select-String -Pattern "Final result:" -CaseSensitive -Path $filePath |Tee-Object D:\temp\pattern.txt
    $pattern2=Select-String -Pattern "Final result:" -CaseSensitive -Path $filePath

    if($pattern2)
    {
        Write-Host "string is not empty"
        $pattern3=Select-String -Pattern "Passed" -CaseSensitive -Path $filePath

        if($pattern3)
        {
        Write-Host "string is not empty"
        Out-File -FilePath $filePath1
         'Success'| Out-File -FilePath $filePath1
        }
        else
        {
         Out-File -FilePath $filePath1
         'failed'| Out-File -FilePath $filePath1
        }
    }
    else
    {
        Out-File -FilePath $filePath1
         'failed'| Out-File -FilePath $filePath1
    }
}

catch
{
    Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
    $errText =  $Error[0].ToString()

    if ($errText.Contains("network-related")) {Write-Host "Connection Error. Check server name, port, firewall."}
    Write-Host $errText
    continue
}

Output from PowerShell Console:

PS D:\sysdba> d:\sysdba\filter.ps1 cx-siscsqltest\sqlinst
1
string is not empty
PS D:\sysdba>

Output from Command Prompt:

H:\>powershell.exe -noexit "& ""d:\sysdba\filter.ps1"""
Fail
Connection Error. Check server name, port, firewall.
Exception calling "Fill" with "1" argument(s): "A network-related or instance-sp
ecific error occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name is correct an
d that SQL Server is configured to allow remote connections. (provider: Named Pi
pes Provider, error: 40 - Could not open a connection to SQL Server)"
PS H:\> d:
PS D:\> powershell "d:\sysdba\filter.ps1"
Fail
Connection Error. Check server name, port, firewall.
Exception calling "Fill" with "1" argument(s): "A network-related or instance-sp
ecific error occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name is correct an
d that SQL Server is configured to allow remote connections. (provider: Named Pi
pes Provider, error: 40 - Could not open a connection to SQL Server)"
PS D:\>


问:
Cocoa UI Analytics
I’d like to track user interaction inside of my OS X application. The goal is incredibly simple to start:

Track how many times a specific item is clicked on

I’m using sparkle to enable application updates and am able to send additional information through a delegate method. Read: Sending (client side) and storing (server side) the data isn’t an issue.

My Questions:

How can I cleanly attach a “hook” into my system to store an event (like “clicked”)

Where do I store the stats on the local machine? (incrementing plist property?)

Does such system already exist?

Really appreciate the help. I’m rather new to Cocoa so please ask if you need further clarification on any of the above points.

Thanks again,

Dustin

答: You might want to consider using an analytics service like Flurry.</p>

Title: Cocoa UI Analytics


问:
Spring-mvc with hibernate maven project
I got this error while running my project on Apache tomcat 9:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean com.cd.coe.configuration.PersistenceJPAConfig.entityManagerFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.cd.coe.configuration.PersistenceJPAConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc.driverClassName] not found
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1452)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
```

<p>This is my pom.xml:</p>

```<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cd.elibrary</groupId>
<artifactId>E-library</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>E-library Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
    <springframework.version>4.0.6.RELEASE</springframework.version>
    <hibernate.version>5.2.10.Final</hibernate.version>
    <mysql.version>5.1.31</mysql.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>
<build>
    <finalName>E-library</finalName>
</build>
```

<p>
And my configuration file is as follows:</p>

```@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig {

@Autowired
private Environment environment;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] { "com.cd.coe.model" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean(name = "dataSource")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}
```

My application.properties file is correct.

There is a problem when running this code on a server so I am not able to find the exact bug. I have tried with different versions of hibernate and mysql connector, but the issue still occurs.

答:
If you analyse the stacktrace correctly, it clearly says the problem as 'required key [jdbc.driverClassName] not found'. Please ensure that the properties file have the mentioned key. You also need to set the PropertySource in your Configuration Class.</p>

```<code>@PropertySource("classpath:application.properties")
</code>```

Title: Spring-mvc with hibernate maven project

Body:
I got this error while running my project on Apache tomcat 9:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean com.cd.coe.configuration.PersistenceJPAConfig.entityManagerFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.cd.coe.configuration.PersistenceJPAConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc.driverClassName] not found
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1452)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)

This is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cd.elibrary</groupId>
<artifactId>E-library</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>E-library Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
    <springframework.version>4.0.6.RELEASE</springframework.version>
    <hibernate.version>5.2.10.Final</hibernate.version>
    <mysql.version>5.1.31</mysql.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>
<build>
    <finalName>E-library</finalName>
</build>

And my configuration file is as follows:

@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig {

@Autowired
private Environment environment;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] { "com.cd.coe.model" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean(name = "dataSource")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

My application.properties file is correct.

There is a problem when running this code on a server so I am not able to find the exact bug. I have tried with different versions of hibernate and mysql connector, but the issue still occurs.

Body:
If you analyse the stacktrace correctly, it clearly says the problem as 'required key [jdbc.driverClassName] not found'. Please ensure that the properties file have the mentioned key. You also need to set the PropertySource in your Configuration Class.

@PropertySource("classpath:application.properties")


问:
C# event with multiple arguments
How to make multiple arguments more than two? CustomButtonClickEventArgs is shared by many places, I don't want to modify. How to append ActiveRow and ActiveCol arguments which indicated the ComboBox location in a Grid into the ComboBoxCustomButtonClick event like below what I 'expected'?

```<code>private void MyUC1_ComboBoxCustomButtonClick(object sender, MyUC.CustomButtonClickEventArgs e, int ActiveRow, int ActiveCol)
</code>```

declares:

```<code>public class CustomButtonClickEventArgs : EventArgs
    {
        public readonly int Index;

        public readonly string Key;

        public readonly string Tag;

        public readonly Keys ModifierKeys;

        public CustomButtonClickEventArgs(int index, string key, string tag, Keys modifierKeys)
        {
            this.Index = index;
            this.Key = key;
            this.Tag = tag;
            this.ModifierKeys = modifierKeys;
        }
    }

public delegate void CustomButtonClickEventHandler(object sender, CustomButtonClickEventArgs e);
</code>```

ComboBox located in Grid Cell(1,1)

答:
You just defined the Event Arguments (EventArgs). What you need is a delegate that defines how the method should look.

Maybe something like this?

```<code>public delegate void CustomButtonClickEventHandler(object sender,
                                                   MyUC.CustomButtonClickEventArgs e,
                                                   int ActiveRow,
                                                   int ActiveCol);
</code>```

When you define the event it needs this delegate:

```<code>public event CustomButtonClickEventHandler ComboBoxCustomButtonClick;
</code>```

Title: C# event with multiple arguments

Body:
How to make multiple arguments more than two? CustomButtonClickEventArgs is shared by many places, I don't want to modify. How to append ActiveRow and ActiveCol arguments which indicated the ComboBox location in a Grid into the ComboBoxCustomButtonClick event like below what I 'expected'?

private void MyUC1_ComboBoxCustomButtonClick(object sender, MyUC.CustomButtonClickEventArgs e, int ActiveRow, int ActiveCol)

declares:

public class CustomButtonClickEventArgs : EventArgs
    {
        public readonly int Index;

        public readonly string Key;

        public readonly string Tag;

        public readonly Keys ModifierKeys;

        public CustomButtonClickEventArgs(int index, string key, string tag, Keys modifierKeys)
        {
            this.Index = index;
            this.Key = key;
            this.Tag = tag;
            this.ModifierKeys = modifierKeys;
        }
    }

public delegate void CustomButtonClickEventHandler(object sender, CustomButtonClickEventArgs e);

ComboBox located in Grid Cell(1,1)

Body:
You just defined the Event Arguments (EventArgs). What you need is a delegate that defines how the method should look.

Maybe something like this?

public delegate void CustomButtonClickEventHandler(object sender,
                                                   MyUC.CustomButtonClickEventArgs e,
                                                   int ActiveRow,
                                                   int ActiveCol);

When you define the event it needs this delegate:

public event CustomButtonClickEventHandler ComboBoxCustomButtonClick;

ContentLicense: CC BY-SA 4.0


问:
Is there a way to change the __add__ method in python to be able to add a string and an int using only the + operator?
Is there a way to rewrite the __add__ method in the str class so that this operation is possible without an exception occurring:

```<code>"apple" + 123
</code>```

This error keeps popping up:

```<code>TypeError: Can't convert 'int' object to str implicitly
</code>```

答: I guess the most pythonic solution would be co convert 123 to str. All you need to do to get "apple123" is "apple" + "123" or "apple" + str(123).

Body:
Is there a way to rewrite the __add__ method in the str class so that this operation is possible without an exception occurring:

"apple" + 123

This error keeps popping up:

TypeError: Can't convert 'int' object to str implicitly


问:
How to change values in a 2-dimensional array?
I have a simple program to find the greater number of two numbers and store them in first line of an array.

the array is arr[tot][2] and I want to compare each element in arr[tot][0] to elements in arr[tot][1] but its giving me Invalid array assignment.
which function/method should I use to do that ?

```<code>for(i=0;i<tot;i++)
    {
        if(arr[i,1]>arr[i,0])
            {
            arr[i,0]=arr[i,1]}
    }
</code>```

Full program

```<code>#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    //Input

    int tot = 23;
    int arr[tot][2] = {
    {9272992,-5268711},
    {-6457223,-8368810},
    {-3415057,-2776446},
    {-6492757,-3453386},
    {4313482,4783138},
    {5573672,8360909},
    {-2546018,2224083},
    {1267093,4700254},
    {6136723,9042717},
    {1277125,2796189},
    {-2062877,2036481},
    {6089545,-6182241},
    {-8795303,6074456},
    {8152425,785931},
    {-5134200,4319924},
    {6820437,-5861208},
    {9051213,-9636786},
    {-4230018,-4363843},
    {-2413233,-722776},
    {2182770,-8099750},
    {-5939638,-2243558},
    {-9738840,1514344},
    {9980524,1528253}
        };

    //the comparing
    int i;
    for(i=0;i<tot;i++)
        {
            if(arr[i,1]>arr[i,0])
                {
                arr[i,0]=arr[i,1]
                }
        }
    for(i=0;i<tot;i++)
        {
        cout<<arr[i,0]<<" ";
        }
    return 0;
}
</code>```

Thanks for answering my questions :)
Also thanks for the downvotes, It really helped me understand that only smart and advanced questions are allowed here and stupid mistakes and syntax errors are not welcome.

答:
Do not use this syntax

```<code> if(arr[i,1]>arr[i,0])
  {
    arr[i,0]=arr[i,1]
  }
</code>```

Instead, try using this :

```<code> if(arr[i][1]>arr[i][0])
   {
      arr[i][0]=arr[i][1]
   }
</code>```

Body:
I have a simple program to find the greater number of two numbers and store them in first line of an array.

the array is arr[tot][2] and I want to compare each element in arr[tot][0] to elements in arr[tot][1] but its giving me Invalid array assignment.
which function/method should I use to do that ?

for(i=0;i<tot;i++)
    {
        if(arr[i,1]>arr[i,0])
            {
            arr[i,0]=arr[i,1]}
    }

Full program

#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    //Input

    int tot = 23;
    int arr[tot][2] = {
    {9272992,-5268711},
    {-6457223,-8368810},
    {-3415057,-2776446},
    {-6492757,-3453386},
    {4313482,4783138},
    {5573672,8360909},
    {-2546018,2224083},
    {1267093,4700254},
    {6136723,9042717},
    {1277125,2796189},
    {-2062877,2036481},
    {6089545,-6182241},
    {-8795303,6074456},
    {8152425,785931},
    {-5134200,4319924},
    {6820437,-5861208},
    {9051213,-9636786},
    {-4230018,-4363843},
    {-2413233,-722776},
    {2182770,-8099750},
    {-5939638,-2243558},
    {-9738840,1514344},
    {9980524,1528253}
        };

    //the comparing
    int i;
    for(i=0;i<tot;i++)
        {
            if(arr[i,1]>arr[i,0])
                {
                arr[i,0]=arr[i,1]
                }
        }
    for(i=0;i<tot;i++)
        {
        cout<<arr[i,0]<<" ";
        }
    return 0;
}

Thanks for answering my questions :)
Also thanks for the downvotes, It really helped me understand that only smart and advanced questions are allowed here and stupid mistakes and syntax errors are not welcome.

Body:
Do not use this syntax

 if(arr[i,1]>arr[i,0])
  {
    arr[i,0]=arr[i,1]
  }

Instead, try using this :

 if(arr[i][1]>arr[i][0])
   {
      arr[i][0]=arr[i][1]
   }


问:
What is the best way to print a table with delimiters in Python
I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:

```<code>>>> tab = [['a', 1], ['b', 2]]
>>> for row in tab:
...     out = ""
...     for col in row:
...             out = out + str(col) + "\t"
...     print out.rstrip()
...
a   1
b   2
</code>```

But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from here) and it is already shorter:

```<code>>>> for row in tab:
...     print "\t".join([str(col) for col in row])
...
a   1
b   2
</code>```

Is there still a better, or more Python-ish, way to do it?

答:
The prettytable library may be useful. It also helps maintain the column alignment and allows additional style customizations.

Example:

```<code># Ref: https://code.google.com/archive/p/prettytable/

import prettytable

# Read the input csv file
with open("input.csv", "r") as input_file:
    table = prettytable.from_csv(input_file)

# Optionally, change the default style
table.set_style(prettytable.PLAIN_COLUMNS)
table.align = "l"
table.valign = "t"

# Write the output ASCII text file
with open("output.txt", "w") as output_file:
    print("{}".format(table.get_string()), file=output_file)

# Optionally, write the output html file
with open("output.html", "w") as output_file:
    print("{}".format(table.get_html_string()), file=output_file)
</code>```

OwnerDisplayName: ketorin

Body:
I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:

>>> tab = [['a', 1], ['b', 2]]
>>> for row in tab:
...     out = ""
...     for col in row:
...             out = out + str(col) + "\t"
...     print out.rstrip()
...
a   1
b   2

But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from here) and it is already shorter:

>>> for row in tab:
...     print "\t".join([str(col) for col in row])
...
a   1
b   2

Is there still a better, or more Python-ish, way to do it?

Body:
The prettytable library may be useful. It also helps maintain the column alignment and allows additional style customizations.

Example:

# Ref: https://code.google.com/archive/p/prettytable/

import prettytable

# Read the input csv file
with open("input.csv", "r") as input_file:
    table = prettytable.from_csv(input_file)

# Optionally, change the default style
table.set_style(prettytable.PLAIN_COLUMNS)
table.align = "l"
table.valign = "t"

# Write the output ASCII text file
with open("output.txt", "w") as output_file:
    print("{}".format(table.get_string()), file=output_file)

# Optionally, write the output html file
with open("output.html", "w") as output_file:
    print("{}".format(table.get_html_string()), file=output_file)


问:
Missing grant type error
I am just trying to learn OAuth. I wrote some code to test it out. when I am submitting a request I am getting
{
    "error": "invalid_request",
    "error_description": "Missing grant type"
}

error in postman.

```<code>import java.util.Optional;

//import static org.assertj.core.api.Assertions.tuple;

import java.util.stream.Stream;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.springframework.security.core.userdetails.User;

//import org.omg.PortableInterceptor.ACTIVE;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@SpringBootApplication
public class SpringAuthServiceApplication {

    @Bean
    CommandLineRunner clr(AccountRepository accountRepository){
        return args -> {
            Stream.of("name1, password1", "name2, password2", "name3, password3", "name4, password4")
            .map(tpl -> tpl.split(",") )
            .forEach(tpl -> accountRepository.save(new Account(tpl[0], tpl[1], true)));
        };

    }

    public static void main(String[] args) {
        SpringApplication.run(SpringAuthServiceApplication.class, args);
    }
}

@Configuration
@EnableAuthorizationServer
class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter{
    private final AuthenticationManager authenticationManager;

    public AuthServiceConfiguration(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
        .inMemory()
        .withClient("html5")
        .secret("password")
        .authorizedGrantTypes("password")
        .scopes("openid");

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(this.authenticationManager);
    }

}

@Service
class AccountUserDetailService implements UserDetailsService{

    private final AccountRepository accountRepository;

    public AccountUserDetailService(AccountRepository accountRepository) {
//      super();
        this.accountRepository = accountRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        return accountRepository.findByUsername (username)
                .map(account -> new User(account.getUsername(),
                        account.getPassword(), account.isActive(), account.isActive(), account.isActive(), account.isActive(),
                        AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER") )
                        )
                .orElseThrow(() -> new UsernameNotFoundException("Couldn't fine user name " + username + "!") ) ;
    }

    /*@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return accountRepository.findByUsername(username)
                .map(account -> {
                    boolean active = account.isActive();
                    return new User(
                            account.getUsername(),
                            account.getPassword(),
                            active, active, active, active,
                            AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER"));
                })
                .orElseThrow(() -> new UsernameNotFoundException(String.format("username %s not found!", username)));
    }*/

}

interface AccountRepository extends JpaRepository<Account, Long>{
    Optional<Account> findByUsername(String username);
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
class Account{

    public Account(String username, String password, boolean active) {
        //super();
        this.username = username;
        this.password = password;
        this.active = active;
    }

    @GeneratedValue @Id
    private long id;
    private String username, password;
    private boolean active;

}
</code>```

Here is what I am sending in postman:

In the header tab:
Content-Type: application/json
Authorization: Basic aHRtbDU6cGFzc3dvcmQ=

In the Authorization tab:
type is Basic Auth
Username: html5
Password: password

Body tab, selected form data and sending the following:

username: username
password: password1
grant_type: password
scope: openid
client_id: html5
client_secret: password

答:
OAuth2 is looking for parameters in the form of a query string inside the request body, aka application/x-www-form-urlencoded.

Change your Content-Type to application/x-www-form-urlencoded and check x-www-form-urlencoded instead of form-data.

Title: Missing grant type error

Body:
I am just trying to learn OAuth. I wrote some code to test it out. when I am submitting a request I am getting
{
    "error": "invalid_request",
    "error_description": "Missing grant type"
}

error in postman.

import java.util.Optional;

//import static org.assertj.core.api.Assertions.tuple;

import java.util.stream.Stream;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.springframework.security.core.userdetails.User;

//import org.omg.PortableInterceptor.ACTIVE;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@SpringBootApplication
public class SpringAuthServiceApplication {

    @Bean
    CommandLineRunner clr(AccountRepository accountRepository){
        return args -> {
            Stream.of("name1, password1", "name2, password2", "name3, password3", "name4, password4")
            .map(tpl -> tpl.split(",") )
            .forEach(tpl -> accountRepository.save(new Account(tpl[0], tpl[1], true)));
        };

    }

    public static void main(String[] args) {
        SpringApplication.run(SpringAuthServiceApplication.class, args);
    }
}

@Configuration
@EnableAuthorizationServer
class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter{
    private final AuthenticationManager authenticationManager;

    public AuthServiceConfiguration(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
        .inMemory()
        .withClient("html5")
        .secret("password")
        .authorizedGrantTypes("password")
        .scopes("openid");

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(this.authenticationManager);
    }

}

@Service
class AccountUserDetailService implements UserDetailsService{

    private final AccountRepository accountRepository;

    public AccountUserDetailService(AccountRepository accountRepository) {
//      super();
        this.accountRepository = accountRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        return accountRepository.findByUsername (username)
                .map(account -> new User(account.getUsername(),
                        account.getPassword(), account.isActive(), account.isActive(), account.isActive(), account.isActive(),
                        AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER") )
                        )
                .orElseThrow(() -> new UsernameNotFoundException("Couldn't fine user name " + username + "!") ) ;
    }

    /*@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return accountRepository.findByUsername(username)
                .map(account -> {
                    boolean active = account.isActive();
                    return new User(
                            account.getUsername(),
                            account.getPassword(),
                            active, active, active, active,
                            AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER"));
                })
                .orElseThrow(() -> new UsernameNotFoundException(String.format("username %s not found!", username)));
    }*/

}

interface AccountRepository extends JpaRepository<Account, Long>{
    Optional<Account> findByUsername(String username);
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
class Account{

    public Account(String username, String password, boolean active) {
        //super();
        this.username = username;
        this.password = password;
        this.active = active;
    }

    @GeneratedValue @Id
    private long id;
    private String username, password;
    private boolean active;

}

Here is what I am sending in postman:

In the header tab:
Content-Type: application/json
Authorization: Basic aHRtbDU6cGFzc3dvcmQ=

In the Authorization tab:
type is Basic Auth
Username: html5
Password: password

Body tab, selected form data and sending the following:

username: username
password: password1
grant_type: password
scope: openid
client_id: html5
client_secret: password


问:
After uploaded a image, resized with JS and saved in PHP, how do I send the resized file via email using PHPMAILER?
I am from Brazil. SO, I am sorry for my bad english.
 I will give my best to explain what I need
 I am new to javascript and php...

I use a javascript where its resize the image before the upload. OK.
 After that, I use php to save the resized image to my server. OK.

What I need now is... how do I get this resized image and send via email using PHPMAILER ??

Here is the codes :

index.html

```<code><!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <title>Cadastro de Foto</title>

    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="js/canvas-to-blob.min.js"></script>
    <script src="js/resize.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <script type="text/javascript">

        // Iniciando biblioteca
        var resize = new window.resize();
        resize.init();

        // Declarando variáveis
        var imagens;
        var imagem_atual;

        // Quando carregado a página
        $(function ($) {

            // Quando selecionado as imagens
            $('#imagem').on('change', function () {
                enviar();
            });

        });

        /*
         Envia os arquivos selecionados
         */
        function enviar()
        {
            // Verificando se o navegador tem suporte aos recursos para redimensionamento
            if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
                alert('O navegador não suporta os recursos utilizados pelo aplicativo');
                return;
            }

            // Alocando imagens selecionadas
            imagens = $('#imagem')[0].files;

            // Se selecionado pelo menos uma imagem
            if (imagens.length > 0)
            {
                // Definindo progresso de carregamento
                $('#progresso').attr('aria-valuenow', 0).css('width', '0%');

                // Escondendo campo de imagem
                $('#imagem').hide();

                // Iniciando redimensionamento
                imagem_atual = 0;
                redimensionar();
            }
        }

        /*
         Redimensiona uma imagem e passa para a próxima recursivamente
         */
        function redimensionar()
        {
            // Se redimensionado todas as imagens
            if (imagem_atual > imagens.length)
            {
                // Definindo progresso de finalizado
                $('#progresso').html('Imagen(s) enviada(s) com sucesso');

                // Limpando imagens
                limpar();

                // Exibindo campo de imagem
                $('#imagem').show();

                // Finalizando
                return;
            }

            // Se não for um arquivo válido
            if ((typeof imagens[imagem_atual] !== 'object') || (imagens[imagem_atual] == null))
            {
                // Passa para a próxima imagem
                imagem_atual++;
                redimensionar();
                return;
            }

            // Redimensionando
            resize.photo(imagens[imagem_atual], 800, 'dataURL', function (imagem) {

                // Salvando imagem no servidor
                $.post('ajax/salvar.php', {imagem: imagem}, function() {

                    // Definindo porcentagem
                    var porcentagem = (imagem_atual + 1) / imagens.length * 100;

                    // Atualizando barra de progresso
                    $('#progresso').text(Math.round(porcentagem) + '%').attr('aria-valuenow', porcentagem).css('width', porcentagem + '%');

                    // Aplica delay de 1 segundo
                    // Apenas para evitar sobrecarga de requisições
                    // e ficar visualmente melhor o progresso
                    setTimeout(function () {
                        // Passa para a próxima imagem
                        imagem_atual++;
                        redimensionar();
                    }, 1000);

                });

            });
        }

        /*
         Limpa os arquivos selecionados
         */
        function limpar()
        {
            var input = $("#imagem");
            input.replaceWith(input.val('').clone(true));
        }
    </script>
</head>

<body>

<div class="container">

    <h1>Cadastro de Foto</h1>

    <form method="post" action="#" role="form">

        <div class="progress">
            <div id="progresso" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0"
                 aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
        </div>

        <div class="form-group row">

            <div class="col-xs-12">
                <input id="imagem" type="file" accept="image/*" multiple/>
            </div>

        </div>

    </form>

</div>

</body>
</html>
</code>```

Below is the php where save the resized file

salvar.php

```<code><?php
   $imagem = $_POST['imagem'];
   list($tipo, $dados) = explode(';', $imagem);
   list(, $tipo) = explode(':', $tipo);
   list(, $dados) = explode(',', $dados);
   $dados = base64_decode($dados);
   $nome = md5(uniqid(time()));
   file_put_contents("../img/{$nome}.jpg", $dados);
 ?>
</code>```

Ok.. After saved the resized file, I need to send this file via email using phpmailer.. to my own email address.. Once I am collecting data.

How do I do that ??
 please, help me

答:
here is the resize.js</p>

```<code>window.resize = (function () {

'use strict';

function Resize() {
    //
}

Resize.prototype = {

    init: function(outputQuality) {
        this.outputQuality = (outputQuality === 'undefined' ? 0.8 : outputQuality);
    },

    photo: function(file, maxSize, outputType, callback) {

        var _this = this;

        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            _this.resize(readerEvent.target.result, maxSize, outputType, callback);
        }
        reader.readAsDataURL(file);

    },

    resize: function(dataURL, maxSize, outputType, callback) {

        var _this = this;

        var image = new Image();
        image.onload = function (imageEvent) {

            // Resize image
            var canvas = document.createElement('canvas'),
                width = image.width,
                height = image.height;
            if (width > height) {
                if (width > maxSize) {
                    height *= maxSize / width;
                    width = maxSize;
                }
            } else {
                if (height > maxSize) {
                    width *= maxSize / height;
                    height = maxSize;
                }
            }
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(image, 0, 0, width, height);

            _this.output(canvas, outputType, callback);

        }
        image.src = dataURL;

    },

    output: function(canvas, outputType, callback) {

        switch (outputType) {

            case 'file':
                canvas.toBlob(function (blob) {
                    callback(blob);
                }, 'image/jpeg', 0.8);
                break;

            case 'dataURL':
                callback(canvas.toDataURL('image/jpeg', 0.8));
                break;

        }

    }

};

return Resize;}());
</code>```

Body:
I am from Brazil. SO, I am sorry for my bad english.
 I will give my best to explain what I need
 I am new to javascript and php...

I use a javascript where its resize the image before the upload. OK.
 After that, I use php to save the resized image to my server. OK.

What I need now is... how do I get this resized image and send via email using PHPMAILER ??

Here is the codes :

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Cadastro de Foto</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Cadastro de Foto

    <form method="post" action="#" role="form">

                <input id="imagem" type="file" accept="image/*" multiple/>

    </form>

Below is the php where save the resized file

salvar.php

<?php
   $imagem = $_POST['imagem'];
   list($tipo, $dados) = explode(';', $imagem);
   list(, $tipo) = explode(':', $tipo);
   list(, $dados) = explode(',', $dados);
   $dados = base64_decode($dados);
   $nome = md5(uniqid(time()));
   file_put_contents("../img/{$nome}.jpg", $dados);
 ?>

Ok.. After saved the resized file, I need to send this file via email using phpmailer.. to my own email address.. Once I am collecting data.

How do I do that ??
 please, help me

Body:
here is the resize.js

window.resize = (function () {

'use strict';

function Resize() {
    //
}

Resize.prototype = {

    init: function(outputQuality) {
        this.outputQuality = (outputQuality === 'undefined' ? 0.8 : outputQuality);
    },

    photo: function(file, maxSize, outputType, callback) {

        var _this = this;

        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            _this.resize(readerEvent.target.result, maxSize, outputType, callback);
        }
        reader.readAsDataURL(file);

    },

    resize: function(dataURL, maxSize, outputType, callback) {

        var _this = this;

        var image = new Image();
        image.onload = function (imageEvent) {

            // Resize image
            var canvas = document.createElement('canvas'),
                width = image.width,
                height = image.height;
            if (width > height) {
                if (width > maxSize) {
                    height *= maxSize / width;
                    width = maxSize;
                }
            } else {
                if (height > maxSize) {
                    width *= maxSize / height;
                    height = maxSize;
                }
            }
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(image, 0, 0, width, height);

            _this.output(canvas, outputType, callback);

        }
        image.src = dataURL;

    },

    output: function(canvas, outputType, callback) {

        switch (outputType) {

            case 'file':
                canvas.toBlob(function (blob) {
                    callback(blob);
                }, 'image/jpeg', 0.8);
                break;

            case 'dataURL':
                callback(canvas.toDataURL('image/jpeg', 0.8));
                break;

        }

    }

};

return Resize;}());


问:
Which product not available in magento why it's job is created
Which product is i have already deleted from magento 1 then import product in odoo then why deleted product job is created ? and then this job is failed and raise this error :  TypeError: int() argument must be a string or a number, not 'NoneType'

This error occured in attribute value get None, But in this problem deleted product job should not be created.

答:
Because some product are not created completely,
so there in product creation some data are missed so that is not display in magento backend.

But that product is already in magento database so it's job is created.


问:
how to set an parameter to not filter the SQL query when not set
I have a page with a list of artists and three buttons; photographers, makeup artists, all

I want to query the database to select each type through $_GET when any of the buttons is clicked which is easy for the first two I can set the url to ?type=photographers

however when I want to set the type to all, there's no value in the type column called all, i tried to set the type to * but it doesn't work

```<code>SELECT name, location, score, type FROM artists WHERE type = ?
</code>```

how to set type to show all what should the variable be equal to?

edit: I'm already using the !empty method, now I want to add more rules to my query and it's getting complicated, any other solution where I don't have to have two queries in the if and else?

答:
```<code> $cond = 1;
 if(!empty($_GET)){
    $cond = ' type = '.$_GET['your-query-string'];
 }

 SELECT name, location, score, type FROM artists WHERE $cond
</code>```

Body:
I have a page with a list of artists and three buttons; photographers, makeup artists, all

I want to query the database to select each type through $_GET when any of the buttons is clicked which is easy for the first two I can set the url to ?type=photographers

however when I want to set the type to all, there's no value in the type column called all, i tried to set the type to * but it doesn't work

SELECT name, location, score, type FROM artists WHERE type = ?

how to set type to show all what should the variable be equal to?

edit: I'm already using the !empty method, now I want to add more rules to my query and it's getting complicated, any other solution where I don't have to have two queries in the if and else?


问:
What is the correct way in reactjs?
I am new to react. In my project, I have a Home Component.

```<code>class Home extends Component {

        logOut(){
            console.log('log out in side home js');
            this.props.LogOutAction();
            localStorage.setItem('loginFlag', null);
        }

        render(){

                return(
                        <div>
                            <Header />
                            <br/>
                            <div className="col-md-12 ">
                                <div className="col-md-3 home-border">
                                        a
                                </div>
                                <div className="col-md-6 home-border">
                                    <User/>

                                </div>
                                <div className="col-md-3 home-border">
                                        c
                                </div>
                            </div>
                        </div>
                )
        }
}
</code>```

And my User component is

```<code>class User extends React.Component {

        viewProfile(id){

        }

        render() {
                var userdetails     =   [   {"id":"1", "name":"Abraham", "country": "USA", "age":"29", "image":""},
                                            {"id":"2", "name":"Gregory", "country": "Canada", "age":"23", "image":""},
                                            {"id":"3", "name":"Mathews", "country": "Newzeland", "age":"24", "image":""},
                                            {"id":"4", "name":"Williamson", "country": "China", "age":"27", "image":""},
                                            {"id":"5", "name":"Edwerd", "country": "Germany", "age":"22", "image":""}
                                ];
                 var myStyle = {
                                      border:"1px solid black",
                                      height:"170px",
                                }

                return(
                        <div>
                            <div>
                                {userdetails.map((data, i) => <div className="col-md-12 div-bottom" style={myStyle} key={i}>

                                        <div  className="col-md-12">
                                            <div className="col-md-12">
                                                <img className="img-thumbnail img-margin" width="150" height="236" src = {'profile.jpg'} />
                                            </div>
                                            <div className="col-md-12 div-bottom"><label>{data.name}</label></div>
                                            <div className="col-md-12 div-bottom">
                                                <div className="col-md-6"><label>age:</label>  {data.age}</div>
                                                <div className="col-md-3"><label>Country:</label> {data.country}</div>
                                            </div>
                                            <div className="col-md-4 .div-bottom"><button className="btn btn-primary" onClick={  () => { this.viewProfile(data.id) } }>view Profile</button></div>
                                        </div>
                                    </div>)
                                }
                            </div>
                        </div>
                )
        }

}
</code>```

I want to show the more user details in place of 'c' in the Home Component on the button click in the User Component.What is the correct method and how it can done?. Thanks in advance..

答:
There are two approaches. First is to use React only. You create a parent component, containing the state of the app. In the parent component you can create a function that changes the state. You can pass the function to your user component and the state to the home component.

Simplified:

```<code>const Home = ({ user }) => <div>{user.name}</div>;
const User = ({ changeUser }) => {
  const users = [
    { name: 'User1' },
    { name: 'User2' },
  ];

  const renderUsers = () => users.map(
    user => <li onClick={() => changeUser(user)}>{user.name}</li>
  );

  return <ul>{renderUsers()}</ul>;
};

class Parent extends React.Component {
  constructor(props) {
    super(props);

    this.changeUser = this.changeUser.bind(this);

    this.state = { user: null };
  }

  changeUser(user) {
    this.setState({ user });
  }

  render() {
    return (
      <div>
        <Home user={this.state.user} />
        <User changeUser={this.changeUser} />
      </div>
    );
  }
}
</code>```

However, when your app grows it becomes very complicated to manage the state via a parent component. You can use something like a "Flux" architecture for this. "Redux" is the most common way in the React world for building up Flux like architecture.

Title: What is the correct way in reactjs?

Body:
I am new to react. In my project, I have a Home Component.

class Home extends Component {

        logOut(){
            console.log('log out in side home js');
            this.props.LogOutAction();
            localStorage.setItem('loginFlag', null);
        }

        render(){

                return(

                                        a

                                    <User/>

                                        c

                )
        }
}

And my User component is

class User extends React.Component {

        viewProfile(id){

        }

        render() {
                var userdetails     =   [   {"id":"1", "name":"Abraham", "country": "USA", "age":"29", "image":""},
                                            {"id":"2", "name":"Gregory", "country": "Canada", "age":"23", "image":""},
                                            {"id":"3", "name":"Mathews", "country": "Newzeland", "age":"24", "image":""},
                                            {"id":"4", "name":"Williamson", "country": "China", "age":"27", "image":""},
                                            {"id":"5", "name":"Edwerd", "country": "Germany", "age":"22", "image":""}
                                ];
                 var myStyle = {
                                      border:"1px solid black",
                                      height:"170px",
                                }

                return(

                                {userdetails.map((data, i) =>

{data.name}

age:  {data.age}

Country: {data.country}

<button className="btn btn-primary" onClick={  () => { this.viewProfile(data.id) } }>view Profile</button>

)
                                }

                )
        }

}

I want to show the more user details in place of 'c' in the Home Component on the button click in the User Component.What is the correct method and how it can done?. Thanks in advance..

Body:
There are two approaches. First is to use React only. You create a parent component, containing the state of the app. In the parent component you can create a function that changes the state. You can pass the function to your user component and the state to the home component.

Simplified:

const Home = ({ user }) => <div>{user.name}</div>;
const User = ({ changeUser }) => {
  const users = [
    { name: 'User1' },
    { name: 'User2' },
  ];

  const renderUsers = () => users.map(
    user => <li onClick={() => changeUser(user)}>{user.name}</li>
  );

  return <ul>{renderUsers()}</ul>;
};

class Parent extends React.Component {
  constructor(props) {
    super(props);

    this.changeUser = this.changeUser.bind(this);

    this.state = { user: null };
  }

  changeUser(user) {
    this.setState({ user });
  }

  render() {
    return (
      <div>
        <Home user={this.state.user} />
        <User changeUser={this.changeUser} />
      </div>
    );
  }
}

However, when your app grows it becomes very complicated to manage the state via a parent component. You can use something like a "Flux" architecture for this. "Redux" is the most common way in the React world for building up Flux like architecture.