Q: Powershell Mysql Error This code is:
$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql = "Select * FROM onaylanan Order by onaylanma_id ASC"
$cm.Connection = $Connection
$cm.CommandText = $sql
$dr = $cm.ExecuteReader()

while ($dr.Read())
{
$cm2 = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql2 = "Delete FROM onaylanan Where onaylanma_id=4"
$cm2.Connection = $Connection
$cm2.CommandText = $sql2
$dr2 = $cm2.ExecuteNonQuery()
  $dr2.Close();

}
$dr.Close();
$Connection.Close()

This Error is:

Exception calling "ExecuteNonQuery" with "0" argument(s): "There is already an open DataReader associated with this Connection which must be closed first."

A: As the error indicates, you can't execute two queries concurrently over the same connection.
Open a second connection (you could name it Connection2) and assign that to $cm2:
$cm2.Connection = $Connection2


Q: Remove PHP extension using .htaccess methods (Keeping Link Juice) I'm trying to remove the .php extension on my URLs to make it Search Engine Friendly using the .htaccess file Redirect 301, to keep the "rank juice" and I as much I've tried almost every example around - It just doesn't seem to work.
Here are some of the methods I've unsuccessfully tried already:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

This is the most common solution given but nothing happens and there is no changes.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1.php [L]

Nothing happens and there is no changes.
RewriteEngine On
# RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
# RewriteRule (.*)\.php$ /$1 [L,R=301]
# RewriteRule (.*)/$ $1.php [L]

I get a Not Found : The requested URL /AMENPTHOME/hostnd/3/9/9/399fc7b78/www/htdocs/web/dive-sites.php was not found on this server.
Amen is my host and the file dive-sites.php in this specific real example is on the root.
My goal is to have: www.domain.com/dive-sites and not www.domain.com/dive-sites.php using a Redirect 301 because this url is already ranked for a while. Can someone please help ?
Thank you very much, all help appreciated.

A: If I didn't missed anything:
RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC]
RewriteRule ^ /%1 [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L]

Requests to /dive-sites.php will issue a 301 redirect to /dive-sites, appending query-strings if any.
Requests to /dive-sites will get a 200 response with /dive-sites.php as Content-Location, appending query-strings if any.

A: try this:

RewriteEngine on
RewriteRule ^/(.+)(($|#)*(.*)) /$1.php$2

If removing only the .php this will work.

$1 = for the name of the page, e.g foo

$2 = take note of the hashtag or the get request
eg.

<domain>/example ----> <domain>/example.php
<domain>/example?get=this ----> <domain>/example.php?get=this
<domain>/example#hash ----> <domain>/example.php#hash

A: Try this code for .php extension removal:
RewriteEngine On

## hide .php extension
# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]


Q: Mustache (Nustache) arbitrarily rendering some of list inline I'm using the code:
{{#Object}}
{{{Name}}} - {{{Property}}}
{{/Object}}

to render a list, but halfway through the list, it'll start printing the list on the same line, which it will continue doing until the end of the list. We use this within emails, and our preview pane renders it within a <pre> tag, and it looks fine. When it's set as the body of an email, we get the line breaking problem. It'll render like the following:
Object1Name - Object1Property
Object2Name - Object2Property
Object3Name - Object3Property
Object4Name - Object4Property Object5Name - Object5Property Object6Name - Object6Property

There are also instances where it puts the entire list on the same line, and there are instances where it doesn't happen, most of the time it starts about halfway through the list and continues.
any help or ideas are welcome.


Q: knockout.js and property not being found in Jquery Template I am getting "caseStudy is not defined" with the below code.  I have to add the full prefix app.viewModel.caseStudy.showFlawDetails to not error.
 app.viewModel.caseStudy = {};
        app.viewModel.caseStudy.cases = ko.observableArray();
        app.viewModel.caseStudy.selectedCaseId = ko.observable(0);
        app.viewModel.caseStudy.selectedCase = ko.mapping.fromJS(caseModel);
app.viewModel.caseStudy.showFlawDetails = function (index) {
        console.log(index);
    };
ko.applyBindings(app.viewModel);

A: Inside of your flawTemplate the scope is caseStudy.selectedCase.Flaws, so when you put caseStudy.showFlawDetails, it is not found as a property of Flaws or globally.
So, you can either reference it with app.viewModel.caseStudy.showFlawDetails, if app has global scope (which it seems to since it works for you).
Otherwise, a good option is to pass the function in via templateOptions.  So, you would do:
data-bind='template: { name: "flawTemplate", data: caseStudy.selectedCase.Flaws, templateOptions: showFlawDetails: caseStudy.showFlawDetails } }'>

Then, you would access it using $item.showFlawDetails
The click (and event) bindings also expect that you pass it a reference to a function.  In your case you are passing it the result of executing the function.  Answered it further here: knockout.js calling click even when jquery template is rendered


Q: how to link through bootstrap tabs Hello the code which i am posting here is just a w3schools example. Its a bootstrap links tabs. All my problem is when i want for example just to link to the second tab i can't i want when i put a link like that http://127.0.0.1:61330/test2.html#menu2
i want it to work to go to menu2 section or div what ever but it doesn't work
i want at the link up tp be like  /test2.html#menu2 /test2.html#menu3 like that but it doesn't happen
i found also this here on stackoverflow but it just show the link up in the browser but when i change the link like http://127.0.0.1:61330/test2.html#menu3 for example it don't work
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

main
<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Dynamic Tabs

Home

Menu 1

Menu 2

Menu 3

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Menu 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.

Menu 3

Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

A: $(document).ready(function(){
    if (location.hash) {
        $('a[href=' + location.hash + ']').tab('show');
    }
});

this is the solution i found it here
here


Q: Insert data to table row using Angular I am new to angular, and currently working on my personal project.
I have a question about how to insert new data to table row.
Can anyone give me snippet/example how to do this?
Here is the form and the table headers:

ADD

Add

              <button type="button" class="close pull-right" aria-label="Close" (click)="smModal.hide()">
                ×
              </button>

              <form>
                ID
                <input type="text" class="form-control" placeholder="id">

                name
                <input type="text" class="form-control" placeholder="name">

                year
                <input type="text" class="form-control" placeholder="year">

                major
                <input type="text" class="form-control" placeholder="major">

                address
                <input type="text" class="form-control" placeholder="address">

                Email
                <input type="text" class="form-control" placeholder="email">

                phone
                <input type="text" class="form-control" placeholder="phone">

                <button type="submit" class="btn btn-primary">Simpan</button>
                <button class="btn btn-danger">Batal</button>
              </form>

      id
      name
      year
      major
      address
      email
      phone

Here is the typescript file:
//app.component.ts

import { Component } from '@angular/core';
import { TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { NgIf } from '@angular/common';

 @Component({
  selector: 'app-root',
  styleUrls:['app.component.css'],
  templateUrl:'app.component.html',
  //template:`<h1 align="center">template</h1>`
})

export class AppComponent
{
  title = 'title';

}

What I need to do is simply insert the user input from that from into a table row.
Please let me know if more snippets are needed.

A: You can declare custom object array in your app.component.ts file like this
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `

      id
      name
      year

      {{row.id}}
      {{row.name}}
      {{row.year}}

  <input type="text" [(ngModel)]="id" placeholder="id" />
  <input type="text" [(ngModel)]="name" placeholder="name" />
  <input type="text" [(ngModel)]="year" placeholder="year" />

  <button (click)="buttonClicked()">Click to Insert New Row</button>
  `,
  styles: []
})
export class AppComponent {
  title = 'app';

  public id: number;
  public name: string;
  public year: number;
  public rows: Array<{id: number, name: string, year: number}> = [];

  buttonClicked() {
    this.rows.push( {id: this.id, name: this.name, year: this.year } );

    //if you want to clear input
    this.id = null;
    this.name = null;
    this.year = null;
  }
}

A: // html data//

        Type
        Name
        Batters
        Toppings

          {{data.type}}

              {{data.name}}

                    {{item.type}}

                       {{y.type}}

//component.ts file//

export class AppComponent {
public newtext:any;
public rows:any=[];
public url:any=["../assets/images/image.jpeg","../assets/images/danger.jpeg","../assets/images/crab.jpeg",
"../assets/images/aws.png","../assets/images/error404.jpg","../assets/images/night.jpg"];
public displayimage:any=["../assets/images/image.jpeg"];
public setimage:boolean=true;
public i:any=1;

Newjson=[
    {
      "id": "0001",
      "type": "donut",
      "name": "Cake",
      "ppu": 0.55,
      "batters":
        {
          "batter":
            [
              { "id": "1001", "type": "Regular"},
              { "id": "1002", "type": "Chocolate"},
              { "id": "1003", "type": "Blueberry"},
              { "id": "1004", "type": "Devil's Food"}
            ]
        },
      "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5005", "type": "Sugar" },
          { "id": "5007", "type": "Powdered Sugar" },
          { "id": "5006", "type": "Chocolate with Sprinkles" },
          { "id": "5003", "type": "Chocolate"},
          { "id": "5004", "type": "Maple" }
        ]
    },
    {
      "id": "0002",
      "type": "donut",
      "name": "Raised",
      "ppu": 0.55,
      "batters":
        {
          "batter":
            [
              { "id": "1001", "type": "Regular"}
            ]
        },
      "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5005", "type": "Sugar" },
          { "id": "5003", "type": "Chocolate"},
          { "id": "5004", "type": "Maple" }
        ]
    },
    {
      "id": "0003",
      "type": "donut",
      "name": "Old Fashioned",
      "ppu": 0.55,
      "batters":
        {
          "batter":
            [
              { "id": "1001", "type": "Regular"},
              { "id": "1002", "type": "Chocolate"}
            ]
        },
      "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5003", "type": "Chocolate"},
          { "id": "5004", "type": "Maple" }
        ]
    }
  ]
}


