问:
Why do Magento configurable products have a SKU
I am about to create about 300 products (not many but enough).  Most of them are configurable so I will be entering a bunch of info then putting it together.  Each simple product that makes up a config product has its own sku, so why would a configurable product need a sku?</p>

答:
SKU is a primary key that does not rely on automatically generated db indexes although when dealing with bundles you can generate the SKU dynamically.

Main reason for that is to gain database irrelevance and enable easy import and export of database contents (cause the items are not identified by auto id's and such that will give troubles if imported and exported and increment id's or duplicates already exist)

So for configurable products you still need SKU to identify the group of products or the range of products that can be configured to be one product. Say you have 3 different configurable PC -s available and you get 3 orders , to define them for program you need a group id and do define them for fulfilling order is nice to know what type of configuration client has bought


来源: stackexchange

问:
The request for url passes 2 times, although it should 1 time
The result of the work should be a text message to the user, which for some reason comes 2 times, the Java code from the Android app sends 1 sms, so problems with the server are excluded</p>

```<code> let url2=URL(string:"url="+PhoneTextField.text!)
let config = URLSessionConfiguration.default
let userPasswordString = "user:pass"
let userPasswordData = userPasswordString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData!
let authString = "Basic \(base64EncodedCredential)"
config.httpAdditionalHeaders = ["Authorization" : authString]
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
URLCache.shared.removeAllCachedResponses()
let session = URLSession.init(configuration: config)

    let task=session.dataTask(with: url2!){
        ( data, response, error) in
            let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
          self.dataStringJSon=dataString as String?
        if(self.dataStringJSon!=="User not found"){

        }else{
            DispatchQueue.main.async {
                let storyboard = UIStoryboard(name: "Main", bundle: nil);
                let vc = storyboard.instantiateViewController(withIdentifier: "MySecondSecreen") as! UIViewController;
                self.present(vc, animated: true, completion: nil);
            }

        }

    }

    task.resume()
</code>```

答:
Disable caching with a session configuration</p>

```<code>config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The result of the work should be a text message to the user, which for some reason comes 2 times, the Java code from the Android app sends 1 sms, so problems with the server are excluded

 let url2=URL(string:"url="+PhoneTextField.text!)
let config = URLSessionConfiguration.default
let userPasswordString = "user:pass"
let userPasswordData = userPasswordString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData!
let authString = "Basic \(base64EncodedCredential)"
config.httpAdditionalHeaders = ["Authorization" : authString]
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
URLCache.shared.removeAllCachedResponses()
let session = URLSession.init(configuration: config)

    let task=session.dataTask(with: url2!){
        ( data, response, error) in
            let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
          self.dataStringJSon=dataString as String?
        if(self.dataStringJSon!=="User not found"){

        }else{
            DispatchQueue.main.async {
                let storyboard = UIStoryboard(name: "Main", bundle: nil);
                let vc = storyboard.instantiateViewController(withIdentifier: "MySecondSecreen") as! UIViewController;
                self.present(vc, animated: true, completion: nil);
            }

        }

    }

    task.resume()

Body:
Disable caching with a session configuration

config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil


问:
Symfony 3 connect forms and entities together
I'm building company details form in Symfony 3.2. The Company entity have several text fields (like company name, address, website url, and so on...). Also I've created another entity, named Services (it's like categories) with relation ManyToMany - because one Company can have many services, and one service can have many Companies.

The services list I can set only in the EasyAdminBundle. On the user-side the 'company details form' should displaying only checkboxes with service names. I don't want to create form for users where they will be able to add new 'service' name. User can fill only text-fields with his Company details and select several checkboxes with the services where his Company will be displayed on the catalog.

My problem is that I completely don't know how to do it. At this moment I've successfully connected the 'user registration form' with the 'Company details form'. I'm still learning Symfony - this is my first project with this framework.

The source of this project is available on my BitBucket account

答:
If you want to show checkboxes, use multiple and expanded property with EntityType field in your CompanyType form.

```<code>       $builder->add('services', EntityType::class, [
            'class'    => 'AppBundle\Entity\Services',
            'label'    => 'Services',
            'multiple' => true,
            'expanded' => true
        ])
</code>```

check http://symfony.com/doc/current/reference/forms/types/entity.html

Body:
If you want to show checkboxes, use multiple and expanded property with EntityType field in your CompanyType form.

       $builder->add('services', EntityType::class, [
            'class'    => 'AppBundle\Entity\Services',
            'label'    => 'Services',
            'multiple' => true,
            'expanded' => true
        ])

check http://symfony.com/doc/current/reference/forms/types/entity.html


问:
Find last cell value in array
I'm looking for a vba code to find the last value in an array in a column. It's also possible with the function LOOKUP(C1; A:B) but I would like to do it with VBA. I've already tried to use the function:
x = Application.Worksheetfunction.Lookup(Range("C1"), Range("A:B"))
But it didn't work. The data looks something like this:

A  :  B

1  :  10

1  :  12

2  :  20

2  :  25

2  :  30

3  :  35

3  :  40

4   : 45

4  :  50

4  :    55

So for 1 it has to return 12, for 2 -> 30, for 3 -> 40 and for 4 -> 55.

答:
Using your example, I think you want:</p>

```<code>Application.Worksheetfunction.VLookup(Range("C1"), Range("A:B"),2)
</code>```

Title: Find last cell value in array

Body:
Using your example, I think you want:

Application.Worksheetfunction.VLookup(Range("C1"), Range("A:B"),2)


问:
How would I run server-side code in Firebase?
I have a function where I want to perform some server-side validations, but I"m not sure how to do this?  Any suggestions where I should look.  THere is nothing in the documentation of how to do it?</p>

答:
It's late. However, just for someone passing by. Firebase has introduce Cloud Function a month ago. Try to check the official link out. It allow you to put some logics in server side.

https://firebase.google.com/docs/functions/

In my understanding instead of thinking about the communication to server as common Request and Response you need to see it as Database trigger event.
You can set up the function that will be called when specific action happen.


问:
How to get the last month? date +%Y%m -d '1 month ago' doesn't work on March 30
I wrote a script to delete old files. Part of the script is following:

```<code>lastmonth=`date +%Y%m -d '1 month ago'`
inputdir0=/var/this/directory/${lastmonth}*

if [ `date +%d` -gt 9 ];
then
    rm -Rf $inputdir0
fi
</code>```

There are some directories named after the date +%Y%m%d format.
Now it's March 29/30/31 and the script deleted all files of this month.
Today I learned this happens because there is no February 29/30/31.

How can i fix this?

答:
If you wish to get the date shifted by number of days you provide :

```<code>Number=222
current_date=$(date +%Y%m%d)
past_date=$(date -d "$current_date - $Number days" +%Y%m%d)
echo "$current_date\t$past_date"
</code>```

If you wish to get for 1 month :

```<code>date -d "$current_date -1 month"
</code>```

Similarily for one year :

```<code>date -d "$current_date -1 year"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a script to delete old files. Part of the script is following:

lastmonth=`date +%Y%m -d '1 month ago'`
inputdir0=/var/this/directory/${lastmonth}*

if [ `date +%d` -gt 9 ];
then
    rm -Rf $inputdir0
fi

There are some directories named after the date +%Y%m%d format.
Now it's March 29/30/31 and the script deleted all files of this month.
Today I learned this happens because there is no February 29/30/31.

How can i fix this?

Body:
If you wish to get the date shifted by number of days you provide :

Number=222
current_date=$(date +%Y%m%d)
past_date=$(date -d "$current_date - $Number days" +%Y%m%d)
echo "$current_date\t$past_date"

If you wish to get for 1 month :

date -d "$current_date -1 month"

Similarily for one year :

date -d "$current_date -1 year"


问:
This application has no explicit mapping for /error, so you are seeing this as a fallback
```<code>    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&libraries=places&callback=initAutocomplete"></script>
    </head>
    <body>
    </body>
</html>
</code>```

<p>The Error Occurs On The script tag as Exception parsing document </p>

答: Thymeleaf templates are valid XML, so inside an attribute you need to use & instead of &.</p>


问:
How to make div states changing dynamically by JQuery?
I have a div working as a button similar to the Youtube "Subscribe" button. There are 3 classes on CSS working as states and styles: .unactive (is not subscribed), active (subscribed) and .remove (when the mouse is over on subscribed).

Per example, when the button is '.unactive and mouse is over, add the class '.active'. Then when the mouse outs, it backs again to '.unactive'. If I click, its change to '.active' (and change the text inside to 'Subscribed'. And much more...

But when I add the class '.unactive' and remove '.active' dinamically, I can't identify/select the div again to remove the '.active' and back again to '.unactive'.

```<code>    $('.btn-circle.unactive').mouseover(function(){
    $(this).addClass('active').removeClass('unactive');
  });
  $('.btn-circle.active').mouseout(function(){
    $(this).addClass('unactive').removeClass('active');
  });
</code>```

What is the best way to make it?

答:
To solve this you can use toggleClass() to change the states on hover(). That way the element will return to it's original state on mouseout:

```<code>$('.btn-circle').hover(function(){
  $(this).toggleClass('active unactive');
});
</code>```

Body:
I have a div working as a button similar to the Youtube "Subscribe" button. There are 3 classes on CSS working as states and styles: .unactive (is not subscribed), active (subscribed) and .remove (when the mouse is over on subscribed).

Per example, when the button is '.unactive and mouse is over, add the class '.active'. Then when the mouse outs, it backs again to '.unactive'. If I click, its change to '.active' (and change the text inside to 'Subscribed'. And much more...

