text:
Q: How to add functions from custom JARs to EMR cluster? I created an EMR cluster on AWS with Spark and Livy. I submitted a custom JAR with some additional libraries (e.g. datasources for custom formats) as a custom JAR step. However, the stuff from the custom JAR is not available when I try to access it from Livy.
What do I have to do to make the custom stuff available in the environment?

A: I am posting this as an answer to be able to accept it - I figured it out thanks to Yuval Itzchakov's comments and the AWS documentation on Custom Bootstrap Actions.
So here is what I did:

*

*I put my library jar (a fat jar created with sbt assembly containing everything needed) into an S3 bucket

*Created a script named copylib.sh which contains the following:
#!/bin/bash

mkdir -p /home/hadoop/mylib
aws s3 cp s3://mybucket/mylib.jar /home/hadoop/mylib

*Created the following configuration JSON and put it into the same bucket besides the mylib.jar and copylib.sh:
[{
   "configurations": [{
       "classification": "export",
       "properties": {
           "PYSPARK_PYTHON": "/usr/bin/python3"
       }
   }],
   "classification": "spark-env",
   "properties": {}
}, {
   "configurations": [{
       "classification": "export",
       "properties": {
           "PYSPARK_PYTHON": "/usr/bin/python3"
       }
   }],
   "classification": "yarn-env",
   "properties": {}
},
{
   "Classification": "spark-defaults",
   "Properties": {
       "spark.executor.extraClassPath": "/usr/lib/hadoop-lzo/lib/*:/usr/lib/hadoop/hadoop-aws.jar:/usr/share/aws/aws-java-sdk/*:/usr/share/aws/emr/emrfs/conf:/usr/share/aws/emr/emrfs/lib/*:/usr/share/aws/emr/emrfs/auxlib/*:/usr/share/aws/emr/goodies/lib/emr-spark-goodies.jar:/usr/share/aws/emr/security/conf:/usr/share/aws/emr/security/lib/*:/usr/share/aws/hmclient/lib/aws-glue-datacatalog-spark-client.jar:/usr/share/java/Hive-JSON-Serde/hive-openx-serde.jar:/usr/share/aws/sagemaker-spark-sdk/lib/sagemaker-spark-sdk.jar:/usr/share/aws/emr/s3select/lib/emr-s3-select-spark-connector.jar:/home/hadoop/mylib/mylib.jar",
       "spark.driver.extraClassPath": "/usr/lib/hadoop-lzo/lib/*:/usr/lib/hadoop/hadoop-aws.jar:/usr/share/aws/aws-java-sdk/*:/usr/share/aws/emr/emrfs/conf:/usr/share/aws/emr/emrfs/lib/*:/usr/share/aws/emr/emrfs/auxlib/*:/usr/share/aws/emr/goodies/lib/emr-spark-goodies.jar:/usr/share/aws/emr/security/conf:/usr/share/aws/emr/security/lib/*:/usr/share/aws/hmclient/lib/aws-glue-datacatalog-spark-client.jar:/usr/share/java/Hive-JSON-Serde/hive-openx-serde.jar:/usr/share/aws/sagemaker-spark-sdk/lib/sagemaker-spark-sdk.jar:/usr/share/aws/emr/s3select/lib/emr-s3-select-spark-connector.jar:/home/hadoop/mylib/mylib.jar"
   }
}
]

The classifications for spark-env and yarn-env are needed for PySpark to work with Python3 on EMR through Livy. And there is another issue: EMR already populates the two extraClassPaths with a lot of libraries which are needed for EMR to function properly, so I had to run a cluster without my lib, extract these settings from spark-defaults.conf and adjust my classification afterwards. Otherwise, things like S3 access wouldn't work.

*When creating the cluster, in Step 1 I referenced the configuration JSON file from above in Edit software settings, and in Step 3, I configured copylib.sh as a Custom Bootstrap Action.
I can now open the Jupyterhub of the cluster, start a notebook and work with my added functions.

A: I use an alternative way that does not use a bootstrap action.

*

*Place the JARs in S3

*Pass them in the --jars option of spark-submit eg. spark-submit --jars s3://my-bucket/extra-jars/*.jar. All the jars will be copied to the cluster.

This way we can use any jar from s3 if we missed to add bootstrap action during cluster creation.


text:
Q: sfDoctrineGuardPlugin forgets credentials after verifying them I am searching for a solution to an authentication problem. I've only found one person (in the symfony-users Google group) with the same problem (#2 at bottom) way back in May of last year. As far as I can tell, no solution was posted to list.
In my development environment on Mac OS X, sfDoctrineGuardPlugin is working properly. When I attempt to access a secure page, I get redirected to login. When I enter valid credentials, I get redirected back to the initially requested page.
In my test environment at DreamHost, it is not working properly. When I attempt to access a secure page, I get redirected to login. When I enter valid credentials, I get redirected back to the initially requested page, but symfony loses my authentication status and (re-)redirects me back to login once again with the form emptied. (In contrast, if I enter invalid credentials, then I receive an error message on the login page and the username remains filled in.)
In each environment, symfony does verify my credentials are valid and that I have 'admin' privileges, but test forgets those credentials as soon as it redirects me back to my requested page.
Nothing interesting shows up in the apache error log.
Dev log snippets:

Feb 09 10:05:51 symfony [info] {sfPatternRouting} Match route "report" (/report.:sf_format) for /report with parameters array (  'module' => 'report',  'action' => 'index',  'sf_format' => 'html',)
Feb 09 10:05:52 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 10:05:52 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 10:05:52 symfony [info] {sfFilterChain} Executing filter "sfBasicSecurityFilter"
Feb 09 10:05:52 symfony [info] {sfBasicSecurityFilter} Action "report/index" requires authentication, forwarding to "sfGuardAuth/signin"
Feb 09 10:05:52 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 10:05:52 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 10:05:52 symfony [info] {sfFilterChain} Executing filter "sfExecutionFilter"
Feb 09 10:05:52 symfony [info] {sfGuardAuthActions} Call "sfGuardAuthActions->executeSignin()"
Feb 09 10:05:52 symfony [info] {sfPHPView} Render "/Library/WebServer/WebSites/Documents/plugins/sfDoctrineGuardPlugin/modules/sfGuardAuth/templates/signinSuccess.php"
Feb 09 10:05:52 symfony [info] {sfPartialView} Render "/Library/WebServer/WebSites/Documents/plugins/sfDoctrineGuardPlugin/modules/sfGuardAuth/templates/_signin_form.php"
Feb 09 10:05:52 symfony [info] {sfPHPView} Decorate content with "/Library/WebServer/WebSites/Documents/apps/backend/templates/layout.php"
Feb 09 10:05:52 symfony [info] {sfPHPView} Render "/Library/WebServer/WebSites/Documents/apps/backend/templates/layout.php"
Feb 09 10:05:52 symfony [info] {sfWebResponse} Send status "HTTP/1.1 401 Unauthorized"
Feb 09 10:05:52 symfony [info] {sfWebResponse} Send header "Content-Type: text/html; charset=utf-8"
Feb 09 10:05:52 symfony [info] {sfWebDebugLogger} Configuration 12.62 ms (12)
Feb 09 10:05:52 symfony [info] {sfWebDebugLogger} Factories 58.15 ms (1)
Feb 09 10:05:52 symfony [info] {sfWebDebugLogger} Action "sfGuardAuth/signin" 6.18 ms (1)
Feb 09 10:05:52 symfony [info] {sfWebDebugLogger} View "Success" for "sfGuardAuth/signin" 13.92 ms (1)
Feb 09 10:05:52 symfony [info] {sfWebDebugLogger} Partial "sfGuardAuth/_signin_form" 4.84 ms (1)
Feb 09 10:05:52 symfony [info] {sfWebResponse} Send content (53797 o)
Feb 09 10:06:04 symfony [info] {sfPatternRouting} Match route "sf_guard_signin" (/login) for /login with parameters array (  'module' => 'sfGuardAuth',  'action' => 'signin',)
Feb 09 10:06:04 symfony [info] {sfGuardSecurityUser} User is authenticated
Feb 09 10:06:04 symfony [info] {sfGuardSecurityUser} Add credential(s) "admin"
Feb 09 10:06:04 symfony [info] {sfFrontWebController} Redirect to "http://localhost/backend_dev.php/"
Feb 09 10:06:04 symfony [info] {sfWebResponse} Send status "HTTP/1.1 302 Found"
Feb 09 10:06:04 symfony [info] {sfWebResponse} Send header "Location: http:/localhost/backend_dev.php/"
Feb 09 10:06:04 symfony [info] {sfWebResponse} Send header "Content-Type: text/html; charset=utf-8"
Feb 09 10:06:04 symfony [info] {sfWebDebugLogger} Configuration 1.30 ms (8)
Feb 09 10:06:04 symfony [info] {sfWebDebugLogger} Factories 58.35 ms (1)
Feb 09 10:06:04 symfony [info] {sfWebDebugLogger} Action "sfGuardAuth/signin" 217.06 ms (1)
Feb 09 10:06:04 symfony [info] {sfWebDebugLogger} Database (Doctrine) 0.03 ms (5)
Feb 09 10:06:04 symfony [info] {sfWebResponse} Send content (123 o)
Feb 09 10:06:04 symfony [info] {sfPatternRouting} Match route "homepage" (/) for / with parameters array (  'module' => 'report',  'action' => 'index',)
Feb 09 10:06:04 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 10:06:04 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 10:06:04 symfony [info] {sfFilterChain} Executing filter "sfBasicSecurityFilter"
Feb 09 10:06:04 symfony [info] {sfFilterChain} Executing filter "sfExecutionFilter"
Feb 09 10:06:04 symfony [info] {reportActions} Call "reportActions->executeIndex()"
Feb 09 10:06:04 symfony [info] {sfPHPView} Render "/Library/WebServer/WebSites/Documents/apps/backend/modules/report/templates/indexSuccess.php"
Feb 09 10:06:05 symfony [info] {main} Call "navigation->executeNavMenu()"
Feb 09 10:06:05 symfony [info] {sfWebResponse} Send status "HTTP/1.1 200 OK"
Feb 09 10:06:05 symfony [info] {sfWebResponse} Send header "Content-Type: text/html; charset=utf-8"
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} Configuration 1.93 ms (10)
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} Factories 60.49 ms (1)
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} Action "report/index" 66.68 ms (1)
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} Database (Doctrine) 0.02 ms (3)
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} View "Success" for "report/index" 454.39 ms (1)
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} Component "navigation/navMenu" 0.17 ms (1)
Feb 09 10:06:05 symfony [info] {sfWebDebugLogger} Partial "navigation/_navMenu" 19.78 ms (1)
Feb 09 10:06:05 symfony [info] {sfWebResponse} Send content (164075 o)

