text:
Q: Linux symlink does not working after reboot I have created on our Debian squeeze my own daemon from skeleton where is my application starting (+I add there some logging to my log file). I have put this file to /etc/init.d/
cp /home/ja /etc/init.d/ucloud-test -f
chown root /etc/init.d/ucloud-test
chmod 775 /etc/init.d/ucloud-test

After that I created symlinks to this daemon:
ln -sf ../init.d/ucloud-test /etc/rc0.d/K02ucloud-test
ln -sf ../init.d/ucloud-test /etc/rc1.d/K02ucloud-test
ln -sf ../init.d/ucloud-test /etc/rc6.d/K02ucloud-test
ln -sf ../init.d/ucloud-test /etc/rc2.d/S17ucloud-test
ln -sf ../init.d/ucloud-test /etc/rc3.d/S17ucloud-test
ln -sf ../init.d/ucloud-test /etc/rc4.d/S17ucloud-test
ln -sf ../init.d/ucloud-test /etc/rc5.d/S17ucloud-test

It created this symlinks:
root@id135728-2:/home/ja# cd /etc
root@id135728-2:/etc# ls -l  rc* | grep ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 K02ucloud-test -> ../init.d/ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 K02ucloud-test -> ../init.d/ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 S17ucloud-test -> ../init.d/ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 S17ucloud-test -> ../init.d/ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 S17ucloud-test -> ../init.d/ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 S17ucloud-test -> ../init.d/ucloud-test
lrwxrwxrwx 1 root root  21 Aug  7 13:15 K02ucloud-test -> ../init.d/ucloud-test

If I try to read some of those symlinks it shows code from my daemon (it should be right).
root@id135728-2:/etc# cat rc0.d/K02ucloud-test

After reboot looks like that my daemon is not executed (application is not working and there is nothing in my log file). But if I execute that daemon myself application is working and there logging in my log.
/etc/init.d/ucloud-test start

Does anyone know where can be a issue?
Thanks, Roman

A: It's difficult to say what might be going on without further debugging (which would mean extensive logging from the script itself to figure out what's not as you expect it to be), but a really good place to start with this kind of issue on Squeeze is the documentation on init script comment conventions that help manage dependencies. Because, 99% of the time, if your init script 'just works' after boot, it's a dependency issue.
What are you using for logging, does it require starting? How about networking? Maybe it needs to connect to a database? Your boot script should definitely be running later, then.
Instead of making the links manually, try adding this near the top of your init script:
### BEGIN INIT INFO
# Provides:       ucloud-test
# Required-Start: $all
# Required-Stop:
# Default-Start:  2 3 4 5
# Default-Stop:
# Description:    Test script that needs to run after boot
### END INIT INFO

Then, run insserv ucloud (note, I eliminated runlevels 1 and 6)
Now, if it turns out all you need is networking to come up (this includes loopback devices and bridges!!!) (which I suspect is the case), then you could change $all to $network, but that can be tricky with advanced networking setups. If that's the case, you should probably check into more granular boot hooks (systemd / systemctl).
The other thing to do is make /etc/ucloud-test/ucloud-defaults and include it in your script after the init info instead of relying on other things to put them in the environment, but I strongly suspect that you just need to wait until later in the boot process to start.
Anyway, that should give you a base on which to figure it out. Key takeaway is, don't manually create init links unless you have a very specific reason for doing so that entails not wanting some speicific behavior that the system utilities to manage this would bring.


text:
Q: Event not triggered i have used a aspx page with vb code. the page is not firing any event after some time if the page is kept idle.
any property needs to set in page attribute??
any iis settings i should update
How to solve the issue

A: Based on just what you posted I would guess your session is timing out.  I'm pretty sure that will break viewstate/postback functionality.
Please post your web.config <system.web><sessionState> configuration section, both for development and production.
Also you implied everything works fine if you postback right away, but if you load a page, wait X minutes, then postback, you get no postback event firing.  We need to know what X is and if it is a consistent number of minutes.
Edit: If this is in fact a session timeout issue, the default session timeout is 20 minutes.  Does this seem to line up with your problem?

redpajama_set_name: RedPajamaStackExchange


text:
Q: SObject row does not allow errors: error updating record i'm getting an error from updating or saving a record on the following trigger:
trigger ActiveSave on CreditInfo_Eval_Rules__c (before insert, before update) {

    for(CreditInfo_Eval_Rules__c credRules : [SELECT Active__c FROM CreditInfo_Eval_Rules__c
                                              WHERE CreditInfo_Fields__r.Used__c = false
                                              AND Id IN :Trigger.new]){
        if(credRules.Active__c == true){
            credRules.addError('The CreditInfo Field is not beeing used!');
        }
    }
}

A:
You can you use the addError method for only those records that are
  available in Trigger Context.

trigger ActiveSave on CreditInfo_Eval_Rules__c (before insert, before update) {

    for(CreditInfo_Eval_Rules__c credRules : [SELECT Active__c FROM CreditInfo_Eval_Rules__c
                                              WHERE CreditInfo_Fields__r.Used__c = false
                                              AND Id IN :Trigger.new]){
        if(credRules.Active__c == true){
            trigger.newmap.get(credRules.id).addError('The CreditInfo Field is not beeing used!');
        }
    }
}

You need to change just one line i.e instead of credRules.addError use
 trigger.newmap.get(credRules.id).addError.

Triggers can be used to prevent DML operations from occurring by
  calling the addError() method on a record or field. When used on
  Trigger.new records in insert and update triggers, and on Trigger.old
  records in delete triggers, the custom error message is displayed in
  the application interface and logged.

reference:-

*

*https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm#apex_System_SObject_addError

*https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_exceptions.htm


text:
Q: How to declare a nested variable of html tag? How to make below nested html tag variable work? Now alist is showing properly, but b_var is showing as [object object] on the web page.
var b_var = $(`

Division
<select class="form-control selector-division">
</select>

`);

var alist = $(`

            and

`+b_var+ `

`);

By the way, there are some other functions using b_var like below:
populate_divisions(b_var.find(".selector-division"), all_divisions_txn);

A: You're seeing [object object] because you are trying to concatinate a jQuery object on to a string, which results in appending the string representation of the object which in this case is [object object].
You would probably be better of by appending HTML on to the DOM by either using jQuery's append() method, or appendChild() from JavaScript's standard library.
You can find documentation on both here:
https://www.w3schools.com/jquery/html_append.asp
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
https://www.w3schools.com/jsref/met_node_appendchild.asp


text:
Q: Apache2 PHP-FPM configuring pools I'm trying to set pools in order to run PHP scripts as different users, but it doesn't work.
Here's step by step what I did (on Ubuntu 16.04):
sudo apt-get install apache2 libapache2-mod-fastcgi php7.0-fpm php7.0

a2enmod actions fastcgi alias

sudo service apache2 restart

vi /etc/apache2/sites-available/000-default.conf

ServerAdmin webmaster@localhost
DocumentRoot /var/www

<IfModule mod_fastcgi.c>
  AddHandler php7-fcgi .php
  Action php7-fcgi /php7-fcgi virtual
  Alias /php7-fcgi /usr/lib/cgi-bin/php7-fcgi
  FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /var/run/php/php7.0-fpm.sock -pass-header Authorization
  <Directory /usr/lib/cgi-bin>
    Require all granted
   </Directory>
</IfModule>

Then I created a user called "web"
sudo adduser web

and set up his home directory in /var/www/web
Create and configure the pool file for the new user:
sudo cp /etc/php/7.0/fpm/pool.d/www.conf /etc/php/7.0/fpm/pool.d/web.conf

[web]
 ...
 user = web
 group = web
 ...
 listen = /run/php/php7.0-fpm.web.sock
 ...
 listen.owner = web
 listen.group = web

sudo service php7.0-fpm reload

vi /etc/apache2/sites-available/web.conf

ServerAdmin webmaster@localhost
DocumentRoot /var/www/web

<IfModule mod_fastcgi.c>
  AddHandler php7-fcgi-web .php
  Action php7-fcgi-web /php7-fcgi-web virtual
  Alias /php7-fcgi-web /usr/lib/cgi-bin/php7-fcgi-web
  FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi-web -socket /var/run/php/php7.0-fpm.web.sock -pass-header Authorization
  <Directory /usr/lib/cgi-bin>
    Require all granted
  </Directory>
</IfModule>

sudo a2ensite web.conf
sudo service apache2 reload

Now to ensure php scripts run as the proper user I put the following script in /var/www and var/www/web
<?php
  $processUser = posix_getpwuid( posix_geteuid() );
  var_dump($processUser);
?>

when I run /var/www/user.php it displays "www-data" which is correct.
But when I run /var/www/web/user.php it still displays "www-data" whereas it should display "web"
So what's wrong with my Apache config ?


text:
Q: How to load XML file data into a UITableView? I am retrieving an XML document from a server and would like to display it in a UITableView in my application. I have the following code so far:
@implementation textxmlViewController

@synthesize tableviews;