Q: Program on GD32f103 microcontroller runs only with debugger attached, won't run after reset I'm using a J-Link EDU Mini debugger/programmer, to upload a simple test program to a GD32f103 microcontroller (the ST32f103 clone/copy). The program is a mere test program, meant to turn an LED on. It's written in SMT32CubeIDE, and here, it is based on the ST32f103.
After uploading the compiled .elf file to the GD32f103 using the J-Kink, the LED turns on just fine. However, once I detach the J-Link and reset the processor, the program appears not to boot, because the LED won't turn on.
What can the source of this problem be?


Q: How to combine multiple querysets in django Suppose there is an event model and for each event there is one client and one consultant. Also, one consultant can have multiple events. Each event has number of different documents. I am trying to display list of events when a consultant logs in and in that list od events it should display their respective documents.
Models.py:
class Client_Profile(models.Model):
    user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)  # Field name made lowercase.
    first_name = models.CharField(db_column='First_name', max_length=50)  # Field name made lowercase.
    last_name = models.CharField(db_column='Last_name', max_length=50)  # Field name made lowercase.
    phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10)  # Field name made lowercase.
    # role_id = models.ForeignKey(Role, on_delete=models.CASCADE)

    def __str__(self):
        return self.first_name

class Consultant_Profile(models.Model):
    user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)  # Field name made lowercase.
    first_name = models.CharField(db_column='First_name', max_length=50)  # Field name made lowercase.
    last_name = models.CharField(db_column='Last_name', max_length=50)  # Field name made lowercase.
    phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10)  # Field name made lowercase.
    # role_id = models.ForeignKey(Role, on_delete=models.CASCADE)

    def __str__(self):
        return self.first_name

class Event(models.Model):
    event_id = models.AutoField(db_column='event_id', primary_key=True)
    client_id = models.ForeignKey(Client_Profile, db_column='Client_ID', on_delete=models.CASCADE)  # Field name made lowercase.
    consultant_id = models.ForeignKey(Consultant_Profile, db_column='Consultant_ID', on_delete=models.CASCADE)  # Field name made lowercase.

    def __str__(self):
        return str(self.event_id)

class Document(models.Model):
    document_id = models.AutoField(db_column='document_id', primary_key=True)
    document_name = models.CharField(db_column='document_name', max_length=50, null=True, blank=True)  # Field name made lowercase.
    path = models.FileField(null=True, upload_to='files/')
    date_uploaded = models.DateTimeField(default=timezone.now, null=True, blank=True)
    event_id = models.ForeignKey(Event, db_column='Client_ID', on_delete=models.CASCADE)  # Field name made lowercase.

    def __str__(self):
        return self.document_name + ": " + str(self.path)  # this specifies how should instance of this class should be printed.

views.py
@login_required
def consultant_home(request):
    consultant_pr = Consultant_Profile.objects.get(user_id=request.user)
    event_id = Event.objects.filter(consultant_id=consultant_pr.pk)
    for id in event_id:
        doc = Document.objects.filter(event_id=id)
    context = {'id': event_id, 'doc': doc, 'consultant_pr': consultant_pr}
    return render(request, 'Consultant/consultant_documents.html', context)

document.html
                    {% for eve in id %}

Event id: {{ eve.event_id }}

                        {% for dox in doc %}

document name: {{ dox.document_name }}

path: {{ dox.path}}

                        {% endfor%}
                    {% endfor %}

A: You can simply loop over the related Document objects from the Event object itself by using document_set (the default related_name for Document i.e. the model name in lowercase with _set appended). Also you can optimise the number of queries made by using prefetch_related [Django docs]:
In your view:
@login_required
def consultant_home(request):
    consultant_pr = Consultant_Profile.objects.get(user_id=request.user)
    events = Event.objects.filter(consultant_id=consultant_pr.pk).prefetch_related('document_set')
    context = {'events': event, 'consultant_pr': consultant_pr}
    return render(request, 'Consultant/consultant_documents.html', context)

In your template:
{% for event in events %}

Event id: {{ event.event_id }}

    {% for document in event.document_set.all %}

document name: {{ document.document_name }}

path: {{ document.path }}

    {% endfor%}
{% endfor %}


Q: Randomly SSLException Unsupported record version Unknown-0.0 Sometimes the code below fails and sometimes it work. I'm using Java8. Is it a server side problem?
Exception in thread "main" javax.net.ssl.SSLException: Unsupported record version Unknown-0.0.
EDIT:
I downgrade to JDK7 from JDK8 and it works. The only solution i found that works.
public static void main(String[] args) throws Exception {
    URL u = new URL("https://c********.web.cddbp.net/webapi/xml/1.0/");
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/plain");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + 140);
    connection.setUseCaches(false);
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
}

A: I got the same error message in a new java installation when trying to use an SSL connection that enforces 256-bit encryption. To fix the problem I found I needed to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html)

A: I had this line
    SSLContext sc = SSLContext.getInstance("SSL");

Had to change it to
    SSLContext sc = SSLContext.getInstance("TLSv1");

And now it works on both, java 7 and java 8
Note: (In java 7 SSL and TLS both worked with the same url, in java 8 just tried TLSv1 but I guess SSLv1 also works)

A: Download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files according to your JDK/JRE version and put it in lib/security folder
By default,Java Cryptographic Extension is limited in accessing function and algorithm usage.We need to make it unlimited.

A: According to the stack trace, the RecordVersion Unknow-0.0 is produced from here
=> referenced from here => which is invoked in InputRecord.readV3Record
most of the time, these two values should not be 0, the reason for this happening is probably the wrong response from server while handshaking.
(This is not an answer though, just some information for easier figuring out the problem and solution)

A: This error is fixed in latest jre's, just upgrade the version of jre. This issue is caused by SNI


Q: File Upload not working in IE and Firefox I have the following code to upload a file to the server. For some weird reason, it does not work in IE and Mozilla Firefox but works perfect in Chrome. What is the problem?
PHP:
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
    $POST_MAX_SIZE = ini_get('post_max_size');
    $unit = strtoupper(substr($POST_MAX_SIZE, -1));
    $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

    if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
        HandleError('File exceeded maximum allowed size. Your file size MUST NOT be more than 100kb.');

// Settings
    $save_path = 'uploads/'; //getcwd() . '/uploads/';The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
    $upload_name = 'userfile';                          // change this accordingly
    $max_file_size_in_bytes = 102400;               // 100k in bytes
    $whitelist = array('jpg', 'png', 'gif', 'jpeg');    // Allowed file extensions
    $blacklist = array('php', 'php3', 'php4', 'phtml','exe','txt','scr','cgi','pl','shtml'); // Restrict file extensions
    $valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format)

// Other variables
    $MAX_FILENAME_LENGTH = 260;
    $file_name = $_FILES[$upload_name]['name'];
    //echo "testing-".$file_name."
";
    //$file_name = strtolower($file_name);
    ////////$file_extension = end(explode('.', $file_name));

    $parts = explode('.', $file_name);
    $file_extension = end($parts);

    $uploadErrors = array(
        0=>'There is no error, the file uploaded with success',
        1=>'The uploaded file exceeds the upload max filesize allowed.',
        2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3=>'The uploaded file was only partially uploaded',
        4=>'No file was uploaded',
        6=>'Missing a temporary folder'
    );

// Validate the upload
    if (!isset($_FILES[$upload_name]))

        **HandleError('No upload found for ' . $upload_name);**//THROWS UP ERROR HERE in IE and Firefox

    else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
        HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
    else if (!isset($_FILES[$upload_name]['tmp_name']) || !@is_uploaded_file($_FILES[$upload_name]['tmp_name']))
        HandleError('Upload failed.');
    else if (!isset($_FILES[$upload_name]['name']))
        HandleError('File has no name.');

HTML:
<form name="upload" action="/upload" method="POST" ENCTYPE="multipart/formdata">

'.MSG142.': <input class="font_upload_picture" type="file" name="userfile">
<input type=hidden name=MAX_FILE_SIZE value=102400 />

                                <input type="image" name="upload" value="upload" src="/img/layout/btnupload.gif" border="0" />

 '.MSG143.'

        </form>

A: The enctype of the form should be multipart/form-data

A: You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />.

A: Some of your logic is off:
if (!isset($_FILES[$upload_name]))

will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4.
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)

You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong.
You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename.
So, your upload validation should look something like:
if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) {
    $fi = finfo_open(FILE_INFO_MIME_TYPE);
    $mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']);
    if (!in_array($valid_mime_type, $mime)) {
       HandleError("Invalid file type $mime");
    }
    etc...
} else {
    HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
}


