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

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

Your Message:

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

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

    </fieldset>
</form>

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

  $newer = sanitize($data1);

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

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

  $final = nl2br($newest);

  return $final;

}

function decode($data) {

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

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

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

  return $newer;
}

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

A: From the documentation for nl2br:

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

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


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

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

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

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

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

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


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

A: UPDATED
Please replace this with your code

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

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

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

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

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


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


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

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

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

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


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

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

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

        </form>";
?>

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

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

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

        }
    });

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

*

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

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

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

    }
});

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

echo "<form name='frmtopdevotees'>

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

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

</form>";
?>


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

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

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

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

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

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


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

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

A: Two solutions are here:

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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


Q: Maybe is right $\frac{n^2 + 1}{4k + 3} \notin \mathbb{Z}, n, k \in \mathbb{N}^{+}$ Prove or disprove
$$\dfrac{n^2 + 1}{4k + 3} \notin \mathbb{Z}, n, k \in \mathbb{N}^{+}$$
I know if $n^2 + 1$ is prime if and only if $n^2 + 1 \equiv 1 \pmod 4$.

A: Suppose $\,4k\!+\!3\mid n^2\!+1.\,$ $\,4k\!+\!3\,$ has a prime factor $\,p\equiv 3\pmod 4\,$ [else all are $\equiv 1\,$ so their product $\equiv 1,\,$ not $\, 3\,$]. Write $\, p = 4j\!+\!3,\,$ therefore $\, \color{#0a0}{p\!-\!1 = 2(2j\!+\!1)},\,$ so by little Fermat
$p\mid 4k\!+\!3\mid \color{#90f}{n^2\!+\!1}\,\Rightarrow\,{\rm mod}\ p\!:\,\ \color{#90f}{n^2\equiv -1}\ \Rightarrow\  \color{#c00}1\equiv n^{\color{#0a0}{p-1} }\equiv (\color{#90f}{n^2})^{\color{#0a0}{2j+1}}\equiv (\color{#90f}{-1})^{2j+1}\equiv \color{#c00}{-1}$
therefore $\ p\mid 2=\color{#c00}{1-(-1)},\ $ contra $\,p = 4j+3\,$ is odd.


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

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

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


Q: The maximum of $|x^3 + ax^2 + bx + c|$ on $[-1, 1]$ is at least $1/4$ Let $f(x)=x^{3}+ax^{2}+bx+c$ with a, b, c real.
Show that
$$\frac{1}4 \le \max_{-1 \le x \le 1\hspace{2mm}} |f(x)|=M$$
and find all cases where equality occurs.

A: Note that
$$
\max_{[-1,1]}\,\left|\,x^3-\tfrac34x\,\right|=\tfrac14\tag{1}
$$
Considering the symmetry about $0$ of the domain, we have for any $t\in[0,1]$
$$
\max_{\{t,-t\}}\,\left|\,x^3+ax^2+bx+c\,\right|=\left|\,t^3+bt\,\right|+\left|\,at^2+c\,\right|\tag{2}
$$
Using $(2)$, it is obvious that
$$
M_b=\max_{[-1,1]}\,\left|\,x^3+bx\,\right|\le\max_{[-1,1]}\,\left|\,x^3+ax^2+bx+c\,\right|\tag{3}
$$
It is straightforward to compute
$$
M_b=\left\{\begin{array}{}
2(-b/3)^{3/2}&\text{if }b\in\left[-3,-\tfrac34\right]\\
|\,1+b\,|&\text{otherwise}
\end{array}\right.\tag{4}
$$
and $M_b$ reaches a minimum of $\frac14$ only at $b=-\frac34$. For any other value of $b$, $(3)$ says that
$$
\max_{[-1,1]}\,\left|\,x^3+ax^2+bx+c\,\right|\ge M_b>\tfrac14\tag{5}
$$
Setting $b=-\frac34$ and $t=\frac12$ in $(2)$ yields
$$
\max_{[-1,1]}\,\left|\,x^3+ax^2-\tfrac34x+c\,\right|\ge\tfrac14+\left|\,\tfrac14a+c\,\right|\tag{6}
$$
and this can be $\frac14$ only if $c=-\frac a4$.
At $|x|=\frac12$,
$$
\left|\,x^3+ax^2-\tfrac34x-\tfrac a4\,\right|=\tfrac14\tag{7}
$$
However, at $x=\pm\frac12$, the derivative of $x^3+ax^2-\frac34x-\frac a4$ is $\pm a$. Therefore, the maximum of $\left|\,x^3+ax^2-\tfrac34x-\tfrac a4\,\right|$ will be greater than $\frac14$ unless $a=0$.
Thus,
$$
\max_{[-1,1]}\,\left|\,x^3+ax^2+bx+c\,\right|\ge\tfrac14\tag{8}
$$
where equality holds only for $x^3-\frac34x$.


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

type = array / bool / string / int

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

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

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


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

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

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

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

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

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


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

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

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

*

*new

*alloc

*retain

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

*

*want ownership or

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

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

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

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

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

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

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

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

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

But all "initWithXXX" functions return autoreleased objects instead.

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

*

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

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

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

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

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

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

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


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

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

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

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

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

More details you can read here:
Charts

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

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

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

Result

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

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

A: Fill.fillWithLinearGradiant has been updated to LinearGradientFill

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


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

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

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

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

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

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

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

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

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

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


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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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


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

data=table('data.txt')

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

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

aaa = getattr(ax1,'xaxis')

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

for a in sorted(nax):

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

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

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

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

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

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

for ax in nax:

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

   ax.xaxis.set_tick_position('bottom')


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

Sugar

Fruits

hello
hello
hello
hello

Click the button to delete the HTML elements

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

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

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

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

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

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

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

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

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


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

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

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


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


Q: Is it possible to extract pixel values for multiple image layers at specific locations? I am attempting to gather data for an urban forest, I am more or less trying to run transects through the forest but with Google Earth Engine. I have a few rasters that I am wanting to extract data from and I want to do so at the same point for every raster.
I tried to do this with ee.Image.sample, but it places the sample point at different locations, I imagine due to the resolution of each image. In the following code "fromList" is the forested area featureCollection. "drain" and "elev" are the different rasters, which are both clipped to the featureCollection "fromList"
//SAMPLE
var samples = drain.sample({
  region: fromList,
  geometries: true,
  scale: 90,
});
var samples2 = elev.sample({
  region: fromList,
  geometries: true,
  scale: 90,
});

 print(samples, samples2);
 Map.addLayer(samples);
 Map.addLayer(samples2);

My next guess was to try and use pins, however, I can't seem to figure out how to get the data from each pixel. The pins are saved into a featureCollection called "pts".

A: Combine the two images' bands into one image. Then, you will get only one set of points.
var samples = drain.addBands(elev).sample({
  region: fromList,
  geometries: true,
  scale: 90,
});

(You may wish to, first, rename the images' bands in case any of them have the same name.)


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

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

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

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

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


Q: How do I create a better guest account experience in MacOS X Lion? I'm running Mac OS X 10.7.5. In previous versions of MacOS X, there would be a guest account created from a template when a guest wanted to use the computer, and then the files would be destroyed upon logout. If I remember correctly, the user was also sandboxed so they couldn't access any of the other files (this may be wrong).
In any case, I'm using FileVault2 on my MacBook Air. I still want to provide guests access to our computer, but the current guest mode is deficient in the following ways:

*

*It doesn't run at native resolution. Instead of 1920x1080, it runs at something lower.

*It doesn't auto-connect to my wifi network. This means my guest has to re-enter credentials every time they login.

*It does a reboot and then logs in. I realize this is a security measure in case the computer gets stolen.
So my first question is this: Is there a way to modify the default guest experience to run at native video resolution and remember wifi connected networks? I'm quite comfortable with the command line. I used to edit the template in "/System/Library/User Template/" to achieve the effects I wanted in the default guest.
If not, my next option is to create my own "guest" user. I'd like to use a logout hook (I googled it). Are there suggestions on how to configure this 'guest' account? One question I have is what would be an appropriate group to assign this temporary user too. I'd also like to invoke similar templating behavior on login and logout. Is it possible to invoke the login/logout script on a per user basis? Or does the script itself need to incorporate this logic? (i.e. do I need a if [-user 'temp'] blah blah).

A: Try this:  Create a user TestGuest.  Configure it the way you want.
Create a user visitor.
In your own terminal window type "id visitor"
You will get a return something like this:
uid=504(visitor) gid=20(staff) groups=20(staff),404(com.apple.sharepoint.group.3),402(com.apple.sharepoint.group.1),12(everyone),61(localaccounts),403(com.apple.sharepoint.group.2),405(com.apple.sharepoint.group.4)
You may want to compare this to the guest account to see what groups guest is normally lacking, compared to visitor.
Check the owner and group of all files in the regular guest account.  See if these are anything other than guest and whatever group guest is a member of.
As an admin, you can change the groups that TestGuest and Visitor are member of.
Create a script.  This script checks to see of visitor is logged in, and if it doesn't it does the following:
A:  rsync between TestGuest and visitor.
B:  change ownership and group of visitor to match the real visitor.
C:  Put a flag file that indicates a fresh visitor install
Once you get this script working to your satisfaction, add a test to see if visitor is logged in.  If visitor is logged in, it checks for the existence of a flag file.  If that file is there, it is removed, and the script exits.  If the visitor is not logged in, it checks for the flag file, and if does the rsync, adds the flag file, and exits.  If the flag file is there, it exits.
Fresh Creation of visitor account
Fresh Flag in place
Visitor Logs in
Fresh Flag removed
Visitor Logs out
No Flag, so visitor account is recreated.
The idea is that the flag tells the script if it has run since visitor last logged in or out.
You can check for login with "last | grep console" which will show you all logged in window users. Look for "still logged in"
You can do tests for this by enabling multiple logins.
Once you get the script working properly running manually after the visitor logs in and out, then create a cron job that runs as root that runs every 2 minutes.


Q: Screen is flickering when full screen in intel UHD 620 I'm new to ubuntu. I have recently installed ubuntu 20.04 along with windows 10. Screen is flickering when videos turn to fullscreen.  Same thing happening for ppt files when in presentation mode. In windows everything is ok.
It's annoying.
Plz help.
Processor: Intel Core i5-8265U
VGA compatible controller: Intel Corporation UHD Graphics 620 (Whiskey Lake)
Here is the details of graphics

A: I have Lenovo T480S with Ubuntu 20.04. Playing on Intel video with VLC full screen mode - screen is flickering. As work around I turned off Tools->Interface->Show controls in full screen mode.

A: I was facing a similar issue. It is due to the change in display settings we've done before. Go to display settings and revert back the fractional scaling to 100% if it is not. It should work fine. Ubuntu version 20.04


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

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

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

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


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

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


Q: how to get a content from textboxes in a database table with a Button click event? IWhat i wanna do
So I tried this code
but it coudnt get a connection with the Database. I the connection string is correct
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");

        con.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "insert into [kunde]Vorname()values(@nm)";

        cmd.Parameters.AddWithValue("@nm", Vorname.Text);
        cmd.Connection = con;

        SqlCommand cmdd = new SqlCommand();

        cmdd.CommandText = "insert into [kunde]Nachname()values(@nmm)";

        cmdd.Parameters.AddWithValue("@nmm", Nachname.Text);
        cmdd.Connection = con;

        int a = cmd.ExecuteNonQuery();

        if (a == 1)
        {
            MessageBox.Show("Dateien bitte");

        }

A: follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.
 try
        {
            SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert into tableName(column1,column2) values(@nm,@nmm)";
            cmd.Parameters.AddWithValue("@nm", Vorname.Text);
            cmd.Parameters.AddWithValue("@nmm", Nachname.Text);
            cmd.Connection = con;
            int a = cmd.ExecuteNonQuery();
            if (a == 1)
            {
                MessageBox.Show("Dateien bitte");

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error:"+ex.ToString());
        }


Q: creating dynamic menu using json, Html, JS & css for mobile platforms Am creating a dynamic menu from json object(downloaded from server) using html, js & css for mobile platforms without using libraries like JQuery
i read like "document.write should not be used in event handlers like onLoad() or onclick() . its better to use DOM"
plz give your valuable suggestions.

A: You can create elements in javascript using DOM by using the .createElement() method.
Example: Create a div for your menu and give it a css class name.
menudiv = document.createElement('div');
menudiv.className = 'menu';

Now you can plug your json data into it by creating other elements. For example if you would like to create a link using DOM.
link = document.createElement('a');
link.setAttribute('href', 'urlFromYourJsonData');
link.appendChild(document.createTextNode('Your Link Description'));
menudiv.appendChild(link);

and so on ...
I suggest you have a look at: https://developer.mozilla.org/en/DOM/document.createElement and make your way from there.
Edit: After seeing your second comment I also suggest you have a look at http://json.org to look up what JSON is. If you want to copy HTML code into your page you should use the innerHTML attribute.
Example:
div = document.createElement('div');
div.className = 'menu';
div.innerHTML = yourAjaxResponseHere;


Q: can't access submenu link using mouseover i am trying to access submenu link "WHAT IS Flex?" under "About Flex" from
http://flex.apache.org/ using selenium Web Driver.
Whenever a mouseover is performed submenu is highlighted and disappears before i can access submenu.
*Imported a few unnecessary packages.Please don't mind.
Code:
package com.ram.workingtitle;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.Alert;
import org.openqa.selenium.interactions.Actions;
import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;

public class Mouseover {
    public static void main(String[] args) throws Exception
    {
        WebDriver driver= new FirefoxDriver();
        driver.navigate().to("http://flex.apache.org/");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        /*
        Used Firepath for generating xpath
        */
        WebElement element=driver.findElement(By.xpath(".//*[@id='nav']/li[2]/a"));
        WebElement sub=driver.findElement(By.xpath(".//*[@id='nav']/li[2]/ul/li[1]/a"));

        Actions action=new Actions(driver);
        action.moveToElement(element).build().perform();

        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

        action.moveToElement(sub).build().perform();

        System.out.println("executed");
    }
}

Please help.
Thanks&Regards,
Ram.

A:    Actions action = new Actions(webDriver);
            action.moveToElement(webDriver.findElement(By.xpath("//*[@id='nav']/li[2]/a")))
            .build()
            .perform();
            Thread.sleep(5000);
            webDriver.findElement(By.xpath("//*[@id='nav']/li[2]/ul/li[1]/a")).click();

Note: Thread.sleep is not a good practice. Just use implicit wait in your program or/and WebDriverWait.


Q: How to clean double lines from joint statement in R? Having done a join operation to compare addresses with itself.
library(tidyverse)
library(lubridate)
library(stringr)
library(stringdist)
library(fuzzyjoin)
doTheJoin <- function (threshold) {
      joined <- trimData(d_client_squashed) %>%
        stringdist_left_join(
          trimData(d_client_squashed),
          by = c(address_full="address_full"),
          distance_col = "distance",
          max_dist = threshold,
          method = "jw"
        )
    }

The structure of d_client_squashed is the following and contains string values:

Client_Reference
adress_full

C01
Client1 Name, Street, Zipcode, Town

C02
Client2 Name, Street2, Zipcode2, Town2

...
...

The following operation:
sensible_matches <- doTheJoin(0.2)
View(sensible_matches %>% filter(Client_Reference.x != Client_Reference.y))

Results in the following output:

Client_Reference.x
address_full.x
Client_Reference.y
address_full.y
Distance

C01
Client1 Name, Street, Zipcode, Town
C02
Client2 Name, Street2, Zipcode2, Town2
0.05486

C02
Client2 Name, Street2, Zipcode2, Town2
C01
Client1 Name, Street, Zipcode, Town
0.05486

...
...
...
...
...

The output of this join operation is double with reversed client information. The distance value is not unique. How can I subset the data frame to avoid those double lines?

A: In order to remove the rows containing the same data, you can order them based on the contained elements, so there is not difference between rows containing the same pair of Client_Reference, and then delete the duplicates. After that you can filter the ones containing the same Client_Reference as you did.
sensible_matches <- sensible_matches[!duplicated(t(apply(sensible_matches,1,sort))),]
View(sensible_matches  %>% filter(Client_Reference.x != Client_Reference.y))


Q: OSX SSH tunnel from remote port to local I've created SSH tunnels in the past, but I'm having trouble on OSX. I'm looking to take a website's port 80, and direct it to my localhost:8080. When I run this command
ssh -L 8080:<cloud_ip_address>:80 root@<cloud_ip_address> -N

I get the default apache 'it works!' page.
Why am I not getting the port 80 of the remote machine (which is running a web app)?
UPDATE
I still do not have a solution yet, but I have some more information. The page I am getting is the default page in /var/www/html but I am serving a Flask app which does not have static pages.

A: Because HTTP protocol contains not only the IP address, but also the hostname (the URL you type into your browser), which differs between the <cloud_hostname> and localhost. The easiest way to trick it is to create /etc/hosts (there will be some OSX alternative -- search ...) entry redirecting the hostname of your remote machine to localhost.
127.0.0.1 <cloud_hostname>

But note that in this case you will not be able to access the remote machine using the hostname!


Q: Creating object in django model form with foreign key I am inserting a new record in my model form where my model is child form containing a foriegn key. When I am submitting the form it give error it should be instance of the foriegn key.
Here is my model
class MMEditidState(models.Model):
  state_id = models.IntegerField(primary_key = True)
  state_dremelid = models.ForeignKey(MMDremelDump, db_column = 'state_dremelid')
  assignee = models.CharField(max_length = 50)
  state = models.CharField(max_length = 50)
  role = models.CharField(max_length = 50)
  date = models.DateTimeField()
  class Meta:
    db_table = u'mm_editid_state'
  def __unicode__(self):
    return u'%s %s' % (self.state_dremelid, self.assignee)

  class MMEditidErrors(models.Model):
     error_id = models.IntegerField(primary_key = True)
     error_stateid = models.ForeignKey(MMEditidState, db_column = 'error_stateid')
     feature_type = models.CharField(max_length = 20)
     error_type = models.CharField(max_length = 20)
     error_nature = models.CharField(max_length = 50, null = True)
     error_details = models.CharField(max_length = 50)
     error_subtype = models.CharField(max_length = 200)
     date = models.DateTimeField()
  class Meta:
     db_table = u'mm_editid_errors'
  def __str__(self):
     return "%s" % (self.error_dremelid)
  def __unicode__(self):
     return u'%s' % (self.error_dremelid)

Here is my View
def qcthisedit(request, get_id):
  if request.method == "POST":
     form = forms.MMEditidErrorForm(get_id, request.POST)
     if form.is_valid():
        form.save()
     return http.HttpResponseRedirect('/mmqc/dremel_list/')
  else:
    form = forms.MMEditidErrorForm(get_id)
    return shortcuts.render_to_response('qcthisedit.html',locals(),
                                  context_instance = context.RequestContext(request))

Here is my form
class MMEditidErrorForm(forms.ModelForm):
   def __init__(self,get_id, *args, **kwargs):
     super(MMEditidErrorForm, self).__init__(*args, **kwargs)
     dremel = MMEditidState.objects.filter(pk=get_id).values('state_id')
     dremelid = int(dremel[0]['state_id'])
     self.fields['error_stateid'] = forms.IntegerField(initial = dremelid,
                                                   widget = forms.TextInput(
                                                              attrs{'readonly':'readonly'}))
     feature_type  = forms.TypedChoiceField(choices = formfields.FeatureType)
     error_type  = forms.TypedChoiceField(choices = formfields.ErrorType)
     error_nature = forms.TypedChoiceField(choices = formfields.ErrorNature)
     error_details = forms.TypedChoiceField(choices = formfields.ErrorDetails)
     error_subtype = forms.TypedChoiceField(choices = formfields.ErrorSubType)
     class Meta:
        model = models.MMEditidErrors
        exclude = ('error_id','date')

When I submit the form I am getting the error
Cannot assign "1": "MMEditidErrors.error_stateid" must be a "MMEditidState" instance.

So I have added line
get_id = MMEditidState.objects.get(pk = get_id)

Now I am getting the below mentioned error
int() argument must be a string or a number, not 'MMEditidState'

in form = forms.MMEditidErrorForm(get_id, request.POST)
Can someone help on this
Thanks
Vikram

A: I have solved this problem by simply using the custom forms instead of model forms. While storing the data in the database, I managed myself in the views.py


Q: symfony in a home directory on debian with apache & userdir.conf After installing symfony in a user's directory (/home/user/public_html/my-project), the web directory does not appear by querying http://nameserver.com/~user/my-project and the following apache error appears by querying http://nameserver.com/~user/my-project/web : Internal Server Error
If the installation is done in /var/www/html/my-project, everything works well. However, I have to install it in the user's directory :(
Should I change/adapt the web/.htaccess if symfony is in /home/user/public_html ?
Server is a debian with apache 2.4.25
/etc/apache2/mods-enabled/userdir.conf :
<IfModule mod_userdir.c>
    UserDir public_html
    UserDir disabled root

    <Directory /home/*/public_html>
        AllowOverride FileInfo AuthConfig Limit Indexes
        Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
        Require method GET POST OPTIONS
        Require all granted
    </Directory>
</IfModule>

error.log apache2:
AH01630: client denied by server configuration: /home/user/public_html/symfony/src/, referer: https://nameserver.com/~user/
/home/user/public_html/symfony/web/.htaccess: Options not allowed here, referer: https://nameserver.com/~user/
AH01630: client denied by server configuration: /home/user/public_html/symfony/app/, referer: https://nameserver.com/~user/
Symfony :
-------------------- -------------------------------------------
  Symfony
 -------------------- -------------------------------------------
  Version              3.4.8
  End of maintenance   11/2020
  End of life          11/2021
 -------------------- -------------------------------------------
  Kernel
 -------------------- -------------------------------------------
  Type                 AppKernel
  Name                 app
  Environment          dev
  Debug                true
  Charset              UTF-8
  Root directory       ./app
  Cache directory      ./var/cache/dev (773 KiB)
  Log directory        ./var/logs (41 KiB)
 -------------------- -------------------------------------------
  PHP
 -------------------- -------------------------------------------
  Version              7.0.27-0+deb9u1
  Architecture         64 bits
  Intl locale          n/a
  Timezone             Europe/Berlin (2018-04-24T16:37:05+02:00)
  OPcache              true
  APCu                 false
  Xdebug               false
 -------------------- -------------------------------------------

A: Probably Symfony .htaccess tries to change some settings that is not allowed by your configuration. At first I suggest change line: AllowOverride FileInfo AuthConfig Limit Indexes into AllowOverride all. Or if you can't do this for security reasons, look into symfony .htaccess, and try to change tihs AllowOverride directives list to work with this used in symfony .htacces.


Q: How to properly cancel MediaPlayer.prepare()? I am using the Android MediaPlayer to play a Video in my app.
I use MediaPlayer.prepare() instead of MediaPlayer.prepareAsync() deliberately, because I want to be able to know when the statement is finished so that I can, for example, hide a progress bar.
I realize that I could do this with a MediaPlayer.prepareAsync(), but since this would create an ugly overhead in my code, would only be used for this detection and probably wouldn't help in this situation anyway, I don't want to do that.
When I start my activity with the video loading and I try to go back to the previous activity before it finished MediaPlayer.prepare(), it throws an IllegalStateException.
All the steps I take before that are synchronized, so just catching the Exception and ignoring it would be possible here, however, I don't want to have throwing and catching an Exception as expected behavior if I can avoid it.
I've already tried to call MediaPlayer.reset() while MediaPlayer.prepare() is running, but the same thing happens.


Q: What does "get someone all over something" mean? I found it in Crash Course Media Literacy. It is at around 2 minute and 3 second. Here is the context:

This campaign wants you to like their product because you like their spokespeople. Or a public relations firm might start a publicity campaign to get their client all over the media.

A: In this context, it's talking about exposure. They want their client's picture and information to be broadcast by all sorts of media outlets.

A: The colloquial phrase all over means "wherever you look, everywhere, ubiquitous".

There was confetti all over the floor after the party.
Did you hear about the discovery?! It's all over the news.

To get something all over is to cause it to be such.

You've gotten mustard all over your shirt.
We will help you get this picture of your lost dog all over town.


Q: sort the elements in java using priority queue I want to sort the elements using Priority Queue in Java.
Here is my code. What is wrong in it?
import java.io.*;
import java.util.*;

class PQ {
    static class IntCompare implements Comparator<Integer>{
        @Override
        public int compare(Integer arg0, Integer arg1) {
            if(arg0 > arg1)
                return -1;
            else if(arg0 < arg1)
                return 1;
            else
                return 0;
        }
   }

    public static void main (String[] args) {
        int a[] = { 1, 3, 8, 5, 2, 6 };

        Comparator<Integer> c = new IntCompare();
        PriorityQueue<Integer> pq=new PriorityQueue<>(c);

        for(int i = 0; i < a.length; i++)
            pq.add(a[i]);

        System.out.println(pq);
    }
}

my output is:
8, 5, 6, 1, 2, 3

correct output:
8, 6, 5, 3, 2, 1

A: When you call System.out.println(pq), the toString method is called implicitly.
The toString method of PriorityQueue  extends from AbstractCollection, which

Returns a string representation of this collection. The string
  representation consists of a list of the collection's elements in the
  order they are returned by its iterator, enclosed in square brackets
  ("[]").

While the iterator of PriorityQueue is not guaranteed to traverse in particular order:

The Iterator provided in method iterator() is not guaranteed to
  traverse the elements of the priority queue in any particular order.

since the queue is based on heap.
You can poll elements one by one to get ordered elements:
while (pq.size() != 0) {
    System.out.print(pq.poll() + ","); // 8,6,5,3,2,1,
}

A: You should poll() all the elements until the queue is empty and save them somewhere to get them ordered.

A: Try the following, list contains items in sorted order. The priority key by itself not maintain the elements in sorted order, it just keeps the top element as minimum or maximum based on your implementation of the PQ.
public static void main (String[] args) {
        int a[]={1,3,8,5,2,6};
        Comparator<Integer> c = new IntCompare();
        PriorityQueue<Integer> pq=new PriorityQueue<>(c);
        for(int i=0;i<a.length;i++)
            pq.add(a[i]);
        ArrayList<Integer> list  = new ArrayList<>();
        while(!pq.isEmpty()){
            list.add(pq.poll());
        }
        for(Integer i : list)
            System.out.println(i);
}


Q: Case when SQL statement into variable I need to create a variable for a case when statement on sybase sql. I have this error from my sql client

A SELECT statement that assigns a value to a variable must not be
  combined with data-retrieval operations.

What do I need to do to use this variable the right way?
DECLARE @OutputName CHAR(50)
SELECT @OutputName=
(case when (a.M_TRN_TYPE='XSW' or a.M_TRN_TYPE='SWLEG') then 'FXSW'
      when (a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS='C') then 'DCS'
      when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)='+1' then
                                                                                (case when b.M_DTE_SKIP_1>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end)
      when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)<>'+1' then
                                                                                (case when b.M_DTE_SKIP_2>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end)
end),
case when @OutputName='XSW' and
                (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST
                      then 0
                 else a.M_NB
                 end as 'NBI'
from TP_COMPL_PL_REP b
join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA)
left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA)

A: The problem is that you can't combine a SELECT which sets a variable with a SELECT which returns data on the screen.
You set @OutputName to (case when (a.M_TRN_TYPE='XSW' .. ) but in the same SELECT you're also trying to display the results of:
case
    when @OutputName='XSW' and
         (case
              when c.M_DATESKIP='+1OD'
                  then b.M_DTE_SKIP_1
              else b.M_DTE_SKIP_2
          end)=a.M_TP_DTEFST
              then 0
    else a.M_NB
end as 'NBI'

You can't have these two in the same SELECT, in the format you're using. My recommendation is to split them, one for assigning the variable:
DECLARE @OutputName CHAR(50)
SELECT @OutputName=
(case when (a.M_TRN_TYPE='XSW' or a.M_TRN_TYPE='SWLEG') then 'FXSW'
      when (a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS='C') then 'DCS'
      when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)='+1' then
                                                                                (case when b.M_DTE_SKIP_1>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end)
      when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)<>'+1' then
                                                                                (case when b.M_DTE_SKIP_2>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end)
end)
from TP_COMPL_PL_REP b
join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA)
left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA)

and one for returning the data:
SELECT case when @OutputName='XSW' and
                (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST
                      then 0
                 else a.M_NB
                 end as 'NBI'
from TP_COMPL_PL_REP b
join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA)
left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA)


Q: Read JSON Object in PHP send with Android I´m currently having problems with exchanging JSON Objects between my Android Appliction and my Server Backend. For whatever reason
$json = file_get_contents('php://input');

doesn´t work. $json always is null.
The App sends the JSON Object with:
        url = new URL("www.example.com/app/request.php");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);
        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        OutputStreamWriter wr = new OutputStreamWriter(out);
        wr.write(request.toString());
        Log.i(TAG, "OUT: " + request.toString());
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuilder stringbuilder = new StringBuilder();
        while ((line = br.readLine()) != null){
            stringbuilder.append(line);
            Log.i(TAG, "Stringline: " + line);

        }
        in.close();
        Log.i(TAG, "Server responds: " + stringbuilder.toString());

The php-Script simply runs:
        <?php
        echo file_get_contents('php://input');
        ?>

So it simply returns the JSONObject back to the sender. Anyway the Logs says:
      OUT: {"firstname":"Foo"}
      Server responds:

then breaks down on JSONObjection cause of course null can´t be parsed to JSONOBject. Appache error_log doesn´t display a error, otherwise the Android Log would also crash into a FileNotFoundException. access_ssllog logs POST on correct file by correct device.
What did I do wrong? I rembember that php://input doesn´t work under some Server Conditions... What would be the alternatives?
Any help is appreciated


Q: Trying to import/convert a CRA app into Razzle JS I'm new to Razzle and I'm trying to learn it.  I took a Material-UI dashboard app and am trying to "import" or "convert" it into my blank-ish razzle app.
I copied the contents of the CRA app's ./src into my razzle source at the right spot, referenced the right components, etc.
At first, Razzle didn't like the @import statements in the CRA repo.  I fixed that by using npm to install razzle-plugin-scss, which got me past that issue.  But now I'm hitting something I don't understand at all (nor even how to go about finding a resolution):
{ Error: Cannot find module 'css-loader/locals'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
    at Function.resolve (internal/modules/cjs/helpers.js:19:19)
    at module.exports (/home/user/my-project/node_modules/razzle-plugin-scss/index.js:106:31)
    at runPlugin (/home/user/my-project/node_modules/razzle/config/runPlugin.js:26:10)
    at plugins.forEach.plugin (/home/user/my-project/node_modules/razzle/config/createConfig.js:549:16)
    at Array.forEach (<anonymous>)
    at module.exports (/home/user/my-project/node_modules/razzle/config/createConfig.js:548:13)
    at main (/home/user/my-project/node_modules/razzle/scripts/start.js:48:22)
    at processTicksAndRejections (internal/process/next_tick.js:81:5) code: 'MODULE_NOT_FOUND' }

I looked in css-loader and found that you (maybe?) need to instruct it to export locals with the exportOnlyLocals: true webpack directive.  I'm not sure how to do that in Razzle.  I found this page that shows an example of how to configure it through razzle.config.js, but it assumes more knowledge than I have.
How can I configure webpack in Razzle to ... do something? ... to tell the underlying webpack plugin css-loader to load locals?
Any help is much appreciated.
Update
It looks like this is caused by a breaking change in css-loader when it moved to v2.0.0.  I still don't know what the solution is, but that's getting me closer.

A: I ended up reverting to css-loader version 1.0.1 to fix the problem.


Q: Redirect HTTP to HTTPS in Spring Security or Tomcat Currently my Spring application only accepts request on HTTPS protocol. Below is a portion of the security-context.xml
<http auto-config="false" use-expressions="true"
        disable-url-rewriting="true">
        <intercept-url pattern="/signup*" access="permitAll"
            requires-channel="https" />
        <intercept-url pattern="/login*" access="permitAll"
            requires-channel="https" />
        <intercept-url pattern="/logout" access="permitAll"
            requires-channel="https" />
        <form-login authentication-success-handler-ref="myAuthenticationSuccessHandler"
            login-page="/login" authentication-failure-url="/loginFailed" />
        <intercept-url pattern="/**" access="isFullyAuthenticated()"
            requires-channel="https" />
        <session-management
            session-authentication-error-url="/loginFailed">
            <concurrency-control error-if-maximum-exceeded="true"
                max-sessions="2" />
        </session-management>
        <logout invalidate-session="true" delete-cookies="JSESSIONID" />
    </http>

Now, I also would like the application to be able to redirect HTTP GET request to HTTPS when user visit the domain e.g from http://mydomain.com to https://mydomain.com. How can I achieve that ? Should I apply the changes in the security-context.xml, the controller or perhaps Tomcat itself ?

A: I configured the redirection from HTTP(port 80) to HTTPS(port 443) within server.xml as
<Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>


Q: Regarding the using expressjs on Apache web server Can i use server side scripting language i.e  expressjs on Apache web server for  web site development ..??
Plz suggest tutorial for that any help about that is valuable to me...

A: Read about node.js and expressjs.
Node.js is server and Expressjs - web framework under Node.js.
Apache is also web server and you don't need to use them together.
You can place Node.js app behind Nginx or HAproxy if you want.

A: You can use a Node.js app (built with Express or whatever you like) standalone, you don't need to use something in front of it.
If you want to use something in front of it though, I suggest you use something like Nginx better than Apache, since Nginx is also asynchronous (like Node) and it's performs really well at serving static files.

A: All you have to do is set node.js as proxy pass inside your site config
here is text on it http://httpd.apache.org/docs/2.0/mod/mod_proxy.html
Just decided which port to use and which framework :) eg. http://www.expressjs.com