-(void)viewDidLoad{
    [super viewDidLoad];

    NSURL *url = [[NSURL alloc] initWithString:@"http://theserver.com/demo.xml"];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [xmlParser setDelegate:self];
    BOOL success = [xmlParser parse];

    if(success)
        NSLog(@"success");
    else
        NSLog(@"Error");
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSLog(string);
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if (qName) {
        elementName = qName;
    }
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
        attributes:(NSDictionary *)attributeDict {
    if (qName) {
        elementName = qName;
    }
    if ([elementName isEqualToString:@"text"]) {
    }
}

I already have a UITableView in this view, my question is how can I display the XML's content in the table view?
My XML data looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Answers>
    <Answer>
        <Result>it's good</Result>
        <Evaluate>can you tell me why?</Evaluate>
    </Answer>
    <Answer>
        <Result>about 5 hours</Result>
        <Evaluate>it's too long</Evaluate>
    </Answer>
</Answers>

So how can I do it? Thanks

A: It depends on how you want the info to be displayed. At least you should implement cellForRowAtIndexPath: to return the UITableViewCell to be displayed.
According to your XML structure, you can have cells for answers, each having two UITextFields to display the result and evaluate.
Please take a look at http://adeem.me/blog/2009/05/19/iphone-programming-tutorial-part-1-uitableview-using-nsarray/ for a tutorial.

A: I would recommend to use another XML parser instead of using NSXMLParser.
Ray Wenderlich wrote a good article about the different XML parsing possibilities on the iPhone(iOS): http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project
I think it'd be easier for you using a DOM based XML parser. you could use the indexPath to get the data right out of the parsed xmlData.
For example: if your using GDataXML you just need to call the method
+ (GDataXMLElement *)elementsWithName:(NSString *)name;

with name = 'Answers' which returns the Node for all the answer.
on this GDataXMLElement call the method
 - (NSArray *)elementsForName:(NSString *)name;

with name = 'Answer' which gives you all the answers as a NSArray.
You can use this array as datasource for you UITableView by returning numberOfRowsInSection with [answersArray count]. And in the cellForIndexPath method get the GDataXMLElement for the answer by calling
GDataXMLElement  * answerElement = [answersArray objectAtIndex: indexPath.row];

Just parse the answerElement for the elements 'name' and 'value' to show the data in your UITableView.


text:
Q: I receive "Error: React.Children.only expected to receive a single React element child." with TouchableWithoutFeedback I receive the following error:
Error: React.Children.only expected to receive a single React element child.

When I use the 'TouchableWithoutFeedback' component with ReactNative:
 return (
    <TouchableWithoutFeedback onPress={() => {
      Keyboard.dismiss();}}>
      <View style={styles.container}>
        <Header />
        <Exercises exercises={exercises} handleChange={handleChange} handlePress={handlePress} exercise={exercise}/>
      </View>
`    </TouchableWithoutFeedback>
  );

I am not sure why because everything is wrapper in a View component. Any advice?

A: Try wrapping the content of View with a react fragment:
 return (
    <TouchableWithoutFeedback onPress={() => {
      Keyboard.dismiss();}}>
      <View style={styles.container}>
       <>
        <Header />
        <Exercises exercises={exercises} handleChange={handleChange} handlePress={handlePress} exercise={exercise}/>
       </>
      </View>
`    </TouchableWithoutFeedback>
  );


text:
Q: yaml configuration for Istio and gRPC I am working on a POC for  Istio + gRPC, the Istio version is 1.6, but I could not see any gRPC traffic to my pods.
I suspect my Istio Gateway or VirtualService miss something, but I could not figure out what's wrong here? Could anybody help review my yaml file and correct me what's missing or wrong in my yaml?
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: syslogserver
  name: syslogserver
  namespace: mynamespace
spec:
  selector:
    matchLabels:
      app: syslogserver
  replicas: 1
  template:
    metadata:
      labels:
        app: syslogserver
    spec:
      containers:
        - name: syslogserver
          image: docker.io/grpc-syslog:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 5555
      imagePullSecrets:
        - name: pull-image-credential
---
apiVersion: v1
kind: Service
metadata:
  name: syslogserver
  namespace: mynamespace
  labels:
    app: syslogserver
spec:
  selector:
    app: syslogserver
  ports:
  - name: grpc
    port: 6666
    protocol: TCP
    targetPort: 5555
---
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: xyz-ingress-gateway
  namespace: istio-system
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 7777
        name: http2
        protocol: HTTP2
      hosts:
        - "*"
---
apiVersion: v1
kind: Service
metadata:
  name: xyz-istio-ingressgateway
  namespace: istio-system
  labels:
    app: xyz-istio-ingressgateway
spec:
  selector:
    app: istio-ingressgateway
    istio: ingressgateway
  type: NodePort
  ports:
    - protocol: TCP
      nodePort: 32555
      port: 7777
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: xyz-ingress-gateway-virtualservice
  namespace: istio-system
spec:
  hosts:
    - "*"
  gateways:
    - xyz-ingress-gateway
  #tls:
  http:
    - match:
        - port: 7777
      route:
        - destination:
            host: syslogserver.mynamespace.svc.cluster.local
            port:
              number: 6666
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: xyz-destinationrule
  namespace: istio-system
spec:
  host: syslogserver.mynamespace.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      simple: ROUND_ROBIN

Please give your guidance, thanks.

A: From what I see the service name: xyz-istio-ingressgateway should be deleted, as that's not how you communicate when using Istio.

Instead you should use istio ingress gateway, combined with a gateway, virtual service and destination rule.

If you've choosen port number 7777 on your gateway, you have to open this port on istio ingress gateway, there are few ways to do that in this stackoverflow question. There are the default istio ingress gateway values.

After you configure the port you can use kubectl get svc istio-ingressgateway -n istio-system to get the istio ingress gateway external IP.
If the external IP value is set, your environment has an external load balancer that you can use for the ingress gateway. If the EXTERNAL-IP value is pending, then your environment does not provide an external load balancer for the ingress gateway. In this case, you can access the gateway using the service's node port.

The rest of your configuration looks fine for me. Just a reminder about injecting  a sidecar proxy to your pods.


text:
Q: Need Windows Phone Games scraping API I am building a database of windows phone games. I want to scrape that data. But I couldn't find any libraries or apis or documentation for this.
Please don't duplicate this question with this: windows store api to access metro and phone apps information
Because that answer is related to windows PC apps only, not windows phone apps.

A: This is how you could get the most popular games:
The Download and Parse part:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;

namespace TestAPI
{
    public class WindowsPhoneGamesScraper
    {
        static string[] categories = new string[]
        {
            "action-adventure/actionandadventure",
            "card-board/cardandboard",
            "classics/classics",
            "educational/educational",
            "family/family",
            "music/music",
            "platformer/platformer",
            "puzzle-trivia/puzzleandtrivia",
            "racing-flying/racingandflying",
            "role-playing/roleplaying",
            "shooter/shooter",
            "sports-recreation/sportsandrecreation",
            "strategy-simulation/strategy",
            "xbox-companion/xboxcompanion"
        };
        static string[] types = new string[] { "xbox-games", "top-free-games", "new-games", "top-paid-games", "top-rated-games" };

        public static async Task<List<WindowsPhoneAppInfo>> GetWindowsPhoneApps(string store, Action<string> updateStatus)
        {
            return await GetWindowsPhoneApps(store, categories.ToList(), types.ToList(), updateStatus);
        }
        public async static Task<List<WindowsPhoneAppInfo>> GetWindowsPhoneApps(List<string> categories, List<string> app_types, Action<string> updateStatus)
        {
            return await GetWindowsPhoneApps("en-US", categories, app_types, updateStatus);
        }

        public async static Task<List<WindowsPhoneAppInfo>> GetWindowsPhoneApps(string store, List<string> categories, List<string> app_types, Action<string> updateStatus)
        {
            List<WindowsPhoneAppInfo> data = new List<WindowsPhoneAppInfo>();
            foreach (string category in categories)
            {
                foreach (string type in app_types)
                {
                    updateStatus(string.Format("Downloading Category {0} and Type{1} Total:{2}", category, type, data.Count));
                    data.AddRange(await ScrapeAppsFromUrl("http://www.windowsphone.com/" + store + "/store/" + type + "/" + category, true));
                }
            }
            return data;
        }

        public async static Task<List<WindowsPhoneAppInfo>> GetNewWindowsPhoneGames(string store, string category = "")
        {
            List<WindowsPhoneAppInfo> data = new List<WindowsPhoneAppInfo>();
            data.AddRange(await ScrapeAppsFromUrl("http://www.windowsphone.com/" + store + "/store/new-games/" + category, false));
            return data;
        }
        public async static Task<List<WindowsPhoneAppInfo>> GetFeaturedWindowsPhoneGames(string store)
        {
            List<WindowsPhoneAppInfo> data = new List<WindowsPhoneAppInfo>();
            data.AddRange(await ScrapeAppsFromUrl("http://www.windowsphone.com/" + store + "/store/featured-games", false));
            return data;
        }

        private async static Task<List<WindowsPhoneAppInfo>> ScrapeAppsFromUrl(string p, bool handlePaging)
        {
            List<WindowsPhoneAppInfo> data = new List<WindowsPhoneAppInfo>();
            string res = "";
            WebClient client = new WebClient();
            try
            {
                TaskCompletionSource<string> tcsDownloadedText = new TaskCompletionSource<string>();
                client.DownloadStringCompleted += (sen, ev) =>
                {
                    if (ev.Error != null)
                        tcsDownloadedText.TrySetResult("");
                    else
                        tcsDownloadedText.TrySetResult(ev.Result);
                };
                client.DownloadStringAsync(new Uri(p, UriKind.Absolute));
                res = await tcsDownloadedText.Task;
                if (string.IsNullOrEmpty(res))
                    return data;
            }
            catch (Exception x) { }
            try
            {
                var list = res.Split(new[] { "" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string item in list.Skip(1).ToList().Take(list.Length - 2))
                {
                    try
                    {
                        var xelem = XElement.Parse("" + item.Replace("
", "").Replace("
", ""));
                        WindowsPhoneAppInfo wpai = new WindowsPhoneAppInfo(xelem);
                        data.Add(wpai);
                    }
                    catch (Exception e)
                    {
                        //Log the errors if you need
                    }
                }
                if (res.Contains(@"id=""nextLink""") && handlePaging)
                {
                    var lista = res.Split(new string[] { "id=\"nextLink\"" }, StringSplitOptions.RemoveEmptyEntries);
                    string url = "http://www.windowsphone.com" +
                                 (lista[1].Split(new string[] { "\"" }, StringSplitOptions.RemoveEmptyEntries)[1]);
                    List<WindowsPhoneAppInfo> apps = await ScrapeAppsFromUrl(url, handlePaging);
                    data.AddRange(apps);
                }

            }
            catch (Exception e)
            {
                //Log the errors if you want
            }
            return data;
        }
    }

    public class WindowsPhoneAppInfo
    {
        public WindowsPhoneAppInfo(XElement xelem)
        {
            var elements = xelem.Elements("a").ToList();
            Title = elements[1].Value;
            var xAttribute = elements[1].Attribute("href");
            if (xAttribute != null)
            {
                Url = xAttribute.Value;
                AppID = Url.Split(new[] { '/' }).Last();
            }

            var imageLogo = xelem.Descendants("img").FirstOrDefault();
            if (imageLogo != null)
            {
                var logoURLAttribute = imageLogo.Attribute("src");
                if (logoURLAttribute != null)
                    LogoURL = logoURLAttribute.Value;
            }
            if (xelem.Descendants("div")
                    .ToList()
                    .Any(
                        elem => elem.Attributes("class").ToList().Any(att => att.Value.Contains("ratingSmall"))))
                Rating =
                    xelem.Descendants("div")
                        .ToList()
                        .First(
                            elem => elem.Attributes("class").ToList().Any(att => att.Value.Contains("ratingSmall")))
                        .Attributes("class")
                        .First()
                        .Value.Split(new[] { ' ' })
                        .Last();
            Price = xelem.Descendants("div").Last().Value;
        }
        public string AppID { get; set; }
        public string Title { get; set; }

        public string Url { get; set; }

        public string LogoURL { get; set; }
        private ImageSource _logo;
        public ImageSource Logo
        {
            get
            {
                if (_logo == null)
                    _logo = new BitmapImage(new Uri(LogoURL, UriKind.Absolute));
                return _logo;
            }
        }

        public string Rating { get; set; }

        public string Price { get; set; }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((WindowsPhoneAppInfo)obj);
        }
        protected bool Equals(WindowsPhoneAppInfo other)
        {
            return string.Equals(AppID, other.AppID);
        }

        public override int GetHashCode()
        {
            return (AppID != null ? AppID.GetHashCode() : 0);
        }
    }
}

The sample:
List<WindowsPhoneAppInfo> data = await WindowsPhoneGamesScraper.GetFeaturedWindowsPhoneGames("en-US");//, categories.ToList(), types.ToList());
data.AddRange(await WindowsPhoneGamesScraper.GetWindowsPhoneApps("en-US", UpdateAction));
data = data.Distinct().ToList();
lboGames.ItemsSource = data;

You can call the same action with all the supported cultures.


text:
Q: LaTeX is not able to process the string in python Trying to graph a weibull distribution in python3 using the code available at (http://www.astroml.org/book_figures/chapter3/fig_weibull_distribution.html)
# Author: Jake VanderPlas
# License: BSD
#   The figure produced by this code is published in the textbook
#   "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
#   For more information, see http://astroML.github.com
#   To report a bug or issue, use the following forum:
#    https://groups.google.com/forum/#!forum/astroml-general
import numpy as np
from scipy.stats import dweibull
from matplotlib import pyplot as plt

#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX.  This may
# result in an error if LaTeX is not installed on your system.  In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)

#------------------------------------------------------------
# Define the distribution parameters to be plotted
k_values = [0.5, 1, 2, 2]
lam_values = [1, 1, 1, 2]
linestyles = ['-', '--', ':', '-.', '--']
mu = 0
x = np.linspace(-10, 10, 1000)

#------------------------------------------------------------
# plot the distributions
fig, ax = plt.subplots(figsize=(5, 3.75))

for (k, lam, ls) in zip(k_values, lam_values, linestyles):
    dist = dweibull(k, mu, lam)
    plt.plot(x, dist.pdf(x), ls=ls, c='black',
             label=r'$k=%.1f,\ \lambda=%i$' % (k, lam))

plt.xlim(0, 5)
plt.ylim(0, 0.6)

plt.xlabel('$x$')
plt.ylabel(r'$p(x|k,\lambda)$')
plt.title('Weibull Distribution')

plt.legend()
plt.show()

I keet getting the following error:
RuntimeError: LaTeX was not able to process the following string:
b'lp'
Here is the full report generated by LaTeX:

<matplotlib.figure.Figure at 0x22c11c7a2e8>

I cant figure out where is "b'lp'".


text:
Q: Erro popular dropdown PHP com array Olá,
Tenho a seguinte função que me retorna os dados necessários para popular o meu dropdown:
    function listaRedes($conexao){
    $dados = array();

    $resultado = mysqli_query($conexao, "SELECT DISTINCT rede FROM evolucao_originacao");
    while($valores = mysqli_fetch_array($resultado)){
        array_push($dados, $valores);
    }
    return $dados;
};

E no meu dropdown, estou fazendo o seguinte código:
 <?php $redesBanco = listaRedes($conexão); ?>

            <select class="form-control" id="dropdown-parceria">
                <option value="0">---SELECIONE---</option>
                <?php
                    while($redesBanco){
                        echo "<option value='".$redesBanco."'>".$redesBanco."</option>";
                    }
                ?>
            </select>

Porém na hora que ele popula o meu dropdown, o resultado é o seguinte:

A: use foreach para percorrer o array:
<?php $redesBanco = listaRedes($conexão); ?>

                <select class="form-control" id="dropdown-parceria">
                    <option value="0">---SELECIONE---</option>
                    <?php
                        foreach ($redesBanco as $chave){
                            echo "<option value='".$chave[0]."'>".$chave[1]."</option>";
                        }
                    ?>
                </select>

A: Tente colocar $redesBanco[0]. Pois você esta tentando dar um echo em um array, é recomendado você dar uma var_dump para ver a estrutura para escrever por exemplo, <?php echo "".$redesBanco['acesse'].""; ?>
Mas tambem pode ser feito da primeira maneira, informando o indice com o numero $redesBanco[0].
No caso do seu exemplo deveria ser feito de uma forma tipo essa...:
<?php $redesBanco = listaRedes($conexão); ?>

        <select class="form-control" id="dropdown-parceria">
            <option value="0">---SELECIONE---</option>
            <?php
                while($redesBanco){
                    echo "<option value='".$redesBanco[0]."'>".$redesBanco[1]."</option>";
                }
            ?>
        </select>

Espero ter ajudado de alguma forma


text:
Q: How to prove $2x+1$ is the unit of $\mathbb{Z}_8[x]$? Same as what I stated in the title.
What are the general steps to find or prove a polynomial is the unit of a ring of polynomials.
Def for the ring of polynomials $R[x] = \{ a_0 + a_1x + ... + a_n x^n | a_0,..,a_n \in R,  n \in \mathbb{Z}_{\geq 0}\}$.

A: If an element $a$ of a ring is nilpotent $a^n=0$, then $1+a$ is always invertible. Such elements $1+a$ with $a$ nilpotent are called unipotents. Observe that
$$(1+a)(1-a+a^2-a^3+a^4-\dots)=1$$
Now, the second factor on the left is actually a finite sum, since $a^n=0$ and so $a^{n+1}=a^{n+2}=\dots=0$.
In your ring, $2x$ is nilpotent since $2$ already is: $2^3=8=0$ in $\mathbb Z_8$, and so $(2x)^3=0$.

A: In a ring $R$, an element $u \in R$ is a unit if there exists a $v \in R$ such that $uv=1$ where $1$ is the multiplicative identity in $R$.
You're working in $R=\mathbb{Z}_8[x]$. So what you're looking for is a polynomial $u(x) \in \mathbb{Z}_8[x]$ such that $(2x+1)u(x)=1$.


text:
Q: How can I automatically save images in different folder with CK Finder 3 I am having difficulty getting this newer version of CKFinder (CKFinder 3) to work like how the old version did. The system used to automatically detect image files and store them in an "images" subfolder and for all other files, in a "files" subfolder.
It now seems the images subfolder only gets files to saved to it when you navigate to the folder in the "browse server" popup window and add files after clicking on the images folder. Uploading and clicking "Send to server" also sends all files to the "files" subfolder regardless of filetype.
The major problem with this is it ignores the file-size rules that are set-up for images, unless you navigate to the images folder, and then it will enforce it. It also is much less convenient as the user will not likely navigate to the subfolder each time.
Currently I have setup the config.php for CKFinder 3 like so:
$config['backends'][] = array(
    'name'         => 'default',
    'adapter'      => 'local',
    'baseUrl'      => $baseDir, // "/mywebsite/sites/default/uploads/"
    //'root'         => '', // Can be used to explicitly set the CKFinder user files directory.
    'chmodFiles'   => 0777,
    'chmodFolders' => 0755,
    'filesystemEncoding' => 'UTF-8',
);

/*================================ Resource Types =====================================*/
// https://ckeditor.com/docs/ckfinder/ckfinder3-php/configuration.html#configuration_options_resourceTypes

$config['defaultResourceTypes'] = '';

$config['resourceTypes'][] = array(
    'name'              => 'Files', // Single quotes not allowed.
    'directory'         => '/files/',
    'maxSize'           => '10M',
    'allowedExtensions' => '7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gz,gzip,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip,gif,jpeg,jpg,png,svg',
    'deniedExtensions'  => '',
    'backend'           => 'default',
);

$config['resourceTypes'][] = array(
    'name'              => 'Images',
    'directory'         => '/images/',
    'maxSize'           => '500K',
    'allowedExtensions' => 'bmp,gif,jpeg,jpg,png,svg',
    'deniedExtensions'  => '',
    'backend'           => 'default',
);

Any help is appreciated, thank you!!

A:
The system used to automatically detect image files and store them in an "images" subfolder and for all other files, in a "files" subfolder.

This is not correct, CKFinder never worked like this. Although, you can achieve such behavior using a connector plugin.
Let's say I want all the uploaded images to be placed in Images:/ and other files should go to Files:/.
<?php

// plugins/MyPlugin/MyPlugin.php

namespace CKSource\CKFinder\Plugin\MyPlugin;

use CKSource\CKFinder\CKFinder;
use CKSource\CKFinder\Event\BeforeCommandEvent;
use CKSource\CKFinder\Event\CKFinderEvent;
use CKSource\CKFinder\Image;
use CKSource\CKFinder\Plugin\PluginInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MyPlugin implements PluginInterface, EventSubscriberInterface
{
    public function setContainer(CKFinder $app) {}

    public function getDefaultConfig() {
        return [];
    }

    public static function getSubscribedEvents()
    {
        return [
            CKFinderEvent::BEFORE_COMMAND_FILE_UPLOAD => 'handleBeforeFileUpload',
            CKFinderEvent::BEFORE_COMMAND_QUICK_UPLOAD => 'handleBeforeFileUpload'
        ];
    }

    public function handleBeforeFileUpload(BeforeCommandEvent $event) {
        $request = $event->getRequest();

        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile */
        $uploadedFile = $request->files->get('upload');

        if ($uploadedFile && $uploadedFile->isValid()) {
            $resourceType = 'Files';

            if (Image::isSupportedExtension($uploadedFile->getClientOriginalExtension())) {
                $resourceType = 'Images';
            }

            $request->query->set('type', $resourceType);
            $request->query->set('currentFolder', '/');
        }
    }
}

Save the above plugin code as plugins/MyPlugin/MyPlugin.php and enable it in config.php:
$config['plugins'] = ['MyPlugin'];


text:
Q: Showing a album cover I was wondering how to add a album cover on my spotify-app?
With this code I can reveal the album title, but how can I show the album cover!?
function updatePageWithAlbumName() {

var header = document.getElementById("album");

// This will be null if nothing is playing.
var playerTrackInfo = sp.trackPlayer.getNowPlayingTrack();

if (playerTrackInfo == null) {
    header.innerText = "Geen album!";
} else {
    var track = playerTrackInfo.track;
    header.innerText = track.album.name;
}

}

A: Please don't use any of the sp. APIs - they're private and going away soon.
The public API is documented here: http://developer.spotify.com/download/spotify-apps-api/preview/reference/
You can show an album cover like this:
<img src="[cover URI]">

Edit: To get the cover URI of the current track:
var sp = getSpotifyApi(1);
var models = sp.require('sp://import/scripts/api/models');

var currentTrackCoverUri = models.player.track.album.cover;

A: I would like to point out that the property seems to be called "image" and not "cover".
So the snippet provided by iKenndac would be rewritten as
var sp = getSpotifyApi(1);
var models = sp.require('sp://import/scripts/api/models');
var currentTrackCoverUri = models.player.track.album.image;

Not sure if this is dependant on my Spotify version, I'm running 0.8.10.3.g07d01e81.

A: The UX guidelines requires you to present an album cover with playability when appropriate. This can be done with the solution from another topic: Views.player album cover


text:
Q: Web App Authentication/Security Best Practice with Google Cloud Database (Bigtable) I am developing a webapp to access data in Bigtable in Vue and hosting it on Firebase Hosting and I am using Firebase Authentication to control user access for the app. I am curious as to best practices for authentication and security when it comes to such a use case.
I've read this:
https://cloud.google.com/docs/authentication/end-user
https://cloud.google.com/bigtable/docs/authentication
Here is my question:
I was taught once that the reason we build APIs in front of SQL servers for example was because we didn't want to expose the SQL server directly to the end user and risk bad things happening. So the API sits in between to act as a layer of protection.
In the Bigtable world, Google has provided their client SDKs for Bigtable that interacts with Google APIs but it has also suggested to use service account json files in most use cases. Wouldn't this be dangerous since the service account credentials then allows anybody who somehow finds it in the app files to do read or write to Bigtable and potentially mess up the database?
Should I build an API in front of Bigtable and use Firebase Auth to check if the client is authenticated using JWT before allowing operations? Or is there some other best practice?
Also,
https://cloud.google.com/docs/authentication/end-user
This article suggests that I use OAuth, so can it be linked to Firebase Authentication somehow?
Thank you!


text:
Q: How to automate reply in outlook via Excel VBA? I'm trying my luck to have a program wherein you could reply to selected email in outlook using Excel VBA. Unfortunately, I can't find any working code.
Option Explicit
Sub ReplyMSG()
  Dim olItem As Outlook.MailItem
  Dim olReply As MailItem ' Reply
  Dim olRecip As Recipient ' Add Recipient
  Dim myOlExp As Outlook.Explorer
  Dim myOlSel As Outlook.Selection

  Set myOlExp = Application.ActiveExplorer
  Set myOlSel = myOlExp.Selection

  For Each olItem In myOlSel
  Set olReply = olItem.ReplyAll
  Set olRecip = olReply.Recipients.Add("Email Address Here") ' Recipient Address
    olRecip.Type = olCC
        olReply.HTMLBody = "Hello, Thank you. " & vbCrLf & olReply.HTMLBody
    olReply.Display

    'olReply.Send
  Next olItem
End Sub

I'm trying to use this code but error 438 object doesn't support this property or method keeps on coming out. Hoping to get help with this automation.

A: If you are writing in Excel VBA, then the term Application applies to Excel. Excel Application doesn't have ActiveExplorer property. You should hook back to your Outlook Application which i do not see in the code supplied, like Set myOlExp = refToOutlookApplication.ActiveExplorer
Look at what you have shown above:
Set myOlExp = Application.ActiveExplorer
This means Set myOlExp = Excel.Application.ActiveExplorer, and the thing is that Excel Application has no Explorer Object.
So you need: Set myOlExp = refToOutlookApplication.ActiveExplorer
You need to explicitly state that you wish to assign a variable to the property of the Outlook Application - which at this stage I am going to assume that you have created a reference somewhere else earlie in your module.
If not, then you will need to do so with:
Dim refToOutlookApplication As Object    'Outlook.Application
Set refToOutlookApplication = GetObject(, "Outlook.Application")


text:
Q: D3D9 Application not working w/ Intel HD Graphics I've inherited an application that uses D3D9 to display graphics full screen on monitor #2.  The application works properly on a desktop machine with a GeForce 9500 GT.  When I attempt to get the application running on a laptop equipped with onboard Intel HD Graphics, all of the graphics are not displayed.  One of the vertex buffers is drawn but the rest are black.
I'm not very familiar with D3D, so I'm not sure where to begin debugging this problem.  I've been doing some searching but haven't been able to turn anything up.
Update:
Drawing simple vertex buffers with only 2 triangles works, but anything more complex doesn't.

A: My gut feeling is likely the supported shader models for the given GPU.
Generally it is good practice to query the gfx card to see what it can support.
There is also a chance it could be specific D3D API functionality - you see this more so with switching between say GeForce & ATI(AMD), but of course also possible with Intel being its own vendor; but I would start by querying supported shaders.
For D3D9 you use IDirect3D9::GetDeviceCaps to query the gfx device.
links:
Post here: https://gamedev.stackexchange.com/questions/22705/how-can-i-check-for-shader-model-3-support
http://msdn.microsoft.com/en-us/library/bb509626%28VS.85%29.aspx
DirectX also offer functionality to create features for a given device level:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876%28v=vs.85%29.aspx

A: Solution #1:
Check every error code for every D3D9 call. Use DXGetErrorString9 and DXGetErrorDescription9 to get human-readable translation of error code. See DirectX documentation for more info. When you finally encounter a call that returns something other thant D3D_OK, investigate DirectX documentation for the call.
Solution #2:
Install debug DirectX drivers (should be included with DirectX SDK), examine debug messages process outputs while being run (messages are being printed using OutputDebugMessage, so you'll only see then in debugger/IDE). With high debug settings, you'll see every single problem in your app.


text:
Q: jQuery Ajax post to WCF getting bad request I am attempting to create an auto-complete box... and I can retrieve appropriate JSON using Fiddler, but when implemented in code, I get a connection error.
Code:
<htm>

<input type="text" id="txt_search" name="search">

I cannot provide the URL, but I can connect using Fiddler to test it. I'm thinking it could be a problem with WCF, but how then can I test correctly with Fiddler?

A: I don't know if this is your primary problem here, but by setting the contentType to application/json, you're telling WCF that you're sending it parameters in JSON serialized format, but when you pass a native object to jQuery like that, it's going to URL encode those parameters instead. In other words, you're sending ?FirstPartOfName=Med instead of {"FirstPartOfName":"Med"}. More about that here: http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/
In this simple case, you can fix that by explicitly sending a JSON string instead:
data: '{"FirstPartOfName":"Med"}'

It looks similar, but is completely different over the wire.
Building the JSON string by hand is workable enough in the simplest case, but gets to be cumbersome. You can also use JSON.stringify to automatically build the string from objects instead.


text:
Q: How to sort items in a list by a comma delimited number and remove the number afterwards in Python I have text in a list like this:
something , 3
something else , 1
something this , 2

And this code correctly sorts the list by the number to the right of the comma:
data_list= sorted(data_list, key=lambda line: int(line.rsplit(' ,', 1)[1]))

After the sort, how can I remove the comma delimited numbers, leaving just the part before the comma?
I tried this and it removes the numbers, but the sorting is lost. Somehow this changes the order.
data_list= [sen.split(' ,')[0] for sen in data_list]

A: Rather than sort while in string form and parse afterwards, it would be better to parse first, then sort.
>>> import csv
>>> from operator import itemgetter
>>> text = ['something , 3', 'something else , 1', 'something this , 2']
>>> list(map(itemgetter(0), sorted(csv.reader(text), key=itemgetter(1))))
['something else ', 'something this ', 'something ']

Here are the steps explained:
# First parse the commas into separate fields
csv.reader(text)
 \-->  [['something ', ' 3'], ['something else ', ' 1'], ['something this ', ' 2']]

# Then sort using the second field as the key
sorted(_, key=itemgetter(1))
 \--> [['something else ', ' 1'], ['something this ', ' 2'], ['something ', ' 3']]

# The extract just the field
list(map(itemgetter(0), _))
 \--> ['something else ', 'something this ', 'something ']

As @donkopotamus mentioned, you can replace the key-function with key=lambda x: int(x[1]) to sort numerically rather than alphabetically.

A: This will do
data_list = ['something , 3',
'something else , 1',
'something this , 2']

data_list= [i.split(',')[0] for i in sorted(data_list, key=lambda line: int(line.split(',')[1]))]

results in
['something else ', 'something this ', 'something ']

A: Something like:
[x.strip() for x, y in sorted([x.split(",") for x in data],
                              key=lambda row: int(row[1]))]

Gives:
['something else', 'something this', 'something']

Here we:

*

*split each row, then

*sort the data according to the second item as an integer, then

*take the first items (stripping them for whitespace)


text:
Q: Javascript code does not work when getting the value from button When I press a button I get the value of the 1st button. I want the value of the button that was pressed.
JavaScript
function GetHadess() {
        var title = $(".myButtonn").val();
        alert(title);
}

The value of the button that was pressed should be shown in alert, but here value of the 1st button is shown.
HTML code

<input class="myButtonn" type="submit" name="title1" value=" bbb " onclick="GetHadess()">

<input class="myButtonn" type="submit" name="title1" value=" bb " onclick="GetHadess()">

A: You have to pass this context to the function so that it will know which button clicked,like below:-

function GetHadess(element) {
  var title = $(element).val();
  alert(title);
}

    <input class="myButtonn" type="submit" name="title1" value=" bbb " onclick="GetHadess(this)">

    <input class="myButtonn" type="submit" name="title1" value=" bb " onclick="GetHadess(this)">

A: *

*Use this context to tell which is the click button

$('.myButtonn').click(function() {

  alert($(this).val())
})

      <input class="myButtonn" type="submit" name="title1" value=" bbb " onclick="GetHadess()">

      <input class="myButtonn" type="submit" name="title1" value=" bb " onclick="GetHadess()">

A: Change your code like this:

<input class="myButtonn" type="submit" name="title1" value=" bbb " onclick="GetHadess(this)">

<input class="myButtonn" type="submit" name="title1" value=" bb " onclick="GetHadess(this)">

function GetHadess(this) {
        var title = this.val();
        alert(title);
}

A: Instead of getting value using class, Pass event in the function and access value using event.target.value.

function GetHadess(e) {
        console.log(e.target.value);
        alert(e.target.value);
}

<input class="myButtonn" type="submit" name="title1" value=" bbb " onclick="GetHadess(event)">

<input class="myButtonn" type="submit" name="title1" value=" bb " onclick="GetHadess(event)">


text:
Q: Script detection of mobile devices - please correct my code I have this code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function isMobile() {
   return preg_match("/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i", $_SERVER["HTTP_USER_AGENT"]))
}

</script>
if (isMobile)
    <meta HTTP-EQUIV="REFRESH" content="0; url=http://www.google.com/">
else
    <meta HTTP-EQUIV="REFRESH" content="0; url=http://mail.yahoo.com/">
</head>

<body>

</body>
</html>

Tested with Firefox, it shows the correct site but before redirection the phrase "if (isMobile) else" is shown.
Tested with IE, it shows the wrong site. What am I doing wrong? (I did the tests with my desktop pc.)

A: You closed your script tag, but then kept writing JavaScript. You need to do all of your JS inside the script tag. This should work, but I didn't test it.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">

function isMobile() {
    return /Mozilla/g.test(navigator.userAgent);
}

var meta = document.createElement('meta');
meta['HTTP-EQUIV'] = "REFRESH";

var url = "";
if (isMobile()){
    url = "http://www.google.com/";
}else{
    url = "http://mail.yahoo.com/";
}
meta.content = '0; url=' + url;
document.head.appendChild(meta);
</script>
</head>

A: I did a small change to your code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">

function isMobile() {
    return /Mozilla/g.test(navigator.userAgent);
}

if (isMobile()){
    window.location.href = "http://www.google.com"
}else{
    window.location.href = "http://mail.yahoo.com"
}
</script>
</head>

and both Firefox and IE open google. If I change your function with mine then nothing happens.


text:
Q: SSH VPN - cannot send ICMP packets to confirm if VPN is up I am trying to setup SSH based VPN between 2 devices, following the instructions from the website here in a lab environment.
The 2 devices are Kali Linux 2017.1 (client), and Ubuntu Linux Mint 18.2 (server).
The IP addresses of the devices are:

*

*Kali Linux (client) - 192.168.56.103, VPN endpoint IP: 1.1.1.2

*Linux Mint (server) - 192.168.56.102, VPN endpoint IP: 1.1.1.1.

I have performed the following steps on each device.
On client,
sudo ssh -w 0:0 root@192.168.56.102
ip link set tun0 up
ip addr add 1.1.1.2/32 peer 1.1.1.1 dev tun0

On server,
service ssh start
ip link set tun0 up
ip addr add 1.1.1.1/32 peer 1.1.1.2 dev tun0

The output from client is shown below:
$ ifconfig tun0
tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
    inet 1.1.1.2  netmask 255.255.255.255  destination 1.1.1.1
    inet6 fe80::73bc:5f32:6ba2:9419  prefixlen 64  scopeid 0x20<link>
    unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 500  (UNSPEC)
    RX packets 597  bytes 50040 (48.8 KiB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 602  bytes 50280 (49.1 KiB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

The output from server is shown below:
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
      inet addr:1.1.1.1  P-t-P:1.1.1.2  Mask:255.255.255.255
      inet6 addr: fe80::d0f:d97a:3bc0:c1ad/64 Scope:Link
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:671 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:500
      RX bytes:0 (0.0 B)  TX bytes:56256 (56.2 KB)

While the tunnel IPs are setup, I am unable to communicate icmp pings between the 2 IPs - 1.1.1.1, 1.1.1.2
If I start ping from server to client, I can see that the client is receiving the pings from the server and responding, but the server is not receiving the replies.
So on server, I have started the pings and monitor tcpdump response.
$ ping 1.1.1.2
$ sudo tcpdump -i tun0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
03:07:01.494334 IP 1.1.1.1 > 1.1.1.2: ICMP echo request, id 8371, seq 810, length 64
03:07:02.517661 IP 1.1.1.1 > 1.1.1.2: ICMP echo request, id 8371, seq 811, length 64
03:07:03.541852 IP 1.1.1.1 > 1.1.1.2: ICMP echo request, id 8371, seq 812, length 64

On client, I see the following responses being sent by client in tcpdump, but these are not registered by the server
$ tcpdump -ni tun0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
03:09:48.485679 IP 1.1.1.1 > kali: ICMP echo request, id 8371, seq 1125, length 64
03:09:48.485711 IP kali > 1.1.1.1: ICMP echo reply, id 8371, seq 1125, length 64
03:09:49.510028 IP 1.1.1.1 > kali: ICMP echo request, id 8371, seq 1126, length 64
03:09:49.510052 IP kali > 1.1.1.1: ICMP echo reply, id 8371, seq 1126, length 64

Can anyone spot why I am not able to communicate between the client and server? I am not able to successfully send any network protocol (not just icmp) between the client and server.
I have tried the following already:

*

*On server side, I have made sure that PermitTunnel is enabled and root user is used as per the requirements stated in the documentation.

*I have removed all iptables firewall rules and checked that default policy is ACCEPT.
iptables -t nat -F
iptables -t filter -F
iptables -t mangle -F

*I have disabled and removed ufw for testing by:
sudo ufw disable
sudo apt-get remove ufw

*Tried looking for other instructions here and here, but they didn't give me any clues on what the issue could be.
Here is my sshd_config file from the server.
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
#PermitRootLogin prohibit-password
PermitRootLogin yes
PermitTunnel yes
StrictModes yes
GatewayPorts yes
AllowTcpForwarding yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

UPDATE:
As per feedback from dirkt, I have now used internal IP addresses. 10.1.1.1 instead of 1.1.1.1, 10.1.1.2 instead of 1.1.1.2. However, the issue still persists.
On Client,
tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
    inet 10.1.1.1  netmask 255.255.255.255  destination 10.1.1.2
    inet6 fe80::23ca:f7ce:e4c7:24c8  prefixlen 64  scopeid 0x20<link>
    unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 500  (UNSPEC)
    RX packets 316  bytes 26436 (25.8 KiB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 320  bytes 26628 (26.0 KiB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

On Server,
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
      inet addr:10.1.1.2  P-t-P:10.1.1.1  Mask:255.255.255.255
      inet6 addr: fe80::e633:5f17:9b14:ae06/64 Scope:Link
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:191 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:500
      RX bytes:0 (0.0 B)  TX bytes:15936 (15.9 KB)

Also, here is the routing table from ip route commands:
On Client,
default via 10.0.2.2 dev eth0
10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15
10.1.1.2 dev tun0 proto kernel scope link src 10.1.1.1
192.168.56.0/24 dev eth1 proto kernel scope link src 192.168.56.103
192.168.56.0/24 dev eth1 proto kernel scope link src 192.168.56.103 metric 100

On Server,
default via 10.0.2.2 dev enp0s3  proto static  metric 100
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.15  metric 100
10.1.1.1 dev tun0  proto kernel  scope link  src 10.1.1.2
169.254.0.0/16 dev enp0s3  scope link  metric 1000
172.17.0.0/16 dev docker0  proto kernel  scope link  src 172.17.0.1 linkdown
172.18.0.0/16 dev br-56e99b53b1be  proto kernel  scope link  src 172.18.0.1 linkdown
192.168.56.0/24 dev enp0s8  proto kernel  scope link  src 192.168.56.102  metric 100

UPDATE
On running telnet, it is clear that traffic is being forwarded from Kali Linux (client) to Linux Mint (server), but not the other way around. Even after port 12345 is opened on client, SynAck packets are not being registered by the client at all.
On server, we run following:
telnet 10.1.1.1 12345
Trying 10.1.1.1....

On server, we see syn packets to client
tcpdump -ni tun0
root@linuxmint-VirtualBox /home/linuxmint # tcpdump -ni tun0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
17:47:28.869970 IP 10.1.1.2.49674 > 10.1.1.1.12345: Flags [S], seq 2551141293, win 29200, options [mss 1460,sackOK,TS val 2598500 ecr 0,nop,wscale 7], length 0
17:47:29.874205 IP 10.1.1.2.49674 > 10.1.1.1.12345: Flags [S], seq 2551141293, win 29200, options [mss 1460,sackOK,TS val 2598752 ecr 0,nop,wscale 7], length 0
17:47:31.890376 IP 10.1.1.2.49674 > 10.1.1.1.12345: Flags [S], seq 2551141293, win 29200, options [mss 1460,sackOK,TS val 2599256 ecr 0,nop,wscale 7], length 0

On client, we see the reset responses going back but telnet just sits there.
tcpdump -ni tun0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
17:47:18.918860 IP 10.1.1.2.49676 > 10.1.1.1.12345: Flags [S], seq 3064866770, win 29200, options [mss 1460,sackOK,TS val 2605333 ecr 0,nop,wscale 7], length 0
17:47:18.918899 IP 10.1.1.1.12345 > 10.1.1.2.49676: Flags [R.], seq 0, ack 3064866771, win 0, length 0
17:47:19.921367 IP 10.1.1.2.49676 > 10.1.1.1.12345: Flags [S], seq 3064866770, win 29200, options [mss 1460,sackOK,TS val 2605584 ecr 0,nop,wscale 7], length 0
17:47:19.921412 IP 10.1.1.1.12345 > 10.1.1.2.49676: Flags [R.], seq 0, ack 1, win 0, length 0

A: The netmask you selected (255.255.255.255) leaves no room for hosts. Technically you have the network-address and broadcast-address on the same address (10.1.1.1). my recommendation is, to change the netmask to 255.255.255.252 if you want to add more hosts (as this netmask leaves only room for two hosts) then I recommend you to change to a lower subnetmask look on google for subnet-calculators for further examples.


text:
Q: Cannot grab the value of the user's input with jquery while using DateTimePicker plugin Hey StackOverflow wizards! I'm not quite sure what I'm doing wrong, but maybe you can help me.
I'm building a giant form wizard with lots of user input. The form has multiple tabs and on the first page I have an input where the user chooses a Start Date and an input where a user chooses an End Date. The last tab is a summary of all of the user's chosen inputs.
I'm trying to grab the value of the Start Date and End Date and spit them into a span element on the last tab of the form wizard. I'm using the DateTimePicker plugin here.
Here is my HTML:

    Start Date

    End Date

    Start Date

    End Date

And my JQuery:
var projectStartDate = $('#project-start-date').blur(function() {
  $('#project-start-date').data('DateTimePicker').date();
  console.log(projectStartDate);
});
$('#confirmation-start-date').text(projectStartDate);

//get the value of End Date and spit it onto the summary page
var projectEndDate = $('#project-end-date').blur(function() {
  $('#project-end-date').data('DateTimePicker').date();
  console.log(projectEndDate);
});
$('#confirmation-end-date').text(projectStartDate);

With this current code text stating [Object object] gets returned in the 's for those inputs.
Console.log also returns an object, rather than a value.
I'm super new to jquery/javascript and any help is appreciated.
Thanks in advance!
My Full Javascript Code:
< script type = "text/javascript" >
  //Escrow Form Validations
  $().ready(function() {
    $(".no input").radio('check');

    var $validator = $("#wizardForm").validate({
      rules: {
        email: {
          required: true,
          email: true,
          minlength: 5
        },
        first_name: {
          required: false,
          minlength: 5
        },
        last_name: {
          required: false,
          minlength: 5
        },
        price: {
          number: true
        }
      }
    });

    //Tab Control for Form Wizard
    $('#wizardCard').bootstrapWizard({
      tabClass: 'nav nav-pills nav-pills-blue',
      nextSelector: '.btn-next',
      previousSelector: '.btn-back',
      onNext: function(tab, navigation, index) {
        var $valid = $('#wizardForm').valid();

        if (!$valid) {
          $validator.focusInvalid();
          return false;
        }
      },
      onInit: function(tab, navigation, index) {

        //check number of tabs and fill the entire row
        var $total = navigation.find('li').length;
        $width = 100 / $total;

        $display_width = $(document).width();

        if ($display_width < 600 && $total > 3) {
          $width = 50;
        }

        navigation.find('li').css('width', $width + '%');
      },
      onTabClick: function(tab, navigation, index) {
        // Disable the posibility to click on tabs
        return false;
      },
      onTabShow: function(tab, navigation, index) {
        var $total = navigation.find('li').length;
        var $current = index + 1;

        var wizard = navigation.closest('.card-wizard');

        // If it's the last tab then hide the last button and show the finish instead
        if ($current >= $total) {
          $(wizard).find('.btn-next').hide();
          $(wizard).find('.btn-finish').show();
        } else if ($current == 1) {
          $(wizard).find('.btn-back').hide();
        } else {
          $(wizard).find('.btn-back').show();
          $(wizard).find('.btn-next').show();
          $(wizard).find('.btn-finish').hide();
        }
      }
    });
  });

$().ready(function() {
  //Max amount of milestones
  var max_milestone = 5

  // Initial Milestone Count
  var x = 1;

  //function for add milestone button
  //if button.add-milestone is clicked
  $('.add-milestone').click(function(e) {
    //console.log('dope')
    e.preventDefault();
    if (x < max_milestone) { // if the milestone count is smaller than 5
      x++; //increment milestones
      $('.additional-milestones').before('

Milestone #1

Milestone Title<input class="form-control" type="text" name="Milestone[' + (x - 1) + '][MilestoneTitle]" placeholder="Dusty Bench" required />

Deadline<input type="text" class="form-control datetimepicker" name="Milestone[' + (x - 1) + '][MilestoneTitle]" placeholder="Deadline" required/>

Milestone Description<textarea class="form-control" id="exampleTextarea" name="Milestone[' + (x - 1) + '][MilestoneTitle]" rows="3" required> </textarea>

 - Delete This Milestone

');
      $('.delete-milestone').click(function() {
        //console.log('dope')
        $(this).parents(".milestone").remove();
      });
    }
  });
  //then
  //populate with milestone form with Milestone+Next Milestone Number

  //Delete Milestone
});

//Buying extra TB of Storage
//If 'yes' radio dial is chosen
//show TB input and submit
$('.yes input').on('toggle', function() {
  $(".buy-more-storage").show('slow');
  $(".no input").radio('uncheck');
});

$('.no input').on('toggle', function() {
  $(".buy-more-storage").hide('slow');
  $(".yes input").radio('uncheck');
});

///Date-Time Picker Classes
$('.datetimepicker').datetimepicker({
  icons: {
    time: "fa fa-clock-o",
    date: "fa fa-calendar",
    up: "fa fa-chevron-up",
    down: "fa fa-chevron-down",
    previous: 'fa fa-chevron-left',
    next: 'fa fa-chevron-right',
    today: 'fa fa-screenshot',
    clear: 'fa fa-trash',
    close: 'fa fa-remove'
  },
  format: 'MM/DD/YYYY',
});

//Function for flaring error if picked date is before current date
//if(pickedDate <=todaysDate){
//return true;
//}
//else{
//return false;
//}

//If 'Buyer' is chosen from the Role dropdown menu then the buyer's choices are shown
$('#project-role').on('change.states', function() {
  $(".buyer-choices").toggle($(this).val() == 'Payer');
}).trigger('change.buyer-choices');

//If 'Asset-Producer' is chosen from the Role dropdown menu then the Asset Producer's choices are shown
$('#project-role').on('change.states', function() {
  $(".asset-producer-choices").toggle($(this).val() == 'Payee');
}).trigger('change.asset-producer-choices');

//If 'Credit-Card' is chosen from the Payment Options
$('#payment-type').on('change.states', function() {
  $(".credit-card-form").toggle($(this).val() == 'credit-card');
}).trigger('change.credit-card-form');

//If 'Link Bank Account' is chosen from the Payment Options
$('#payment-type').on('change.states', function() {
  $(".link-bank-account").toggle($(this).val() == 'bank-transfer');
}).trigger('change.link-bank-account');

//If 'Credit-Card' is chosen from the Project Setup Fee
$('#projectFeePayment').on('change.states', function() {
  $(".projectFeePaymentCCForm").toggle($(this).val() == 'projectFeePaymentCC');
}).trigger('change.projectFeePaymentCCForm');

//If 'Link Bank Account' is chosen from the Project Setup Fee
$('#projectFeePayment').on('change.states', function() {
  $(".projectFeePaymentBAForm").toggle($(this).val() == 'projectFeePaymentBT');
}).trigger('change.projectFeePaymentBAForm');

//Send Escrow Project button at end of wizard
function onFinishWizard() {
  //Affirmation of project being
  $('#wizardForm').submit(function(e) {
    var postData = $(this).serializeArray();
    var formURL = "<?php echo $portalfqdn; ?>" + $(this).attr("action");
    $.ajax({
      url: formURL,
      type: "POST",
      data: postData,
      success: function(data) {
        //var emailResult = jQuery.parseJSON(data);
        if (data.Message.Code === "00") {
          swal({
            title: "Success!",
            text: "Your new escrow project has been sent for approval! Look out for an alert indicating when your project has been approved!",
            type: "success",
            confirmButtonText: "Ok",
          });
        } else {
          swal({
            title: "Error!",
            text: "There was a problem with your form submission.",
            type: "error",
            confirmButtonText: "Fix Errors",
          });
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        $('#email-search-result').removeClass("success");
        $('#email-search-result').addClass("error");
        $('#email-search-result').html("An error occurred.");
      }
    });
    e.preventDefault(); //STOP default action
  });

  $('#wizardForm').submit(); //Submit  the FORM

  //If there are errors flag this message, change button to go back to form to address these errors
  //$('.sweet-confirm.btn.btn-info.btn-fill').click(function(){
  //replace this with ajax submit
  //window.location.href='updated-escrow-list.html';
  //$('#wizardForm').submit(); //Submit  the FORM
};

//get the value of project name and spit it onto the summary page
$('.ProjectName').keyup(function() {
  $('#confirmation-project-name').text($(this).val());
});

//Begin get start and end dates of project and spit them onto summary tab
$().ready(function() {
  var projectStartDate;
  var projectEndDate;

  $('#project-start-date').blur(function() {
    projectStartDate = $(this).val();
  });

  $('#project-end-date').blur(function() {
    projectEndDate = $(this).val();
  });

  console.log(projectStartDate);
  console.log(projectEndDate);

  $('#confirmation-start-date').html(projectStartDate);
  $('#confirmation-end-date').html(projectEndDate);
});
//End----------------------------------------------------//

//get the value of project collaborator and spit it onto the summary page
$('.collaborator').keyup(function() {
  $('#confirmation-collaborator').text($(this).val());
});

//get the value of project deliverable description and spit it onto the summary page
$('.ProjectDeliverable').keyup(function() {
  $('#confirmation-project-deliverable').text($(this).val());
});

//get the value of project role and spit it onto the summary page
$('.ProjectRole').change(function() {
  var selectedText = $(this).find("option:selected").text();
  $('#confirmation-project-role').text(selectedText);
});

//if .ProjectRole is Buyer then show chosen payment method

//if .ProjectRole is asset-producer then show chosen payment recieving method

//get the value of project amount and spit it onto the summary page
$('.ProjectAmount').keyup(function() {
  $('#confirmation-project-amount').text($(this).val());
  console.log($('#confirmation-project-amount').text());
});

var projectAmount = parseInt($('#confirmation-project-amount').text());
console.log(projectAmount);

//search for a user by email address to see if they have a Stratuscore account
$('#email-search').click(function(e) {
  if ($('#ProjectPartner').val() === '') {
    return false;
  }
  var postData = {
    Email: $('#ProjectPartner').val(),
    ApiAction: "find-user-by-email"
  }

  var formURL = "<?php echo $portalfqdn; ?>account-api.php";
  $.ajax({
    url: formURL,
    type: "POST",
    data: postData,
    success: function(data) {
      //var emailResult = jQuery.parseJSON(data);
      if (data.Message.Code === "00") {
        $('#email-search-result').removeClass("error alert alert-danger");
        $('#email-search-result').addClass("success alert alert-success");
      } else {
        $('#email-search-result').removeClass("success");
        $('#email-search-result').addClass("error alert alert-danger");
      }
      $('#email-search-result').html(data.Message.Description);
      $('#email-search-result').show();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      $('#email-search-result').removeClass("success");
      $('#email-search-result').addClass("error");
      $('#email-search-result').html("The user you are searching for wasn't found. Please check the email entered and try again.");
    }
  });
  e.preventDefault(); //STOP default action
}); < /script>

SOLUTION
After much frustration at myself for being a javascript novice, I realized I had a scope issue on my hands and instead wrote functions to handle the DOM updating and passed the variables as parameters to those functions. Works for now!
//Begin get start and end dates of project and spit them onto summary tab
function updateStartDate (projectStartDate) {
    $('#confirmation-start-date').html(projectStartDate);
    console.log(projectStartDate);
}

function updateEndDate (projectEndDate) {
    $('#confirmation-end-date').html(projectEndDate);
    console.log(projectEndDate);
}

$('#project-start-date').blur(function() {
    var projectStartDate = $(this).val();
        //console.log(projectStartDate);
    updateStartDate(projectStartDate);
});

$('#project-end-date').blur(function() {
    var projectEndDate = $(this).val();
        //console.log(projectEndDate);
    updateEndDate(projectEndDate);
});

A: One of the great things about jQuery is that almost all its methods return the element on which they're called, thus allowing you to chain a bunch of them together. However, because the methods almost always return an element, something like this...
var projectStartDate = $('#project-start-date').blur( ... );

... is just going to set projectStartDate = $('#project-start-date');, rather than its value. I've created a brief example to demonstrate this here.

If you want to set projectStartDate equal to the value of this field, consider something like the following...
var projectStartDate;
var projectEndDate;

$('#project-start-date').blur(function() {
    projectStartDate = $(this).val();
});

$('#project-end-date').blur(function() {
    projectEndDate = $(this).val();
});

$('#confirmation-start-date').html(projectStartDate);
$('#confirmation-end-date').html(projectEndDate);


text:
Q: The boy who lived... come to die? (Harry Potter) I hope I'm not giving away any Harry Potter plot points. I just watched the last movie of the series, and I'm pretty sure that they made an error in the German translation of a line from Voldemort taken right from the book:
As you can see in the trailer, Voldemort says

Harry Potter, the boy who lived...come to die.

Note that the sentence ends in a period, not an exclamation point. Now I had always understood this to mean:

(Look at) Harry Potter, the boy who lived (who has now) come to die.

In the German dub, they translated it as:

Harry Potter, der Junge der überlebte. Komm her und stirb!
(Harry Potter, the boy who lived. Come here and die!)

Surely that's not correct. Or is it? Is this ambiguous at all?

A: I think the English (as written) is a bit ambiguous. It could be an ellipsis, as you wrote:

The boy who lived (has now) come to die.

or it could be a command

The boy who lived. Come (here), to die!

The tone of the speaker would probably make it clear. I feel that the if the speaker was speaking in the first case, the word "come" would probably be spoken more softly, whereas in the second case, "Come!" is a command and would be spoken more forcefully.
The trailer is here and it sounds to me like it's an observation than a command, so I think the first interpretation is correct.

A: In the way it is written, it is in the imperative mood. The two sentences are grammaticaly separate:

*

*Harry Potter, the boy who lived (a different way of saying "Hello Harry")

*Come to die!

With a different context, the present of the indicative mood could also be used, but the meaning would be altogether different:

(Voice-over) Harry Potter, the boy who lived, (pause for dramatic effect) comes to die

Of course, being the singular third person, comes then has a final s.

A: Not really ambiguous to me. Even in English, it is "Come (here) to die" like a command.


text:
Q: How to Receive IVR Voice without pressing any key to continue on call start on Twilio? I have been using trail account. I have made a application to make a call and say Birthday greetings. I can able to make a call to the registered phone number and the message is speaking when i press a button. I need to receive the message without pressing any button. is there any option to do this? Kindly share if we can do that.
Is there any feature that makes straightforward call without prompting the caller to press any keys in dial pad ?
Thank you in advance.

A: Twilio developer evangelist here.
The message prompt to get the recipient to press a key is a feature of our trial account. The way to remove that message is to upgrade your Twilio account by adding a credit card or PayPal account and adding some funds.
Once you have done that, the message will go away and your call recipient will only hear the birthday greetings.


text:
Q: react. How to change icon src by onClick or onPress? I wanna campaigns_icon change to campaigns_icon_selected when I click.
Then if I click  search_icon_pic, it will be the search_icon_pic_selected and campaigns_icon_selected changed to campaigns_icon
Here is part of my code:

import campaigns_icon from '../../image/sidebar/campaigns white.png';
import campaigns_icon_selected from '../../image/sidebar/campaigns white.png';
import search_icon_pic from '../../image/sidebar/search white.png';
import search_icon_pic_selected from '../../image/sidebar/search white.png';

    return (
      <Sider
        trigger={null}
        collapsible={true}
        collapsed={collapsed}
        className="isomorphicSidebar"
      >
        <Link to={`${url}/status_board`}>

        </Link>
        <Link to={`${url}/search_result`}>

        </Link>

      </Sider>
    );

A: For simple, I think you can create 2 state properties then toggle the image over it. And also, you will need 2 method to change it, for example:
    constructor(props){
        super(props);
        this.state = {
            campaigns: false,
            search: false
        }
    }

    handleChangeCampaign(){
        this.setState({campaigns:!this.state.campaigns})
    }

    handleChangeSearch(){
        this.setState({search:!this.state.search})
    }

Then in your render method you can set it:
    return (
        <Sider
        trigger={null}
        collapsible={true}
        collapsed={collapsed}
        className="isomorphicSidebar"
        >
        <Link to={`${url}/status_board`} onClick={this.handleChangeCampaign.bind(this)}>

        </Link>
        <Link to={`${url}/search_result`} onClick={this.handleChangeSearch.bind(this)}>

        </Link>

        </Sider>
    );

A: import campaigns_icon from '../../image/sidebar/campaigns white.png';
import campaigns_icon_selected from '../../image/sidebar/campaigns white.png';
import search_icon_pic from '../../image/sidebar/search white.png';
import search_icon_pic_selected from '../../image/sidebar/search white.png';

class MyCls extends React.Component {
   constructor(props) {
     super(props);
     this.state = {
       campaignsIconClicked: false,
       searchIconClicked: false
     };
   }

   render() {
     return (
      <Sider
        trigger={null}
        collapsible={true}
        collapsed={collapsed}
        className="isomorphicSidebar"
      >
        <Link to={`${url}/status_board`}>
             this.setState({campaignsIconClicked: true}) } alt="" src={this.state.campaignsIconClicked ? campaigns_icon_selected : campaigns_icon} />
        </Link>
        <Link to={`${url}/search_result`}>
             this.setState({searchIconClicked: true}) } alt="" src={this.state.searchIconClicked ? search_icon_pic_selected : search_icon_pic}/>
        </Link>
      </Sider>
    );
   }
}


text:
Q: How to bind value from UI to controller with complex model in c# mvc I'm new to .net. I have this model that has been a real trouble for me for days.
class DetailedRecordModel
public class DetailedRecordModel
    {
        public string RecordID { get; set; }
        public string EmployeeID { get; set; }
        public string CustomerID { get; set; }

        [DataType(DataType.Date)]
        public string InitDate { get; set; }

        [DataType(DataType.Date)]
        public string DeliveryDate { get; set; }
        public virtual ICollection<PurchaseDetail> detail{ get; set; }
}

class PurchaseDetail
public class PurchaseDetail
    {
        public string ProductID { get; set; }
        public int Qty { get; set; }
        public double price { get; set; }
        public string RecordID { get; set; }

    }

controller
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(DetailedRecordModel record)
        {
            if (ModelState.IsValid)
            {
            return View(record);

            }
                return RedirectToAction("ViewRecords");
        }

html

            @Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewData["sellistemp"])
                @Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.CustomerID, (IEnumerable<SelectListItem>)ViewData["sellistcust"])
                @Html.ValidationMessageFor(model => model.CustomerID, "", new { @class = "text-danger" })

       1
       sp00002
       12123
       2312

       2
       sp00003
       2323
       3223

for RecordID, EmployeeID, CustomerID, InitDate and DeliveryDate  passing them to the controller is all fine, however I always get null for <PurchaseDetail> detail. How can I solve this problem?

A: you have to pass the model to the view by using View(myModel) or RedirectToAction("ViewRecords", record)
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(DetailedRecordModel record)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("ViewRecords", record);

        }
        return View(record);
    }

    public IActionResult ViewRecords(DetailedRecordModel model)
    {
        return View(model);
    }

then in the View you can access the model like here How to pass model in MVC view

*

*add the definition of your model at the top of @model DetailedRecordModel;

*after you added the model you can access it everywhere in your file with @Model (in html) or Model

    @model DetailedRecordModel;
    @{
        ViewData["Title"] = "ViewRecords";
    }

ViewRecords

        @Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewData["sellistemp"])
            @Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.CustomerID, (IEnumerable<SelectListItem>)ViewData["sellistcust"])
            @Html.ValidationMessageFor(model => model.CustomerID, "", new { @class = "text-danger" })

    @foreach (var entry in Model.detail)
    {

            1
            sp00002
            12123
            2312

    }

A: After 2 wretching days of desperation I know that in order to bind the values, I found the answer by declaring an object DetailedRecordModel inside model PurchaseDetail and I have to change the name of each <input> tag into detail[index].somevariable


text:
Q: Processing an input file in batch I want to write a batch file to read an input text file, extract information from it put it in an output file.

*

*Each line in the input file has different information so I want the batch to loop through each line.

*I want to extract certain information from the input file and discard the rest.

*The input file can have any number of lines.

*I want to leave an error message if the input line has no useful information.

*I need two counters, the first telling the number of lines in the input file, and the second telling the number of lines in the output file (without counting empty lines) .

*I want the batch to treat special characters like normal letters.

For example:
FILE_NAME=apple FILE_SIZE=312     C=fwef sdf asdetg

FILE_SIZE=7867 C=ehtrghr  FILE_NAME=sea&ocean G=tryr    yujg
C=gert FILE_NAME=chair=12 tgrgd sfsf FILE_SIZE=66
dfgg ertergf C=ert A=344

fgdfg FILE_NAME=cat

I want to extract only the FILE_NAME=XXX and FILE_SIZE=XXX part, discarding everything else in that line. The output should be:
-name apple -size 312
-name sea&ocean -size 7867
-name chair=12 -size 66
ERROR!!!
-name cat

 input_count=5 and output_count=4

A: People don't give enough credit to batch scripts. Try this:
@echo off
setlocal enableDelayedExpansion
set INPUT_FILE=input.txt
set OUTPUT_FILE=output.txt
set INPUT_COUNT=0
set OUTPUT_COUNT=0

:: Read the input file
for /f "tokens=*" %%s in (%INPUT_FILE%) do call :ParseLine "%%s"
echo. >>%OUTPUT_FILE%
echo input_count=!INPUT_COUNT! and output_count=!OUTPUT_COUNT! >>%OUTPUT_FILE%
exit /b

:: Parse one line and write to output
:ParseLine
set "str=%~1"
set ^"str=!str: =^

!"
set file_name=
set file_size=
for /f "eol=  tokens=1,2 delims==" %%a in ("!str!") do (
    set "tag=%%a"
    set "value=%%b"
    if "!tag!" equ "FILE_NAME" set "file_name=-name !value!"
    if "!tag!" equ "FILE_SIZE" set "file_size=-size !value!"
)
set /a input_count+=1
if "!file_name!" equ "" if "!file_size!" equ "" (
    echo ERROR^^!^^!^^! >>%OUTPUT_FILE%
    goto Done
)
echo.!file_name! !file_size! >>%OUTPUT_FILE%
set /a output_count+=1
:Done

Here's a little explanation about what this does:

*

*The first for loop reads the file line by line, the contents of each line being sent as input arguments to the ParseLine subroutine.

*The ParseLine subroutine receives each line in str and iterates through its space-separated words (using jeb's advanced method described here).
The logic of the subroutine loop is pretty straightforward: it breaks each word into tag (the text that precedes =) and value (the text that follows =), and sets file_name and file_size accordingly.

I believe that this method can handle pretty much any input file, with or without special characters.


text:
Q: Android: ArrayList and app memory I have a messaging application, in which the received messages are stored in an SQLite database. Every time the main fragment is loaded, the messages are loaded into an ArrayList, and the ArrayList is passed to a RecyclerView for display.
There is one thought that's been bugging me - what if there are too many messages in the database? The ArrayList may end up consuming too much memory and then the app may crash.
How can I resolve this?


text:
Q: Batch : Search Directory in every Directory and Subdirectory I want to delete all directories with a specific name. E.g. "vendor"

D:\Data\Project1\Dir\vendor
D:\Data\Project2\AnotherDir\AnotherDir\vendor
D:\Data\Project3\vendor

This is what I have at this moment. This lists all the folders, and subfolders.
for /d %%a in (*) do dir /ad /on /s /b %%a

Now I wish to put one path in a variable, and check whether the directory is equal to a name (for example "vendor"). But I can't find how.
Can you help me?
Regards,
Demian

A: The DIR command has an unfortunate limitation that it cannot recursively list specific folder names. The simplest solution is to list all folders, and use FINDSTR to filter out all but the folders that match.
dir /ad /on /s /b | findstr /iec:"\vendor"

Then you simply iterate the results using FOR /F and add your RD command
for /f "eol=: delims=" %%F in
  'dir /ad /on /s /b ^| findstr /iec:"\vendor"'
) do rd /s /q "%%F" 2>nul

A: This is my working solution if you have RimRaf installed:
@ECHO off

setlocal enableDelayedExpansion

:: Folders where the batch program doesn't need to search.
set skipTheseFolders=Decleir Pinokkio

:: All the folders that need to be deleted
set foldersToDelete=vendor node_modules

for /d /r %%d in (*.*) do (

    @ECHO %%d

    set folder=%%~nxd
    set canI="true"

    :: For loop to skip folders
    for %%s in (%skipTheseFolders%) do (
        :: Need to be implemented
        set canI="true"
    )

    IF !canI! =="true" (
        for %%l in (%foldersToDelete%) do (
            :: If the folder is one of the folders To Delete
            IF "!folder!" == "%%l" (
                @echo %%d
                cd %%d
                cd ..
                :: Using Rimraf because when you delete node_modules, normal delete won't work
                start /B rimraf !folder!
            )
        )
    )
)

A: You can try this :
@Echo OFF
set "Folder=D:\Data"
set "FolderString=vendor"
Setlocal Enabledelayedexpansion
FOR /f "tokens=*" %%F IN ('dir /b /s /ad %Folder%\ ^| find "%FolderString%"') DO (set var="%%F"
ECHO rd /s /q !var! && rd /s /q !var!)
EndLocal
pause


text:
Q: Get Sum & Average of each month using SQL I have below database table,In here i need group some data and get sum and avg of some data.
In here i need to calculate Item marketers monthly sales(Each Month)
As a Example :
I need to get a Patric Newton's Sales in Each months.
And also i need to calculate AvarageFactor of each month Each employee.
AvgFactor = SUM(Daily Sales)/ SUM(Value Factor) * 100( Each Month )

Database Table

I have tried it like below,
SELECT ItemMarketerName,DailySales,ValueFactor,[Month],[Year]
FROM [SR_Hotel].[dbo].[Table_1]
WHERE ItemMarketerName IS NOT NULL
Group by ItemMarketerName,DailySales,ValueFactor,[Month],[Year]
Order by ItemMarketerName

A: You should not include your aggregated columns in your GROUP BY.
Try:
SELECT ItemMarketerName, [Month], [Year], SUM(DailySales), SUM(DailySales) / SUM(ValueFactor) * 100
FROM [SR_Hotel].[dbo].[Table_1]
WHERE ItemMarketerName IS NOT NULL
GROUP BY ItemMarketerName, [Month], [Year]
ORDER BY ItemMarketerName


text:
Q: Overriden method does not throw I'm having some errors here. I cant quite figure out.
Hmmm.
class myException extends Exception {

    interface MyInterface {
        void myMethod () throws myException;
    }

    class MyImplementation implements MyInterface {

        @Override
        public void myMethod() throws MyException {
            System.out.println("in myMethod()");
            throw new MyException();
        }
    }

    class TheInterface { }

    public static void main(String[] args) {
        MyImplementation m;
        m = new MyImplementation();
        try {
            m.myMethod();
        } catch (MyException e) {
            System.out.println("MyException caught");
        }
    }
}

Please help.

A: You are using user defined exception and have not created that. Try this or use generic Exception
public class MyImplementation implements MyInterface {

    @Override
    public void myMethod() throws MyException {
        System.out.println("in myMethod()");
        throw new MyException();
    }

}

interface MyInterface {
    void myMethod () throws MyException;
}

public class MyException extends Exception {

}

public class TestThrowsException {

    public static void main(String[] args) {
        MyImplementation m = new MyImplementation();
         try {
            m.myMethod();
         }
         catch (MyException e) {
            System.out.println("MyException caught");
         }
    }
}

By test way:-
public class TestThrowsException {
    @Test(expected = MyException.class)
    public void shoudldThrowException() throws MyException {
         MyImplementation m = new MyImplementation();
         m.myMethod();
    }
}

A: I think you have typo .
interface MyInterface {
    void myMethod () throws myException; // Change it to MyException
}

Also make sure you close braces properly
class myException extends Exception {}

A: Try it as:
class myException extends Exception {}

interface MyInterface {
void myMethod () throws myException;
}

class MyImplementation
implements MyInterface {

@Override
public void myMethod() throws myException {
    System.out.println("in myMethod()");
    throw new myException();
}
}

public class TheInterface {
public static void main(String[] args) {
MyImplementation m;
m = new MyImplementation();
try {
m.myMethod();
} catch (myException e) {
e.printStackTrace();
        System.out.println("MyException caught");
}
}
}


text:
Q: Add or Remove element from array in nested Object in React hooks
In this below example, I want add or remove the products array elements from object3 and need to updated in react hooks state.
I have tried with filter method inside setter for deleting an element but it won't work. can anyone pls help to do with efficiently.

const myValue = {
                object1: {},
                object2: {},
                object3: {
                    products: [{
                        name: 'Fruits',
                        id: '1'
                    },
                    {
                        name: "Vegtables",
                        id: '2'
                    }],
                    number: 1
                }
            }

A: You can extract out the object3 as another variable, do whatever operations you want to do and set state again combining it with the current state value.
const {object3} = myValue;

// for example if you want to filter based on condition for id
const modifiedProducts = object3.products.filter((item) => item.id > '1');

setMyValue({
    ...myValue,
    object3: {
        ...object3,
        products: modifiedProducts
    }
})

I would also suggest making multiple states for each object if all objects are independent from each other. Here if some component only depends on object1, ideally it should not re render when object 3 updates.