Q: JavaFX 2 Window Icon not working I'm trying to add an Icon to my JavaFX 2 application, but the ways I have found don't seem to work.
Image icon = new Image(getClass().getResourceAsStream("/images/icon.png"));
stage.getIcons().add(icon);

The icon is 32x32 in size.
When I try
Image icon = new Image("http://goo.gl/kYEQl");

It does work, in Netbeans and in the runnable jar.
I hope this can be fixed.

A: The problem was in the icon itself. It did load it like it should, but for some reason it didn't display like it should.
I remade the icon I was trying to use to different sizes (16x16 up to 512x512) and added them all to the icon list.
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_16.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_32.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_64.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_128.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_256.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_512.png")));

Now it uses the icon like it should.


Q: Unset one Array on the basis of another array value in php? How can I remove one array index on the basis of another array value.
For example-
Array1
(
[0] => @@code
[1] => @@label
[2] => @@name
[3] => @@age
)

Array2
(
[0] => 123jj
[1] => test
[2] => john
[3] => 45
)

Array3
(
[0] => 2 #2 is index to be unset in array1 and array2
[1] => 3 #3 is index to be unset in array1 and array2
)

I have  3 arrays , I want to unset array1 and array2 index on the basis of value of array3 using php.How can I use unset() Method for this?
unset($array1,$array3) #this is wrong, but some thing like that
unset($array2,$array3)

With Out for loop.
I should get
Array1
(
[0] => @@code
[1] => @@label
)

Array2
(
[0] => 123jj
[1] => test
)

A: You asked similar question and removed it after getting the answer :
unset array indexs from value of another array?
$firstArray = array( 0 => '@@code' ,1 => '@@label' ,2 => '@@name' ,3 => '@@age' );

$keysArray = array( 0 ,1 );

$resultArray = array_diff_key( $firstArray ,array_flip( $keysArray ) );

var_dump( $resultArray );

A: Maybe you need this?
foreach($array3 as $tmp){
  unset($array1[$tmp]);
  unset($array2[$tmp]);
}


Q: executing two queries in firebase and finding the difference of the two
My Firebase has two children

*

*expenditure

*sales

I want to find the difference between sales and expenditure.
Currently i am able to find the total of both children.
However i am stuck trying to find the difference between the two.
Below is the code I have executed to compute the sum.
    dref = FirebaseDatabase.getInstance().getReference();

    DatabaseReference dref = FirebaseDatabase.getInstance().getReference();
    dref= dref.child("LukenyaExpenditure");

    dref.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot snapshot) {
            int totalAmount = 0;
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
                totalAmount += dogExpenditure.getAmount();
            }

            textView4.setText("Your total expenses for Lukenya Unit is:" +Integer.toString(totalAmount));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

Any help will be appreciated


Q: How to add trace to plotly scatter plot  p <- plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
               symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
               text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,hoverinfo = 'text'
         )

Above code produces this plot.

Now to this chart I want to add a trace with scatter plot with color depending on Currency column.
I tried this but it produces combination of two field as the legend.
Basically I want to classify the plot based on currency type but also add overlay or trace based on column SYM as the symbol.
  p <- plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
               symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
               text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,hoverinfo = 'text'
         ) %>%
    add_trace(x = ~`Maturity Date`, y =  ~YVal , color=~Crncy)

data:
bData <- structure(list(Crncy = structure(c(9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 3L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L,
5L, 9L, 9L, 9L, 9L, 6L, 5L, 9L, 9L, 3L, 9L, 5L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 7L, 6L, 7L, 6L, 9L,
7L, 7L, 3L, 2L, 7L, 9L, 9L, 9L, 9L, 8L, 9L, 9L, 9L, 10L, 9L,
9L, 4L, 4L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 4L, 9L, 9L,
9L, 5L, 9L, 9L, 9L, 9L, 5L, 9L, 5L, 9L, 2L, 9L, 5L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 2L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 1L, 5L, 1L, 9L, 9L, 9L,
9L, 9L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 6L, 9L, 9L,
9L, 9L, 1L, 1L, 9L, 9L, 9L, 9L, 9L, 1L, 9L, 9L), .Label = c("AUD",
"CAD", "CHF", "COP", "EUR", "GBP", "JPY", "PEN", "USD", "ZAR"
), class = "factor"), `Maturity Date` = structure(c(20772, 19689,
18969, 18969, 20815, 20119, 20865, 20864, 20134, 20873, 20873,
20887, 20011, 20897, 20162, 19797, 20908, 20908, 20923, 19841,
19107, 19107, 20941, 20935, 20936, 20936, 20953, 20049, 19138,
19860, 21005, 21027, 19562, 19562, 21014, 19222, 21047, 19950,
19264, 19285, 19292, 19292, 19323, 19382, 19381, 20000, 19404,
20176, 19437, 19875, 19875, 19508, 20635, 19555, 19555, 20658,
19038, 19628, 18946, 19745, 19746, 19021, 19042, 19042, 20545,
20623, 19047, 19412, 19415, 20178, 20178, 19611, 19807, 20168,
20551, 20640, 20957, 20223, 19858, 19692, 19158, 20258, 19720,
20269, 20999, 20999, 20290, 20278, 20300, 20300, 21029, 19753,
20318, 20328, 20423, 20120, 20223, 20240, 19335, 20594, 19510,
19905, 20073, 20347, 20392, 18897, 20962, 20994, 21009, 21043,
19287, 19505, 18899, 19006, 19081, 19323, 19373, 19203, 19417,
19415, 19430, 19469, 19492, 19527, 19599, 20344, 19638, 19655,
19675, 19688, 20068, 19711, 19780, 19803, 19838, 19865, 19892,
19890, 19940, 19962, 20706, 20011, 18927, 20041, 18949, 20777,
20116, 20145, 19041, 20156, 20177, 20174, 20173, 20205, 20208,
20235, 20248, 20249, 19523, 20521, 20588, 20574, 20465, 20482,
19400, 20588, 21021, 20649, 20389, 20409, 19950, 19600, 19601,
20346, 19658, 20747, 19657, 19656, 19657, 20307, 20347, 19259,
20087, 20810, 20077, 19349, 20118, 20483, 20112, 20109, 19392,
19594, 20144, 21056, 19407, 20749, 20573, 19296, 19300, 19300,
19310, 20041, 19346, 20907, 19976, 20744, 20202, 19132, 19132,
19132), class = "Date"), Sym = structure(c(4L, 3L, 4L, 1L, 2L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 1L, 4L, 3L, 2L, 1L, 4L, 1L, 2L, 1L, 2L,
1L, 2L, 3L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 3L, 2L,
1L, 4L, 1L, 4L, 1L, 2L, 1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 2L, 3L, 4L,
3L, 4L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 4L, 4L, 4L), .Label = c("Axe",
"Axe, Owned", "None", "Owned"), class = "factor"), YVal = c(20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217,
218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229)), class = "data.frame", row.names = c(NA,
-210L))

A: Maybe is this what you are looking for? (I have used split from plotly):
library(plotly)
#Code
plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
        split = ~Crncy,
        text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,
        hoverinfo = 'text')

Output:

Update: Here somo other options for OP:
#Option 1
plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
        text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,
        hoverinfo = 'text',legendgroup = 'group1'
) %>%
  add_trace(x = ~`Maturity Date`, y =  ~YVal , symbol=~Crncy,legendgroup = 'group2')

Output:

Option 2:
#Option 2
plot_ly(bData, x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
               legendgroup = 'group1',color = ~Sym) %>%
  add_trace(y = ~YVal, legendgroup = 'group2',type = 'scatter', mode='markers',
            color=~Crncy)

Output:


Q: define parameter in update query in python psycopg2 This my python code which is used to perform update operation from reading the csv file. I tried with this also. It doesn't work out.
for i  in cin:
    try:
        conn=psycopg2.connect("dbname=pharmaflare user=postgres")
        cursor=conn.cursor()
        cursor.execute("UPDATE pharmaflare_drug_interaction SET se_interaction ='%s' WHERE primary_drug ='%s' AND secondary_drug ='%s' AND side_effect ='%s'"%(i[3],i[0],i[1],i[2]))
        conn.commit()
        cursor.close()
        conn.close()
        #print "done",i[0],i[1],i[2],i[3]
    except Exception as e:
        cerr.writerow(i)
        ferr.flush()
        traceback.print_exc(file=sys.stdout)
        continue

Here I am facing the exception like syntax error due to the QUOTE's problem:
Wherever the single quotes presents this exception arises.
  Traceback (most recent call last):
  File "<ipython console>", line 5, in <module>
  ProgrammingError: syntax error at or near "S"
  LINE 1: ...secondary_drug ='NEUER' AND side_effect ='MENIERE'S DISEASE'

Is there any alternative way available to define query statement without troubling the Quotes problem?

A: There are a couple ways to solve it. The easy/hack way to do it is to employ the re.escape() function. That function can be thought of as an equivalent to PHP's addslashes() function, though it pains me to make that comparison.
Having said that, my reading indicates psycopg2 takes advantage of PEP 249. If that's true, then you should be able to pass in parameterized queries and have it escape them for you.