But when I add the class '.unactive' and remove '.active' dinamically, I can't identify/select the div again to remove the '.active' and back again to '.unactive'.

    $('.btn-circle.unactive').mouseover(function(){
    $(this).addClass('active').removeClass('unactive');
  });
  $('.btn-circle.active').mouseout(function(){
    $(this).addClass('unactive').removeClass('active');
  });

What is the best way to make it?

Body:
To solve this you can use toggleClass() to change the states on hover(). That way the element will return to it's original state on mouseout:

$('.btn-circle').hover(function(){
  $(this).toggleClass('active unactive');
});


问:
How to add a button inside each DevExtreme PivotGrid cells using Angular2
I want to add a button inside each DevExtreme PivotGrid cells using Angular2.
It is possible to do achieve the same using jQuery like this:

dxPivotGrid - How to add a button to the description cell

答:
The cellPrepared event helps you to achieve the behavior you described:

Html:

```<code><dx-pivot-grid
    ...
    (onCellPrepared)="cellPrepared($event)">
</code>```

TS:

```<code>cellPrepared(e) {
    $("<div>").dxButton({text: "Hello"}).appendTo(e.cellElement);
}
</code>```

Body:
The cellPrepared event helps you to achieve the behavior you described:

Html:

<dx-pivot-grid
    ...
    (onCellPrepared)="cellPrepared($event)">

TS:

cellPrepared(e) {
    $("<div>").dxButton({text: "Hello"}).appendTo(e.cellElement);
}


问:
Scala Spark - How reduce a dataframe with many couple columns in a single couple columns?
i have a dataframe with many couple (count and score) columns.
This situation is not a pivot, but similar an unpivot.
Example:

```<code>|house_score | house_count | mobile_score | mobile_count | sport_score | sport_count | ....<other couple columns>.....|
|   20            2              48              6             6             78     |
|   40            78             47              74            69             6     |
</code>```

I want a new dateframe with only two columns, score e count. The new dataframe reduce all couple columns in a only couple columns.

```<code>_________________
| score | count |
|   20  |   2   |
|   40  |   78  |
|   48  |   6   |
|   47  |   74  |
|   6   |   78  |
|   69  |   6   |
|_______________|
</code>```

What's the best solution (elegant code/performance)?

答:
You can achieve this using a foldLeft over the column names (excluding the part after the _). This is reasonably efficient since all intensive operations are distributed, and the code is fairly clean and concise.</p>

```<code>// df from example
val df = sc.parallelize(List((20,2,48,6,6,78), (40,78,47,74,69,6) )).toDF("house_score", "house_count", "mobile_score", "mobile_count", "sport_score", "sport_count")

// grab column names (part before the _)
val cols = df.columns.map(col => col.split("_")(0)).distinct

// fold left over all columns
val result = cols.tail.foldLeft(
   // init with cols.head column
   df.select(col(s"${cols.head}_score").as("score"), col(s"${cols.head}_count").as("count"))
){case (acc,c) => {
   // union current column c
   acc.unionAll(df.select(col(s"${c}_score").as("score"),     col(s"${c}_count").as("count")))
}}

result.show
</code>```

Body:
i have a dataframe with many couple (count and score) columns.
This situation is not a pivot, but similar an unpivot.
Example:

|house_score | house_count | mobile_score | mobile_count | sport_score | sport_count | ....<other couple columns>.....|
|   20            2              48              6             6             78     |
|   40            78             47              74            69             6     |

I want a new dateframe with only two columns, score e count. The new dataframe reduce all couple columns in a only couple columns.

_________________
| score | count |
|   20  |   2   |
|   40  |   78  |
|   48  |   6   |
|   47  |   74  |
|   6   |   78  |
|   69  |   6   |
|_______________|

What's the best solution (elegant code/performance)?

Body:
You can achieve this using a foldLeft over the column names (excluding the part after the _). This is reasonably efficient since all intensive operations are distributed, and the code is fairly clean and concise.

// df from example
val df = sc.parallelize(List((20,2,48,6,6,78), (40,78,47,74,69,6) )).toDF("house_score", "house_count", "mobile_score", "mobile_count", "sport_score", "sport_count")

// grab column names (part before the _)
val cols = df.columns.map(col => col.split("_")(0)).distinct

// fold left over all columns
val result = cols.tail.foldLeft(
   // init with cols.head column
   df.select(col(s"${cols.head}_score").as("score"), col(s"${cols.head}_count").as("count"))
){case (acc,c) => {
   // union current column c
   acc.unionAll(df.select(col(s"${c}_score").as("score"),     col(s"${c}_count").as("count")))
}}

result.show


问:
ValueError: number of bits must be greater than zero During handling of the above exception, another exception occurred
I am trying to implement genetic algorithm, the program terminates after 1st generation.. not sure why.. the code is below.. the xeception raised is..

File
  "C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib\random.py",
  line 255, in choice
      i = self._randbelow(len(seq))   File "C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib\random.py",
  line 232, in _randbelow
      r = getrandbits(k)          # 0 <= r < 2**k ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
  "C:/Users/Eshan/Desktop/model/simple_ga.py", line 87, in
      ga()   File "C:/Users/Eshan/Desktop/model/simple_ga.py", line 32, in ga
      agents = crossover(agents)   File "C:/Users/Eshan/Desktop/model/simple_ga.py", line 62, in crossover
      parent1 = random.choice(agents)   File "C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib\random.py",
  line 257, in choice
      raise IndexError('Cannot choose from an empty sequence') IndexError: Cannot choose from an empty sequence

Process finished with exit code 1

```<code>from fuzzywuzzy import fuzz
import random
import string

class Agent:
    def __init__(self, length):

        self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length))
        self.fitness = -1

    def __str__(self):
        return 'String: ' + str(self.string) + ' Fitness: ' + str(self.fitness)

in_str = 'string-python'
in_str_len = len(in_str)
population = 20
generations = 1000

def ga():

    agents = init_agents(population, in_str_len)

    for generation in range(generations):

        print('Generation: ' + str(generation))

        agents = selection(agents)
        agents = fitness(agents)
        agents = crossover(agents)
        agents = mutation(agents)

        if any(agent.fitness >= 90 for agent in agents):
            print('Threshod met!')
            exit(0)

def init_agents(population, length):
    return [Agent(length) for _ in range(population)]

def fitness(agents):
    for agent in agents:
        agent.fitness = fuzz.ratio(agent.string, in_str)

    return agents

def selection(agents):

    agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True)
    print('\n'.join(map(str, agents)))
    agents = agents[:int(0.2 * len(agents))]
    return agents

def crossover(agents):
    offspring = []
    for _ in range(int((population - len(agents)) / 2)):
        parent1 = random.choice(agents)
        parent2 = random.choice(agents)
        child1 = Agent(in_str_len)
        child2 = Agent(in_str_len)
        split = random.randint(0, in_str_len)
        child1.string = parent1.string[0:split] + parent2.string[split:in_str_len]
        child2.string = parent2.string[0:split] + parent1.string[split:in_str_len]
        offspring.append(child1)
        offspring.append(child2)

    return agents

def mutation(agents):

    for agent in agents:
        for idx, param in enumerate(agent.string):
            if random.uniform(0.0, 1.0) <= 0.1:
                agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1:in_str_len]

    return agents

if __name__ == '__main__':
    in_str = 'string-python'
    in_str_len = len(in_str)
    ga()
</code>```

答: Looks like your agents is empty, so when you do parent1 = random.choice(agents), this raises the error you're seeing, because you can't make a random choice from an empty list.

Body:
I am trying to implement genetic algorithm, the program terminates after 1st generation.. not sure why.. the code is below.. the xeception raised is..

File
  "C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib\random.py",
  line 255, in choice
      i = self._randbelow(len(seq))   File "C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib\random.py",
  line 232, in _randbelow
      r = getrandbits(k)          # 0 <= r < 2**k ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
  "C:/Users/Eshan/Desktop/model/simple_ga.py", line 87, in
      ga()   File "C:/Users/Eshan/Desktop/model/simple_ga.py", line 32, in ga
      agents = crossover(agents)   File "C:/Users/Eshan/Desktop/model/simple_ga.py", line 62, in crossover
      parent1 = random.choice(agents)   File "C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib\random.py",
  line 257, in choice
      raise IndexError('Cannot choose from an empty sequence') IndexError: Cannot choose from an empty sequence

Process finished with exit code 1

from fuzzywuzzy import fuzz
import random
import string

class Agent:
    def __init__(self, length):

        self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length))
        self.fitness = -1

    def __str__(self):
        return 'String: ' + str(self.string) + ' Fitness: ' + str(self.fitness)

in_str = 'string-python'
in_str_len = len(in_str)
population = 20
generations = 1000

def ga():

    agents = init_agents(population, in_str_len)

    for generation in range(generations):

        print('Generation: ' + str(generation))

        agents = selection(agents)
        agents = fitness(agents)
        agents = crossover(agents)
        agents = mutation(agents)

        if any(agent.fitness >= 90 for agent in agents):
            print('Threshod met!')
            exit(0)

def init_agents(population, length):
    return [Agent(length) for _ in range(population)]

def fitness(agents):
    for agent in agents:
        agent.fitness = fuzz.ratio(agent.string, in_str)

    return agents

def selection(agents):

    agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True)
    print('\n'.join(map(str, agents)))
    agents = agents[:int(0.2 * len(agents))]
    return agents