Test log snippets:

Feb 09 06:21:36 symfony [info] {sfPatternRouting} Match route "report" (/report.:sf_format) for /report with parameters array (  'module' => 'report',  'action' => 'index',  'sf_format' => 'html',)
Feb 09 06:21:36 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 06:21:36 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 06:21:36 symfony [info] {sfFilterChain} Executing filter "sfBasicSecurityFilter"
Feb 09 06:21:36 symfony [info] {sfBasicSecurityFilter} Action "report/index" requires authentication, forwarding to "sfGuardAuth/signin"
Feb 09 06:21:36 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 06:21:36 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 06:21:36 symfony [info] {sfFilterChain} Executing filter "sfExecutionFilter"
Feb 09 06:21:36 symfony [info] {sfGuardAuthActions} Call "sfGuardAuthActions->executeSignin()"
Feb 09 06:21:36 symfony [info] {sfPHPView} Render "/home/username/test.example.com/project/plugins/sfDoctrineGuardPlugin/modules/sfGuardAuth/templates/signinSuccess.php"
Feb 09 06:21:36 symfony [info] {sfPartialView} Render "/home/username/test.example.com/project/plugins/sfDoctrineGuardPlugin/modules/sfGuardAuth/templates/_signin_form.php"
Feb 09 06:21:36 symfony [info] {sfPHPView} Decorate content with "/home/username/test.example.com/project/apps/backend/templates/layout.php"
Feb 09 06:21:36 symfony [info] {sfPHPView} Render "/home/username/test.example.com/project/apps/backend/templates/layout.php"
Feb 09 06:21:36 symfony [info] {sfWebDebugLogger} Configuration 822.85 ms (12)
Feb 09 06:21:36 symfony [info] {sfWebDebugLogger} Factories 343.18 ms (1)
Feb 09 06:21:36 symfony [info] {sfWebDebugLogger} Action "sfGuardAuth/signin" 7.63 ms (1)
Feb 09 06:21:36 symfony [info] {sfWebDebugLogger} View "Success" for "sfGuardAuth/signin" 19.09 ms (1)
Feb 09 06:21:36 symfony [info] {sfWebDebugLogger} Partial "sfGuardAuth/_signin_form" 4.44 ms (1)
Feb 09 06:21:36 symfony [info] {sfWebResponse} Send content (52356 o)
Feb 09 06:21:45 symfony [info] {sfPatternRouting} Match route "sf_guard_signin" (/login) for /login with parameters array (  'module' => 'sfGuardAuth',  'action' => 'signin',)
Feb 09 06:21:45 symfony [info] {sfGuardSecurityUser} User is authenticated
Feb 09 06:21:45 symfony [info] {sfGuardSecurityUser} Add credential(s) "admin"
Feb 09 06:21:45 symfony [info] {sfFrontWebController} Redirect to "http://test.rippil.com/backend_dev.php/"
Feb 09 06:21:45 symfony [info] {sfWebDebugLogger} Configuration 21.18 ms (8)
Feb 09 06:21:45 symfony [info] {sfWebDebugLogger} Factories 162.69 ms (1)
Feb 09 06:21:45 symfony [info] {sfWebDebugLogger} Action "sfGuardAuth/signin" 233.96 ms (1)
Feb 09 06:21:45 symfony [info] {sfWebDebugLogger} Database (Doctrine) 0.03 ms (7)
Feb 09 06:21:45 symfony [info] {sfWebResponse} Send content (118 o)
Feb 09 06:21:46 symfony [info] {sfPatternRouting} Match route "homepage" (/) for / with parameters array (  'module' => 'reporttt',  'action' => 'index',)
Feb 09 06:21:46 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 06:21:46 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 06:21:46 symfony [info] {sfFilterChain} Executing filter "sfBasicSecurityFilter"
Feb 09 06:21:46 symfony [info] {sfBasicSecurityFilter} Action "report/index" requires authentication, forwarding to "sfGuardAuth/signin"
Feb 09 06:21:46 symfony [info] {sfFilterChain} Executing filter "sfRenderingFilter"
Feb 09 06:21:46 symfony [info] {sfFilterChain} Executing filter "sfGuardRememberMeFilter"
Feb 09 06:21:46 symfony [info] {sfFilterChain} Executing filter "sfExecutionFilter"
Feb 09 06:21:46 symfony [info] {sfGuardAuthActions} Call "sfGuardAuthActions->executeSignin()"
Feb 09 06:21:46 symfony [info] {sfPHPView} Render "/home/username/test.example.com/project/plugins/sfDoctrineGuardPlugin/modules/sfGuardAuth/templates/signinSuccess.php"
Feb 09 06:21:46 symfony [info] {sfPartialView} Render "/home/username/test.example.com/project/plugins/sfDoctrineGuardPlugin/modules/sfGuardAuth/templates/_signin_form.php"
Feb 09 06:21:46 symfony [info] {sfPHPView} Decorate content with "/home/username/test.example.com/project/apps/backend/templates/layout.php"
Feb 09 06:21:46 symfony [info] {sfPHPView} Render "/home/username/test.example.com/project/apps/backend/templates/layout.php"
Feb 09 06:21:46 symfony [info] {sfWebDebugLogger} Configuration 13.92 ms (12)
Feb 09 06:21:46 symfony [info] {sfWebDebugLogger} Factories 251.75 ms (1)
Feb 09 06:21:46 symfony [info] {sfWebDebugLogger} Action "sfGuardAuth/signin" 31.00 ms (1)
Feb 09 06:21:46 symfony [info] {sfWebDebugLogger} View "Success" for "sfGuardAuth/signin" 57.79 ms (1)
Feb 09 06:21:46 symfony [info] {sfWebDebugLogger} Partial "sfGuardAuth/_signin_form" 8.09 ms (1)
Feb 09 06:21:46 symfony [info] {sfWebResponse} Send content (52428 o)

It's probably worth mentioning this snippet from backend/templates/layout.php which accounts for the navigation/_navMenu lines in Dev but not in test:

<?php if ($sf_user->isAuthenticated()): ?>
    <?php include_component('navigation', 'navMenu'); ?>
    ...
 <?php endif ?>

Related post in symfony-users group:

You should check the logs for both symfony and apache.
gabriel
On May 28, 2:33 pm, sdwdd  wrote:

Hi, All.
Having a couple of problems with Symfony 1.4 installation:
    1. [unrelated]
    2. A problem with sfGuard plugin.
    It works okay in the development environment, however in test
    environment after the user is logged in it looses the session. User
    gets logged in, but after a page reload the authentication session is
    lost.
The installation is core Symfony 1.4 with sfGuardPlugin and some
    custom templating.
Any ideas on those? I'm feeling like there's a problem with server
    config, however don't know what could be wrong(raised the memory_limit
    to 512Mb).
Thanks,
    Serg

A: I found an answer after tips from the symfony-users Google group.
First tip:

This seems to be an issue with the session on your server. If the session variable are not stored, the authentication status cannot be saved. You should ask the Dreamhost support to know why session variables does not work.
Christophe | Stof

Second tip:

This is not a symfony related suggestion.
  I found often Session issues were caused by the suhosin module, which
  comes with many Ubuntu based hosts. Try to turn session encryption off
  and see if it helps. I found for example that sometimes the Document
  Root is part of the encryption and it may not always work as expected.
  HTH
  Kind Regards,
  Jochen Daum

It turns out that my hosting
environment uses suhosin hardened PHP which is likely the cause of the
problem. Adding suhosin into my solution search, I found this in
oldforums.symfony-project.org:

Re: User sessions do not persist on Ubuntu Server [message #100928 is a reply to message #100918 ]
  Mon, 14 June 2010 19:33 dklanac
  Here is my final post. I figured out that the issue was only on my test environment. sfSessionTestStorage was not setting the cookie that I needed. I changed it over to sfSessionStorage and renamed my cookie with a "test" suffix to prevent production cookie conflicts, and things behaved appropriately. This would also explain why I was able to see the correct behavior on my dev instance, since it also uses the regular sfSessionStorage class.

We use separate subdomains for dev, test, stage, and production, so my
solution was even simpler. I just changed sfSessionTestStorage to
sfSessionStorage in apps/appname/config/factories.yml. I don't expect
to need to alter the cookie name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to send file as attachment to an API POST request I am trying to send a file for a candidate in POST request naturalHR API:
I have tried the same request using POSTMAN and it worked fine. But when i try to integrate the API's POST request using python to attach the file I am getting an error that It cv parameter should be a file(its API error response).
Source Code:
from pprint import pprint
import json
import requests
import urllib.request
headers = {
    'accept': 'application/json',
    'Authorization': api_key,
    'Host': 'api02.naturalhr.net',
    'Referer': 'https://api02.naturalhr.net/api/documentation',
    'Content-type': 'multipart/form-data',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}
payLoad = dict()
payLoad["firstname"] = json_of_vals['firstname']
payLoad["surname"] = json_of_vals['surname']
payLoad["email"] = json_of_vals['email']
payLoad["cv"] = "Path/To/PDF_File"
files = {'file': "outfilename.pdf"}
api_url = "https://api02.naturalhr.net/api/v1/candidate"
res = requests.post(api_url, files=files, headers=headers, data=request_data)
print(res.content)

Please dont mark this as a duplicate to a question here which is already been answered because I have tested it by using files as request's argument  like:
res = requests.post(api_url, files=files, headers=headers, data=request_data)

Edited:
The answer which I have tried:
Using Python Requests to send file and JSON in single request

A: I was adding a header
'accept': 'application/json'

Which should not be there, I tried it using only user-agent and an API-key and it worked perfectly fine as per requirements.
Corrected Code:
from pprint import pprint
import json
import requests
import urllib.request
headers = {
    'Authorization': api_key,
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}
payLoad = dict()
payLoad["firstname"] = json_of_vals['firstname']
payLoad["surname"] = json_of_vals['surname']
payLoad["email"] = json_of_vals['email']

files = {'file': "PATH/TO/FILE/FROM/LOCAL/DRIVE"}

api_url = "https://api02.naturalhr.net/api/v1/candidate"
res = requests.post(api_url, headers=headers, data=payLoad, files=files)
print("Status Code is: ", res.status_code)
print("Returned JSON Response is:\n")
pprint(res.text)


text:
Q: jade.tmbundle not working with textmate I installed Jade.TmBundle for Textmate 2.0-alpha.9547 (according to instructions) but does not work.
There is no syntax highlighting for .jade files.
When I open bundles (form Preferences) it shows bundle selected, but when I try to unselect and select again in simple, doesn't select.
Can anyone help?
Updated:
Found a new bundle that works like a charm: https://github.com/davidrios/jade-tmbundle


text:
Q: Pass MySQL datas to Javascript I have some MySQL datas in a table. This table shows how the datas are connected to each other. I also have buttons for each datas. And I want to visualize these relations. I'm using vis.js for the visualization. I'm new in Javascript and I don't know how to pass the MySQL datas to the function drawNetwork(). How can I do this?
Example

function drawNetwork() {

  var nodes = [{
      id: 1,
      label: 'data1',
      shape: 'box'
    },
    {
      id: 2,
      label: 'data2',
      shape: 'box'
    },
    {
      id: 3,
      label: 'data3',
      shape: 'box'
    },
    {
      id: 4,
      label: 'data4',
      shape: 'box'
    }
  ];

  var edges = [{
      from: 1,
      to: 2,
      label: 'Description1',
      arrows: {
        to: true
      }
    },
    {
      from: 1,
      to: 3,
      label: 'Description2',
      font: {
        align: 'top'
      },
      arrows: {
        to: true
      }
    },
    {
      from: 1,
      to: 4,
      label: 'Description3',
      font: {
        align: 'top'
      },
      arrows: {
        to: true
      }
    }
  ];

  var container = document.getElementById('network-container');

  var data = {
    nodes: nodes,
    edges: edges
  };

  var width = 600;
  var height = 500;
  var options = {
    width: width + 'px',
    height: height + 'px',
    edges: {
      smooth: false
    },
    physics: false,
    interaction: {
      hover: true,
      dragNodes: true, // allow dragging nodes
      zoomView: false, // do not allow zooming
      dragView: false // do not allow dragging
    }
  };

  var network = new vis.Network(container, data, options);

}

$('#model4temp').on('shown.bs.modal', function() {
  drawNetwork();
});

        <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.css" rel="stylesheet" type="text/css" />

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

            Name
            Connect to
            View

            Data1
            Data2, Data3, Data4
            <input type="button" data-toggle="modal" data-target='#model4temp' value="View" class="btn btn-success btn-md">

            Data2
            Data3, Data4

            Data3

            Data4
            Data5

            Data5
            Data6

            Data6

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Sample Network in modal

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: If you are getting your mysql data in this variable "network" then just do this.
$('#model4temp').on('shown.bs.modal', function() {
  drawNetwork(network);
});

And define your function like this
function drawNetwork(network) {
  // Your stuff here
}

A: To get data you need to make a request to the server(a computer that serves data).
How do you do it?
Browser:
Enter resource address to your address bar. When you request a web page the server sends you data.(HTML raw text that is latter rendered to form this web page)
JavaScript:
To programmatically do it, you need a set of a protocol.
Case 1: How does the client(Browser) request data?
Case 2: How does the server respond to the request?

*

*Case 1: Requesting data with JavaScript.

In JavaScript you can use the following code to request data.
xhttp.open("GET", "https://reqres.in/api/users?page=2", true);
xhttp.send();

The url https://reqres.in/api/users?page=2
responds with data, your MYSQL data from the server.
But how is it possible?
Well, each server has its own back end mechanism. Let's use php for responding to server requests(GET Requests)

*

*Case 2: Responding Case 1 request with PHP.

$result = Array( 'Categories' => Array(), 'Products' => Array());

$stmt = $mysqli->prepare( 'SELECT id, parent_id, name FROM category' );
$stmt->bind_result( $id, $parent_id, $name );
$stmt->execute();
while( $stmt->fetch() ) {
  $result['Categories'][] = Array( 'id' => $id, 'parent_id' => $parent_id, 'name' => $name );
}
$stmt->close();
//Do the same for the other one

$jsonstring = json_encode( $result );

The    $jsonstring  variable contains the data you need and you can echo it to respond to any request.
But how does JavaScript handle responses from the server, so that you use it in your browser?
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
  //use data here.(here we just print the data on the screen)
    document.getElementById("demo").innerHTML = this.responseText;
  }
};
xhttp.open("GET", "https://reqres.in/api/users?page=2", true);
xhttp.send();

I hope this helps, you can do the same with jquery easily
$.get("https://reqres.in/api/users?page=2", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });

What you need to research on:
AJAX Calls in JavaScript,
working with databases with PHP(or any other language)
This is just a basic intro, you will need to use the keywords in this post to research on what you should know.


text:
Q: iTunes Connect problem When I try to do the following: Login Itunes connect -> Manage your applications -> Choose an app -> Rights and Pricing, then it returns an error, saying:

Cannot Process Request
An error has occurred processing your request. Please try again later or send an e-mail for assistance.

This only happens with my mac safari browser, but not on chrome, and not even on iPhone safari. Anyone got an idea how to fix this? Thanks in advance