Q: php form won't send or go to header location after submit I have a simple php form for contact purposes. However, it won't send the email or go to the correct page after submit. It redirects to the mail.php instead.
My contact form named contact.php is as follows:
 <form id="contact-form" action="mail.php" method="POST">
    <fieldset>

        Your Name: <input type="text" name="name">
        Your Email:<input type="text" name="email">
        Your Contact No:<input type="text" name="contact">

Your Message:

            <textarea name="message" rows="6" cols="25"></textarea>

        <input class="button" type="submit" value="Send">
        <input class="button" type="reset" value="Clear">

    </fieldset>
</form>

And the php code named mail.php is as follows:
    <?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    &contact = $_POST['contact'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "info@whatever.co.za";
    $subject = "Contact form message";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    header("Location:contact.php");
    ?>

What am i doing wrong. It just wont send the message to email or redirect to the correct page??

A: Your syntax is ever so slightly wrong. &contact on line 5 should be $contact. I assume you're on a production server, so error reporting would be disabled and you wouldn't get any warnings.

A: Try using @ before mail function
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$contact = $_POST['contact'];
$formcontent="From: $name \n Message: $message";
$recipient = "info@whatever.co.za";
$subject = "Contact form message";
$mailheader = "From: $email \r\n";
@mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("location: contact.php");
?>

this will let you pass even if mail function produce any issue. Also please check if there are any other header are not sent using http://php.net/manual/en/function.headers-sent.php function.
I would strongly suggest to use PHPMailer or some other class to send any kind of email.

A: Please check the contact.php file whether some redirection is happening from contact.php to mail.php

A: I think there may be an issue sending mail from your server. The mail.php file is probably tripping up on the mail function and not doing the redirect.
Create a new file with just the php mail function in there (with your email address and a test message) and browse it from your web browser, does it send?

A: Try to use ob_start() at the start of script, and exit(); after header("Location: contact.php");
smth like this ...
<?php
    ob_start();
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    &contact = $_POST['contact'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "info@whatever.co.za";
    $subject = "Contact form message";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    header("Location: contact.php");
    exit();
?>

A: Change the mail.php to the following:
<?php
mail("info@whatever.co.za", "Contact form message", $_POST['message'], "From: ".$_POST['name']." <".$_POST['email'].">");
header("Location: contact.php");
?>


Q: HTTP Status 500 - Servlet.init() for servlet appServlet threw exception Spring - beans are not created org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reorderLevelController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected com.bvas.insight.service.ExcelService com.bvas.insight.controller.BaseController.excelService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'excelService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.bvas.insight.service.ExcelService.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'localSessionFactory' defined in ServletContext resource [/WEB-INF/servlet-context.xml]: Cannot resolve reference to bean 'localDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'localDataSource' defined in ServletContext resource [/WEB-INF/servlet-context.xml]: Cannot create inner bean 'com.zaxxer.hikari.HikariConfig#73d35ee2' of type [com.zaxxer.hikari.HikariConfig] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.zaxxer.hikari.HikariConfig#73d35ee2' defined in ServletContext resource [/WEB-INF/servlet-context.xml]: Cannot create inner bean '${jdbc.driver}#3f778a58' of type [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for bean with name '${jdbc.driver}#3f778a58' defined in ServletContext resource [/WEB-INF/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)

Here it is the pom.xml
<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.4.RELEASE</org.springframework-version>
    <hibernate.version>4.2.2.Final</hibernate.version>
    <org.aspectj-version>1.6.10</org.aspectj-version>
    <org.slf4j-version>1.6.6</org.slf4j-version>
    <mysql.connector.version>8.0.17</mysql.connector.version>
    <jackson.version>1.9.10</jackson.version>
</properties>

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
        <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.5</version>
        <type>jar</type>
    </dependency>

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

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

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

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.2.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>

    <!-- AspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>

    <!-- IText -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.5</version>
    </dependency>

    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${org.slf4j-version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.15</version>
        <exclusions>
            <exclusion>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
        </exclusions>
        <scope>runtime</scope>
    </dependency>

I just change the mysql driver version. Project is ruuning smoothly on server but am getting error on my local. Eclipse verion is 2019-09. I also change the JDK 1.7 to 1.8. Any one can please help me. also i need to know is we need any spring plugin or ide in eclipse or just declared jar files are enough.

A: I don't see mysql driver dependency in your pom, it could be running fine on the server because your server may have the driver jar, in that case adding mysql driver dependency in provided scope should solve the issue.


Q: function adding in an extra line break? I have a function which sanitizes input from a form and another function which decodes it. It's kind of like bbcode which also converts line breaks into
 when storing it in the database (using the nl2br() function), and then converts the
 back into line breaks whenever it is put back into a field for the "edit page" where the user can edit their post (using str_replace('
',"\n",$data)).
The problem is that every time a post is decoded for editing and then coded again for storage, each
 turns into two

.
Is a \n or \r equal to two HTML line breaks?
Here is the code for the two functions.
function sanitize2($data) {

  $patterns = array();
    $patterns[0] = '/</';
    $patterns[1] = '/>/';
  $data1 = preg_replace($patterns, "", $data);

  $bopen = substr_count($data1, '[b]') + substr_count($data1, '[B]');
  $bclosed = substr_count($data1, '[/b]') + substr_count($data1, '[/B]');
  $iopen = substr_count($data1, '[i]') + substr_count($data1, '[I]');
  $iclosed = substr_count($data1, '[/i]') + substr_count($data1, '[/I]');
  $uopen = substr_count($data1, '[u]') + substr_count($data1, '[U]');
  $uclosed = substr_count($data1, '[/u]') + substr_count($data1, '[/U]');

    $bx = $bopen - $bclosed;
    $ix = $iopen - $iclosed;
    $ux = $uopen - $uclosed;

    if ($bx > 0) {
        for ($i = 0; $i < $bx; $i++) {
            $data1 .= "[/b]";
        }
    }
    if ($ix > 0) {
        for ($i = 0; $i < $ix; $i++) {
            $data1 .= "[/i]";
        }
    }
    if ($ux > 0) {
        for ($i = 0; $i < $ux; $i++) {
            $data1 .= "[/u]";
        }
    }

  $newer = sanitize($data1);

    $search  = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]', '[B]', '[/B]', '[I]', '[/I]', '[U]', '[/U]');
    $replace = array('', '', '', '', '', '', '', '', '', '', '', '');

  $newest = str_replace($search, $replace, $newer );

  $final = nl2br($newest);

  return $final;

}

function decode($data) {

$new = str_replace('
',"\n",$data);

    $search  = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]');
    $replace = array('', '', '', '', '', '');

  $newer = str_replace($replace, $search, $new );

  return $newer;
}

UPDATE:
I found this page which gives a workaround. Apparently this is a problem with the nl2br() function. :-/
http://websolstore.com/how-to-use-nl2br-and-its-reverse-br2nl-in-php/

A: From the documentation for nl2br:

nl2br — Inserts HTML line breaks before all newlines in a string

(emphasis mine).
It doesn't replace the newlines, it just inserts linebreaks. So if you try to revert nl2br by replacing
, you will get two \n, the old one and the one you inserted when replacing the
.
The easiest fix would be removing all \n in the string you get from nl2br, the right thing would be storing the text without the
 and convert when you display it.


Q: Launch screen doesn't show first after the first launch time? I am developing App with React native.
I set an image in the launchScreen.Xib.
The first time, the launch screen works well. After the launch screen hide,
then I will see the View MainView.
I shut up the App in the background. A moment later, I tap the App icon to launch the App again.
To my surprise, the App will show the MainView first, the MainView continue show 0.2 seconds.
After the MainView flash, the launch screen show now. A few seconds later, the MainView show again.
My issue is the MainView will show before the launch screen in the later launch time.
In my opinion, the launch screen should show first and the MainView show later.
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"patient"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

This is my code above in the AppDelegate.m. This is the initial code of React native.
One more thing, the MainView show a moment, and the screen shows a white view instead of the MainView, a moment later, the MainView show again.

A: Well, you’re trying to instantiate and show with timer your own launch screen (not good!) while also asking iOS to do one.  Just get rid of most or all of this code.  Use the standard approach of having a launch storyboard then set up your main VC as normal in your appDelegate.
Using that timer is making assumptions about the timing of each app launch that iOS can’t guarantee.


Q: Why is this embedded iframe video not playing? I want to add this video on my website. I added this code but it’s not working. Please help me.

A: UPDATED
Please replace this with your code

and css
#container {
    border: 1px solid red;
    text-align:center;
    width: 80%;
    margin-left:auto;
    margin-right:auto;
}

as you are not using correct code for video..go in video link..then share and then embed code and take that code and it will work..hope this help.
Updated : now your video is responsive..change width according to your need.

A: I didn't clearly understand what you're trying to achieve but try this example:

              <button onclick="playPause()">Play/Pause </button>

              <video id="video" width="420">
                <source src="video.mp4" type="video/mp4">
                Your browser does not support HTML5 video.
              </video>


Q: Multiple plots sharing one datasource Core Plot In case of real time data ; I am maintaining a single datasource and multiple plots each having unique identifier and linestyles having unique colour. Inserting data in every plot using the insertDataAtIndex and then in the numberForPlot function returning the appropriate value else returning nil. However only one of the plots gets successfully plotted though it still enters the numberForPlot and symbolForPlot accordingly.Is it possible for multiple plots to share the same datasource or am I missing something here.


Q: Using NOIP with RPI node.js server Im no expert in networks so sorry if something seems stupid.
I'm having a problem connecting to RPI node.js server located in my home externally. I used NO-IP and configured it on router with specific host-name. I have port forwarded to 8888 port.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require('socket.io')(http);
var path = require('path');
http.listen(8888, "0.0.0.0");

/*app.use(function (req, res, next){
    res.setHeader('Access-Control-Allow-Origin', 'http://hostname:port');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});*/
app.use(express.static(path.join(__dirname, '/')));
app.get("/home",function(req,res,next){
    res.sendFile(path.join(__dirname + "/index.html"));
});
console.log("server ubi jeza");

If I try to connect to http://hostanme.org it connect to my router. If I try connect to http://hostanme.org:8888 it times-off.
Port forward check works fine and says that port 8888 is working when I run the server. When server is not running it say that connection is closed.
I also tried with sudo nano /etc/sysctl.conf and net.ipv4.ip_forward=1 but it doesn't work ither.
Am I doing something wrong?

A: I can access page from outside world. When I'm on local network I can not access it with external IP.


Q: Retrieving Data with jQuery AJAX Without Reloading Page in php I have try to stop refresh page on click on select option but when I stop refresh page then data can not get.
here code
echo "<form name='frmtopdevotees' method='post' action='topuser_load.php'>

select month  <select id='seldrp' name='themonth' OnChange ='document.frmtopdevotees.submit()'>

                        $optionsmonths
                </select>
                <select name='topdevotees' id='seldrp' OnChange ='document.frmtopdevotees.submit()'>
                        <option value=10 $M10>Top 10</option>
                        <option value=20 $M20>Top 20</option>
                        <option value=50 $M50>Top 50</option>
                        <option value=100 $M100>Top 100</option>
                </select>

        </form>";
?>

when I remove Onchange = 'document.frmtopdevotees.submit()' then page stop to refresh but not data change.

A: Change name to id in ajax,
$('#seldrp').onchange(function(){
   ^     ^
// ajax here
});

And you have syntax errors in ajax.
   var themonth = $('#seldrp').val();
   var topdevotee = $('#topdevotees').val();//topdevotess should be the id of 2nd select box.
   $.ajax({
        type: 'post',
        data: {
            topdevotees: topdevotees,
            themonth: themonth
        },
        async:false,// this line for waiting for the ajax response.
        url: "topuser_load.php?topdevotees=" + topdevotees + "&themonth=" + themonth,
        success: function (response) {
            $('themonth').append(response);
            $('#frmtopdevotees').submit();

        }
    });

A: From your code what I can understand is you want to trigger a server call without refreshing the page (AJAX) whenever your any one the select option changes.
There are errors in the code posted. Following is my observation -

*

*There can be only one ID in entire page. You have used 'seldrp' in couple of places.

*If you want the AJAX functionality, you should avoid calling submit() function of the form.

*The AJAX syntax is wrong which should be as follows -
$.ajax({
    url : "topuser_load.php?topdevotees=" + topdevotees + "&themonth=" + themonth,
    method: "post",
    data: {
        topdevotees: topdevotees,
        themonth: themonth
    }, // can even put this in variable and JSON stringify it
    success: function (response) {
        $('themonth').append(response);

    }
});

Now coming to the solution part of it:
I would do this as follows -
1. Will just listen on the select change in JQUERY
2. Once a select change is triggered, AJAX call is made and which returns the response.
The modified code is -

echo "<form name='frmtopdevotees'>

select month  <select id='seldrp1' name='themonth'>

        $optionsmonths
    </select>
        <select name='topdevotees' id='seldrp2'>
            <option value=10 $M10>Top 10</option>
            <option value=20 $M20>Top 20</option>
            <option value=50 $M50>Top 50</option>
            <option value=100 $M100>Top 100</option>
        </select>

</form>";
?>


Q: Write new value of a key in an already defined JSON file I have a JSON file of every user in my database. I want to change the value of a key from true to false on an action. How can I write it in  the file? Below is the JSON file:
{
  "name": "hi",
  "email": "hi@mail.com",
  "secFactorType": "microsoftTotpAuth",
  "loginid": "9867033239",
  "timezone": "+5.5",
  "workStartHours": "0900",
  "workEndHours": "1700",
  "ifRegenerateQR": true
}

I want to change the value of ifRegenerateQR to false in file.
JSON.parse(fs.readFileSync(userInfoFile)).ifRegenerateQR = false;

This is not writing in the file. How do I use fs.writeFile() to write changes to file?

A: Read file and store in JS object.
const obj = JSON.parse(fs.readFileSync(userInfoFile));

Change whatever you want to change.
obj.ifRegenerateQR = false;

Write obj back to file.
fs.writeFile(JSON.stringify(obj));


Q: WinJS List GridLayout header above list How to put header in listview with GridLayout.
When I put header above listview my header take some height and last row in listview is not showed, because of header.
I also found a way to set header in listview directly:
data-win-options="{ header: select('.header') }">

With this my header is positioned on the left side of list, not above the list, like normal header should be.
I did not see any example with listview GridLayout and header section above (for instance I wanna put search box and heading in header).
Any example of this ?

A: Two solutions are here:

1) This is answer I get from Microsoft:
In the list view the WinJS.UI.GridLayout's viewport is loaded
  horizontally.

  You need to change the viewport's orientation to vertical. You can do
  this by attaching the event onloadingstatechanged event.
args.setPromise(WinJS.UI.processAll().then(function () {
                listview.winControl.onloadingstatechanged = function myfunction() {
                    if (listview.winControl.loadingState == "viewPortLoaded")
                    {
                        var viewport = listview.winControl.element.getElementsByClassName('win-viewport')[0];
                        viewport.className = 'win-viewport win-vertical';
                    }
                }
            }));

and change the class win-horizontal to win-vertical.

2) Problem could be also solved adding standard html header and list below header, without data-win-options="{ header: select('.header') }" attribute.
In that case we need to calculate height of the list:
 .list {
    height: calc(100% - headerHeight);
 }


Q: Not able to show the menu button in place of back button in Ionic I am working on the Ionic app and I have used navbar in my ionic app. When I move to other page, In place of menu button it is showing the back button. I don't want to show the back button, I always want to show the menu button in the navbar.
This is page1.html:
<ion-header>
  <ion-navbar hideBackButton="true">
    <button ion-button menuToggle start>
      <ion-icon name="menu"></ion-icon>
    </button>
  </ion-navbar>
</ion-header>

It is only hiding the back button and not showing the menu button. I want to show the menu button in place of back button.
This is page1.html: Another Try.
<ion-header>
  <ion-navbar swipeBackEnabled="false">
    <button ion-button menuToggle start>
      <ion-icon name="menu"></ion-icon>
    </button>
  </ion-navbar>
</ion-header>

This is not working. In this case, It is showing the back button.
This is page1.ts:
 ionViewWillEnter() {
  // Reset the content nav to have just this page
  // we wouldn't want the back button to show in this scenario
  this.navCtrl.setRoot(MerchandisePage);
 }

So I decided the make the page as a root page but It is continuously loading. This is not working.
This is my page.html:
<button (click)="merchandisepage2()" class="mybtn22" ion-button round>View All</button>

In this page, I have the button that will push to the other page.
This is my page.ts:
 movetopage1()
{
    this.navCtrl.push(Page1);
}

I don't want to show the back button, it should always show the menu button in the navbar. Any help is much appreciated.

A: There is an issue with ionic when you have a custom button in the navbar and the page is not root.
You can find a quick fix here..
Ionic 3: Menutoggle keeps getting hidden

A: The solution is that, set the page to the root page.
page.ts:
movetopage1()
{
    this.navCtrl.setRoot(Page1);
}

This is the method that comes in the Ionic sidebar theme.
This is the one that comes in the Ionic sidebar theme:
 openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }


Q: finding prime numbers c# the program should ask for a number and print all the primes numbers between 1 to the number the user entered... why isn't it working?
bool isPrime = true;
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
    for (int j = 2; j <= Math.Sqrt(i); j++)
    {
        if (i % j == 0)
        {
            isPrime = false;
        }
    }
    if (isPrime)
    {
        Console.WriteLine(i + " is a prime number");
        primes++;
    }
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");

A: You have put the boolean out of the loops. So, once it is false, it will never be true in other loops and this cause the issue.
        int primes = 0;
        Console.WriteLine("Enter a number");
        int N = int.Parse(Console.ReadLine());
        for (int i = 2; i <= N; i++)
        {
           bool isPrime = true;
            for (int j = 2; j <= Math.Sqrt(i); j++)
            {
                if (i % j == 0)
                {
                    isPrime = false;
                }

            }
            if (isPrime)
            {
                Console.WriteLine(i + " is a prime number");
                primes++;
            }
        }
        Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");

A: First define this class:
public static class PrimeHelper
{
    public static bool IsPrime(int candidate)
    {
        if ((candidate & 1) == 0)
        {
            if (candidate == 2)
            {
            return true;
            }
            else
            {
            return false;
            }
        }
        for (int i = 3; (i * i) <= candidate; i += 2)
        {
            if ((candidate % i) == 0)
            {
            return false;
            }
        }
        return candidate != 1;
    }
}