def crossover(agents):
    offspring = []
    for _ in range(int((population - len(agents)) / 2)):
        parent1 = random.choice(agents)
        parent2 = random.choice(agents)
        child1 = Agent(in_str_len)
        child2 = Agent(in_str_len)
        split = random.randint(0, in_str_len)
        child1.string = parent1.string[0:split] + parent2.string[split:in_str_len]
        child2.string = parent2.string[0:split] + parent1.string[split:in_str_len]
        offspring.append(child1)
        offspring.append(child2)

    return agents

def mutation(agents):

    for agent in agents:
        for idx, param in enumerate(agent.string):
            if random.uniform(0.0, 1.0) <= 0.1:
                agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1:in_str_len]

    return agents

if __name__ == '__main__':
    in_str = 'string-python'
    in_str_len = len(in_str)
    ga()


问:
Java: using switch statement with enum under subclass
First I'll state that I'm much more familiar with enums in C# and it seems like enums in java is a quite mess.

As you can see, I'm trying to use a switch statement @ enums in my next example but I always get an error no matter what I'm doing.

The error I receive is:

The qualified case label SomeClass.AnotherClass.MyEnum.VALUE_A must be replaced with the unqualified enum constant VALUE_A

The thing is I quite understand the error but I can't just write the VALUE_A since the enum is located in another sub-class. Is there a way to solve this problem? And why is it happening in Java?

```<code>//Main Class
public class SomeClass {

    //Sub-Class
    public static class AnotherClass {
        public enum MyEnum {
            VALUE_A, VALUE_B
        }
        public MyEnum myEnum;
    }

    public void someMethod() {
        MyEnum enumExample //...

        switch (enumExample) {
            case AnotherClass.MyEnum.VALUE_A: { <-- error on this line
                //..
                break;
            }
        }
    }
}
</code>```

答:
This is how I am using it. And it is working fantastically -

```<code>public enum Button {
        REPORT_ISSUES(0),
        CANCEL_ORDER(1),
        RETURN_ORDER(2);

        private int value;

        Button(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }
</code>```

And the switch-case as shown below

```<code>@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
    switch (button) {
        case REPORT_ISSUES: {
            break;
        }
        case CANCEL_ORDER: {
            break;
        }
        case RETURN_ORDER: {
            break;
        }
    }
}
</code>```

Body:
First I'll state that I'm much more familiar with enums in C# and it seems like enums in java is a quite mess.

As you can see, I'm trying to use a switch statement @ enums in my next example but I always get an error no matter what I'm doing.

The error I receive is:

The qualified case label SomeClass.AnotherClass.MyEnum.VALUE_A must be replaced with the unqualified enum constant VALUE_A

The thing is I quite understand the error but I can't just write the VALUE_A since the enum is located in another sub-class. Is there a way to solve this problem? And why is it happening in Java?

//Main Class
public class SomeClass {

    //Sub-Class
    public static class AnotherClass {
        public enum MyEnum {
            VALUE_A, VALUE_B
        }
        public MyEnum myEnum;
    }

    public void someMethod() {
        MyEnum enumExample //...

        switch (enumExample) {
            case AnotherClass.MyEnum.VALUE_A: { <-- error on this line
                //..
                break;
            }
        }
    }
}

Body:
This is how I am using it. And it is working fantastically -

public enum Button {
        REPORT_ISSUES(0),
        CANCEL_ORDER(1),
        RETURN_ORDER(2);

        private int value;