A: (I'm late to the party, but in case anyone else stumbles across this Q.)
Try deleting cookies for the site. This worked for me (in the opposite direction — Chrome was broken).

A: the same thing happened to me this week as well, I am using the Firefox browser so while waiting for a reply from Apple I cleared the history and cache etc. From there I was once again able to log in to my iTunes Connect account as usual.
I hope this helps.

A: I just logged out and logged in again and it worked for me.

A: Try with other internet connection, worked for  me. May be the problem is accruing due to some proxies or blocking on your internet connection. Also try with other browser or system may resolve your problem.


text:
Q: Problems with finding errors using errorlevel I'm having issues with errors one some af my batchjobs. I'm currently running 50 batchjobs each day, with a log file, which tells me if the batchjob was completed successfully or not.
The last week i've noticed some errors, and right now, I don't have any control which shows or just tells me if a batchjob fails with an error.
My batchjobs are starting af script via sqlplus.
I've tried use errorlevel, but id didn't Work.
My batchjob is looking like this so far.
I've included the errorlevel code I tried to use.
@Echo Off
@For /F "tokens=1,2,3,4 delims=-/ " %%A in ('Date /t') do @(
Set Day=%%A
Set Month=%%B
Set Year=%%C
Set All=%%A-%%B-%%C
)
@For /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do @(
Set Hour=%%A
Set Min=%%B
Set Sec=%%C
Set Allm=%%A.%%B.%%C
)
@For /F "tokens=3 delims=: " %%A in ('time /t ') do @(
Set AMPM=%%A
@Echo On
)
echo Start: %date% %time%    >> ..\log\Scriptname_%All%_%Allm%.log
sqlplus "Script" >> ..\log\Scriptname_%All%_%Allm%.log
IF %errorlevel% NEQ 0 GOTO :Error
GOTO :Success
:error
echo There was an error.
echo Stop: %date% %time%    >> ..\log\Scriptname_%All%_%Allm%.log
EXIT 1
:end
echo Success.
echo Stop: %date% %time%    >> ..\log\Scriptname_%All%_%Allm%.log
EXIT 0

A: I think sqlplus dosn't by default return error codes so always returns 0.
Some options for changing this are described in this thread:
Sql*plus always returns exit code 0?
Another way is to capture the output and parse it to detect errors.

A: Your batch file looks fine. The problem is most likely with your SQL*PLUS script.
SQL*PLUS does not return with an error by default if an error occurs within the SQL*PLUS script. You can use WHENEVER SQLERROR and WHENEVER OSERROR within your SQL*PLUS script to force termination with a non-zero error code upon error.
whenever sqlerror exit failure
whenever oserror exit failure

There are various options to better control the returned code, and to control the transaction behavior (commit or rollback). Follow the links for more info.


text:
Q: All browsers are crashing using Selenium Hi there I'm new to coding but especially to python/selenium et.c. so please bare with me.
I've been trying to develop a scrapper for Facebook for an art project by using Selenium. After some dabbling about and starting to actually experiment with the python code, installing chromedriver into the environments et.c. I started trying to access Facebook through the scrapper when suddenly---
all my browsers (but mostly Chrome) started crashing on any page with a general exception stating: STATUS_ERROR_VIOLATION (see attached pic for reference). Once it even blocked my whole internet access through a DNS fail (513 I think) and I had to flush the DNS.
I searched everywhere but nobody seems to have had this exact problem.
I deleted all chromedrivers, uninstalled them from the environments, updated Google Chrome a few times, uninstalled it and reinstalled it, restarted all processes and the computer multiple times but the problem persists.
Any help would be greatly appreciated, I am so frustrated because there is NO improvement whatsoever...
Snapshot of the error:

A: google-chrome have recently added specific error codes to the Aw snap crash pages.

The very first step in resilving this issue would be to ensure the following:

*

*ChromeDriver is updated to  current ChromeDriver v97.0.4692.71 level.

*Chrome is updated to  current chrome=97.0.4692.99 (as per chrome=97.0.4692.71 release notes).

Addressing STATUS_ERROR_VIOLATION
STATUS_ERROR_VIOLATION still doesn't have any definite fix available. However Will B 7332 in a comment suggests the following steps:

*

*Locate the Chrome application. You will most likely find this in C:\Program Files (x86)\Google\Chrome\Application.

*Rename the Chrome executable to anything other than Chrome. For example, chrm.

*Open Chrome again and test.

Additionally, review the extensions visiting chrome://extensions on a new tab and check all the installed extensions.

*

*If you have Tampermonkey extension installed, uninstall it. Restart Chrome and execute your again.

*If you find any other extensions that you no longer use, uninstall them as well.


text:
Q: QClipboard.mimedata() always has black background I want to copy & paste by QtGui.QClipboard from QApplication()
QtGui.QClipboard has mimedata() method.
I can copy & paste from Web Site.
For example, I copied from here Matahari Wikipedia

I pasted it on my sample text editer window.
At first, the pasted text was as follows:

and pressed Key_1 for saving its contents.
and reexcuted my code and pressed Key_2 for loading the contents.
so...,

The saved contents are always changed to black.
Why?
I checked the html by printing the mimedata.html().
As the result of it,
Matahari

You can see the color is (0,0,0). So this html is black.
So, I tried to do as follows:
clipboard = QtGui.QApplication.clipboard()
html = clipboard.mimeData().html()
print(html)
html = html.replace("color: rgb(0, 0, 0);","color: rgb(255, 255, 255);")
clipboard.mimeData().setHtml(html)

as the result of this execution:
Matahari

I could make it. I could change the color (0,0.0) to (255,255,255)
And I resaved it and reloaded it, but the result was unchanged.
I want  to change the contents from black to white.
What should I do?
Here is the sample code for saving and reloading.
from PySide import QtGui

from PySide import QtCore
import sys
import os
class TextEdit(QtGui.QTextEdit):
    def __init__(self,parent=None):
        super(TextEdit,self).__init__(parent=None)
    def keyPressEvent(self,event):
        if event.key() == QtCore.Qt.Key_1:
            self.save()
            return
        elif event.key() == QtCore.Qt.Key_2:
            self.load()
            return
        elif event.key() == QtCore.Qt.Key_V:
            self.copy_paste()
            return
        return QtGui.QTextEdit.keyPressEvent(self,event)
    def save(self):
        print(os.getcwd()+"copy_paste_test.dat")
        file = QtCore.QFile(os.getcwd()+"copy_paste_test.dat")
        file.open(QtCore.QFile.ReadWrite)
        out = QtCore.QDataStream(file)
        out.writeQString(self.toHtml())
        file.close()
    def load(self):
        file = QtCore.QFile(os.getcwd()+"copy_paste_test.dat")
        file.open(QtCore.QFile.ReadOnly)
        out = QtCore.QDataStream(file)
        self.insertHtml(out.readQString())
        file.close()
    def copy_paste(self):

        clipboard = QtGui.QApplication.clipboard()
        self.insertFromMimeData(clipboard.mimeData())

def main():
    try:
        QtGui.QApplication([])
    except Exception as e:
        print(e)
    textedit = TextEdit()
    textedit.show()
    sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
    main()

A: You should check toHtml() in save() method.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<meta name="qrichtext" content="1" />

Matahari

You can see the background-color:#000000
So,you must change it to background-color:#FFFFFF
toHtml = self.toHtml()
toHtml = toHtml.replace("background-color:#000000;","background-color:#FFFFFF;")
out.writeQString(toHtml)


text:
Q: is there any way to change the default text editor for textfield django in admin panel? I am working on this project on django,i have this model which have few char fields and a text field. What i want to know is is there anyway i can edit the appearance of the text field in django admin panel so that i can edit what i write in that text field like the one in word press where you get options to make a text bold or insert links and images.
I tried this module called grappelli but it just changes the appearance of my admin panel adding colors and decorative stuffs.
class Heading(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=5000)
    content = models.TextField()
    date = models.DateField(default=datetime.now())

def __str__(self):
    return self.title

A: use ckeditor
https://github.com/django-ckeditor/django-ckeditor
on shell:
pip install django-ckeditor
on settings.py:
add 'ckeditor' on INSTALLED_APPS
on models.py:
from ckeditor.fields import RichTextField
class Heading(models.Model):
    content = RichTextField()

A: You can use django-summernote
https://github.com/summernote/django-summernote
step 1: Install django-summernote
pip install django-summernote

step 2: Add django_summernote to INSTALLED_APP in settings.py.
INSTALLED_APPS = [
    'django_summernote',

    '...',
  ]

step 3: Add django_summernote.urls to project urls.py.
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
# ...
urlpatterns = [
    ...
    path('summernote/', include('django_summernote.urls')),
    ...
]
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

step 4: Give MEDIA_URL in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

step 5: on admin.py
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Heading

class HeadingAdmin(SummernoteModelAdmin):
    summernote_fields = ('content',)

admin.site.register(Heading, HeadingAdmin)

step 6: Run database migration
python manage.py migrate


text:
Q: How can I automate importation and formatting of a text file? Excel 2007:
I have an app which outputs several rows, with pipe delimiters, into an ascii text file on a quarterly basis.
row example:  NAME|ADDRESS|CITY|DESCRIPTION|AMOUNT|

I'm currently importing this file on a manual basis into a blank spreadsheet, using the following commands:

Data, Import from Text, {Wizard Step 1} Delimited, {Next}  {Wizard
  Step 2} Delimiter Type = Other = |, Text Qualifier = None, {Next}
  {Wizard Step 3} Column Format = General, {Finish} {Accept} {File, Save
  As, FileName}

I would like to automate all these manual steps when opening up a blank sheet.

A: Use the macro recorder and that remove code overhead .. it is straight forward ..

A: The best way to import is to define it as a data source.  In Excel 2007 it's on the data ribbon, from text.  This way you won't even need to run the macro again, set the data source to refresh on open and it will update any time you open the excel file.

A: If your data is already coming from an SQL database (as mentioned in a comment above), add the SQL database as a data source. It will update the data each time (also as mentioned above), and the formatting should stay.


text:
Q: WPF ResourceDictionary not found in Excel 2013 Plugin I have some code that has been running in a Visual Studio plugin project without issues. We are now porting some of the functionality to an Excel Plugin, but are running into issues.
string fileUriPath = "pack://application:,,,/WpfVisualControls;Component/Resources/Localization-EN-US.xaml";
ResourceDictionary dict.Source = new Uri(fileUriPath);

When running within Excel, this throws the following exception:
A first chance exception of type 'System.UriFormatException' occurred in System.dll

Additional information: Invalid URI: Invalid port specified.

It runs fine under Visual Studio, so I am suspecting that something about the pack://application needs to be changed in Excel, I just don't know what that might be.
Any ideas on how to resolve this?

A: Found a solution to this after quite the goose chase:
string fileUriPath = "WpfVisualControls;Component/Resources/Localization-EN-US.xaml";
dict = Application.LoadComponent(new Uri(fileUriPath, UriKind.Relative)) as ResourceDictionary;

The Application.Current object being null caused the error, so using the static load component method resolved the URI for me.


text:
Q: Use resolve (or any data) in states custom data Using angular 1.2 and ui-router 2.8
Was wondering if it was possible to inject data from either the resolve or $scope into a states custom data object. I know I can alter this data in a controller "$state.$current.data.key = value;" but this will not inherent to children.

A: I'm not sure about using the custom data the way you're asking - I haven't done that and I can't find an example of it in the docs.
You could define a resolve dependency on the parent, and the child will have access to it as long as it's injected as a dependency within the child as well. See this UI-Router wiki page for an example.


text:
Q: AttributeError: 'UserManager' object has no attribute 'create_superuser' I have my customUser manager setup in this way per Django and I am still getting the attribute error.  I'm not sure what else can be wrong.
class UserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, date_of_birth, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(email,
            password=password,
            date_of_birth=date_of_birth
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

I have defined the user and the superuser. And set the object to UserManager.
Traceback is:
Traceback (most recent call last):
  File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
self.execute(*args, **cmd_options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 50, in execute
    return super(Command, self).execute(*args, **options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 149, in handle
           self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
 AttributeError: 'UserManager' object has no attribute 'create_superuser'

The code I am running is:
python manage.py createsuperuser

A: I supposed that you have Django 1.8. Here is what you have to do to create your own models which inherit of AbstractUser model.
In your models :
from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
  pass

Your User model will automatically inherit of the UserManager of AbstractUser then you don't have to write : objects = YourUserManager() unless you want to extend it. In this case, you can do this :
from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager
from django.db import models

class UserManager(AbstractUserManager):
  pass

class User(AbstractUser):
    objects = UserManager()

Define the User model in settings.py used in your Django apps :
# <module_name>.<user_model_name>
AUTH_USER_MODEL = 'user.User'

Now, when you want to import your user model in an other app to use it, use settings.AUTH_USER_MODEL. here is an example :
from django.db import models
from django.conf import settings

class Token(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

Read the right Django documentation for more information : Extending the existing user model

A: Try this and replace the fields according to your requirements:
class UserManager(BaseUserManager):

    def create_user(self, email, password=None,is_active=True,is_staff=False,is_admin=False):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_staffuser(self, email, password):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user


text:
Q: Ordering of harmonic mean and log of geometric mean I have a set of real number bounded by 1 and $c$ (inclusive), where $c$ is greater than 1.
With $H$ the harmonic mean and $G$ the geometric mean of this set, I know that $1 \leq H \leq G \leq c$.
Does such a relationship, that would make use of $\log G$ (i.e. arithmetic mean of the log-values) rather than $G$, exist?
In particular, I am interested in the signs of
$$1- \frac Hc + \log\frac Gc $$ and $$1 - H + \log G.$$
It is obvious that $1-\frac Hc$ is positive and $1-H$ is negative, and that $\log\frac Gc$ is negative and $\log G$ is positive. However, I cannot work out results for the sums.


text:
Q: jquery datatable excel export button not showing Hi i'm using Datatables js version 1.9.4 css version 1.9.4. And initialize the data table using below code.
Also added support js and css
<script type="text/javascript" th:src="@{/resources/js/excel-export/dataTables.buttons.min.js}"></script>
<script type="text/javascript" th:src="@{/resources/js/excel-export/buttons.flash.min.js}"></script>
<script type="text/javascript" th:src="@{/resources/js/excel-export/jszip.min.js}"></script>
<script type="text/javascript" th:src="@{/resources/js/excel-export/buttons.html5.min.js}"></script>
<script type="text/javascript" th:src="@{/resources/js/excel-export/buttons.print.min.js}"></script>
<link th:href="@{/resources/js/excel-export/buttons.dataTables.min.css}"
    type="text/css" rel="stylesheet" />

var tblUnSubscribedKeys = $('#tblUnSubscribedKeys').DataTable({
                     "aoColumns" : [ null, null,null,null,null,null],
                     "processing": true,
                     "serverSide": true,
                     dom: 'Bfrtip',
                           buttons: [
                               'excel'
                           ]
                 });

The problem is, the data on the table populated correctly. But the excel export button is not visible.

A: You seem to be using the buttons configuration for datatables 1.10
It's a little different in Datatables 1.9
Here's a bit of code I've used in the past to show CSV buttons:
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
            "aButtons" : [
                {
                    "sExtends" : "csv",
                    "sButtonText" : "Download Excel"
                },
                {
                    "sExtends" : "pdf",
                    "sButtonText" : "Download PDF",
                    "sPdfOrientation": "landscape"
                }
            ],
            "sSwfPath": "/swf/copy_csv_xls_pdf.swf"
        },

That worked for me, but you should check the docs and adapt it as you see fit.
Hope it helps!

A: This is working for me. Add this cdn css and js in your page.
  <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css">

  <script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.0.3/js/buttons.html5.min.js"></script>


text:
Q: Troubleshooting Intermittent Failures on Web Applications (ASP.NET) Got reports of a web app going down twice in three weeks. Need to do some root cause analysis. works fine after a reboot. I'm not really an expert in this field.
It is hosted on IIS and Windows 2003.
There is nothing interesting in the event viewer, and IIS logs just show lots of successful GET operations. There is nothing interesting in SQL logs on the remote SQL server it connects to.
I'm not sure how to decipher the IIS log. It just looks like a bunch of successful GET messages with no errors.
I don't think I can really get too much further with root cause analysis track down the cause of the issue?

A: The only thing you could try to get some real results is this excellent blog by Tess Ferrandez. I think that you will find crash lab very enlightening :)

A: Take a look at this, it might help you find the app shutdown cause.

A: Depending on your traffic, twice in three weeks doesn't sound like a lot.  The root cause may relate to the fix- if you were able to bring it back up by restarting IIS, it could be a memory leak.  If you had to restart the server, it could be a deeper problem.


text:
Q: Convert File Names into UTF I have a folder full of sub folders and files which are named using Hebrew encoding (Windows XP - Windows-1255).
I now use Windows 7 and I want to convert all file names into UTF (Native Windows 7 which supports Hebrew characters).
Is there a tool to do so automatically?
Pay attention, I'm not after converting the internals of the file, only its file name.
Thanks!

A: Background
What is needed to be done to fix this is to find some way to automatically know each of these Gibberish characters which Hebrew character they were before being getting that way.
I compiled to such lists of characters. I've seen both kinds of corruptions, sometimes it was using one set and sometimes the other. Here are both sets (and here it is pasted in separate rows, which is needed for what we 'll be doing: Set 1 and Set 2):

*

*à=א
á=ב
â=ג
ã=ד
ä=ה
å=ו
æ=ז
ç=ח
è=ט
é=י
ê=ך
ë=כ
ì=ל
í=ם
î=מ
ï=ן
ð=נ
ñ=ס
ò=ע
ó=ף
ô=פ
õ=ץ
ö=צ
÷=ק
ø=ר
ù=ש
ú=ת
'=ג
"=ד
‡=א
ˆ=צ
‰=ה
˜=ק
¯=ר
Á=ח
Â=ו
È=י
Ê=ז
Ë=ט
Ì=ם
Í=ך
Î=כ
Ï=ל
Ò=ס
Ó=מ
Ô=ן
Ù=פ
Ú=ע
Û=ף
Æ=.
¨=,
ß='
¢="

*Ç=א
ü=ב
é=ג
â=ד
ä=ה
à=ו
å=ז
ç=ח
ê=ט
ë=י
è=ך
ï=כ
î=ל
ì=ם
Ä=מ
Å=ן
É=נ
æ=ס
Æ=ע
ô=ף
ö=פ
ò=ץ
û=צ
ù=ק
ÿ=ר
Ö=ש
Ü=ת

Got it Fixed!
To actually rename files and folders, I figured out an easy way to got this done using Bulk Rename Utility

*

*Open the programs and browse to the folder containing all the files with this kind of names.

*In the bottom of the interface, in the Special section, click on Character Translations

*In the dialog that opens paste the whole list of the charachter set your files are displayed in from the Pastbin link above, and click OK

*In the Filters section, place a checkmark at Subfolders if you want to do more then one folder at a time.

*Select all files and folder in the list (you should see the name it'll become after renaming it in the 2nd coulmn) and click Rename. And now all names should be displyed in Hebrew!

A: Windows stores file names on disk in UTF-16 (two-byte code units, variable-length) encoding. This applies to FAT, FAT32, NTFS and exFAT.
It's unlike Linux/FreeBSD where filesystems have one-byte encoding, and it can be Windows-1255, UTF-8, ISO-8859-* etc.
UTF-16 is converted to ANSI (one-byte encoding) by Windows for some old non-Unicode software which is using old system calls like FindFirstFileA(), FindNextFileA() instead of new system calls FindFirstFileW(), FindNextFileW().
So all you need on Windows is to change "language for non-Unicode programs" setting in Control Panel / Regional and Language Settings. On-disk data is not affected.


text:
Q: Throw error when any of the request parameter is missing/invalid I have to accept a multipart form data consisting of JSON and multiple files and pass it to some third party APIs.
Currently, I have created a component as
@Component
public class Submit{
  private Multipart file;
  private String json;
  //getters setters
}

The controller looks like
 @Controller
 {
   //some code
   @PostMapping("/submit")
   public void post(@ModelAttribute @Valid Submit submit) throws Exception{
     getName()
   }
 }

When a request, not having all the parameters i.e. file & json, is made from Postman client to /submit API, Spring Boot doesn't seem to throw any kind of validation exception/bad request error.
Instead it proceeds with the getName() function.
How can I ensure that an exception is thrown if any of the parameter from the submit model is missing?
Shouldn't @Valid be the one responsible for making this happen?
Thanks!

A: Use annotations and BindingResult.
In your Submit Class:
import javax.validation.constraints.NotNull;
public class Submit{
  @NotNull
  private Multipart file;
  @NotNull
  private String json;
  //getters setters
}

In post method You have to supply BindingResult.
import org.springframework.validation.BindingResult;
@PostMapping("/submit")
public void post(@ModelAttribute @Valid Submit submit, BindingResult bindingResult, HttpServletResponse response) throws Exception{
  if (bindingResult.hasFieldErrors()){
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return;
  }
  getName()
}

This should work for you.


text:
Q: Devexpress xaf ungroup layout of inherited class. (programmaticaly) I am using devexpress xaf to create a multi platform app. I have class 'commonFields' which contains common fields "creation_date, created_by" etc. all other classes inherit from this class. My problem is that, in detailView layout, common fields are displayed in a group labled commonFields.
I know it can be solved using the model editor where I can simply right click over the group and choose ungroup, but if I have lets say more than 50 tables I will have to edit all the layouts individually from the GUI.
I wanted to know if there is any other way, a method or some attribute I can add to the class which will display inherited fields in the same group.
Thankyou

A: Sure you can do it via code. Here is the DevExpress documentation: Extend and Customize the Application Model in Code.
You need to provide your own ModelNodesGeneratorUpdater for the detail views part of the XAF model. It should look something like this:
public class MyDetailViewGeneratorUpdater : ModelNodesGeneratorUpdater<ModelDetailViewLayoutNodesGenerator>
{
    public override void UpdateNode(ModelNode node)
    {
        IModelDetailViewLayout layout = node as IModelDetailViewLayout;
        IModelDetailView detailView = (IModelDetailView)layout.Parent;
        if (!XafTypesInfo.Instance.FindTypeInfo(typeof(MyBase)).IsAssignableFrom(detailView.ModelClass.TypeInfo))   return;
        foreach (IModelDetailViewLayoutElement element in layout)
            UpdateLayoutItems(element, detailView.Items, XafTypesInfo.Instance.FindTypeInfo(typeof(MyBase)).FindMember("Description"));
    }

    private void UpdateLayoutItems(IModelDetailViewLayoutElement element, IModelDetailViewItems items, IMemberInfo member) {
        IModelLayoutItem item = element as IModelLayoutItem;
        IModelLayoutGroup group = element as IModelLayoutGroup;
        if(group != null){
            foreach(IModelDetailViewLayoutElement element1 in group)
            UpdateLayoutItems(element1, items, member);
        }
        else if (item != null) {
            RemoveFromGroup(item); // you just need to code this bit of magic
        }
    }
}

Don't forget to register your updater in the module:
public override void AddGeneratorUpdaters(ModelNodesGeneratorUpdaters updaters)
{
    base.AddGeneratorUpdaters(updaters);
    updaters.Add(new MyDetailViewGeneratorUpdater());
}

A: I'm afraid there are no built-in attributes for this, but here are some directions:
First, be sure to read oficial DevExpress recomendations about Layout Customization.
Second, check Xpand framework's partial view inheritance.
Surely a powerful tool, but will not necessarly save you time in the case you described above, but since I don't know all the complexity you've got, here's a player you can count in.
Also, have you considered giving the grouped layout a chance? You can find ways to make it attractive and useful. Check how to make it expandable:
https://www.devexpress.com/Support/Center/Question/Details/Q101774
In case none of the solutions above meets your needs and all you need is to save time ungrouping it in all views, keep in mind you can edit xaf's model XML file directly. LayoutGroups generated after the parent object properties have the same ID across all views, and you can smartly set ShowCaption to false in those groups for all views ;).


text:
Q: Obtain field (td) values by clicking on table row I need your help.
I have the following table as detailed below. What I would like to do is to click on one of the rows in the table (headers excluded) and obtain the column values of the selected row.
How do I populate the textboxes with the information from the selected row in the table?
No libraries please.
<!DOCTYPE html>

>

            first name
            last name
            age
            total
            discount
            diff

            peter
            parker
            28
            9.99
            20.3%
            +3

            john
            hood
            33
            19.99
            25.1%
            -7

            clark
            kent
            18
            15.89
            44.2%
            -15

            bruce
            almighty
            45
            153.19
            44%
            +19

            bruce
            evans
            56
            153.19
            23%
            +9

Firstname is:<input type="text" id="firstname" />

Lastname is:<input type="text" id="lastname" />

Age is:<input type="text" id="age" />

Total is:<input type="text" id="total" />

Discount is:<input type="text" id="discount" />

Diff is:<input type="text" id="diff" />

A: With using just plain javascript you can do this:

            first name
            last name
            age
            total
            discount
            diff

            peter
            parker
            28
            9.99
            20.3%
            +3

            john
            hood
            33
            19.99
            25.1%
            -7

            clark
            kent
            18
            15.89
            44.2%
            -15

            bruce
            almighty
            45
            153.19
            44%
            +19

            bruce
            evans
            56
            153.19
            23%
            +9

Firstname is:<input type="text" id="firstname" />

Lastname is:<input type="text" id="lastname" />

Age is:<input type="text" id="age" />

Total is:<input type="text" id="total" />

Discount is:<input type="text" id="discount" />

Diff is:<input type="text" id="diff" />

A: Try this (see the fiddle):
var table = document.getElementById( 'myTable' ),
    inputHash = {
        '0': 'firstname',
        '1': 'lastname',
        '2': 'age',
        '3': 'total',
        '4': 'discount',
        '5': 'diff'
    };

for ( var i in inputHash )
    inputHash[ i ] = document.getElementById( inputHash[ i ] );

table.addEventListener( 'click', function( evt ) {
    var target = evt.target;

    if ( target.nodeName != 'TD' )
        return;

    var columns = target.parentNode.getElementsByTagName( 'td' );

    for ( var i = columns.length; i-- ; )
        inputHash[ i ].value = columns[ i ].innerHTML;
} );

A: Here is one example how to use event delegation in javascript (it's especially convenient for dynamically added content) . The event handler is attached to TABLE element's onclick attribute:
function run(){
    document.getElementById('myTable').onclick = function(event){
        event = event || window.event; //for IE8 backward compatibility
        var target = event.target || event.srcElement; //for IE8 backward compatibility
        while (target && target.nodeName != 'TR') {
            target = target.parentElement;
        }
        var cells = target.cells; //cells collection
        //var cells = target.getElementsByTagName('td'); //alternative
        if (!cells.length || target.parentNode.nodeName == 'THEAD') { // if clicked row is within thead
            return;
        }
        var f1 = document.getElementById('firstname');
        var f2 = document.getElementById('lastname');
        var f3 = document.getElementById('age');
        var f4 = document.getElementById('total');
        var f5 = document.getElementById('discount');
        var f6 = document.getElementById('diff');
        f1.value = cells[0].innerHTML;
        f2.value = cells[1].innerHTML;
        f3.value = cells[2].innerHTML;
        f4.value = cells[3].innerHTML;
        f5.value = cells[4].innerHTML;
        f6.value = cells[5].innerHTML;
    }
}

JSFIDDLE: code / result page
The alternative solution, where the event handler is directly attached to each TR element can look like this:
function run() {
    var t = document.getElementById('myTable');
    var rows = t.rows; //rows collection - https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement
    for (var i=0; i<rows.length; i++) {
        rows[i].onclick = function () {
            if (this.parentNode.nodeName == 'THEAD') {
                return;
            }
            var cells = this.cells; //cells collection
            var f1 = document.getElementById('firstname');
            var f2 = document.getElementById('lastname');
            var f3 = document.getElementById('age');
            var f4 = document.getElementById('total');
            var f5 = document.getElementById('discount');
            var f6 = document.getElementById('diff');
            f1.value = cells[0].innerHTML;
            f2.value = cells[1].innerHTML;
            f3.value = cells[2].innerHTML;
            f4.value = cells[3].innerHTML;
            f5.value = cells[4].innerHTML;
            f6.value = cells[5].innerHTML;
        };
    }
}

JSFIDDLE: code / result page

A: Place an onclick on each of your trs like this:
onclick="fillme(this)"

and then place this script in your head


text:
Q: How can I make my code go from one void to another in my menu code and get it to randomly generate inputs? My menu code (main) and the testMatrix code do not work properly, the menu code only improperly goes to the GetMatrix method (it has the user input a 4x4 matrix instead of the desired 3X4 and the testMatrix code doesn't even work, as it just uses the user input method instead. The program has asked me to change many of the program headers to make the code even run without crashing.
package sumelementsbycolumn;

import java.util.Random;
import java.util.Scanner;

public class SumElementsByColumn
{
        private final static Scanner myScan = new Scanner(System.in);

    //========================= void main() ==============================
    public static void main(String[] args)
    {
        char choice;
        do
        {
            final int ROWS = 3;
            final int COLUMNS = 4;
            double[][] matrix = new double[ROWS][COLUMNS];
            choice = getMenu();
            switch (choice)
            {
                case '1':
                {
                    matrix = GetMatrix(matrix);
                    sumColumn(matrix);
                    sumPrint(matrix);
                    break;
                }
                case '2':
                {
                    matrix = testMatrix(matrix);
                    sumColumn(matrix);
                    sumPrint(matrix);
                    break;
                }
                case '0':
                    System.out.println("\n==================================");
                    System.out.println("\n=    Thank You for Using The     ="
                                     + "\nSum Elements By Column Determiner");
                    System.out.println("\n=            Goodbye!            =");
                    System.out.println("\n==================================");
            }
        }while(choice != '0');

    }

    //========================= char GetMenu() ===========================
    private static char getMenu()
    {
        System.out.print("===================================\n"
                + "=Sum Elements By Column Determiner=\n"
                + "===================================\n\n"
                + "\t(1) Input 3 rows of integers\n"
                + "\t(2) Test system using random numbers\n"
                + "\t(0) Exit the program\n"
                + "Choose: ");
        char choice = myScan.next().toUpperCase().charAt(0);

        return choice;

    }
    //========================= void sumPrint() ==============================
    private static void sumPrint(double[][] theMatrix)
        {

        // Read a 3-by-4 matrix
        final int ROWS = 3;
                final int COLUMNS = 4;
                double[][] matrix = new double[ROWS][COLUMNS];
                GetMatrix(matrix);

        // Display the sum of each column
        for (int col = 0; col < matrix[0].length; col++)
                {
            System.out.println(
                "Sum of the elements at column " + col +
                " is " + sumColumn(matrix));
        }
    }
    //========================= double getMatrix() ===========================
    private static double[][] GetMatrix(double[][] matrix)
        {
            final int ROWS = 3;
            final int COLUMNS = 4;
            double[][] m = new double[ROWS][COLUMNS];

        // Prompt the user to enter a 3-by-4 matrix
            System.out.println("Enter a " + ROWS + "-by-" +
            COLUMNS + " matrix row by row:");
            for (int row = 0; row < m.length; row++)
                for (int col = 0; col < m[row].length; col++)
                    m[row][col] = myScan.nextDouble();
                    while(!myScan.hasNextDouble())
                    {
                        System.out.println("That is not a valid number!");
                        System.out.println("Re-Enter the Matrix Values: ");
                        myScan.next();
                    }
            return m;
    }

    //========================= double sumColumn() ===========================
    public static double sumColumn(double[][] m)
        {
        double sum = 0;
                int columnIndex = 0;
                for (double[] m1 : m)
                {
                sum += m1[columnIndex];
                }
        return sum;
    }
    //========================= double testMatrix() ===========================
    private static double[][] testMatrix(double[][] blankMatrix)
    {
        Random rnd = new Random();

        int count = 0;

            for (double[] blankMatrix1 : blankMatrix)
            {
                for (int col = 0; col < blankMatrix.length; col++)
                {
                    {
                        blankMatrix1[col] = rnd.nextInt(100);
                    }
                }
            }
        return blankMatrix;
    }

}

A: I had tweaked the code a bit.This should work. Issue is in the sumColumn method that has the column index always set as 0.
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;

public class SumElementsByColumn
{
    private final static Scanner myScan = new Scanner(System.in);

    //========================= void main() ==============================
    public static void main(String[] args)
    {
        char choice;
        do
        {
            final int ROWS = 3;
            final int COLUMNS = 4;
            double[][] matrix = new double[ROWS][COLUMNS];
            choice = getMenu();
            switch (choice)
            {
                case '1':
                {
                    matrix = GetMatrix(matrix);
                   // sumColumn(matrix);
                    sumPrint(matrix);
                    break;
                }
                case '2':
                {
                    matrix = testMatrix(matrix);
                   // sumColumn(matrix);
                    sumPrint(matrix);
                    break;
                }
                case '0':
                    System.out.println("\n==================================");
                    System.out.println("\n=    Thank You for Using The     ="
                            + "\nSum Elements By Column Determiner");
                    System.out.println("\n=            Goodbye!            =");
                    System.out.println("\n==================================");
            }
        }while(choice != '0');

    }

    //========================= char GetMenu() ===========================
    private static char getMenu()
    {
        System.out.print("===================================\n"
                + "=Sum Elements By Column Determiner=\n"
                + "===================================\n\n"
                + "\t(1) Input 3 rows of integers\n"
                + "\t(2) Test system using random numbers\n"
                + "\t(0) Exit the program\n"
                + "Choose: ");
        char choice = myScan.next().toUpperCase().charAt(0);

        return choice;

    }
    //========================= void sumPrint() ==============================
    private static void sumPrint(double[][] theMatrix)
    {

        // Read a 3-by-4 matrix
        final int ROWS = 3;
        final int COLUMNS = 4;
       // double[][] matrix = new double[ROWS][COLUMNS];
        //GetMatrix(matrix);

        // Display the sum of each column
        for (int col = 0; col < theMatrix[0].length; col++)
        {
            System.out.println(
                    "Sum of the elements at column " + col +
                            " is " + sumColumn(theMatrix,col));
        }
    }
    //========================= double getMatrix() ===========================
    private static double[][] GetMatrix(double[][] matrix)
    {
        final int ROWS = 3;
        final int COLUMNS = 4;
        double[][] m = new double[ROWS][COLUMNS];

        // Prompt the user to enter a 3-by-4 matrix
        System.out.println("Enter a " + ROWS + "-by-" +
                COLUMNS + " matrix row by row:");
        for (int row = 0; row < m.length; row++) {
            for (int col = 0; col < m[row].length; col++) {
                m[row][col] = myScan.nextDouble();
            }
        }
        while(!myScan.hasNextDouble())
        {
            System.out.println("That is not a valid number!");
            System.out.println("Re-Enter the Matrix Values: ");
            myScan.next();
        }
        return m;
    }

    //========================= double sumColumn() ===========================
    public static double sumColumn(double[][] m,Integer col)
    {
        double sum = 0;
        int columnIndex = 0;

       // System.out.println(Arrays.deepToString(m));
        for (double[] m1 : m)
        {
           // System.out.println(" sumcolumn "+m1[col]);
            sum += m1[col];
        }
        return sum;
    }
    //========================= double testMatrix() ===========================
    private static double[][] testMatrix(double[][] blankMatrix)
    {
        Random rnd = new Random();

        int count = 0;

        for (double[] blankMatrix1 : blankMatrix)
        {
            for (int col = 0; col < blankMatrix.length; col++)
            {
                {
                    blankMatrix1[col] = rnd.nextInt(100);
                }
            }
        }
        return blankMatrix;
    }

}

Input Array for test:
===================================
=Sum Elements By Column Determiner=
===================================

    (1) Input 3 rows of integers
    (2) Test system using random numbers
    (0) Exit the program
Choose: 1
Enter a 3-by-4 matrix row by row:
1 2 3 4
5 6 7 8
9 10 11 12

Output:
Sum of the elements at column 0 is 15.0
Sum of the elements at column 1 is 18.0
Sum of the elements at column 2 is 21.0
Sum of the elements at column 3 is 24.0


text:
Q: jquery append() doesn't preserve data or click handlers I am trying to append some links with data and a click handler to a containing div.
jQuery 1.4.3
Fails in FireFox 5.0/Chrome 13.0.782, but works in IE9
I first create the element as a jQuery object, then add the data and click handler.  Then I use .append() to append it to the container:
var $selector = $('Test');
$selector.data('testdata', "Test");
$selector.click(function(event) {
   alert('Clicked: ' + $(this).data('testdata'));
   return false;
});

$('#container').append($selector);

I see the link added, but when I click on it, the click handler does not fire.
I thought that maybe I needed to do the append first and then add data+click, but that doesn't work either:
var $selector = $('Test');
$('#container').append($selector);

$selector.data('testdata', "Test");
$selector.click(function(event) {
   alert('Clicked: ' + $(this).data('testdata'));
   return false;
});

Does append not preserve data and handlers?  It seems that when I .append($selector),  $selector and the newly added DOM object are not one in the same.

A: Which browser are you using?  Also, which version of JQuery?  This works for me in firefox, ie, and chrome on JQuery version 1.6.  Here's the test fiddle I was using.

A: I don't think the append is the cause of your problem. It's because the html you're passing into $() to create your elements is not a simple tag.
According to the documentation of jQuery(html):

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new  element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag, such as $('') or $(''), jQuery creates the element using the native JavaScript createElement() function.

This quote is from this page: http://api.jquery.com/jQuery/#jQuery2
This means that you may get a different element than what you intend because it's dependent on the browser's innerHTML property. You may find it easier if you pass in a simple tag '' and add other attributes to it as a second argument map to $(html, props).
To get this to work with a simple tag in the $(html, props) call, you would do something like this:
var $selector = $('',
    {
    "class" : "x",
    "href" : "#",
    text : "Test",
    click: function() {
           alert('Clicked: ' + $(this).data('testdata'));
            return false;
        }
    });

$('#container').append($selector);

$selector.data('testdata', "Test data");

A: For my page, the problem exists using jQuery 1.4.3 and 1.4.4. But if I upgrade to 1.6.1, the problem goes away and the code works as expected.  At this particular point, I am worried about upgrading to 1.6.1.
My other option is to append the element, then requery for it using jquery before adding data and handlers.  That code does work, but obviously not ideal.

A: I ran into the same issue, try using .appendTo() instead of .append().
It worked for me.


text:
Q: How to update the value of a key in a dictionary in Python? I have a dictionary which represents a book shop. The keys represent the book title and values represent the number of copies of the book present. When books are sold from the shop, the number of copies of the book must decrease.
I have written a code for decreasing the number of copies of the sold book, but on printing the dictionary after the update, I get the initial dictionary and not the updated one.
 n = input("Enter number of books in shop: ")

 book_shop = {} # Creating a dictionary book_shop

 # Entering elements into the dictionary
 for i in range(n):
     book_title = raw_input("Enter book title: ")
     book_no = input("Enter no of copies: ")
     book_shop[book_title] = book_no

 choice = raw_input("Do you want to sell?")
 if (choice in 'yesYES'):
        for i in range(n):
             print("Which book do you want to sell: ", book_shop)
             ch1 = raw_input("Enter your choice: ")
             if(book_shop.keys()[i] == ch1):
                    book_shop.keys()[i] = (book_shop.values()[i]-1)
                    break

 print(book_shop)

I would like to solve the problem in the simplest way possible. Have I missed any logic or any line in the code?

A: Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}

In your case:
book_shop[ch1] -= 1

A: You can simply specify another value to the existed key:
t = {}
t['A'] = 1
t['B'] = 5
t['C'] = 2

print(t)

{'A': 1, 'B': 5, 'C': 2}

Now let's update one of the keys:
t['B'] = 3

print(t)

{'A': 1, 'B': 3, 'C': 2}

A: d = {'A': 1, 'B': 5, 'C': 2}
d.update({'A': 2})

print(d)
{'A': 2, 'B': 5, 'C': 2}

A: You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

A: n = eval(input('Num books: '))
books = {}
for i in range(n):
    titlez = input("Enter Title: ")
    copy = eval(input("Num of copies: "))
    books[titlez] = copy

prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
    choice = input('Enter book title: ')
    if choice in books:
        init_num = books[choice]
        init_num -= 1
        books[choice] = init_num
        print(books)


text:
Q: How can I delete across multiple tables with one query? I have two tables that look like the following :
Table 1 :
invoices
Table 2 :
invoice_details
public function deleteInvoice($id='')
    {
        if( !empty( $id ) ){
            $query = "DELETE FROM invoices where uuid ='$id'";
            if(mysqli_query($this->_con, $query))return true;
            else return false;
        }else{
            return false;
        }
    }

Table 2 contains a column called "invoice_id" that relates to the "id" of Table 1
Whenever I remove an invoice using the above function, I also want to remove the invoice_details at the same time.  Is there an easy way to modify the above code to do that?

A: First you need to put a foreign key constraint on invoice_details
ALTER TABLE invoice_details
    ADD CONSTRAINT fk_invoice
    FOREIGN KEY(invoice_id)
    REFERENCES invoices(id)
    ON DELETE CASCADE;

Then you can delete your invoice and it will delete the details automatically

A: Don't modify the code. Have a foreign key relationship between the tables with an ON DELETE CASCADE option.
ALTER TABLE invoice_details ADD CONSTRAINT fk_invoice FOREIGN KEY invoice_id REFERENCES invoices(invoice_id) ON DELETE CASCADE;

Now the database does the job for you.

A: You could do this using foreign key constraints, forcing a CASCADE on delete. See https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html for additional details.


text:
Q: Drop variable using corr = df.corr() Doing a multi-linear regression I would like to drop one variable but do not know how to write the correct statement into corr = df.corr().
Before using pearson for the correlation I have used
df = df.drop('location', axis=1)

but maybe there is a smarter way to do so?
Does anybody know how?

A: In general, your proceeding is correct. If you prefer to keep the location variable in your original df and just remove it from the correlation table you can code this in one line:
corr = df.drop('location', axis = 1).corr()

Since df.drop('location', axis = 1) returns a dataframe you can simply apply any function that is included in the dataframe class like df.corr().


text:
Q: How can i extend Bluetooth range at maximum? I want to extend at "maximum possible" the range of my Bluetooth Low Energy chip, Nordic nRF51822. I have no limits of space, transmit power or energy requirements so i can use whatever i want.
I was looking for a signal amplifier like RFaxis RFX2411N, but what antenna can i couple with this amplifier?
A friend suggest me to use the Smarteq SmartDisc SD2.4W-02-01-01T but it this directional i think, and i need to have an omni-directional antenna to use on my project.
What products (amplifier, antenna or both) are best to use with this BLE SoC?

A: As far as I can tell, the nRF51822 uses a common port for transmit and receive: -

How can you get inside the chip to amplify the TX transmission when it is being transmitted and then switch back to RX when intending to receive?
EDIT section: -
It seems that NORDIC say this about the VDD_PA pin: -

Logic for tuning the PA on/off can be used via pin "VDD_PA", which
  goes high around 80 us before a TX-transmission occurs and goes low
  again when it's finished.

Basically this means that to add a PA (more power output) you have to design an external duplexer switch so that you can control signals into and out of ANT1 and ANT2.

A:
I have no limits of space, transmit power or energy requirements so i
  can use whatever i want.

Hardly. Bluetooth, which operates on 2.4 GHz frequencies is heavily regulated in regards to power output. Most of this legislation is expressed in ERP ("Effective Radiated Power") which means it will take antenna-gain and coax/feed losses into account in any particular direction or plain of radiation.
Furthermore, Bluetooth is classified in various power classes, Class 1 type equipment (which it must be certified to) has a maximum ERP of 100 mW (20dBm). Class 2 type equpment (usually mobile devices such as mobile/cell phones) are classified to 2.5 mW (4dBm).
If you want more power than that, I really think you need to be licensed for such, and your license will stipulate how much output power / ERP you may use.
I would strongly advise to check your local and country legislation.

I want to extend at "maximum possible" the range

There are various ways to do this, and staying within applicable legislation.
Assuming that you are building a "Class 1" type device and obtain the certification for such.
First, split the TX and RX signals to your device. You can do this with a "Circular Coaxial Coupler" for the intended 2.4 GHz frequencies (many references can be found by simply searching with your favorite search engine). This means that you can use two antenna's, one for TX and one for RX.
Second, you ensure that your TX power does not exceed the maximum allowable TX power of 100 mW ERP. You do need to know the following:

*

*Antenna Gain of the antenna you choose (A in dBi)

*Coaxial loss of the length of feeder you use (C in dB)

*Circular Coaxial Coupler insertion loss (CCC in dB)

With those you can now calculate the maximum TX power output of your amplifier you use:
Pout(dBm) = 20 - A + C + CCC
Lastly, you can use an very high gain antenna for RX; for omnidirectional RX you can use various "colinear vertical" designs, which could have typical gain figures of 9dBi or higher! You may consider vertically stacked array's of antenna's. Again you can use a search to obtain further info.
Tip: for both RX as TX antenna's, you can influence the angle of elevation of maximum gain by using stacked antenna arrays, fed with an different phase to influence "maximum gain takeoff angle", this to improve both RX as TX signal towards the horizon or horizontal plane, or even try to improve gain in negative angles below horizontal plane.
This [the need for phased arrays] you will have to establish by modelling your antenna system location, and the relative position of the users of the system. Example: if your antenna is really high (say 100 metres above ground) and your users are really low (say people walking on ground level using mobile phones) then you want a maximum gain of your antenna system with a negative angle of maximum gain, so maximum signal is downwards towards your users. Again, many designs for this, and info of such, can be found searching the internet.
Another thing to consider is: if your signal needs to travel through structures, such as buildings, walls, trees, or others, you may want to consider circular polarised antenna systems. Circular polarisation will improve penetration properties of the transmitted signal, at least to some extend.
In order to further improve range, you can consider directional antenna systems, but you have preempted this in your question, so I won't further comment on this.
Hopefully this will give you the right information to consider different antenna systems design. I have purposely used the term "antenna system" as this answer relates not simply to "one antenna, plug it in and play".
Afterall, you were asking for:

"maximum possible"

HTH.

A: Since you need an omnidirectional  antenna, you can install a quarter-wave whip on a big ground plane. This will give you 5.19 dBi, which is about as good as a passive omnidirectional antenna can be.
If you need more power, you'll need an active antenna (i.e. one with an amplifier). You mentioned RFaxis RFX2411N, which can be connected to a 50 Ohm antenna. A quarter-wave whip can be easily modified to have a resistance close to that by replacing the ground plane with three quarter-wave rods:


text:
Q: Xcode / ios download if you are not part of the developer program Is it possible to download Xcode / ios sdk freely if you are not part of the developer program?

A: You can download Xcode and the iOS sdk for free, but you have to register a free account on developer.apple.com.

A: You can even download Xcode from the App store.

A: Yes! you can Download Xcode for iOS/Mac Development, but first you have to register yourself here
Then you can download it.


text:
Q: Check button for class and if it has a certain class create a 'done' div I am new to Jquery. I have an upload form that when something is uploaded the upload-button changes class from:
Upload a document

To:
Upload a document

I have tried to write a function that adds a div called 'done' if a file has already been uploaded(the class in the button has changed).
Here is what I have got so far:
$('a#upload-button').ready(function() {
            if ($(this).hasClass('white')) {
                $('#three')
                    .append('

')
                    .addClass('grey');
        }
        })

I am not sure why it is not working. Please could somebody help?

A: You should do (if you want to check if a button has a class when the page is loaded, otherwise just take the if part and put it where you need it
//this is a shorthand methot for $(document).ready()
//you should use this to wait for the dom to load
$(function(){
 //if the link has the class
  if($('a#upload-button').hasClass('white')){
     //append the button
     $('#three')
        .append('

')
        .addClass('grey');
  }
});

EDIT - you should modify your script
function verifyFileUploadState(up) {
    if ($(".file-title").length == 0) {
        $("#upload-button span").html("Upload a document");
        $("#upload-button").addClass("upload");
        $("#upload-button").removeClass("white");
    } else {
        $("#upload-button span").html("Upload another document");
        $("#upload-button").removeClass("upload");
        $("#upload-button").addClass("white");
         $('#three')
            .append('

')
            .addClass('grey');
    }
    up.refresh();
}


text:
Q: Is it valid to do K-means clustering on PCA-reduced data? Here is the basic SKLearn tutorial on K-means.
They run PCA and then do K-means on reduced data. Can it radically affect the result? Will we get totally different clusters if we apply PCA on already clustered data?

A: Yes, it can radically affect the result.
You can get completely orthogonal clusters if the variances of the components are different by a large factor.


text:
Q: Get table and column "owning" a sequence I can run the following line:
ALTER SEQUENCE seqName OWNED BY table.id;

How can I get the 'owner' set by OWNED BY for a sequence (in this case: table.id)?

A: I was able to list the table and corresponding sequence for a particular column using the following SQL statement:
SELECT   table_schema
       , table_name
       , column_name
       , LTRIM(RTRIM(RTRIM(column_default, '::regclass)'),''''),'nextval(''') AS SEQUENCE_NAME
FROM information_schema.columns
WHERE  column_default like '%nextval%';

A: SELECT c.relname,u.usename
  FROM pg_class c, pg_user u
 WHERE c.relowner = u.usesysid and c.relkind = 'S'
   AND relnamespace IN (
    SELECT oid
      FROM pg_namespace
     WHERE nspname NOT LIKE 'pg_%'
       AND nspname != 'information_schema'
    );

A: You may use following query:
select s.relname as seq, n.nspname as sch, t.relname as tab, a.attname as col
from pg_class s
  join pg_depend d on d.objid=s.oid and d.classid='pg_class'::regclass and d.refclassid='pg_class'::regclass
  join pg_class t on t.oid=d.refobjid
  join pg_namespace n on n.oid=t.relnamespace
  join pg_attribute a on a.attrelid=t.oid and a.attnum=d.refobjsubid
where s.relkind='S' and d.deptype='a'

It returns all sequences with owner information. Just filter them in WHERE clause and that's it.

A: Get the "owning" table and column

ALTER SEQUENCE seqName OWNED BY table.id;

Your ALTER SEQUENCE statement causes an entry in the system catalog pg_depend with the dependency type (deptype) 'a' and a refobjsubid greater than 0, pointing to the attribute number (attnum) in pg_attribute. With that knowledge you can devise a simple query:
SELECT d.refobjid::regclass, a.attname
FROM   pg_depend    d
JOIN   pg_attribute a ON a.attrelid = d.refobjid
                     AND a.attnum   = d.refobjsubid
WHERE  d.objid = 'public."seqName"'::regclass  -- your sequence here
AND    d.refobjsubid > 0
AND    d.classid = 'pg_class'::regclass;

*

*Double quotes ("") are only needed for otherwise illegal names (mixed case, reserved words, ...).

*No need to assert that refclassid is of type regclass since the join to pg_attribute does that automatically.
No need to assert that the sequence is a sequence since schema-qualified object names are unique across the database.
No need to join to pg_class or pg_namespace at all.

*The schema name is only needed to disambiguate or if it's not in the search_path.
The same table name (or sequence name for that matter) can be used in multiple schemas. A cast to the object identifier type regclass observes the current search_path to pick the best match if you omit the schema qualification. If the table is not visible, you get an error message.

*What's more, a regclass type is displayed as text to the user automatically. (If not, cast to text.) The schema-name is prepended automatically where necessary to be unambiguous in your session.
Get the actual "owner" (the role)
To get the role owning a specific sequence, as requested:
SELECT c.relname, u.usename
FROM   pg_class c
JOIN   pg_user  u ON u.usesysid  = c.relowner
WHERE  c.oid = '"seqName"'::regclass;  -- your sequence here

A: I use that query for get all queries.
Change CTE to filter the result
WITH table_with_sequence as (
SELECT
    d.refobjid::regclass::text tablename,
    c.relname::text sequencename,
    np.nspname::text schemaname,
    a.attname::text attname,
    u.usename::text
FROM
    pg_depend d
    INNER JOIN pg_class c ON c.oid = d.objid
        AND c.relkind = 'S'
    INNER JOIN pg_namespace np ON np.oid = c.relnamespace
        AND (np.nspname NOT LIKE 'pg_%'
            AND np.nspname != 'information_schema')
        INNER JOIN pg_user u ON u.usesysid = c.relowner
        INNER JOIN pg_attribute a ON a.attrelid = d.refobjid
            AND a.attnum = d.refobjsubid
)

SELECT
    'ALTER SEQUENCE '|| QUOTE_LITERAL(QUOTE_IDENT(schemaname) || '.' || QUOTE_IDENT(sequencename)) ||' OWNED BY ' || tablename || '.' || QUOTE_IDENT(attname)
FROM table_with_sequence


text:
Q: laravel5 ajax page pagination,how to change the button url I use ajax to implement pagination. But I don't know how to change the Laravel pagination button href. Next page button always links to page 2.
My ajax code is below:
$('.pagination a').on('click', function (event) {
        event.preventDefault();
        if ( $(this).attr('href') != '#' ) {
            $.ajax({
                url: $(this).attr('href'),
                type: 'POST',
                data:{'_token': "{{ csrf_token() }}"},
                success: function(data) {console.log(data);
                    var data = $.parseJSON(data);
                    // 加载图书列表
                    var html = compiled_tpl.render(data);
                    document.getElementById('booklist').innerHTML = html;
                    $('.ajaxpage').html(data.render);
                }
            });
        }
    });


text:
Q: ContextMenuStrip not showing on the first time of being right clicked I've added a contextmenustrip programmatically through the extension of panel along with some other stuff,
It is being set into the panel's contextmenu through the panel's constructor.
The first time I right click does not work and then it will after the first time always.
I have tried also to put the constructor of the contextmenustrip and the assigning of it to the panel's context menu in other places such as Load and the form's constructor and even in a timer with a flag, All produced the same result..
EDIT:(Some code as requested(as it is and cut to important points))
class FiniteAutomationController : System.Windows.Forms.Panel
{
    public FiniteAutomationController()
        : base()
    {
    this.ContextMenuStrip = (cms = new ContextMenuStrip());
    }
    public ContextMenuStrip cms;
}

EDIT:(Per blaze_125's request, some more code)
//at form designer initializecomponents after Controller(FiniteAutomationController)'s initialization

this.Controller.cms.Opening += new System.ComponentModel.CancelEventHandler(this.cms_Load);

//at form code class
    static State contextS = null;
    static Action contextA = null;
    private void cms_Load(object sender, CancelEventArgs e)
    {
        Controller.cms.Items.Clear();

        if ((contextS = FiniteAutomationData.GetStateFrom(mouseX, mouseY)) != null) // Rclick States
        {
            Controller.cms.Items.Add("Delete"); Controller.cms.Items[0].Click += new EventHandler(cms_DeleteState);
            Controller.cms.Items.Add("Rename"); Controller.cms.Items[1].Click += new EventHandler(cms_RenameState);
            Controller.cms.Items.Add((contextS.final ? '\u2714' : ' ') + " Final"); Controller.cms.Items[2].Click += new EventHandler(cms_Final);
            Controller.cms.Items.Add((contextS.initial ? '\u2714' : ' ') + " Initial"); Controller.cms.Items[3].Click += new EventHandler(cms_Initial);
            Controller.cms.Items.Add("Trap"); Controller.cms.Items[4].Click += new EventHandler(cms_Trap);
            if (!contextS.error.Equals(""))
            {
                Controller.cms.Items.Add("Error: " + contextS.error);
                Controller.cms.Items[5].Enabled = false;
            }
        }
        else if((contextA = FiniteAutomationData.GetActionFrom(mouseX,mouseY)) != null) // Rclick Action
        {
            Controller.cms.Items.Add("Delete"); Controller.cms.Items[0].Click += new EventHandler(cms_DeleteAction);
        }
        else // Rclick null
        {
            Controller.cms.Items.Add("Add State"); Controller.cms.Items[0].Click += new EventHandler(cms_AddState);
        }
    }

A: I found (well, with the help of DotPeek) that when using a blank ContextMenuStrip for a Control's ContextMenuStrip property so that you can add the items dynamically the code in System.Windows.Forms actually sets the Cancel property of the CancelEventArgs that are passed to the Opening handler to true because the context menu at first is empty and contains no items.
On subsequent calls, even if the first thing you do in the Opening handler is clear all items, the Cancel property will be set to false.
So my fix to make sure the context menu shows up at all times (including the first one) was to always set the CancelEventArgs' Cancel property to true or false and not (falsely) relying on it to be initialized to false anyway...

A: Throughout the last 3 days I've managed to find a solution which I think is a really bad one, but a solution still..
What I did is used the MouseDown Event of the Controller and using a flag,
Showed the context menu on the first time using it's Show(Point) method.
The show method placed the menu a bit off and I settled on "new Point(e.X,e.Y+45)" to place it correctly which still I don't like that I'm doing as it seems really unprofessional..
Thanks anyways I guess..

A: For my case, I need to show the context menu by clicking on ToolStripButton. It is not shown for the first click. I managed this problem in this way
    void _TsiMenu_Click(object sender, EventArgs e)
    {
        AdjustableMenu.Show(this, this.PointToClient(Cursor.Position), ToolStripDropDownDirection.Default);
        Application.DoEvents();
        if (AdjustableMenu.Visible == false)
            AdjustableMenu.Show(this, this.PointToClient(Cursor.Position), ToolStripDropDownDirection.Default);
    }

A: Add a MouseClick event to notifyicon.
Handle the event as the following:
private void NotifyIconClicked(object sender, MouseEventArgs e)
{
    _dashboard.ShowHiddenWindow();
    if (e.Button == MouseButtons.Right)
    {
        MethodInfo ShowContextMenu = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
        if (ShowContextMenu != null)
        {
            ShowContextMenu.Invoke(_notifyIcon, null);
        }
    }
}

I believe the main window has to be made active for this, but I haven't tested this conditional for sure. This is something that i had to implement anyway.
    internal static void ShowHiddenWindow(this Window window)
    {
        try
        {
            if (!window.IsVisible)
            {
                window.Show();
            }

            if (!window.IsFocused)
            {
                window.Activate();
            }
            window.WindowState = WindowState.Normal;
        }
        catch
        {
            // Avoids "Cannot set visibility while window is closing".
        }
    }