then call it in your application:
var finalNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < finalNumber; i++)
{
    bool prime = PrimeHelper.IsPrime(i);
    if (prime)
    {
    Console.Write("Prime: ");
    Console.WriteLine(i);
    }
}


Q: Attempting to pull concatenated Q-urls, using data-type in a table Will try and explain as concisely as I can.
Below is a dummy query based on one I'm attempting to edit.
I'm trying to return two different types which are pulled from the same table.
The first type of data is a numeric (a score from 1-10)
The next type of data is a both numbers and letters, used to complete a URL.
My problem is that the concat statement to return only null values. when I use the and statement to specify only URL data, the other column returns only null values.
Is there a way I can change this, to pull only one type of data in one column separate to the other?
Cheers
select
concat("example.com/",rs.answer,"/415x380.png") as Q_URL,

  Ease_of_use.score as "Ease_Of_use"
  from customer_feedback c
  left join response_data Ease_of_use on (Ease_of_booking_use.response_overall_id=c.id and Ease_of_use.data_type_id=1536)
  left join response_data rs on rs.customer_review_id=c.id
  join data_type dt on dt.id=rs.data_type_id
  where c.retailer_id in (678,1651)
  and rs.answer is not null
  and dt.response_type="photo_URL"
  group by c.id

A: I'm not sure what you mean by "I use the and statement to specify only URL data", but I would use isnull function to provide a default value for NULLS
concat("example.com/",isnull(rs.answer,"default value"),"/415x380.png")
rather than using rs.answer is not null


Q: How to implement "array type" grammar like typescript with pegjs? my problem is in the implementation of "array type" like typescript.
according to my grammar. In "array type" you can use "[]" after any type (eg string or int or even array again like int[][]).
this is simplified version of my grammar:
start = type

type = array / bool / string / int

string = "string"
int = "int"
bool = "bool"

// problem
array = t:type "[]" { return { kind: "array",type: t }}

the above code throw an syntax error:
Error: Maximum call stack size exceeded


Q: Python equivalent of matlab corr2 I want to know what is the python equivalent of the matlab function corr2 that gives the correlation coefficient between 2 matrices, return only one value.
http://www.mathworks.com/help/images/ref/corr2.html
I only found that the equivalent in python is scipy.signal.correlate2d but this returns an array.
Thanks.

A: Maybe this can be help you
def mean2(x):
    y = np.sum(x) / np.size(x);
    return y

def corr2(a,b):
    a = a - mean2(a)
    b = b - mean2(b)

    r = (a*b).sum() / math.sqrt((a*a).sum() * (b*b).sum());
    return r

A: import numpy
print numpy.corrcoef(x,y)

Where x and y can be 1-d or 2-d like arrays.
Take a look at the docs here.


Q: How do I know if I need to alloc and if I need to release? Completely new to Objective-C, trying to find out when I need to alloc and release objects.
For example, I want to fetch some data from the Web. I found an article at Apple which has this code:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
                  [NSURL URLWithString:@"http://www.apple.com/"]
                    cachePolicy:NSURLRequestUseProtocolCachePolicy
                timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc]
                                 initWithRequest:theRequest delegate:self];

What I don't understand is: Why do they need to call alloc on the connection but not on the request? How do I know when I need alloc and when not?
Similar questions for release. From what I read, I only ever need to release objects that were initialized using alloc/init. But all "initWithXXX" functions return autoreleased objects instead.
Is this a hard rule, or just convention? Is there a way to find out if I need to release an object or not?

A: Read the Cocoa Memory Management guide. You own an object only if the methods used to obtain it contains one of:

*

*new

*alloc

*retain

*copy
... and you only need to release (i.e. relinquish ownership) if you own it. If you obtain an instance through a method not containing any of these, you don't own it and have to take ownership explicitly (using retain) if you need it.
So, you need to alloc if you:

*

*want ownership or

*if there is no convenience constructor available (and you thus have to use alloc/init)

The initializer methods don't return autoreleased instances, they only initialize an allocd instance.

A: initWithXXX: methods do not return autoreleased objects! somethingWithXXX: class methods, however, do. This is a convention (in that it's not compiler-enforced), but it's followed so closely that you can treat it as a hard rule. The Clang static analyzer will also complain if you don't follow it.
requestWithURL: doesn't have "init" in the name. Also, requestWithURL: is called on the NSURLRequest class, whereas initWithRequest:delegate: is called on the NSURLConenction object returned by calling alloc on the NSURLConnection class.
(I hope that all makes sense.)

A: Please read the Memory Management Programming Guide. All of these are explained there. Also check out Learn Objective-C.

Why do they need to call alloc on the connection but not on the request?

Whenever you need to own an object to make it live longer than the function's scope, the object needs to be -retained. Of course you could use
NSURLConnection* theConnection = [NSURLConnection connectionWithRequest:theRequest
                                                               delegate:self];

but the connection will be -autoreleased. But because there's time for a connection to finish, this variable should be -retained to prevent the connection becoming invalid. Of course, then, you could do
NSURLConnection* theConnection = [[NSURLConnection connectionWithRequest:theRequest
                                                               delegate:self] retain];

But this is equivalent to +alloc → -init → -autorelease → -retain, the last two steps are redundant. Probably that's why Apple chooses to use +alloc/-init here.
(BTW, this style would cause the static analyzer to complain. It's better to store theConnection as an ivar somewhere, e.g. in the delegate object.)
On the other hand, the NSURLRequest is just a temporary object, so it needs to be -released when the function ends.  Again, you could use
NSURLRequest* theRequest = [[NSURLRequest alloc] initWithURL:...];
...
[theRequest release];

this is even more efficient, as the autorelease pool won't be filled up, but using this method one may forget to -release and cause a leak.

But all "initWithXXX" functions return autoreleased objects instead.

No, -init… should never return an -autoreleased object.


Q: Javascript Drag and Drop function order var li = document.getElementsByTagName('li');
var ziel = document.getElementsByClassName('ziel');
var dragItem = null;

for (var i of li) {
  i.addEventListener('dragstart', dragStart);
  i.addEventListener('dragend', dragEnd);
}

function dragStart() {
  dragItem = this;
  setTimeout(() => (this.style.display = 'none'), 0);
}

function dragEnd() {
  setTimeout(() => (this.style.display = 'block'), 0);
  dragItem = null;
}

for (j of ziel) {
  j.addEventListener('dragover', dragOver);
  j.addEventListener('dragenter', dragEnter);
  j.addEventListener('drop', Drop);
}

function Drop() {
  this.append(dragItem);
}

function dragOver(e) {
  e.preventDefault();
}

function dragEnter(e) {
  e.preventDefault();
}

Codepen
I have the problem, every time I take a list item and drop it in the same <ul> it gets thrown to the bottom of the list every time. I want it to stay in the same place if I let it go in the same <ul> but if I drop it in another <ul> it should be listed at the bottom of course. Does anyone have any idea how I do this?


Q: function && qualifier behaviour I'm confused by the following code:
struct test {
  void f() & {
    std::cout << "&" << std::endl;
  }
  void f() const& {
    std::cout << "const&" << std::endl;
  }
  void f() && {
    std::cout << "&&" << std::endl;
  }
  void f() const&& {
    std::cout << "const&&" << std::endl;
  }

  void g() & {
    std::cout << "& -> ";
    f();
  }
  void g() const& {
    std::cout << "const& -> " ;
    f();
  }
  void g() && {
    std::cout << "&& -> ";
    f();
  }
  void g() const&& {
    std::cout << "const&& -> ";
    f();
  }

  test() {} //allow default const construction
};

int main(int, char**) {
    test value;
    const test constant;

    value.g();
    constant.g();

    std::move(value).g();
    std::move(constant).g();
}

When I compile with clang 3.5 I get this output:
& -> &
const& -> const&
&& -> &
const&& -> const&

Why is the r-value qualifier being dropped here? And is there any way to call f from g with the right qualifier?

A: It is because dereferencing1 this always produces an lvalue, irrespective of the fact that it is pointing to a temporary object or not.
So when you write this:
f();

it actually means this:
this->f(); //or (*this).f()
           //either way 'this' is getting dereferenced here

So the overload of f() which is written for lvalue is invoked from g() — and const-correctness is applied accordingly as well.
Hope that helps.

1. Note that this is a prvalue; only after dereferencing it produces an lvalue.

A: ref-qualifiers affect the implicit object parameter, §13.3.1/4:

For non-static member functions, the type of the implicit object
  parameter is

*

*“lvalue reference to cv X” for functions declared
  without a ref-qualifier or with the & ref-qualifier

*“rvalue
  reference to cv X” for functions declared with the &&
ref-qualifier
where X is the class of which the function is a member and cv is
  the cv-qualification on the member function declaration.

Overload resolution is, roughly speaking, performed on the object argument to object parameter conversion just as any other argument->parameter conversion.
However, f() is transformed into (*this).f() (§9.3.1/3), and *this is an lvalue. §5.3.1/1:

The unary * operator performs indirection: […] and the result is an lvalue referring to the object or function to which the expression points.

Hence the overloads of f with the & qualifier are preferred - in fact, the rvalue overloads are entirely ignored since initializers of rvalue object references must be rvalues (last bullet point in §8.5.3/5). Also, non-const references are preferred over const ones in overload resolution (§13.3.3.2/3, last bullet point concerning standard conversions).

A: The call f() is interpreted as (*this).f(). The result of dereferencing a pointer is always an lvalue, so *this is an lvalue and the lvalue-qualified function is called.
This behaviour even makes sense, at least to me. Most of the time the object referred to by an rvalue expression will either be destroyed at the end of the full-expression (a temporary) or at the end of the current scope (an automatic local variable that we choose to std::move). But when you're inside a member function, neither of those is true, so the object should not treat itself as an rvalue, so to speak. This is also why it makes sense for the name of an rvalue reference function parameter to be an lvalue within the function.
If you want the rvalue-qualified f to be called, you can do this:
std::move(*this).f();

A: Well, for f() the right qualifier is always lvalue reference since you use it on this. All your f calls are nothing else than this->f() and this is always lvalue. It doesn't matter that for the outside world the object is rvalue this is lvalue for the object insides.


Q: Gradient Fill in Swift for iOS-Charts I am trying to create a nice gradient fill as seen in the demos on the ios-charts page.  However, I cannot figure this out in swift vs obj-c.
Here is the obj-c code:
NSArray *gradientColors = @[
                    (id)[ChartColorTemplates colorFromString:@"#00ff0000"].CGColor,
                    (id)[ChartColorTemplates colorFromString:@"#ffff0000"].CGColor
                    ];
CGGradientRef gradient = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);

set1.fillAlpha = 1.f;
set1.fill = [ChartFill fillWithLinearGradient:gradient angle:90.f];

Now here is my version of that in swift:
    let gradColors = [UIColor.cyanColor().CGColor, UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)]
    let colorLocations:[CGFloat] = [0.0, 1.0]
    let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradColors, colorLocations)