        Button(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

And the switch-case as shown below

@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
    switch (button) {
        case REPORT_ISSUES: {
            break;
        }
        case CANCEL_ORDER: {
            break;
        }
        case RETURN_ORDER: {
            break;
        }
    }
}


问:
how to clear cache in SharePoint designer Site?
I have try to open SharePoint 2013 site from SharePoint designer 2013 but its not working.

How can I clear SharePoint Site cache?

答:
For clear SharePoint designer site cache follow the below steps.

Close SharePoint Desginer2013.

Delete everything from %USERPROFILE%\AppData\Local\Microsoft\WebsiteCache.

Delete everything from %APPDATA%\Microsoft\Web Server Extensions\Cache.

Now open your SharePoint site from SPD it will definitely work.


问:
how to download in python
I am writing a script which will run on my server. Its purpose is to download the document. If any person hit the particular url he/she should be able to download the document. I am using urllib.urlretrieve but it download document on the server side not on the client. How to download in python at client side?</p>

答: Set the appropriate Content-type header, then send the file contents.

ContentLicense: CC BY-SA 2.5

Title: how to download in python


问:
MySQL return 1 row, PHP return 0 with prepared statement
I'm getting a super wierd situation. If I run the query in phpMyAdmin, mysql return 1 row but in php I get 0 rows.

I don't understand what is going wrong. Can someone see where the code fails?

```<code>$username = strtolower(trim($_POST['username']));
$postpass =            trim($_POST['password']);
//$username = 'mike';

$sql = "SELECT `id`,`username`,`password`,`email`,`phone`
        FROM `users`
        WHERE LOWER(`username`) = ?";

$stmt = preparestmt($db,$sql,'s',array($username));
$res  = $stmt->get_result();

echo $stmt->num_rows.'<br>';

while(list($uid,$username,$password,$email,$phone) = $res->fetch_array(MYSQLI_NUM))
{
...
</code>```

This is the preparestmt function:

```<code>function preparestmt($dbconnection,$sql,$types=null,$params=null)
{
    $stmt=$dbconnection->prepare($sql);

    if($types&&$params)
    {
        $bind_names[]=$types;
        for($i=0;$i<count($params);$i++)
        {
            $bind_name    = "bind{$i}";
            $$bind_name   = $params[$i];
            $bind_names[] = &$$bind_name;
        }
        $return=call_user_func_array(array($stmt,"bind_param"),$bind_names);
    }
    if($stmt->execute()->connect_error) sqlerror($dbconnection,$sql);
    return $stmt;
}
</code>```

This is what a print_r retun on $stmt

```<code>mysqli_stmt Object
(
    [affected_rows] => -1
    [insert_id] => 0
    [num_rows] => 0
    [param_count] => 1
    [field_count] => 5
    [errno] => 0
    [error] =>
    [error_list] => Array
        (
        )

    [sqlstate] => 00000
    [id] => 1
)
</code>```

This is the table in MySQL:

```<code>CREATE TABLE `users` (
    `id`         int(1)       UNSIGNED                   NOT NULL AUTO_INCREMENT COMMENT 'Unik räknare',
    `username`   varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Användarnamn',
    `name`       varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Namn',
    `familyname` varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Efternamn',
    `password`   char(60)     COLLATE  latin1_general_cs NOT NULL                COMMENT 'Lösenord',
    `email`      varchar(250) COLLATE  utf8_general_ci       NULL                COMMENT 'E-post',
    `phone`      varchar(12)  COLLATE  utf8_general_ci       NULL                COMMENT 'Telefonnummer',
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

INSERT INTO `users` (`id`, `username`, `name`, `familyname`, `password`, `email`, `phone`) VALUES
(1, 'Mike', 'Miky', 'Mark', '$2y$11$s9ooqquV123QCI4MLKAjUuH8OoYqW.F4f/UVfetBbFqe/hKVVXe9K', 'try.to@guess.it', '0100123456');
</code>```

This is the query that return 1 row in phpMyAdmin

```<code>SELECT `id`,`username`,`password`,`email`,`phone`
FROM `users`
WHERE LOWER(`username`) = 'mike'
</code>```

答:
What I was trying to do but hade staered me blind to. Sorry for bothering you with stuff thats not a real problem. Changed $stmt->num_rows; to $res->num_rows;

```<code>$res  = $stmt->get_result();
$rows = $res->num_rows;
</code>```

Body:
I'm getting a super wierd situation. If I run the query in phpMyAdmin, mysql return 1 row but in php I get 0 rows.

I don't understand what is going wrong. Can someone see where the code fails?

$username = strtolower(trim($_POST['username']));
$postpass =            trim($_POST['password']);
//$username = 'mike';

$sql = "SELECT `id`,`username`,`password`,`email`,`phone`
        FROM `users`
        WHERE LOWER(`username`) = ?";

$stmt = preparestmt($db,$sql,'s',array($username));
$res  = $stmt->get_result();

echo $stmt->num_rows.'
';

while(list($uid,$username,$password,$email,$phone) = $res->fetch_array(MYSQLI_NUM))
{
...

This is the preparestmt function:

function preparestmt($dbconnection,$sql,$types=null,$params=null)
{
    $stmt=$dbconnection->prepare($sql);

    if($types&&$params)
    {
        $bind_names[]=$types;
        for($i=0;$i<count($params);$i++)
        {
            $bind_name    = "bind{$i}";
            $$bind_name   = $params[$i];
            $bind_names[] = &$$bind_name;
        }
        $return=call_user_func_array(array($stmt,"bind_param"),$bind_names);
    }
    if($stmt->execute()->connect_error) sqlerror($dbconnection,$sql);
    return $stmt;
}

This is what a print_r retun on $stmt

mysqli_stmt Object
(
    [affected_rows] => -1
    [insert_id] => 0
    [num_rows] => 0
    [param_count] => 1
    [field_count] => 5
    [errno] => 0
    [error] =>
    [error_list] => Array
        (
        )

    [sqlstate] => 00000
    [id] => 1
)

This is the table in MySQL:

CREATE TABLE `users` (
    `id`         int(1)       UNSIGNED                   NOT NULL AUTO_INCREMENT COMMENT 'Unik räknare',
    `username`   varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Användarnamn',
    `name`       varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Namn',
    `familyname` varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Efternamn',
    `password`   char(60)     COLLATE  latin1_general_cs NOT NULL                COMMENT 'Lösenord',
    `email`      varchar(250) COLLATE  utf8_general_ci       NULL                COMMENT 'E-post',
    `phone`      varchar(12)  COLLATE  utf8_general_ci       NULL                COMMENT 'Telefonnummer',
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

INSERT INTO `users` (`id`, `username`, `name`, `familyname`, `password`, `email`, `phone`) VALUES
(1, 'Mike', 'Miky', 'Mark', '$2y$11$s9ooqquV123QCI4MLKAjUuH8OoYqW.F4f/UVfetBbFqe/hKVVXe9K', 'try.to@guess.it', '0100123456');

This is the query that return 1 row in phpMyAdmin

SELECT `id`,`username`,`password`,`email`,`phone`
FROM `users`
WHERE LOWER(`username`) = 'mike'

Body:
What I was trying to do but hade staered me blind to. Sorry for bothering you with stuff thats not a real problem. Changed $stmt->num_rows; to $res->num_rows;

$res  = $stmt->get_result();
$rows = $res->num_rows;


答:
Maybe .toggleClass() could fix that?

http://api.jquery.com/toggleclass/

Title: How to make div states changing dynamically by JQuery?


问:
In C why can I pass function name (not a pointer) as parameter to funtion?
I have test the following code:

```<code>#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}
</code>```

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

```<code>void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}
</code>```

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

答:
Because a function decays into a function pointer when it is not used within a function calling context:

```<code>void f(void a()) { a(); }    //void a() decays into void (*a)()
void g(void (*a)()) { a(); }    //equivalent to the above
void h(void a()) { (*a)(); }    //*a is equivalent to a
void i(void a()) { (**a)(); }    //**a is equivalent to *a
void j(void a()) { (***a)(); }    //...
void k() { };

int main() {
    f(k);
    g(k);
    h(k);
    i(k);
    j(k);
}
</code>```

This compiles and runs fine, even though I've been using liberal amounts of the dereferencing operator on the argument function. Each time I use it, the resulting function decays back into a pointer when it hits the next dereferencing operator. Likewise, the function argument void a() decays into a pointer just like int array[] decays into int* array when used as a function argument.

Body:
I have test the following code:

#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

Body:
Because a function decays into a function pointer when it is not used within a function calling context:

void f(void a()) { a(); }    //void a() decays into void (*a)()
void g(void (*a)()) { a(); }    //equivalent to the above
void h(void a()) { (*a)(); }    //*a is equivalent to a
void i(void a()) { (**a)(); }    //**a is equivalent to *a
void j(void a()) { (***a)(); }    //...
void k() { };

int main() {
    f(k);
    g(k);
    h(k);
    i(k);
    j(k);
}

This compiles and runs fine, even though I've been using liberal amounts of the dereferencing operator on the argument function. Each time I use it, the resulting function decays back into a pointer when it hits the next dereferencing operator. Likewise, the function argument void a() decays into a pointer just like int array[] decays into int* array when used as a function argument.


问:
Datetime.Tryparseexact in c# return wrong time
datetime.tryparseexact in c# return wrong time
Below code returns wrong time, it returns {3/30/2017 7:34:09 PM}</p>

```<code>DateTime.TryParseExact("March 30, 2017 2:04:09 PM", MMMM d, yyyy h:mm:ss tt, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal, out time)
</code>```

答:
Don't use AssumeUniversal. It will change the time based on your timezone. Use 0, like:

```<code>bool success = DateTime.TryParseExact("March 30, 2017 2:04:09 PM", "MMMM d, yyyy h:mm:ss tt", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out time);
</code>```

that will return a date with Kind == Unspecified, or use DateTimeStyles.AssumeLocal that will return a date with Kind == Local. If you really want Kind == Utc then use DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal.

Body:
datetime.tryparseexact in c# return wrong time
Below code returns wrong time, it returns {3/30/2017 7:34:09 PM}

DateTime.TryParseExact("March 30, 2017 2:04:09 PM", MMMM d, yyyy h:mm:ss tt, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal, out time)

Body:
Don't use AssumeUniversal. It will change the time based on your timezone. Use 0, like:

bool success = DateTime.TryParseExact("March 30, 2017 2:04:09 PM", "MMMM d, yyyy h:mm:ss tt", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out time);

that will return a date with Kind == Unspecified, or use DateTimeStyles.AssumeLocal that will return a date with Kind == Local. If you really want Kind == Utc then use DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal.


问:
IE7 cause of "Text - Empty Text Node"
I'm using the IE web developer toolbar to troubleshoot an issue.  A blank white space is appearing below a list item, and I can't logically figure out why.  Using the web dev toolbar, I see that in example 1 below, a "Text - Empty Text Node" is being output below  "Text - Google".  Ironically, in the second, with a space manually inserted after the word "Google", that text node no longer appears.  It would make complete sense to me if the results were reversed.  Any ideas what may cause this odd behavior?

Note: this is occuring in IE7, but not IE8.

```<code><li><a href="www.google.com">Google</a></li> - empty text node appears at end

<li><a href="www.google.com">Google </a></li> - no empty text node
</code>```

Update: Ok I've narrowed down this issue. Basically, it seems like there's a conflict between some of the attributes I'm using.  I need the a tags to be display as block, so they will wrap correctly when there are multiple lines.  But I also need no empty space in between the items.  I'm not quite sure why that empty space solves the problem, and would prefer not to just "hack" it.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
a
{
    display:block;
}
li
{
    zoom: 1;
}
</style>
    </head>
<body>
    <ul>
        <li>
        <div style="background-color:blue">
            <a href="#"><img  src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
        </div>
            <ul>
                <li style="background-color:Red"><a href="#">One</a></li>
                <li style="background-color:green"><a href="#">Two </a></li>
                <li style="background-color:Yellow"><a href="#">Three</a></li>
            </ul>
        </li>
    </ul>
</body>
</html>
</code>```

答:
I resolved this cause by adding the align tug to image, like this (i'm use DTD HTML 4.01 Transitional ):

Before

```<code><div class="OpenParagraph"></div>
<div><img alt="-" width="489" height="1" border="0"  src="/image/fadeBigBorder.gif"></div>
<div class="OpenParagraph"></div>
</code>```

After

```<code><div class="OpenParagraph"></div>
<div><img alt="-" width="489" height="1" border="0" align="absMiddle" src="/image/fadeBigBorder.gif"></div>
<div class="OpenParagraph"></div>
</code>```

Title: IE7 cause of "Text - Empty Text Node"

Body:
I'm using the IE web developer toolbar to troubleshoot an issue.  A blank white space is appearing below a list item, and I can't logically figure out why.  Using the web dev toolbar, I see that in example 1 below, a "Text - Empty Text Node" is being output below  "Text - Google".  Ironically, in the second, with a space manually inserted after the word "Google", that text node no longer appears.  It would make complete sense to me if the results were reversed.  Any ideas what may cause this odd behavior?

Note: this is occuring in IE7, but not IE8.

Google
 - empty text node appears at end

Google
 - no empty text node

Update: Ok I've narrowed down this issue. Basically, it seems like there's a conflict between some of the attributes I'm using.  I need the a tags to be display as block, so they will wrap correctly when there are multiple lines.  But I also need no empty space in between the items.  I'm not quite sure why that empty space solves the problem, and would prefer not to just "hack" it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

One

Two

Three

Body:
I resolved this cause by adding the align tug to image, like this (i'm use DTD HTML 4.01 Transitional ):

Before

<div class="OpenParagraph"></div>
<div><img alt="-" width="489" height="1" border="0"  src="/image/fadeBigBorder.gif"></div>
<div class="OpenParagraph"></div>

After

<div class="OpenParagraph"></div>
<div><img alt="-" width="489" height="1" border="0" align="absMiddle" src="/image/fadeBigBorder.gif"></div>
<div class="OpenParagraph"></div>


问:
UWP app packaging error
I am trying to create a package for a UWP app that I have been working on but I keep get the following exception:

```<code>Internal compiler error: MCG0024:UnresolvableTypeReference Unresolvable type reference 'System.ICloneable' in 'Assembly(Name=mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)' found. Please check the references in your build system. A reference is either missing or an assembly is missing an expected type.
</code>```

this issue is occurring only when I try to create the package in the release mode, it is not happening in the debug mode.

答:
This means that your application is using a class or a reference which is not available in UWP. The supported classes between .NET and UWP's .NET Core are not the same and usually issues arise when trying to create the release package.

For example iTextSharp has blogged about this issue before.

The solution is to go through your references and make sure that everything is compatible with UWP apps.

Title: UWP app packaging error

Body:
I am trying to create a package for a UWP app that I have been working on but I keep get the following exception:

Internal compiler error: MCG0024:UnresolvableTypeReference Unresolvable type reference 'System.ICloneable' in 'Assembly(Name=mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)' found. Please check the references in your build system. A reference is either missing or an assembly is missing an expected type.

this issue is occurring only when I try to create the package in the release mode, it is not happening in the debug mode.


问:
Convert contour paths to svg paths
I am using openCV with python to extract contours from an image. Now I need to export these contour paths (list) as an svg paths. How can I achieve this ?

code:

```<code>ret,thresh = cv2.threshold(imgray,27,25,0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_TC89_L1)
print(type(contours)) #type list
</code>```

答:
the problem has been solved as follows:</p>

```<code>c = max(contours, key=cv2.contourArea) #max contour
f = open('path.svg', 'w+')
f.write('<svg width="'+str(width)+'" height="'+str(height)+'" xmlns="http://www.w3.org/2000/svg">')
f.write('<path d="M')

for i in xrange(len(c)):
    #print(c[i][0])
    x, y = c[i][0]
    print(x)
    f.write(str(x)+  ' ' + str(y)+' ')

f.write('"/>')
f.write('</svg>')
f.close()
</code>```

Title: Convert contour paths to svg paths

Body:
I am using openCV with python to extract contours from an image. Now I need to export these contour paths (list) as an svg paths. How can I achieve this ?

code:

ret,thresh = cv2.threshold(imgray,27,25,0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_TC89_L1)
print(type(contours)) #type list

Body:
the problem has been solved as follows:

c = max(contours, key=cv2.contourArea) #max contour
f = open('path.svg', 'w+')
f.write('<svg width="'+str(width)+'" height="'+str(height)+'" xmlns="http://www.w3.org/2000/svg">')
f.write('<path d="M')

for i in xrange(len(c)):
    #print(c[i][0])
    x, y = c[i][0]
    print(x)
    f.write(str(x)+  ' ' + str(y)+' ')

f.write('"/>')
f.write('</svg>')
f.close()


问:
Chart.js - Vertical crosshair (vertical annotation that moves with mouse) in line graph
I am using Chart.js and have been looking for a way to have a vertical annotation/crosshair in my graph.

I want this vertical line to move horizontally, following my mouse cursor when the cursor is in the graph.

How to create a vertical crosshair that changes its horizontal position based on the cursor movement using Chart.js?

答:
This is the way I've done it: I've created an annotation whose value I change with an onmousemove event on the canvas.

```<code>var annotation = {
    annotations: [{
        type: 'line',
        mode: 'vertical',
        scaleID: 'x-axis',
        borderColor: '#b6fcd5',
        borderWidth: 2
    }]
};

var canvas = document.getElementById("chart");
var ctx = canvas.getContext("2d");

var myChart = new Chart(ctx,
    {
    ...
    },
        options: {
            tooltips: {
                mode: 'x',
                intersect: false
            },
            scales: {
                xAxes: [{
                    "id": 'x-axis',
                    type: 'time'
                }],
                ...
            },
            annotation: annotation
        }
    });

$(document).ready(function(){
    canvas.onmousemove = function (evt) {
        var points = myChart.getElementsAtXAxis(evt);
        annotation.annotations[0].value = new Date(myChart.config.data.labels[points[0]._index]);
        myChart.update();
    };
});
</code>```

Body:
This is the way I've done it: I've created an annotation whose value I change with an onmousemove event on the canvas.

var annotation = {
    annotations: [{
        type: 'line',
        mode: 'vertical',
        scaleID: 'x-axis',
        borderColor: '#b6fcd5',
        borderWidth: 2
    }]
};

var canvas = document.getElementById("chart");
var ctx = canvas.getContext("2d");

var myChart = new Chart(ctx,
    {
    ...
    },
        options: {
            tooltips: {
                mode: 'x',
                intersect: false
            },
            scales: {
                xAxes: [{
                    "id": 'x-axis',
                    type: 'time'
                }],
                ...
            },
            annotation: annotation
        }
    });

$(document).ready(function(){
    canvas.onmousemove = function (evt) {
        var points = myChart.getElementsAtXAxis(evt);
        annotation.annotations[0].value = new Date(myChart.config.data.labels[points[0]._index]);
        myChart.update();
    };
});


问:
DRF-Extension cache ignoring query parameters
I am using drf-extension for caching my APIs. But it is not working as expected with cache_response decorator.

It caches the response for say /api/get-cities/?country=india . But when I hit  /api/get-cities/?country=usa, I get the same response.

Here is the sample code:

settings.py

```<code>CACHES = {
   "default": {
       "BACKEND": "django_redis.cache.RedisCache",
       "LOCATION": "redis://127.0.0.1:6379/0",
       "OPTIONS": {
           "CLIENT_CLASS": "django_redis.client.DefaultClient"
       },
       "KEY_PREFIX": "city"
   }
}

REST_FRAMEWORK_EXTENSIONS = {
   'DEFAULT_USE_CACHE': 'default',
   'DEFAULT_CACHE_RESPONSE_TIMEOUT': 86400,
}
</code>```

views.py

```<code>class GetCities(APIView):

    @cache_response()
    def get(self, request):
        country = request.GET.get("country", "")
        return get_cities_function(country)
</code>```

Please help with this.

答:
I was able to find a solution for the problem. I created my own keys in redis with the combination of api name and parameter name(in my case country). So when API is hit with query parameters, I check if a key exists corresponding to that, if it exists then cached response is returned. </p>

```<code>class GetCities(APIView):

    def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
        api = view_instance.get_view_name().replace(' ', '')
        return "api:" + api + "country:" + str(request.GET.get("country", ""))

    @cache_response(key_func='calculate_cache_key')
    def get(self, request):
        country = request.GET.get("country", "")
        return get_cities_function(country)
</code>```

Body:
I am using drf-extension for caching my APIs. But it is not working as expected with cache_response decorator.

It caches the response for say /api/get-cities/?country=india . But when I hit  /api/get-cities/?country=usa, I get the same response.

Here is the sample code:

settings.py

CACHES = {
   "default": {
       "BACKEND": "django_redis.cache.RedisCache",
       "LOCATION": "redis://127.0.0.1:6379/0",
       "OPTIONS": {
           "CLIENT_CLASS": "django_redis.client.DefaultClient"
       },
       "KEY_PREFIX": "city"
   }
}

REST_FRAMEWORK_EXTENSIONS = {
   'DEFAULT_USE_CACHE': 'default',
   'DEFAULT_CACHE_RESPONSE_TIMEOUT': 86400,
}

views.py

class GetCities(APIView):

    @cache_response()
    def get(self, request):
        country = request.GET.get("country", "")
        return get_cities_function(country)

Please help with this.

Body:
I was able to find a solution for the problem. I created my own keys in redis with the combination of api name and parameter name(in my case country). So when API is hit with query parameters, I check if a key exists corresponding to that, if it exists then cached response is returned.

class GetCities(APIView):

    def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
        api = view_instance.get_view_name().replace(' ', '')
        return "api:" + api + "country:" + str(request.GET.get("country", ""))

    @cache_response(key_func='calculate_cache_key')
    def get(self, request):
        country = request.GET.get("country", "")
        return get_cities_function(country)


问:
MutableProperty containing a dictionary in ReactiveSwift
I am using ReactiveSwift to create a struct containing a dictionary. I want to listen for changes in the dictionary.

```<code>struct Model {
    let a: MutableProperty<[String: Int]> = MutableProperty([:])
}
</code>```

However, I'm having a hard time understanding how to bind this property to a listener. I want to do something like:

```<code>textView.reactive.text <~ model.a["key"]
</code>```

Is there a solution to holding dictionaries in mutable properties?

答:
Or you can do it like this:</p>

```<code>textView.reactive.text <~ model.a.map { $0["key"] }
</code>```

Body:
I am using ReactiveSwift to create a struct containing a dictionary. I want to listen for changes in the dictionary.

struct Model {
    let a: MutableProperty<[String: Int]> = MutableProperty([:])
}

However, I'm having a hard time understanding how to bind this property to a listener. I want to do something like:

textView.reactive.text <~ model.a["key"]

Is there a solution to holding dictionaries in mutable properties?

Body:
Or you can do it like this:

textView.reactive.text <~ model.a.map { $0["key"] }


问:
How to remove all special characters in Linux text

How to remove the special characters shown as blue color in the picture 1 like: ^M, ^A, ^@, ^[. In my understanding, ^M is a windows newline character, I can use sed -i '/^M//g' to remove it, but it doesn't work to remove others. The command dos2unix doesn't work, neither. Are there exist any ways that I can use to remove them both?

答:
To ensure that the command works with limited scope in Sed, force use of the "C" (POSIX) character classifications to avoid unpredictable behavior with non-ASCII characters:</p>

```<code>LC_ALL=C sed 's/[^[:blank:][:print:]]//g' file.txt
</code>```

Body:
To ensure that the command works with limited scope in Sed, force use of the "C" (POSIX) character classifications to avoid unpredictable behavior with non-ASCII characters:

LC_ALL=C sed 's/[^[:blank:][:print:]]//g' file.txt


问:
Creating new table which contains unique rows with conditions ; MySQL
I have a table with the following columns:

SessionID - contains actions within a session (1-10 rows per SessionID let's say)

ActionName - is the name of the action

Time - time action occurred

I need to return a new table, whose columns are the same, and contains only 1 row per SessionID IF the action's name is either "a" or "b".

That is, my new table should have a 1 row per SessionID which had the action "a" or "b".

I tried:

```<code>CREATE TABLE U_SessionID (
SELECT DISTINCT(SessionID) AS SessionID FROM test1)
;
</code>```

I copy the unique sessions to a new table

```<code>SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON (SELECT SessionID
FROM test1
WHERE U_SessionID.SessionID = test1.SessionID AND (ActionName =
"a" OR ActionName = "b")
ORDER BY Time DESC
LIMIT 1);
</code>```

But this code causes MySQL workbench to crash (timeout performing query), and I have no idea if it even works.

Sample data:

Can you think of a lighter query to run this?

Maybe a better approach would be:

take all rows with action "a" or action "b":

SELECT * FROM test1 WHERE ActionName = "a" OR ActionName = "b";

drop duplicates based on the SessionID only (no matter the time order)

Ideas for that?

答:
Is the time unique for a session ID?

If so:-

```<code>SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN
(
    SELECT SessionID
            MAX(Time) AS MaxTime
    FROM test1
    WHERE ActionName IN ("a", "b")
    GROUP BY SessionID
) sub0
ON test1.SessionID = sub0.SessionID
INNER JOIN U_SessionID
ON sub0.SessionID = U_SessionID.SessionID
AND sub0.MaxTime = U_SessionID.Time
</code>```

If time isn't unique, but assuming the table has a unique column called id:-

```<code>SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN
(
    SELECT SessionID
            SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY Time DESC), ',', 1) AS MaxId
    FROM test1
    WHERE ActionName IN ("a", "b")
    GROUP BY SessionID
) sub0
ON test1.SessionID = sub0.SessionID
INNER JOIN U_SessionID
ON sub0.SessionID = U_SessionID.SessionID
AND sub0.MaxId = U_SessionID.id
</code>```

EDIT

If you just want a random record for each session id then you could (ab)use the GROUP BY clause. I really do not like this idea as while it probably does work, it might well not work depending on the configuration of your MySQL database, and even if it does work someone might do an update that stops it working. Even then if it still works there is no garuntee that it will bring back a single real record, rather than a single rows whose columns are a mix of those from different rows.

So put here for completeness and to give you an option but I strongly advise against using it

```<code>SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON U_SessionID.SessionID = test1.SessionID
WHERE ActionName  IN ("a" , "b")
GROUP BY U_SessionID.SessionID
</code>```

If you want a simple solution that is more future proof then use my 2nd solution and remove the ORDER BY clause within the GROUP_CONCAT

Body:
I have a table with the following columns:

SessionID - contains actions within a session (1-10 rows per SessionID let's say)

ActionName - is the name of the action

Time - time action occurred

I need to return a new table, whose columns are the same, and contains only 1 row per SessionID IF the action's name is either "a" or "b".

That is, my new table should have a 1 row per SessionID which had the action "a" or "b".

I tried:

CREATE TABLE U_SessionID (
SELECT DISTINCT(SessionID) AS SessionID FROM test1)
;

I copy the unique sessions to a new table

SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON (SELECT SessionID
FROM test1
WHERE U_SessionID.SessionID = test1.SessionID AND (ActionName =
"a" OR ActionName = "b")
ORDER BY Time DESC
LIMIT 1);

But this code causes MySQL workbench to crash (timeout performing query), and I have no idea if it even works.

Sample data:

Can you think of a lighter query to run this?

Maybe a better approach would be:

take all rows with action "a" or action "b":

SELECT * FROM test1 WHERE ActionName = "a" OR ActionName = "b";

drop duplicates based on the SessionID only (no matter the time order)

Ideas for that?

Body:
Is the time unique for a session ID?

If so:-

SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN
(
    SELECT SessionID
            MAX(Time) AS MaxTime
    FROM test1
    WHERE ActionName IN ("a", "b")
    GROUP BY SessionID
) sub0
ON test1.SessionID = sub0.SessionID
INNER JOIN U_SessionID
ON sub0.SessionID = U_SessionID.SessionID
AND sub0.MaxTime = U_SessionID.Time

If time isn't unique, but assuming the table has a unique column called id:-

SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN
(
    SELECT SessionID
            SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY Time DESC), ',', 1) AS MaxId
    FROM test1
    WHERE ActionName IN ("a", "b")
    GROUP BY SessionID
) sub0
ON test1.SessionID = sub0.SessionID
INNER JOIN U_SessionID
ON sub0.SessionID = U_SessionID.SessionID
AND sub0.MaxId = U_SessionID.id

EDIT

If you just want a random record for each session id then you could (ab)use the GROUP BY clause. I really do not like this idea as while it probably does work, it might well not work depending on the configuration of your MySQL database, and even if it does work someone might do an update that stops it working. Even then if it still works there is no garuntee that it will bring back a single real record, rather than a single rows whose columns are a mix of those from different rows.

So put here for completeness and to give you an option but I strongly advise against using it

SELECT U_SessionID.SessionID, test1.ActionName, test1.SessionID
FROM test1
INNER JOIN U_SessionID ON U_SessionID.SessionID = test1.SessionID
WHERE ActionName  IN ("a" , "b")
GROUP BY U_SessionID.SessionID

If you want a simple solution that is more future proof then use my 2nd solution and remove the ORDER BY clause within the GROUP_CONCAT


问:
Add new colors along with custom theme colors angular2 material
how to add new colors in Angular 2 material.

Its specified in the ng2-material docs: color: "primary"|"accent"|"warn" are accepted i want to add something like "progressbarcolor" other than the colors defined in my custom theme for angular2 material.

For eg :

```<code> <md-progress-bar color="progressbarcolor">    </md-progress-bar>
</code>```

答:
Angular Material ships with the Material Design Spec's color palettes built in. In the event that you need to define a custom color palette, you can use $mdThemingProvider to define it, thereby making it available to your theme for use in its intention groups. Note that you must specify all hues in the definition map.      </p>

```<code>angular.module('myApp', ['ngMaterial'])
.config(function($mdThemingProvider) {

  $mdThemingProvider.definePalette('amazingPaletteName', {
    '50': 'ffebee',
    '100': 'ffcdd2',
    '200': 'ef9a9a',
    '300': 'e57373',
    '400': 'ef5350',
    '500': 'f44336',
    '600': 'e53935',
    '700': 'd32f2f',
    '800': 'c62828',
    '900': 'b71c1c',
    'A100': 'ff8a80',
    'A200': 'ff5252',
    'A400': 'ff1744',
    'A700': 'd50000',
    'contrastDefaultColor': 'light',    // whether, by default, text (contrast)
                                        // on this palette should be dark or light

    'contrastDarkColors': ['50', '100', //hues which contrast should be 'dark' by default
     '200', '300', '400', 'A100'],
    'contrastLightColors': undefined    // could also specify this if default was 'dark'
  });

  $mdThemingProvider.theme('default')
    .primaryPalette('amazingPaletteName')

});
</code>```

Body:
how to add new colors in Angular 2 material.

Its specified in the ng2-material docs: color: "primary"|"accent"|"warn" are accepted i want to add something like "progressbarcolor" other than the colors defined in my custom theme for angular2 material.

For eg :

 <md-progress-bar color="progressbarcolor">    </md-progress-bar>

Body:
Angular Material ships with the Material Design Spec's color palettes built in. In the event that you need to define a custom color palette, you can use $mdThemingProvider to define it, thereby making it available to your theme for use in its intention groups. Note that you must specify all hues in the definition map.

angular.module('myApp', ['ngMaterial'])
.config(function($mdThemingProvider) {

  $mdThemingProvider.definePalette('amazingPaletteName', {
    '50': 'ffebee',
    '100': 'ffcdd2',
    '200': 'ef9a9a',
    '300': 'e57373',
    '400': 'ef5350',
    '500': 'f44336',
    '600': 'e53935',
    '700': 'd32f2f',
    '800': 'c62828',
    '900': 'b71c1c',
    'A100': 'ff8a80',
    'A200': 'ff5252',
    'A400': 'ff1744',
    'A700': 'd50000',
    'contrastDefaultColor': 'light',    // whether, by default, text (contrast)
                                        // on this palette should be dark or light

    'contrastDarkColors': ['50', '100', //hues which contrast should be 'dark' by default
     '200', '300', '400', 'A100'],
    'contrastLightColors': undefined    // could also specify this if default was 'dark'
  });

  $mdThemingProvider.theme('default')
    .primaryPalette('amazingPaletteName')

});


问:
Can I remove some lines from some files when archiving them with Gradle?
I have a task to archive some required files in my Gradle config:

```<code>task zip4BuildServer(type: Zip) {
    classifier = 'src'
    from projectDir
    include 'src/**/*'
    include 'lib/**/*'
    include 'gradle/**/*'
    include 'build.gradle'
    include 'settings.gradle'
    include 'data_source.xml'
    include 'gradlew'
    include 'gradlew.bat'
    archiveName "${baseName}-${getDate()}-${revision}.${extension}"
}
</code>```

I would like to remove some lines from build.gradle inside archive (not in source place).

How to do that?

If I write this way

```<code>    from projectDir
    {
        eachFile { FileCopyDetails details ->
            if(details.file.text.contains("some word")) {
            }
        }
    }
</code>```

it says

```<code>212: Ambiguous expression could be a parameterless closure expression, an isolated open code block, or it may continue a previous statement;
   solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an explicit semicolon ';' @ line 212, column 5.
       {
       ^

1 error
</code>```

How to fix? I don't understand the error message.

答:
```<code>from projectDir
{
    eachFile { FileCopyDetails details ->
        if(details.file.text.contains("some word")) {
        }
    }
}
</code>```

does not work, because this is two expressions, from projectDir followed by something Groovy is not sure what you want, an unused closure, a code block, ... just like the error describes. In Groovy a newline character can terminate an expression if it is complete. (No unclosed parentheses, no unclosed quotes, ...). So if you would write

```<code>from(projectDir) {
    eachFile { FileCopyDetails details ->
        if(details.file.text.contains("some word")) {
        }
    }
}
</code>```

it should actually work, but I would simply do it like this:

```<code>from projectDir
eachFile { FileCopyDetails details ->
    if(details.file.text.contains("some word")) {
    }
}
</code>```

or in my opinion even better like this:

```<code>from projectDir
filter { it.contains('some word') ? null : it }
</code>```

But be aware that you should only filter text files. If you apply filters to binary files, you might destroy the binary files in the process. This does not only apply to the last solution, but also to the eachFile solution.

If you also have binary files in your copy spec, you might e. g. want to use filesMatching like

```<code>from projectDir
filesMatching(['build.gradle', '**/*.java']) {
    filter { it.contains('some word') ? null : it }
}
</code>```

Body:
I have a task to archive some required files in my Gradle config:

task zip4BuildServer(type: Zip) {
    classifier = 'src'
    from projectDir
    include 'src/**/*'
    include 'lib/**/*'
    include 'gradle/**/*'
    include 'build.gradle'
    include 'settings.gradle'
    include 'data_source.xml'
    include 'gradlew'
    include 'gradlew.bat'
    archiveName "${baseName}-${getDate()}-${revision}.${extension}"
}

I would like to remove some lines from build.gradle inside archive (not in source place).

How to do that?

If I write this way

    from projectDir
    {
        eachFile { FileCopyDetails details ->
            if(details.file.text.contains("some word")) {
            }
        }
    }

it says

212: Ambiguous expression could be a parameterless closure expression, an isolated open code block, or it may continue a previous statement;
   solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an explicit semicolon ';' @ line 212, column 5.
       {
       ^

1 error

How to fix? I don't understand the error message.

Body:
from projectDir
{
    eachFile { FileCopyDetails details ->
        if(details.file.text.contains("some word")) {
        }
    }
}

does not work, because this is two expressions, from projectDir followed by something Groovy is not sure what you want, an unused closure, a code block, ... just like the error describes. In Groovy a newline character can terminate an expression if it is complete. (No unclosed parentheses, no unclosed quotes, ...). So if you would write

from(projectDir) {
    eachFile { FileCopyDetails details ->
        if(details.file.text.contains("some word")) {
        }
    }
}

it should actually work, but I would simply do it like this:

from projectDir
eachFile { FileCopyDetails details ->
    if(details.file.text.contains("some word")) {
    }
}

or in my opinion even better like this:

from projectDir
filter { it.contains('some word') ? null : it }

But be aware that you should only filter text files. If you apply filters to binary files, you might destroy the binary files in the process. This does not only apply to the last solution, but also to the eachFile solution.

If you also have binary files in your copy spec, you might e. g. want to use filesMatching like

from projectDir
filesMatching(['build.gradle', '**/*.java']) {
    filter { it.contains('some word') ? null : it }
}


问:
php inventory management open source
iam looking for a php/mysql open source inventory management software.
Can anyone suggest me a good, free script?

I have heard about VTigerCRM, SugarCRM, Magento... which among these is the best for inventory, and anything else is preferable ?

答: Check this out, http://phpbms.org/ I dont know to what extent it will satisfy your needs, but it can be easily customized. And it is open source running on php/mysql.</p>

Title: php inventory management open source


问:
error when merge using hibernate 3 and ojdbc 7
I get an error when I save my entity using the merge() method from EntityManager. This issue happens when I use Hibernate 3 combined with ojdbc7 12.1.0.2.0 JDBC 4.1, but if I change to ojdbc6 11.2.0.3.0 JDBC 4.0 this error will disappear. Can anyone help to resolve my problem, because I need to use ojdbc7.

```<code>>[2017-03-30 14:52:42.184]: ERROR - TransactionAspectSupport.completeTransactionAfterThrowing(408) | Application exception overridden by rollback exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:404)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
    Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:695)
    at sun.reflect.GeneratedMethodAccessor915.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    at com.sun.proxy.$Proxy104.merge(Unknown Source)

Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2041)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3293)
    at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
    at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
    at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
    at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285)
    at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
    at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
    at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:1038)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:630)
    at org.hibernate.type.EntityType.resolve(EntityType.java:438)
    at org.hibernate.type.EntityType.replace(EntityType.java:298)
    at org.hibernate.type.AbstractType.replace(AbstractType.java:176)
    at org.hibernate.type.TypeHelper.replace(TypeHelper.java:212)
    at org.hibernate.event.def.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:600)
    at org.hibernate.event.def.DefaultMergeEventListener.mergeTransientEntity(DefaultMergeEventListener.java:337)
    at org.hibernate.event.def.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:303)
    at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:258)
    at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:84)
    at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:867)
    at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:851)
    at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:855)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:686)
    ... 143 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    at org.jboss.jca.adapters.jdbc.WrappedStatement.checkException(WrappedStatement.java:1446)
    at org.jboss.jca.adapters.jdbc.WrappedResultSet.checkException(WrappedResultSet.java:5986)
    at org.jboss.jca.adapters.jdbc.WrappedResultSet.next(WrappedResultSet.java:2693)
    at org.hibernate.loader.Loader.doQuery(Loader.java:825)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
    ... 167 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 128
    at oracle.jdbc.driver.T4CTTIrxd.readBitVector(T4CTTIrxd.java:135)
    at oracle.jdbc.driver.T4C8TTIrxh.unmarshalV10(T4C8TTIrxh.java:123)
    at oracle.jdbc.driver.T4C8Oall.readRXH(T4C8Oall.java:678)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
    at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1066)
    at oracle.jdbc.driver.OracleStatement.fetchMoreRows(OracleStatement.java:3716)
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.fetchMoreRows(InsensitiveScrollableResultSet.java:1015)
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.absoluteInternal(InsensitiveScrollableResultSet.java:979)
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.next(InsensitiveScrollableResultSet.java:579)
    at org.jboss.jca.adapters.jdbc.WrappedResultSet.next(WrappedResultSet.java:2689)
    ... 170 more