What I am missing is the :
Chart Fill fillWithLinearGradient
I can't find the fillWithLinearGradient in the pod anywhere so I am a bit confused.
Thanks in advance for any help!
Rob

A: For Swift 5 use the following:
yourDataSetName.fill = LinearGradientFill(....
or
yourDataSetName.fill = ColorFill(...

More details you can read here:
Charts

A: I believe this is the code that you are looking for. You should be able to use the same ChartFill class in Swift to set set1.fill.
let gradColors = [UIColor.cyanColor().CGColor, UIColor.clearColor.CGColor]
let colorLocations:[CGFloat] = [0.0, 1.0]
if let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradColors, colorLocations) {
    set1.fill = ChartFill(linearGradient: gradient, angle: 90.0)
}

A: This works perfectly (Swift 3.1 and ios-charts 3.0.1)

let gradientColors = [UIColor.cyan.cgColor, UIColor.clear.cgColor] as CFArray // Colors of the gradient
let colorLocations:[CGFloat] = [1.0, 0.0] // Positioning of the gradient
let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations) // Gradient Object
yourDataSetName.fill = Fill.fillWithLinearGradient(gradient!, angle: 90.0) // Set the Gradient
set.drawFilledEnabled = true // Draw the Gradient

Result

A: For swift4
let colorTop =  UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor

let gradientColors = [colorTop, colorBottom] as CFArray
let colorLocations:[CGFloat] = [0.0, 1.0]
let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations) // Gradient Object
yourDataSetName.fill = Fill.fillWithLinearGradient(gradient!, angle: 90.0)

A: Fill.fillWithLinearGradiant has been updated to LinearGradientFill

A: Make sure to use the latest version of ios-charts. If you use CocoaPods to install ios-charts change this:
pod 'Charts'
to this
pod 'Charts', '~> 2.2'


Q: Are there any scope that escape all special characters in mysql query? I have a set of queries with randoms data that i want to insert in database. Randoms data may have any special characters.
for example:
INSERT INTO tablename VALUES('!^'"twco\dq');

Are there any scope that escape all special characters?
please help.

A: You can use \ character to escape special characters like below. See this DEMO if in doubt.
INSERT INTO tablename VALUES('\!\^\'\"twco\\dq');

Per MySQL documentation, below are the defined escape sequences
Table 9.1 Special Character Escape Sequences

\0  An ASCII NUL (0x00) character.
\'  A single quote (“'”) character.
\"  A double quote (“"”) character.
\b  A backspace character.
\n  A newline (linefeed) character.
\r  A carriage return character.
\t  A tab character.
\Z  ASCII 26 (Control+Z). See note following the table.
\\  A backslash (“\”) character.
\%  A “%” character. See note following the table.
\_  A “_” character. See note following the table.