</code>```

答: If you are using Oracle 12c, try using Oracle12cDialect for the dialect. </p>

Body:
I get an error when I save my entity using the merge() method from EntityManager. This issue happens when I use Hibernate 3 combined with ojdbc7 12.1.0.2.0 JDBC 4.1, but if I change to ojdbc6 11.2.0.3.0 JDBC 4.0 this error will disappear. Can anyone help to resolve my problem, because I need to use ojdbc7.

>[2017-03-30 14:52:42.184]: ERROR - TransactionAspectSupport.completeTransactionAfterThrowing(408) | Application exception overridden by rollback exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:404)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
    Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:695)
    at sun.reflect.GeneratedMethodAccessor915.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    at com.sun.proxy.$Proxy104.merge(Unknown Source)

Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.mycomp.casa.persistence.model.CustomerAccountOpening#554]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2041)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3293)
    at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
    at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
    at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
    at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285)
    at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
    at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
    at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:1038)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:630)
    at org.hibernate.type.EntityType.resolve(EntityType.java:438)
    at org.hibernate.type.EntityType.replace(EntityType.java:298)
    at org.hibernate.type.AbstractType.replace(AbstractType.java:176)
    at org.hibernate.type.TypeHelper.replace(TypeHelper.java:212)
    at org.hibernate.event.def.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:600)
    at org.hibernate.event.def.DefaultMergeEventListener.mergeTransientEntity(DefaultMergeEventListener.java:337)
    at org.hibernate.event.def.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:303)
    at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:258)
    at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:84)
    at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:867)
    at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:851)
    at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:855)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:686)
    ... 143 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    at org.jboss.jca.adapters.jdbc.WrappedStatement.checkException(WrappedStatement.java:1446)
    at org.jboss.jca.adapters.jdbc.WrappedResultSet.checkException(WrappedResultSet.java:5986)
    at org.jboss.jca.adapters.jdbc.WrappedResultSet.next(WrappedResultSet.java:2693)
    at org.hibernate.loader.Loader.doQuery(Loader.java:825)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
    ... 167 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 128
    at oracle.jdbc.driver.T4CTTIrxd.readBitVector(T4CTTIrxd.java:135)
    at oracle.jdbc.driver.T4C8TTIrxh.unmarshalV10(T4C8TTIrxh.java:123)
    at oracle.jdbc.driver.T4C8Oall.readRXH(T4C8Oall.java:678)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
    at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1066)
    at oracle.jdbc.driver.OracleStatement.fetchMoreRows(OracleStatement.java:3716)
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.fetchMoreRows(InsensitiveScrollableResultSet.java:1015)
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.absoluteInternal(InsensitiveScrollableResultSet.java:979)
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.next(InsensitiveScrollableResultSet.java:579)
    at org.jboss.jca.adapters.jdbc.WrappedResultSet.next(WrappedResultSet.java:2689)
    ... 170 more


问:
How to parse xml to Json ionic 2
I have been on this problem for the past three days. I want to convert an XML which is retrieved via HTTP into JSON so I can display it in ionic 2. Here is my codes in a provider.. Any help will be much appreciated.. thank you!

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

import * as xml2js from "xml2js";

@Injectable()
export class News {

    constructor(public http: Http) { }

    public getData() {

        this
            .http
            .get('https://www.ug.edu.gh/news.xml')
            .map(res => {

                var cleanedString = res.toString().replace("\ufeff", "");

                xml2js
                .parseString(cleanedString, (error, result) => {

                    console.log(result);
                    return result;

                });

            })
            .subscribe((data) => {
                console.log(data)
            }, (err) => {
                console.log(err)
            });

    }
}
```

答:
For Parsing xml to json in ionic 2
You can install the typings for xml2json now using the command

```<code>typings install xml2json --save
</code>```

If it generate error like this

```<code>'typings' is not recognized as an internal or external command,
 operable program or batch file.
</code>```

Then first use this command to install typing

```<code>npm install typings -g
</code>```

Then run previous command

```<code>typings install xml2json --save
</code>```

Then it'll work fine.
Hope it work for you

Title: How to parse xml to Json ionic 2

Body:
For Parsing xml to json in ionic 2
You can install the typings for xml2json now using the command

typings install xml2json --save

If it generate error like this

'typings' is not recognized as an internal or external command,
 operable program or batch file.

Then first use this command to install typing

npm install typings -g

Then run previous command

typings install xml2json --save

Then it'll work fine.
Hope it work for you


问:
Ionic Spinner not showing up
I fill a Ionic collection-repeat list with a http-request, but I don't want to load everything directly into the DOM. So I'm only displaying a few of the items and add the rest of them when you scroll down. For that I have implemented the infinite-scroll function. It should show a spinner, when I get to the bottom of the page but it doesn't. The items do show up at least.

Here is the Code:

HTML:

```<code><!DOCTYPE html>
<html ng-app="ionicApp">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href=" http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-controller="MyCtrl">

    <ion-pane>
      <ion-header-bar class="bar-positive">
        <h1 class="title">Ionic Refresher testApp</h1>
      </ion-header-bar>
      <ion-content>
       <ion-refresher on-refresh="doRefresh()" spinner="bubbles"></ion-refresher>
      <ion-list>
        <ion-item class="item-thumbnail-left" collection-repeat="item in items | limitTo:numberOfItemsToDisplay">
        <img src="img/ionic.png" class="circle">
        <p>Link</p>
    <h2>{{item.id}}</h2>
    <h2>{{item.title}}</h2>
        </ion-item>
       <i class="icon ion-ios-arrow-right"></i>
        <ion-infinite-scroll
    on-infinite="addMoreItem()"
    distance="1%" spinner="bubbles">
  </ion-infinite-scroll>
      </ion-list>
      </ion-content>
    </ion-pane>
  </body>
</html>
</code>```