A: No, there is no "scope" in MySQL to automatically escape all special characters.
If you have a text file containing statements that were created with potentially unsafe "random values" like this:
INSERT INTO tablename VALUES('!^'"twco\dq');
                              ^^^^^^^^^^^

You're basically screwed. MySQL can't unscramble a scrambled egg. There's no "mode" that makes MySQL work with a statement like that.
Fortunately, that particular statement will throw an error. More tragic would be some nefariously random data,
x'); DROP TABLE students; --

if that random string got incorporated into your SQL text without being escaped, the result would be:
INSERT INTO tablename VALUES('x'); DROP TABLE students; --');

The escaping of special characters has to be done before the values are incorporated into SQL text.
You'd need to take your random string value:
!^'"twco\dq

And run it through a function that performs the necessary escaping to make that value safe for including that as part of the the SQL statement.
MySQL provides the real_escape_string_function as part of their C library. Reference https://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html. This same functionality is exposed through the MySQL Connectors for several languages.
An even better pattern that "escaping" is to use prepared statements with bind placeholders, so your statement would be a static literal, like this:
INSERT INTO tablename VALUES ( ? )


Q: How to get the list of "jar's" used by an android application? I would like to find the list of "libraries" (not "shared libraries") that are in used by an Application ?
Thanks a lot.

A: You have to go trough analyzer tool  like this. Quoting introduction:

The purpose of this tool is to analyze Java™ class files in order to learn more about the dependencies between those classes.


Q: Oracle Fusion Middleware Encryption / Decryption Sensitive Payload Data Does anyone know of a encryption / decryption technique for sensitive data in a message payload to prevent the information from showing up in audit logs? For example, a payload containing a password. The password should not appear in any logs. When the payload is received, the password needs to be encrypted and then just before the payload is forwarded the password needs to be decrypted. I'm looking for a generic solution that will work with OSB and BPEL.

A: What you can do is create an Encryption/Decryption Web Service and use it in BPEL, OSB and you ADF application if you want, there are many Encryption Algorithms with this solution you should be able to choose what you want to use.

A: Found the answer. It was in the Oracle code examples all along. See bpel-310 Partial Message encryption
https://java.net/projects/oraclesoasuite11g/pages/BPEL


Q: Overriding Python mock's patch decorator I have a Python TestCase class where all test methods, except one, need to patch an object the same way. The other method need some other behavior from the same object. I'm using mock, so I did:
@mock.patch('method_to_patch', mock.Mock(return_value=1))
class Tests(TestCase):

    @mock.patch('method_to_patch', mock.Mock(return_value=2))
    def test_override(self):
         (....)

But that's not working. When test_override is run, it still calls the patched behavior from the class decorator.
After a lot of debugging, I found out that during the TestSuite build, the @patch around test_override is being called before the one around Tests, and since mock apply the patches in order, the class decorator is overriding the method decorator.
Is this order correct? I was expecting the opposite and I'm not really sure how to override patching... Maybe with a with statement?

A: Well, turns out that a good night sleep and a cold shower made me rethink the whole issue.
I'm still very new to the concept of mocking, so it still hasn't sunk in quite right.
The thing is, there's no need to override the patch to a mocked object. It's a mocked object and that means I can make it do anything. So my first try was:
@mock.patch('method_to_patch', mock.Mock(return_value=1))
class Tests(TestCase):

    def test_override(self):
         method_to_patch.return_value = 2
         (....)

That worked, but had the side effect of changing the return value for all following tests. So then I tried:
@mock.patch('method_to_patch', mock.Mock(return_value=1))
class Tests(TestCase):

    def test_override(self):
         method_to_patch.return_value = 2
         (....)
         method_to_patch.return_value = 1

And it worked like a charm. But seemed like too much code. So then I went the down the road of context management, like this:
@mock.patch('method_to_patch', mock.Mock(return_value=1))
class Tests(TestCase):

    def test_override(self):
         with mock.patch('method_to_patch', mock.Mock(return_value=2):
             (....)

I think it seems clearer and more concise.
About the order in which the patch decorators were being applied, it's actually the correct order. Just like stacked decorators are applied from the bottom up, a method decorator is supposed to be called before the class decorator. I guess it makes sense, I was just expecting the opposite behavior.
Anyway, I hope this help some poor newbie soul like mine in the future.


Q: Python object attributes as variables I am trying to assign a python object attribute a variable. Here is what I have been trying to do:
from read import *
import matplotlib.pyplot as plt
import numpy as np

data=table('data.txt')

semi=data['data']['a']
ecc = data['data']['e']
incl= data['data']['i']
bias = data['data']['bias']

fig = plt.figure()
ax1 = fig.add_axes([0.06, 0.1, 0.4, 0.35])
ax2 = fig.add_axes([0.06, 0.6, 0.4, 0.35])
ax3 = fig.add_axes([0.55, 0.6, 0.4, 0.35])
ax4 = fig.add_axes([0.55, 0.1, 0.4, 0.35])

aaa = getattr(ax1,'xaxis')

nax={'ax1':ax1,'ax2':ax2,'ax3':ax3,'ax4':ax4}

for a in sorted(nax):

  aax = {'xaxis':nax[a].get_xaxis()}
  for axis in ['bottom','left']:
     nax[a].spines[axis].set_linewidth(0.5)
  for axis in ['right','top']:
     nax[a].spines[axis].set_visible(False)
  for b in sorted(aax):
     nax[a].b.set_tick_position('bottom')

When I run my code it says:
Traceback (most recent call last):
  File "./test1.py", line 35, in <module>
    ax1.b.set_ticks_position('bottom')
AttributeError: 'Axes' object has no attribute 'b'

Originally it works when:
ax1.xaxis.set_tick_position('bottom')

but I need to make the XAxis attribute a variable for the sake of creating plotting templates.
Any idea how to make the above thing work?

A: Try x.set_tick_position('bottom') instead of ax1.x.set_tick_position('bottom'). x is already an attribute off of the ax1 object, so you don't need to access ax1 again.
Furthermore, no need for getattr if you know the name of the attribute statically. You can just do x = ax1.xaxis.

A: I would suggest to work on the objects directly.
nax=[ax1,ax2,ax3,ax4]

for ax in nax:

   for axis in ['bottom','left']:
       ax.spines[axis].set_linewidth(0.5)
   for axis in ['right','top']:
       ax.spines[axis].set_visible(False)

   ax.xaxis.set_tick_position('bottom')


Q: JavaScript: Delete all iframe in DOM I would like to delete all iframe tags using JavaScript. Already tried using for and while but none of my attempts at deleting all iframe elements work for me.
For example, let's use this RANDOM web page's HTML:

Sugar

Fruits

hello
hello
hello
hello

Click the button to delete the HTML elements

<button onclick="myFunction()">Try it</button>

I tried these JavaSrcipts
Attempt 1:
function myFunction() {
  var elements = document.getElementsByTagName('iframe');
  elements.parentNode.removeChild(elements);
}

Attempt 2:
function myFunction() {
   var elements = document.getElementsByTagName("iframe");

   while (elements.hasChildNodes()) {
     elements.removeChild(elements.lastChild);
   }
}

A: On modern browsers, you can use querySelectorAll and iterate over the NodeList directly, .remove()ing every iframe:
document.querySelectorAll('iframe')
  .forEach(iframe => iframe.remove());

Or, for ES5 compatibility:
Array.prototype.forEach.call(
  document.querySelectorAll('iframe'),
  function(iframe) {
    // can't use .remove: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
    iframe.parentElement.removeChild(iframe);
  }
);

A: A loop is the right way. Here's a simple version that will work cross-browser:
function myFunction() {
   var elements = document.getElementsByTagName("iframe");

   while (elements.length) {
     elements[0].parentNode.removeChild(elements[0]);
   }
}

That continually removes the last entry in the HTMLCollection. The HTMLCollection is live, so removing an element that's in that collection from the DOM also removes it from the collection, so that will reduce the length until eventually length is zero.


Q: Google API PHP Client library for Youtube is NOT connecting to Youtube I have been trying to work in youtube php client library but was unable to connect it.
I have read and tried the google documentation (google developers) and github repository documentation (https://github.com/google/google-api-php-client#installation) for its installation using composer or cloning directly using git.
But whenever I tried to surf the webpage, it always show a blank page. I tried to debug it; in which I came to know that the at the require_once 'vendor/autoload.php' line, it is stucking.
My directory structure is:
/var/www/html/test/index.php (My logical code)
/var/www/html/test/google-php-api-client (Php client API folder)
Try 1: Downloaded Directly from RELEASE (google-php-api-client-2.0.2) or by using Composer -- NOT WORKING
require_once 'google-api-php-client/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_API_KEY");
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results as $item) {
  echo $item['volumeInfo']['title'], "<br /> \n";
}

Try 2: Cloning from GitHub (git clone -b v1-master https://github.com/google/google-api-php-client.git
    ) -- NOT WORKING
Please, help. Thanks
set_include_path('google-api-php-client/src');
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

In this try, the code is not executing after this line require_once 'Google/Service/YouTube.php';
Please, help.


Q: Boost named_semaphore ownerwship in shared library I have a shared library where I created some functionality with semaphores. I am using boost::interprocess::named_semaphore with a thin wrapper around it. This library I am now linking dynamically with a small program.
The problem I am experiencing is that the semaphores are not deleted after I run my application. This problem only happens on Windows, on Linux the semaphores do get deleted. Now, I am calling boost::interprocess::named_semaphore::remove in the destructor of the wrapper I mentioned because the named_semaphore does not do that itself.
Also, if I call boost::interprocess::named_semaphore::remove directly in my application and not inside the library code the semaphore does get deleted! Strange!
Any ideas of what could be going wrong?


Q: In pygtk, why does importing the gtk module change my locale settings? I was surprised to find out that in a Pygtk program, merely importing the gtk module will change the currently loaded locale. If I run the following test program I get two different results in the print statements:
import locale
import pygtk

print "Locale before:", locale.setlocale(locale.LC_ALL, None)
import gtk
print "Locale after:", locale.setlocale(locale.LC_ALL, None)

The output:
Locale before: C
Locale after: LC_CTYPE=pt_BR.UTF-8;LC_NUMERIC=en_US.utf8;LC_TIME=en_US.utf8;LC_COLLATE=en_US.utf8;LC_MONETARY=en_US.utf8;LC_MESSAGES=en_US.utf8;LC_PAPER=en_US.utf8;LC_NAME=en_US.utf8;LC_ADDRESS=en_US.utf8;LC_TELEPHONE=en_US.utf8;LC_MEASUREMENT=en_US.utf8;LC_IDENTIFICATION=en_US.utf8

After the import gtk line the locale is configured according to my LC_xxx environment variables, as if someone had called locale.setlocale(locale.LC_ALL, ""). Is this intentional behavior from pygtk or gtk? Is it documented somewhere?
If I do not want to use the locale settings from the LC_xxx family of environment variables, where should I be calling locale.setlocale? I want to be sure that the locale I set in my program will not be overwritten by by one of the libraries that I am using.

A: One should use gtk_disable_setlocale() or whatever the language analogue is to bypass locales from GTK. Should be called prior to any subsequent calls of functions that enter the gtk main loop.
That is the intended behavior of GTK, because it supports internationalization, but I am not sure why it changes the locale globally.


Q: Avoiding duplicating graph in tensorflow (LSTM model) I have the following simplified code (actually, unrolled LSTM model):
def func(a, b):
    with tf.variable_scope('name'):
        res = tf.add(a, b)
    print(res.name)
    return res

func(tf.constant(10), tf.constant(20))

Whenever I run the last line, it seems that it changes the graph. But I don't want the graph changes. Actually my code is different and is a neural network model but it is too huge, so I've added the above code. I want to call the func without changing the graph of model but it changes. I read about variable scope in TensorFlow but it seems that I've not understand it at all.

A: You should take a look at the source code of tf.nn.dynamic_rnn, specifically _dynamic_rnn_loop function at python/ops/rnn.py - it's solving the same problem. In order not blow up the graph, it's using tf.while_loop to reuse the same graph ops for new data. But this approach adds several restrictions, namely the shape of tensors that are passing through in a loop must be invariant. See the examples in tf.while_loop documentation:
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 10
b = lambda i, m: [i+1, tf.concat([m, m], axis=0)]
tf.while_loop(
    c, b, loop_vars=[i0, m0],
    shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])


Q: how to find Interaction effect(by generating impulse response for low and high regimes) in non linear Structural VAR framework? imagine we have five variable X1, X2, X3, X4, X5. what I am looking to find is the effect of X1 on X3,X4,X5 when the X2 is at its lowest and highest periods.
for this, I applied the TVAR function in TsDyn package in r
> data <-  cbind(X5,X4,X3,X2,X1)
> model <- TVAR(data, lag=1, nthresh=2, thDelay=1, trim=0.1, mTh=4, plot=TRUE)
> plot(irf(model, regime = "L", boot = TRUE))
> plot(irf(model, regime = "H", boot = TRUE))
> plot(irf(model, regime = "M", boot = TRUE))

but i want modify the relationship among variables that X2,X3,X4,X5 affects X1 contemporously and X1 affects X3,X4,X5 in lag.
So what I am looking for is to model this effect X1 on other variables in the high and low regimes of X2(interaction effect) with the ability to modify the relationship between the other Variables in the system. is there any package that is able to do Structural Vector autoregression Method in a non-linear framework? or how can I find out the effect of X1 on others when interacted with X2(when x2 is in its lowest decile and the highest decile)