App.js:

```<code>angular.module('ionicApp', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.factory('TweetService', function($http){
  var BASE_URL = "http://jsonplaceholder.typicode.com/posts";
  var items = [];

  return {
    GetFeed: function(){
      return $http.get(BASE_URL).then(function(response){
        items = response.data;
        return items;
      });
    },
    GetNewTweets: function(){
      return $http.get(BASE_URL).then(function(response){
        items = response.data;
        return items;
      });
    }
  }
})

.controller('MyCtrl', function($scope, $timeout, TweetService) {
  $scope.items = [];
  $scope.numberOfItemsToDisplay = 5;

  TweetService.GetFeed().then(function(items){
  $scope.items = items;
  });

   $scope.addMoreItem = function() {
        if ($scope.items.length > $scope.numberOfItemsToDisplay)
          $scope.numberOfItemsToDisplay += 5; // load 5 more items
        $scope.$broadcast('scroll.infiniteScrollComplete');
      };

  $scope.doRefresh = function() {
    TweetService.GetNewTweets().then(function(items){
      $scope.items = items;

      //Stop the ion-refresher from spinning
      $scope.$broadcast('scroll.refreshComplete');
    });
  };

});
</code>```

答:
Try this snippet it works... </p>

```<code>//css
.my-spinner{
z-index: 99999999 !important;
position: absolute;
bottom:0px;
left:45%;
right:45%;
}

//template
<ion-infinite-scroll
    ng-if="!noMoreItemsAvailable"
    icon="ion-load-d"
    on-infinite="getpagenation()"
    distance="1%">
  </ion-infinite-scroll>

<div  ng-if="!noMoreItemsAvailable">
      <ion-spinner ng-show="ItemLoading" icon="ios" class="spinner spinner-ios my-spinner">
</div>

//js
$scope.getpagenation = function() {
        $scope.ItemLoading = true;
 //you can call services

 //have items
        $scope.ItemLoading = false;
 //no more items
        $scope.noMoreItemsAvailable = true;
        $scope.ItemLoading = false;
        $scope.$broadcast('scroll.infiniteScrollComplete');
}
</code>```

Title: Ionic Spinner not showing up

Body:
I fill a Ionic collection-repeat list with a http-request, but I don't want to load everything directly into the DOM. So I'm only displaying a few of the items and add the rest of them when you scroll down. For that I have implemented the infinite-scroll function. It should show a spinner, when I get to the bottom of the page but it doesn't. The items do show up at least.

Here is the Code:

HTML:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href=" http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <ion-pane>
      <ion-header-bar class="bar-positive">

Ionic Refresher testApp

      </ion-header-bar>
      <ion-content>
       <ion-refresher on-refresh="doRefresh()" spinner="bubbles"></ion-refresher>
      <ion-list>
        <ion-item class="item-thumbnail-left" collection-repeat="item in items | limitTo:numberOfItemsToDisplay">

Link

{{item.id}}

{{item.title}}

        </ion-item>

        <ion-infinite-scroll
    on-infinite="addMoreItem()"
    distance="1%" spinner="bubbles">
  </ion-infinite-scroll>
      </ion-list>
      </ion-content>
    </ion-pane>

App.js:

angular.module('ionicApp', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.factory('TweetService', function($http){
  var BASE_URL = "http://jsonplaceholder.typicode.com/posts";
  var items = [];

  return {
    GetFeed: function(){
      return $http.get(BASE_URL).then(function(response){
        items = response.data;
        return items;
      });
    },
    GetNewTweets: function(){
      return $http.get(BASE_URL).then(function(response){
        items = response.data;
        return items;
      });
    }
  }
})

.controller('MyCtrl', function($scope, $timeout, TweetService) {
  $scope.items = [];
  $scope.numberOfItemsToDisplay = 5;

  TweetService.GetFeed().then(function(items){
  $scope.items = items;
  });

   $scope.addMoreItem = function() {
        if ($scope.items.length > $scope.numberOfItemsToDisplay)
          $scope.numberOfItemsToDisplay += 5; // load 5 more items
        $scope.$broadcast('scroll.infiniteScrollComplete');
      };

  $scope.doRefresh = function() {
    TweetService.GetNewTweets().then(function(items){
      $scope.items = items;

      //Stop the ion-refresher from spinning
      $scope.$broadcast('scroll.refreshComplete');
    });
  };

});

Body:
Try this snippet it works...

//css
.my-spinner{
z-index: 99999999 !important;
position: absolute;
bottom:0px;
left:45%;
right:45%;
}

//template
<ion-infinite-scroll
    ng-if="!noMoreItemsAvailable"
    icon="ion-load-d"
    on-infinite="getpagenation()"
    distance="1%">
  </ion-infinite-scroll>

<div  ng-if="!noMoreItemsAvailable">
      <ion-spinner ng-show="ItemLoading" icon="ios" class="spinner spinner-ios my-spinner">
</div>

//js
$scope.getpagenation = function() {
        $scope.ItemLoading = true;
 //you can call services

 //have items
        $scope.ItemLoading = false;
 //no more items
        $scope.noMoreItemsAvailable = true;
        $scope.ItemLoading = false;
        $scope.$broadcast('scroll.infiniteScrollComplete');
}


问:
timer fire twice
i ve used some ex from stackoverflow but sometimes my timer fire twice:
this clock should fire each one minute, but just assume that it fires 00:00:59.666
then step1 = 59;
step2 = 59;
step3 = 1;
return (1000-666); so it should fire not next minute but next 333 mili second, what can i do? </p>

```<code>public int SyncTime = 60;
Clock = new System.Timers.Timer {AutoReset = false};
            Clock.Elapsed += DoJob;
            Clock.Interval = GetSync(SyncTime);
            Clock.Start()
   private void DoJob(object sender, ElapsedEventArgs elapsedEventArgs)
   {

            Clock.Interval = GetSync(SyncTime);
            Clock.Start();

    }
    private static double GetSync(int syncTime)
    {
        DateTime now = DateTime.Now;
        int step1 = (now.Minute * 60 + now.Second); //amount of miliseconds in this hour
        int step2 = step1 % syncTime;               //amount of miliseconds since last update
        int step3 = syncTime - step2;               //amount of miliseconds to next upadte
        return (step3 * 1000 - now.Millisecond);
    }
</code>```

答:
Ok not sure if this is the answer to your specific issue but your GetSync function is calculating the remaining time till the full minute incorrectly.

It should be (unless I am missing something which is completely possible):

```<code>private static double GetSync(int syncTime)
{
  DateTime now = DateTime.Now;
  return ((2 * syncTime) - now.Second) * 1000) - now.Millisecond;
}
</code>```

This may resolve your issue as calculating the remaining time this way will never result in you returning a 0 value from GetSync.

Title: timer fire twice

Body:
i ve used some ex from stackoverflow but sometimes my timer fire twice:
this clock should fire each one minute, but just assume that it fires 00:00:59.666
then step1 = 59;
step2 = 59;
step3 = 1;
return (1000-666); so it should fire not next minute but next 333 mili second, what can i do?

public int SyncTime = 60;
Clock = new System.Timers.Timer {AutoReset = false};
            Clock.Elapsed += DoJob;
            Clock.Interval = GetSync(SyncTime);
            Clock.Start()
   private void DoJob(object sender, ElapsedEventArgs elapsedEventArgs)
   {

            Clock.Interval = GetSync(SyncTime);
            Clock.Start();

    }
    private static double GetSync(int syncTime)
    {
        DateTime now = DateTime.Now;
        int step1 = (now.Minute * 60 + now.Second); //amount of miliseconds in this hour
        int step2 = step1 % syncTime;               //amount of miliseconds since last update
        int step3 = syncTime - step2;               //amount of miliseconds to next upadte
        return (step3 * 1000 - now.Millisecond);
    }

Body:
Ok not sure if this is the answer to your specific issue but your GetSync function is calculating the remaining time till the full minute incorrectly.

It should be (unless I am missing something which is completely possible):

private static double GetSync(int syncTime)
{
  DateTime now = DateTime.Now;
  return ((2 * syncTime) - now.Second) * 1000) - now.Millisecond;
}

This may resolve your issue as calculating the remaining time this way will never result in you returning a 0 value from GetSync.