text:
Q: Error org.hibernate.PropertyValueException: not-null property references a null or transient value : com.example.pgfinder.models.User.password I encountered this error when I tried to submit my form. React form is being used to submit the details.
User.java
package com.example.pgfinder.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long user_id;

    @Column(nullable= false)
    private String user_name;

    @Column(nullable= false)
    private String password;

    @Column(nullable= false)
    private String user_firstName;

    @Column(nullable= false)
    private String user_lastName;

    @Column(nullable= false)
    private String user_email;

    @Column(nullable= false)
    private String user_phone_no;

    public User() {
        super();
    }

    public User(String user_name, String password, String user_firstName, String user_lastName, String user_email,
            String user_phone_no) {
        super();
        this.user_name = user_name;
        this.password = password;
        this.user_firstName = user_firstName;
        this.user_lastName = user_lastName;
        this.user_email = user_email;
        this.user_phone_no = user_phone_no;
    }

    public long getUser_id() {
        return user_id;
    }
    public void setUser_id(long user_id) {
        this.user_id = user_id;
    }
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUser_firstName() {
        return user_firstName;
    }
    public void setUser_firstName(String user_firstName) {
        this.user_firstName = user_firstName;
    }
    public String getUser_lastName() {
        return user_lastName;
    }
    public void setUser_lastName(String user_lastName) {
        this.user_lastName = user_lastName;
    }
    public String getUser_email() {
        return user_email;
    }
    public void setUser_email(String user_email) {
        this.user_email = user_email;
    }
    public String getUser_phone_no() {
        return user_phone_no;
    }
    public void setUser_phone_no(String user_phone_no) {
        this.user_phone_no = user_phone_no;
    }
}

Here is the controller file
UserController.java
package com.example.pgfinder.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.pgfinder.models.repository.UserRepository;
import com.example.pgfinder.models.User;

@CrossOrigin(origins = "http://localhost:3000/")
@RestController
@RequestMapping("/api/v1/")
public class UserController
{
    @Autowired
    private UserRepository userRepository;

    //get all user
    @GetMapping("/user")
    public List<User> getAllUserDetails(){
        return userRepository.findAll();
    }

    //create the user
    @PostMapping("/user")
    public User createUser(@RequestBody User user)
    {
        return userRepository.save(user);
    }
}

And the UserRepository.java
package com.example.pgfinder.models.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.pgfinder.models.PGDetails;

@Repository
public interface PGDetailsRepository extends JpaRepository<PGDetails,Long>{

}

The form looks like this
SignUp.js
import React, { useEffect, useRef, useState } from "react";
import { FiMapPin } from 'react-icons/fi';
import { faCheck, faTimes, faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Navbar from "./Navbar";
import './signup.css';
import Footer from "./Footer";
import { useNavigate } from "react-router-dom";
import UserService from "../services/UserService";

const SignUp = () => {

    const USER_REGEX = /^[A-z][A-z0-9-_]{3,23}$/;
    const PWD_REGEX = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%]).{8,24}$/;
    const EMAIL_REGEX = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
    const PHONE_REGEX = /^[0-9]{10}$/;

    const userRef = useRef(); //will set the focus on the user input when the component loads
    const errRef = useRef(); //this is for error reference

    const [user_name, setUser] = useState(''); //for the user name field
    const [validName, setValidName] = useState(false); //for setting validations in user name field
    const [userFocus, setUserFocus] = useState(false); //for checking if the focus is on user name field or not

    const [pwd, setPwd] = useState('');
    const [validPwd, setValidPwd] = useState(false);
    const [pwdFocus, setPwdFocus] = useState(false);

    const [matchPwd, setMatchPwd] = useState('');
    const [validMatch, setValidMatch] = useState(false);
    const [matchFocus, setMatchFocus] = useState(false);

    const [phone, setPhone] = useState('');
    const [validPhone, setValidPhone] = useState(false);
    const [phoneFocus, setPhoneFocus] = useState(false);

    const [email, setEmail] = useState('');
    const [validEmail, setValidEmail] = useState(false);
    const [emailFocus, setEmailFocus] = useState(false);

    const [fname, setFName] = useState('');
    const [fnameFocus, setFNameFocus] = useState(false);

    const [lname, setLName] = useState('');
    const [lnameFocus, setLNameFocus] = useState(false);

    const [errMsg, setErrMsg] = useState('');

    const navigate = useNavigate();

    useEffect(() => {
        userRef.current.focus();

    }, [])

    useEffect(() => {
        const result = USER_REGEX.test(user_name);
        console.log(result);
        console.log(user_name);
        setValidName(result);
    }, [user_name])

    useEffect(() => {
        const result = PHONE_REGEX.test(phone);
        console.log(result);
        console.log(phone);
        setValidPhone(result);
    }, [phone])

    useEffect(() => {
        const result = PWD_REGEX.test(pwd);
        console.log(result);
        console.log(pwd);
        setValidPwd(result);
        const match = pwd === matchPwd;
        setValidMatch(match);
    }, [pwd, matchPwd])

    useEffect(() => {
        const result = EMAIL_REGEX.test(email);
        console.log(result);
        console.log(email);
        setValidEmail(result);
    }, [email])

    useEffect(() => {
        setErrMsg('');
    }, [user_name, pwd, matchPwd, email])

    const saveUser = (e) =>{
        e.preventDefault();
        const userDetails = {user_name, pwd, phone, email, fname, lname};
        UserService.createUser(userDetails).then((response) =>{
            console.log(response.data);

        }).catch(error => {
            console.log(error);
        })

    }

    return (
        <>
            <Navbar />

 Hello, Friend!

 Fill up personal information and start the

                journey of finding PG

                <button className="btn-pgsearch">Search PG <FiMapPin/></button>

{errMsg}

Create Account

                <form>
                    {/*Username*/}

                        Username:

                            <FontAwesomeIcon icon={faCheck} />

                            <FontAwesomeIcon icon={faTimes} />

                    <input
                        text="text"
                        id="username"
                        ref={userRef}    /*Set focus on the input*/
                        autoComplete="off"
                        className="input-field"
                        onChange={(e) => setUser(e.target.value)}    /*Set to true when the input loads */
                        value={user_name}
                        required
                        aria-invalid={validName ? "false" : "true"}  /*Like when you start tying in that field it shows the required or the validation nire and then once you enter the valid name or you satisfy the given it will be removed*/
                        aria-describedby="uidnote"
                        onFocus={() => setUserFocus(true)}
                        onBlur={() => setUserFocus(false)}
                    />

 {/* if the focus is on userinput field and if user field is not empty and if all the validation are match */}
                        <FontAwesomeIcon icon={faInfoCircle} />
                        4 to 24 characters.

                        Must begin with a letter.

                        Letters, numbers, underscores, hyphens allowed.

                    {/*Password */}

                        Password:
                        <FontAwesomeIcon icon={faCheck} className={validPwd ? "valid" : "hide"} />
                        <FontAwesomeIcon icon={faTimes} className={validPwd || !pwd ? "hide" : "invalid"} />

                    <input
                        type="password"
                        id="password"
                        onChange={(e) => setPwd(e.target.value)}
                        className="input-field"
                        value={pwd}
                        required
                        aria-invalid={validPwd ? "false" : "true"}
                        aria-describedby="pwdnote"
                        onFocus={() => setPwdFocus(true)}
                        onBlur={() => setPwdFocus(false)}
                    />

                        <FontAwesomeIcon icon={faInfoCircle} />
                        8 to 24 characters.

                        Must include uppercase and lowercase letters, a number and a special character.

                        Allowed special characters: ! @
                        # $ %

                        Confirm Password:
                        <FontAwesomeIcon icon={faCheck} className={validMatch && matchPwd ? "valid" : "hide"} />
                        <FontAwesomeIcon icon={faTimes} className={validMatch || !matchPwd ? "hide" : "invalid"} />

                    <input
                        type="password"
                        id="confirm_pwd"
                        onChange={(e) => setMatchPwd(e.target.value)}
                        value={matchPwd}
                        className="input-field"
                        required
                        aria-invalid={validMatch ? "false" : "true"}
                        aria-describedby="confirmnote"
                        onFocus={() => setMatchFocus(true)}
                        onBlur={() => setMatchFocus(false)}
                    />

                        <FontAwesomeIcon icon={faInfoCircle} />
                        Must match the first password input field.

                    {/*First Name */}

                        First Name:

                    <input
                        text="text"
                        id="fname"
                        ref={userRef}    /*Set focus on the input*/
                        autoComplete="off"
                        onChange={(e) => setFName(e.target.value)}    /*Set to true when the input loads */
                        className="input-field"
                        value={fname}
                        required
                        onFocus={() => setFNameFocus(true)}
                        onBlur={() => setFNameFocus(false)}
                    />

                    {/*Last Name */}

                        Last Name:

                    <input
                        text="text"
                        id="lname"
                        ref={userRef}    /*Set focus on the input*/
                        className="input-field"
                        autoComplete="off"
                        onChange={(e) => setLName(e.target.value)}    /*Set to true when the input loads */
                        value={lname}
                        required
                        onFocus={() => setLNameFocus(true)}
                        onBlur={() => setLNameFocus(false)}
                    />

                    {/*Email*/}

                        Email Address:

                            <FontAwesomeIcon icon={faCheck} />

                            <FontAwesomeIcon icon={faTimes} />

                    <input
                        text="email"
                        id="email"
                        ref={userRef}    /*Set focus on the input*/
                        autoComplete="off"
                        onChange={(e) => setEmail(e.target.value)}    /*Set to true when the input loads */
                        className="input-field"
                        value={email}
                        required
                        aria-invalid={validEmail ? "false" : "true"}  /*Like when you start tying in that field it shows the required or the validation nire and then once you enter the valid name or you satisfy the given it will be removed*/
                        aria-describedby="eidnote"
                        onFocus={() => setEmailFocus(true)}
                        onBlur={() => setEmailFocus(false)}
                    />

 {/* if the focus is on userinput field and if user field is not empty and if all the validation are match */}
                        <FontAwesomeIcon icon={faInfoCircle} />
                        valid email.

                        Must have @ symbol.

                        Letters, numbers, hyphens allowed.

                    {/*Phone Number */}

                        Phone Number:

                            <FontAwesomeIcon icon={faCheck} />

                            <FontAwesomeIcon icon={faTimes} />

                    <input
                        text="text"
                        id="phone"
                        ref={userRef}    /*Set focus on the input*/
                        autoComplete="off"
                        onChange={(e) => setPhone(e.target.value)}    /*Set to true when the input loads */
                        className="input-field"
                        value={phone}
                        required
                        maxLength={10}
                        aria-invalid={validPhone ? "false" : "true"}  /*Like when you start tying in that field it shows the required or the validation nire and then once you enter the valid name or you satisfy the given it will be removed*/
                        aria-describedby="pidnote"
                        onFocus={() => setPhoneFocus(true)}
                        onBlur={() => setPhoneFocus(false)}
                    />

 {/* if the focus is on userinput field and if user field is not empty and if all the validation are match */}
                        <FontAwesomeIcon icon={faInfoCircle} />
                        Contains number only.

                        Maximum length is 10.

                    <button className="btn-signup-s" onClick={(e) => saveUser(e)} disabled={!validName || !validPwd || !validMatch || !validEmail || !validPhone ? true : false}>
                        Sign Up
                    </button>
                </form>

                    Already registered?

                        Sign In

        </>
    )

}

export default SignUp

UserService.js
import axios from 'axios';
const USER_API_BASE_URL="http://localhost:8090/api/v1/user";

class UserService{

    getUserInfo(){
        return axios.get(USER_API_BASE_URL);
    }

    createUser(user)
    {
        return axios.post(USER_API_BASE_URL, user);
    }
}
export default new UserService();

Whenever I pass details on the console, they are printed. Please guide me why am I still getting null entry error in password field.
Console Pic
Thank you.


text:
Q: how can i solve the issue of right overflowed by 382 pixels Problem:
I have an overflow error when i use this widget (code below), How i solve the issue?
You can see the error in the image below.
enter image description here
Container(
  height: 150,
  decoration: BoxDecoration(
      color: Colors.red,
      borderRadius: BorderRadius.circular(20),
  ),
  child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20),
            )
)...

You can check the complete here.

A: Try wrapping the widget with Flexible().
Read more here https://api.flutter.dev/flutter/widgets/Flexible-class.html

A:
The child Container should have defined height, try giving it a given height,
and the height must not be greater than the parent height.

- Increase the height of the parent container and also give the child Container a height and width

.
    Container(
      height: 300,
      decoration: BoxDecoration(
          color: Colors.red,
          borderRadius: BorderRadius.circular(20),
      ),
      child: Container(
               height:'your height',
              width:'your width',
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                )
    )...

A: your Row widget is too big for screen. you should change your layout or wrap you code in FittedBox wiget like this:
Container(
        height: 150,
        decoration: BoxDecoration(
          color: Colors.red,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
          ),
          child: FittedBox(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[...],
            ),
          ),
        ),
      )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set public DNS server on work PC, can no longer authenticate with domain controller As in topic title, I have a domain account with admin privileges to the particular PC I use.
I'm an idiot, and when some addresses wouldn't resolve thought I'd try changing DNS server.
Obviously now everything is screwed - no network, and I can't authenticate with the domain at the admin prompt to edit the adaptor properties.
Is there any way of starting an elevated command prompt with runas and specifying a logon server/bypassing DNS? I have access to other PCs on the network here and know the IP of our logon server.
To my knowledge there are no local admin accounts on the box, and the default administrator account is disabled. The only thing I can think of is using a linux live USB with chntpw to enable the built-in admin account and correcting the problem with that.
Please send help.


text:
Q: Why do I get a NPE after assigning an Integer variable with value null to an int variable? I want to know how the compiler reads this code.
public class obj {
    public static void main(String[] args) {
        Integer obj = null; //line4
        int x = obj;   //line 5
        System.out.println(x); //line6
    }
}

My understanding is that line 5 can do auto unboxing which means it converts the Integer type to primitive int.
But I am not calling any method on x, just printing. Why is it giving me a NullPointerException?.

A: Autoboxing here means that
int x = obj;

is actually:
int x = obj.intValue();

and hence the NullPointerException, as obj is null.

A: Java has something called autoboxing where the Integer object is automatically converted to an int primative.

A: Look at the bytecode
javap -c com.interviews.practise.obj


text:
Q: Joining elements in list of Strings in loop with a condition Every 2 elements should be joined in a loop till the end of the list
This is what i have been trying to do
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for i in range(len(items)+1):
  items[i]=items[i]+items[i+1]
  i=i+2
print(items)

Expected Output: ['ab' , 'cd' , 'ef' , 'gh' , 'ij']

A: You can supply another argument to range to specify the increment ("step"):
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
res = []
for i in range(0, len(items), 2):
    res.append(items[i] + items[i + 1])
print(res)
# ['ab', 'cd', 'ef', 'gh', 'ij']

Or, better yet, use a list comprehension instead:
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
items = [items[i] + items[i + 1] for i in range(0, len(items), 2)]
print(items)
# ['ab', 'cd', 'ef', 'gh', 'ij']

A: you can do it using list comprehension like this:
items = [items[i] + items[i+1] for i in range(0, len(items), 2)]

A: A solution with regex:
>>> import re
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> re.findall('.{1,2}', ''.join(items))
['ab', 'cd', 'ef', 'gh', 'ij']

A: Your thought process is correct, I would double check your print statement.  You are printing items, but are updating items[i] to items[i] + items[i+1]. I believe you want to print the variable you are updating.

A: First of all, you need to know that len() returns the number of item, not the size of the array (remember that the array index starts at 0). Here, if you want, you can look at the docs for the len() function.
Next, just to inform you, you can use the method append() to insert an object into the final position of the array. Here you can find some info on arrays.
Moreover, I want to add that in python, when using range, you can take advantage of the step value that you can pass to range: range(start, stop, step). You can read more about it here.
Said so, I would do something as follow:
output=[]
for i in range(0, len(items), 2):
    output.append(items[i]+items[i+1]);
print(output)


text:
Q: View Controller in the "More" tab doesn't rotate, but it will if it's on the home row. I have an app built in storyboard that needs to support landscape mode in just one view controller. I decided to support iOS 6 after some issues with supporting iOS 5 and running iOS 6 on my phone. I used this Stack Overflow answer: https://stackoverflow.com/a/12505461/1050388 but I'm still seeing a weird quirk. (For those interested, my controller scheme is Tab Controller -> Navigation Controller -> TableViewController -> UIWebView. The UIWebView is the only VC I need to rotate.)
I blocked all but one VC from turning, but that VC is in the "More" tab. I initially had a quirk where this "More" VC would change orientation to landscape when rotated and then any subsequent VC would be in landscape, but I found this (https://stackoverflow.com/a/12526152/1050388) and creating a category for UINavigationController helped to solve that issue.
However, when I navigate to that tab in the "More" list, and turn the VC, it doesn't rotate. But when I click "Edit" and move that tab to the home row of the initial 4 tabs, it rotates just fine. If I move it back, it doesn't rotate. Anyone have an idea why this is happening?

A: I believe the problem stems from the fact that the More navigation controller is generated dynamically by iOS and is read-only.
http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITabBarController_Class/Reference/Reference.html#//apple_ref/occ/instp/UITabBarController/moreNavigationController
It would be great if the technique of using a custom category would work here but based on your experience I guess it doesn't.
I also need better control of orientations for More tab views.  Please post anything you come up with.  Thanks.


text:
Q: How to make my code support multiple data sources? I'm looking to update some NodeJS code used on AWS Lambda so it can potentially use data from different sources.
As it stands, the code only supports using data from one source. I'd like the code to still work if we changed to a different source of data in the future.
What design pattern would this fall under? And are theire some good examples of how to implement something like this?
As an example, something like FlySystem https://github.com/thephpleague/flysystem where it can handle file uploading to FTP or to Google Drive, just by changing the file adapter type.


text:
Q: Error running coffee code with pm2: Error: spawn /usr/local/lib/node_modules/pm2/node_modules/.bin/coffee ENOENT After I upgraded pm2 from 2.1.5 to 3.4.1 I started to get the following error when I try to start/restart an app pm2 restart api:
PM2      | App [api:6] starting in -fork mode-
PM2      | App [api:6] online
PM2      | Error: spawn /usr/local/lib/node_modules/pm2/node_modules/.bin/coffee ENOENT
PM2      |     at Process.ChildProcess._handle.onexit (internal/child_process.js:247:19)
PM2      |     at onErrorNT (internal/child_process.js:431:16)
PM2      |     at processTicksAndRejections (internal/process/task_queues.js:81:17)
PM2      | App [coffee:10] exited with code [0] via signal [SIGINT]

I tried to install coffee for pm2 with pm2 install coffee but it didn't help - I see a lot of this in the pm2 logs:
PM2      | App [coffee:11] exited with code [0] via signal [SIGINT]
PM2      | App [coffee:11] starting in -fork mode-
PM2      | App [coffee:11] online
PM2      | App [coffee:11] exited with code [0] via signal [SIGINT]
PM2      | App [coffee:11] starting in -fork mode-
PM2      | App [coffee:11] online

A: To install coffeescript version 1 for pm2 run
pm2 install coffee-script

To install coffeescript version 2 run
pm2 install coffeescript


text:
Q: Include dot operator in mysql like query I need to execute a query like this :-
First-Name Last-Name

Anand     Kumar

Mr.       Abc

select * from ( SELECT CONCAT(first_name ,' ', last_name) as full_name FROM `rm_users`) as a WHERE full_name LIKE '%mr abc%'

Here the like query does not take account the .(dot) in first name and gives no record found where it should.
Also i tried to used regexp query like this :-
select * from ( SELECT CONCAT(first_name ,' ', last_name) as full_name FROM `rm_users`) as a WHERE full_name REGEXP '^["abc"]'

In this second query it gives me both result as characters matches both records.Any solution for this please?

A: If you don't need . remove it:
select *
from ( SELECT CONCAT(first_name ,' ', last_name) as full_name
       FROM rm_users) a
WHERE REPLACE(full_name, '.', '') LIKE '%mr abc%';


text:
Q: Java 1.7.0_45 Update and Eclipse Helios incompatibility issues Anyone else getting this error after Java update to 1.7.0_45 ?
running Eclipse Helios on Windows 8 - x64

A: Quoting Fredrik comment:

Are you using a 64b JRE/JDK and 64b Eclipse? Using different versions will cause issues. See superuser.com/questions/246863/…

This is due to versions incompatibility.


text:
Q: Google map navigation using Google Maps API v2 I am using Google Maps API v2 in my app. I want to enable navigation feature in my app. I have read other posts which start an Intent and open stock Google Maps application to show navigation. But I want to display the navigation inside my application(SupportMapFragment that I have used) only. How can I implement that?
This code works well but it starts an Intent :
Intent NavIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + incAddress));
    startActivity(NavIntent);

A: there is no way to show the google maps app navigation in your app, it is a completely different app. the only way you can display navigation in your app is to use Google Directions API and plot the route on your map but then you dont have the turn by turn directions.
I created a library that uses the google directions api and its easy to use if you want to try it out.
https://github.com/tyczj/MapNavigator


text:
Q: How to log a button press with specific info? I am working on developing a program for my school that tracks when the students leave and come back to class. This program would be on a computer in class, and the students would select their period, name, and where they were going. I have a system already in place where they select their information and press the sign-out button. I will admit there are minor bugs with the program. EX: You can not click the Sign-In or Sign-Out button before all three pickers with the student information are filled out, but if you fill out the pickers, click sign out you can refill out the info click sign out again without aver signing back in.
The next goal that I am stumped on, is to log all signouts sign-out in another Stacklayout that is made visible when you click the log button in the top left of the screen and I want it to push the other elements out of the way so it makes the illusion of switching to another page. I have the idea but I'm not sure how to add a label to the stack layout with the picker info when you click sign-out.
Here is the c# code I have at the moment:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Sign_In_Out
{
    public partial class MainPage : ContentPage
    {
        string[] firstPeriodNames = { "Kid 1", "Kid 2", "Kid 3", " Kid 4" };
        string[] secondPeriodNames = { "Kid 5", "Kid 6", "Kid 7", " Kid 8" };
        string[] thirdPeriodNames = { "Kid 9", "Kid 10", "Kid 11", " Kid 12" };
        string[] fourthPeriodNames = { "Kid 13", "Kid 14", "Kid 15", " Kid 16" };
        string[] fivePeriodNames = { "Kid 17", "Kid 18", "Kid 19", " Kid 20" };
        string[] sixPeriodNames = { "Kid 21", "Kid 22", "Kid 23", " Kid 24" };
        string[] sevenPeriodNames = { "Kid 25", "Kid 26", "Kid 28", " Kid 28" };

        public MainPage()
        {
            InitializeComponent();

            BindingContext = this;
        }

        private void PeriodPicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            Picker picker = sender as Picker;
            var selectedItem = picker.SelectedItem;

            if (selectedItem.ToString() == "1st Period")
            {
                kidSelector.ItemsSource = firstPeriodNames;
            } else if (selectedItem.ToString() == "2nd Period")
            {
                kidSelector.ItemsSource = secondPeriodNames;
            }
            else if (selectedItem.ToString() == "3rd Period")
            {
                kidSelector.ItemsSource = thirdPeriodNames;
            }
            else if (selectedItem.ToString() == "4th Period")
            {
                kidSelector.ItemsSource = fourthPeriodNames;
            }
            else if (selectedItem.ToString() == "5th Period")
            {
                kidSelector.ItemsSource = fivePeriodNames;
            }
            else if (selectedItem.ToString() == "6th Period")
            {
                kidSelector.ItemsSource = sixPeriodNames;
            }
            else if (selectedItem.ToString() == "7th Period")
            {
                kidSelector.ItemsSource = sevenPeriodNames;
            }

            if (PeriodPicker.SelectedItem != null && kidSelector.SelectedItem != null && destination.SelectedItem != null)
            {
                SignOut.IsEnabled = true;
            }
            else
            {
                SignOut.IsEnabled = false;
            }
        }

        private void SignInButton(object sender, EventArgs e)
        {
            SignOut.IsEnabled = true;
            BackgroundColor = Color.ForestGreen;
            SignIn.IsEnabled = false;
        }

        private void SignOutButton(object sender, EventArgs e)
        {
            SignIn.IsEnabled = true;
            BackgroundColor = Color.Red;
            destination.SelectedIndex = -1;
            kidSelector.SelectedIndex = -1;
            PeriodPicker.SelectedIndex = 0;
            SignOut.IsEnabled = false;
        }

        private void kidSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PeriodPicker.SelectedItem != null && kidSelector.SelectedItem != null && destination.SelectedItem != null)
            {
                SignOut.IsEnabled = true;
            }
            else
            {
                SignOut.IsEnabled = false;
            }
        }

        private void destination_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PeriodPicker.SelectedItem != null && kidSelector.SelectedItem != null && destination.SelectedItem != null)
            {
                SignOut.IsEnabled = true;
            }
            else
            {
                SignOut.IsEnabled = false;
            }
        }

        private void LogButtonClicked(object sender, EventArgs e)
        {

        }

        private void AdminButtonClicked(object sender, EventArgs e)
        {

        }
    }
}

And here is the Xamarin code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Sign_In_Out.MainPage"
             BackgroundColor="ForestGreen"
             NavigationPage.HasNavigationBar="False">

    <StackLayout>
        <StackLayout Orientation="Horizontal" HorizontalOptions="End">
            <Button Clicked="AdminButtonClicked" Text="Admin" Margin="0" BackgroundColor="Black" VerticalOptions="End"></Button>
            <Button Clicked="LogButtonClicked" Text="Log" Margin="0" BackgroundColor="Black" VerticalOptions="End"></Button>
        </StackLayout>
        <StackLayout IsVisible="False" x:Name="Admin">

        </StackLayout>
        <StackLayout IsVisible="False" x:Name="Log">

        </StackLayout>
        <StackLayout>
            <Grid>
                <Grid.RowDefinitions>
                   <RowDefinition Height="1*"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                    <ColumnDefinition Width="3*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Picker x:Name="PeriodPicker" SelectedIndex="0" SelectedIndexChanged="PeriodPicker_SelectedIndexChanged" Grid.Column="1" Margin="0, 150, 0, 0">
                    <Picker.Items>
                        <x:String></x:String>
                        <x:String>1st Period</x:String>
                        <x:String>2nd Period</x:String>
                        <x:String>3rd Period</x:String>
                        <x:String>4th Period</x:String>
                        <x:String>5th Period</x:String>
                        <x:String>6th Period</x:String>
                        <x:String>7th Period</x:String>
                    </Picker.Items>
                </Picker>
                <Picker Grid.Column="3" x:Name="kidSelector" SelectedIndexChanged="kidSelector_SelectedIndexChanged" Margin="0, 150, 0, 0"></Picker>
                <Picker Grid.Column="5" x:Name="destination" SelectedIndexChanged="destination_SelectedIndexChanged" Margin="0, 150, 0, 0">
                    <Picker.Items>
                        <x:String>Bathroom</x:String>
                        <x:String>Office</x:String>
                        <x:String>Clinic</x:String>
                        <x:String>Leaving Early</x:String>
                    </Picker.Items>
                </Picker>
            </Grid>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Button x:Name="SignOut" Grid.Column="1" Margin="0, 125, 0, 0" Clicked="SignOutButton" HeightRequest="150" IsEnabled="False" Text="Sign-Out" FontSize="Large"></Button>
                <Button x:Name="SignIn"  Grid.Column="3" Margin="0, 125, 0, 0" Clicked="SignInButton" HeightRequest="150" IsEnabled="False" Text="Sign-In" FontSize="Large"></Button>
            </Grid>
        </StackLayout>
    </StackLayout>

</ContentPage>

Thanks in advance to anyone who can help me out.

A: Instead of using this:
if (PeriodPicker.SelectedItem != null && kidSelector.SelectedItem != null && destination.SelectedItem != null)
        {
            SignOut.IsEnabled = true;
        }
        else
        {
            SignOut.IsEnabled = false;
        }

you should declare a string like this:
...
string[] sevenPeriodNames = { "Kid 25", "Kid 26", "Kid 28", " Kid 28" };
string period = "", kid ="", destination = ""; //<--add this

after you declare the string, you can use it like this:
private void PeriodPicker_SelectedIndexChanged(object sender, EventArgs e)
{
    ...
    ...
    if (PeriodPicker.SelectedIndex != -1)
    {
         period = PeriodPicker.Items[PeriodPicker.SelectedIndex];
    }
}

use that for 2 other SelectedIndexChanged, after that you can use that variable in any method that exist in your application.
Let's say you want to use it in SignOutButton Clicked Event:
private void SignOutButton(object sender, EventArgs e)
{
    if (period != "" && kid != "" && destination != "")
    {
    SignIn.IsEnabled = true;
    BackgroundColor = Color.Red;
    destination.SelectedIndex = -1;
    kidSelector.SelectedIndex = -1;
    PeriodPicker.SelectedIndex = 0;
    SignOut.IsEnabled = false;
    }
}

A: You could create a SignOutLog class:
public class SignOutLog
{
    public string PeriodNames{ get; set; }
    public string KidNames{ get; set; }
    public string Destination { get; set; }
}

then when you click the sign out button,save the SignoutLog information with Preferences:
private void SignOutButton(object sender, EventArgs e)
   {
        SignIn.IsEnabled = true;
        BackgroundColor = Color.Red;
        destination.SelectedIndex = -1;
        kidSelector.SelectedIndex = -1;
        PeriodPicker.SelectedIndex = 0;
        SignOut.IsEnabled = false;

        List<SignOutLog> logs;
        if (Preferences.ContainsKey("sign_out_log"))
        {
            string logsString = Preferences.Get("sign_out_log", "default_value");
            logs = JsonConvert.DeserializeObject<List<SignOutLog>>(logsString);
        }
        else
        {
            logs = new List<SignOutLog>();
        }
        SignOutLog log = new SignOutLog () {PeriodNames=PeriodPicker.SelectedItem,KidNames= kidSelector.SelectedItem,Destination = destination.SelectedItem};
        logs.Add(log);
        string logsJsonString = JsonConvert.SerializeObject(logs);
        Preferences.Set("sign_out_log", logsJsonString);  //save the data

   }

after you clicl the log button,you could push a new page:
 private void LogButtonClicked(object sender, EventArgs e)
  {
       Navigation.PushAsync(new LogsPage());
  }

in your LogsPage,you could define a listview to display the logs:
public partial class LogsPage: ContentPage
{
    public LogsPage()
    {
        InitializeComponent();

    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        string logsString = Preferences.Get("sign_out_log", "default_value");
        List<SignOutLog>  logs = JsonConvert.DeserializeObject<List<SignOutLog>>(logsString);
        yourListView.ItemsSource= logs;
    }
}


text:
Q: What is an algorithm to detect whether all my game pieces are surrounded by nonadjacent enemy pieces? I'm implementing a game in java where the goal is to reach the gameboard's edge. Therefore, if all of one player's pieces are surrounded by not-necessarily-adjacent enemy pieces so that they cannot reach the edge of the board after any number of moves, that player loses.
I'm stumped trying to develop an algorithm to check for this condition. I have approached looking at conditions of both the enemies and the surrounded pieces and made no good progress. Any help would be appreciated.

A: You could use a filling-method. I am assuming you have some kind of board where game pieces are placed. We will use additional pieces of a third color. If there is white and black, lets say your third color is red.
This is one possible algorihtm for white:
Step 1: If there are no empty spaces around the positions of white (or red, see below), you are done: either white is at the border or its surrounded. Return answer (and remove all red pieces, again see below).
Step 2: Find an empty spot (there must be one otherwise you would have ended in step 1), add a red color at the spot. Go back to Step 1.

A: A Delaunay Triangulation gives you the adjacency information of a set of points in arbitrary spatial distribution. There are libraries to do this.
The geometric dual of Delaunay Triangulation is called Voronoi Diagram. The latter concept is maybe a bit easier to understand at first.
In the image you see the Delaunay Triangulation in black, and the Voronoi Diagram in red.
https://en.wikipedia.org/wiki/File:Delaunay_Voronoi.svg


text:
Q: OOP: Is it normal to have a lot of inherited classes? I started writing some code for a 2D game, created a class "objets" trying to keep it as generic as possible. I have a few methods and attributes that are common to every kind of element (buldings, ppl, interface buttons, etc) like (w, h, x, y ...you know) but most of them only make sense when applied to and specific type of item.
So I would have to inherit a new class for every type of actor in the game?
Just wondering if this is a common practice, or maybe i should manage it in a different way.
Thanks in advance.

A: If you're introducing behaviour then subclass, however if the difference is attribute based then don't e.g.
Animal (has .colour and .makeSound) -> Dog (has .eatOwnPoop) -> RedDog (no, too specific, covered by colour)
Notice how I had ".makeSound" in Animal. I could have put .bark in dog, but then I'd have to put .meow in cat etc. The subclass can simply override and provide a concrete sound.
However, you can use interfaces to better cross-cut your code, but that's quite a lengthy topic and probably overkill for your needs (although it could help any unit testing you do).

A: It sounds like you are over-using inheritance. It is certainly a red flag when you simultaneously say "common attributes like ..." and "...only make sense when applied to a specific type." Also, it is a red flag that domain objects such as building share a common base class with an interface object like button. Finally, it is quite unusual to define your own objet (object?) class from which every class in your system derives. It's not inconceivable, but in combination with your other comments, it sounds like you've started down an unproductive path.
You might want to refer to a good tutorial on object-oriented design and analysis such as "Head First OOA&D"

A: You do not HAVE to do anything. Generally, it is useful to use derived classes if they exhibit some kind of commonality but become more specialised in nature requiring specific functionality at each level of inheritance. It is also good to use if you want to have polymorphic behaviour. You have asked a very open ended question but basically do not feel that you HAVE to use inheritance as not every problem requires it and indeed some people overuse inheritance, introducing it in places where it really is not needed. All in all, I would really recommend that if you haven't already that you read a good book on object oriented design as this will then get you to think about your code from a different perspective and greatly improve the way you view software and design it. It may sound like a cop out but this kind of question is very hard to answer without knowing all details of what you are doing.


text:
Q: Tomcat failed to start when shut down port changed to -1 When I tried to change tomcat shut down port from 8005 to -1 and starting tomcat, it did not start and threw an "invalid port number" exception.
Is there any process for changing tomcat shutdown port to -1?

A: From the docs:

port
The TCP/IP port number on which this server waits for a shutdown command. Set to -1 to disable the shutdown port.

So you can set the port value to -1 to disable the shutdown port; note, however, that this is merely a configuration setting of Tomcat as port numbers have positive integer values.


text:
Q: With multiple versions of Lua installed is it possible to specify which one luarock to install to? I have both Lua 5.1 and Lua 5.2 installed on Linux. When using luarocks to install a package is it possible to pass on option to luarocks that specifies which version of Lua the rock should be installed for?

A: Not a command line option, but you may have different variants of the LuaRocks command line program available (luarocks-5.1 and luarocks-5.2) if you installed LuaRocks for both Lua versions.
You can do so from source using (assuming a Debian/Ubuntu-like lua5.1 executable):
./configure --lua-version=5.1 --lua-suffix=5.1 --versioned-rocks-dir
# make sure that you got the correct Lua executable and include directory
sudo make bootstrap

and the same for Lua 5.2.
In case configure's auto-detection does not find the correct executables/directories, the following flags might be of help:

*

*--with-lua-bin=DIR (directory where the Lua executable is installed)

*--with-lua-include=DIR (directory where the Lua include files are)

*--with-lua-lib=DIR (you probably don't need this one on Linux)

When you have done that, luarocks-5.1 install some-package installs the given package for Lua 5.1, and luarocks-5.2 install some-package installs that same package for Lua 5.2.
If LuaRocks was installed via a package manager, multiple Lua versions may or may not be supported (e.g. the Debian/Ubuntu package is configured for Lua 5.1 only).

A: You can use luaver for installing, managing and switching between different versions of lua, luarocks.
To install luaver run:

curl https://raw.githubusercontent.com/dhavalkapil/luaver/master/install.sh -o install.sh && . ./install.sh

Then you can install and use multiple versions of lua as follows:

luaver install 5.3.1             # Installs lua version 5.3.1
luaver install 5.3.0             # Installs lua version 5.3.0
luaver use 5.3.1                 # Switches to lua version 5.3.1

See https://dhavalkapil.com/luaver/ for more details.


text:
Q: I can't view or add comments Hey, there. I just got this site up and going. http://www.paledogstudios.com It works fine except for the fact I can't seem to see past comments (this blog was imported from blogger) or add comments.
I know it's the code not the settings since someone else told me but he didn't help me further.
He said it was probably on the index.php
Help?

A: It appears that your posts titles do not link to the single post pages, they link to the archive page. By example, the lastest article "It really is that small" links to "http://www.paledogstudios.com/2010/10/04/".
The error should be in your theme index.php file.

A: From the looks of things, you're missing a call to comments_template() in your files.  I wouldn't recommend putting this in index.php (that's the file that generates your entire list of blogs ... listing comments there would make your page huge).
What you want to do is add <?php comments_template(); ?> in your single.php file (the template file for Single Posts) before <?php endwhile; ?>.
So an example from the TwentyTen theme:

<?php previous_post_link( '%link', '' . _x( '←', 'Previous post link', 'twentyten' ) . ' %title' ); ?>

<?php next_post_link( '%link', '%title ' . _x( '→', 'Next post link', 'twentyten' ) . '' ); ?>

    <?php comments_template( '', true ); ?>

<?php endwhile; // end of the loop. ?>

You can see they're placing the comment block after contextual navigation but before the loop closes.  This is what you'll want to do in your own theme as well.

A: Please note that enabling comments or Disqus at a time, will not affect old posts. You should add new posts afterward to allow commenting or go to Setting -> Posts -> Quick Edit, to allow comments on a particular post or take a bulk edit action to allow comments on all older posts.
Is commenting for the affected pages closed within WordPress itself? To determine this:

*

*Navigate to your WordPress Dashboard > Posts > click Quick Edit on an affected post

*Make sure the "Allow comments" checkbox is enabled

If comments are enabled within WordPress, a thread can be opened by clicking the "Open thread" link in the thread's Settings dropdown in the Disqus embed on your site. For reference, here's a screenshot:


text:
Q: How to make Android UI that looks exactly the same in every screen? I'm currently working on an Android Application development. I have written a UI Code that looks perfect in Android Simulator But when the same App is run on my Android Smartphone, the UI gets distorted.
I have tried my layouts including LinearLayout, Relative Layout & Constraint Layout but the results are not very much different.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradient"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/Heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-smallcaps"
        android:gravity="center_horizontal"
        android:includeFontPadding="true"
        android:paddingTop="10sp"
        android:paddingBottom="10sp"
        android:text="PHYSICS"
        android:textColor="#FFFFFF"
        android:textSize="30dp"
        android:textStyle="bold"
        android:verticalScrollbarPosition="defaultPosition" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="460sp"
        android:background="#FFFFFF"
        android:orientation="vertical">

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Mechanics" />

        <Button
            android:id="@+id/button5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Oscillations and Waves" />

        <Button
            android:id="@+id/button6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Thermodynamics" />

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Solid States" />
    </LinearLayout>

</LinearLayout>

What do I need to make a UI that looks the same on every Android screen when the screen size is 4 inches or 5.
Original UI on Emulator

This is what it appears on my Smartphone

A: In your layout you have used sp for padding and height and dp for textSize. You should use dp for padding and height (view dimension) and sp for textSize.

A: Try using DP instead of SP. SP is influenced by the Android user's font preferences, which can make it look different.


text:
Q: Autofs with multiple path parameters autofs has a auto.master configuration file that assignes maps files to paths, and in these maps files we can define how to mount subdirectories of the paths from auto.master. These subdirectories can be explicit or we can use * which becomes a wildcard(which we can refer to in the mount options using &). Additionally, if we make a maps file executable it will receive that subdirectory as it's first(and only) argument, and be expected to write the mount definition to stdout.
Now, my problem is that I need 2 wildcards/arguments. I want that if someone tries to access /mymount/<foo>/<bar>, where <foo> and <bar> can be any legal file names, it will create a mountpoint on /mymount/<foo>/<bar> to a target that depends on both <foo> and <bar>. My problem is that the I can only use one wildcard(which is <foo>), and with the executable maps file approach the argument I get is just <foo> and I autofs expects me to return mount options that will be mounted on /mymount/<foo>.
Is what I want even possible with autofs? I can easily find docs for a single parameter, but nothing about using multiple parameters...

A: What you might be able to do is have them combined into one, say foo+bar, so it will be one argument, then have the executable map script split on the + and use the results as the two path parts to use.  But as far as I know autofs (and really any mounting) only takes one argument for the path to mount on, not two.


text:
Q: facebook plugin - share and like I have a web page with photo gallery. At the moment there are 3500+ photos uploaded, so each photo (post) has he's unique link. The facebook comment box and like + send buttons are working, I successfully implemented the META elements (title, description and thumbnail), but I have some trouble or misunderstands.
When somebody like's the photo, why the post isn't showed on he's news feed? It's only showed on he's own wall. I want something like, when you share a video on yo*tube, the video immediately are showed on you're wall and news feed, so everybody can see the shared video.
I want to make some extra visits, but with this method, I only get if somebody visits others wall.
Is there any difference between like and share buttons? If is, where can I find share button plugin?
Here is my code:
<fb:like href='http://www.example.com/index.php?id=XX' send='true' width='450' show_faces='false'></fb:like>

It's XFBML

A: When someone clicks your Like Button, a News Story should also show up in the News Feeds of some of their friends, but this will be inconsistent and based on Facebook's Edge Rank Algorithm.
Facebook no longer officially supports the Share Button, but for now you can still implement it, either with JavaScript:
Share

Or by linking to the Sharer.php app:
Share


text:
Q: How to create a quadrant-circle shape-matrix in Matlab? Currently I have a problem with creating a matrix with a quadrant-shape. The problem is as follow:
I would like to have a 138 x 140 matrix with values of 2 and 3. Inside and on the quadrant circle, the values should be 2. Everything outside the circle, I need to have a value of 3. The radius of the circle is 138 (=R138). Hopefully the image below will support my explanation.

I was thinking of using 'triu' (and then flip) in matlab: then I will not get a circle, but a triangle instead (have not tried it yet). And that is not what I want.
What is the simplest way to create this matrix?

A: You could try this:
a = ones(138, 140)*3;
[gx, gy] = meshgrid(139:-1:0, 137:-1:0);
a(gx.*gx + gy.*gy <= 138*138) = 2;


text:
Q: SBT stop run without exiting How do you terminate a run in SBT without exiting?
I'm trying CTRL+C but it exits SBT. Is there a way to only exit the running application while keeping SBT open?

A: From sbt version 0.13.5 you can add to your build.sbt
cancelable in Global := true

It is defined as "Enables (true) or disables (false) the ability to interrupt task execution with CTRL+C." in the Keys definition
If you are using Scala 2.12.7+ you can also cancel the compilation with CTRL+C. Reference https://github.com/scala/scala/pull/6479
There are some bugs reported:

*

*https://github.com/sbt/sbt/issues/1442

*https://github.com/sbt/sbt/issues/1855

A: I've found the following useful when I have control over the main loop of the application being run from sbt.
I tell sbt to fork when running the application (in build.sbt):
fork in run := true

I also tell sbt to forward stdin from the sbt shell to the application (in build.sbt):
connectInput in run := true

Finally, in the main thread of the application, I wait for end-of-file on stdin and then shutdown the JVM:
while (System.in.read() != -1) {}
logger.warn("Received end-of-file on stdin. Exiting")
// optional shutdown code here
System.exit(0)

Of course, you can use any thread to read stdin and shutdown, not just the main thread.
Finally, start sbt, optionally switch to the subproject you want to run, run.
Now, when you want to stop the process, close its stdin by typing CTRL-D in the sbt shell.

A: In the default configuration, your runs happen in the same JVM that sbt is running, so you can't easily kill them separately.
If you do your run in a separate, forked JVM, as described at Forking, then you can kill that JVM (by any means your operating system offers) without affecting sbt's JVM:
run / fork := true

A: Consider using sbt-revolver. We use it in our company and it's really handy.
For what you're asking can be done with:
reStart

reStop

Without need to configure build.sbt file.
Your can use this plugin by adding:
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")

To your project/plugins.sbt


text:
Q: Left join filtering null values with custom function in where I have a table referencing city table with a key called cityId.
I fetch data from it using this query:
SELECT t.ID, city.areaId FROM transp t
LEFT JOIN city ON city.ID = t.cityId;

Like this, it returns the table as is, with NULL for city.areaId If the cityId was null.
But when I add function to the where clause that is using city.areaId, even function that is always true, the query does not show rows in which the cityId is null. for example:
SELECT t.ID, city.areaId FROM transp t
LEFT JOIN city ON city.ID = t.cityId
WHERE always_true(city.areaId);

Will not show any rows with null cityId. I don't understand why this happens, because I am using an left join and if I put the function in the SELECT, I can see that it indeed is always true.
SQLFiddle

A: Well, though looks like MySQL does some internal optimization that I would say is buggy (converting left join to inner in that case is incorrect) there is a workaround
SELECT t.ID, city.areaId
FROM transp t
LEFT JOIN city ON city.ID = t.cityId
WHERE always_true(coalesce(city.areaId, null));


text:
Q: Node.JS with Mongoose OOP - how to separate mongoose data access code from pure data object? I came across a bit of a design problem with Mongoose - but maybe I am following the wrong approach?
In good old OOP style I want to have a class called User. The class has several member such as username, firstname, lastname, salt and hash, and it has a method called authenticate which takes a hashed password as an argument.
However to fill my User object with data, I need to write code like this, as far as I am aware:
    var userSchema = mongoose.Schema({
    firstName: String,
    lastName:  String,
    userName: String,
    salt: String,
    hashed_pwd:String

});

userSchema.methods =  {
    authenticate: function(passwordToMatch) {

        return crypto.hashPwd(this.salt, passwordToMatch) === this.hashed_pwd;
    }
}

This code is cluttered with Mongoose specific code - calling mongoose.Schema, and to add the method I have to use userSchema.methods.
When I tried to declare my User class separately and tried to create the Mongoose Schema out of it, I encountered all kinds of errors, and the member method was not recognised.
So when I want to use a different database using the same schema, I have to redeclare everything.
But I want to declare all my schemas separately as they will reoccure all over the place in my application.
Is there any elegant solution to this, is there a different library I can use, or am I following a completely wrong approach?
thanks in advance..

A: This is perhaps a partial answer, but it might help guide you in a useful direction.
It's worth understanding what mongoose is and what it does. Mongoose is an ODM (not an ORM—read here for the difference. TL;DR: ODM is to NoSQL as ORM is to SQL; non-relational DB to relational DB.) Mongoose helps abstract some of the boilerplate boring stuff like validations; stuff you want when dealing with a data in or being written into a database. The basis of this validation comes from mongoose.Schema with which you define what each model should contain and what each property on a model should be cast as (i.e. username should be a string, updatedOn should be a datestamp.)
If you want your code to be database-agnostic (that is, not requiring any specific database), Mongoose is not what you're looking for. If not being tied to any specific DB is important to you, you should try looking for a database agnostic ORM/ODM. At the moment, Waterline comes to mind.
It should be mentioned that, if you don't care about validations, data casting, etc. that mongoose provides, you could just roll vanilla MongoDB queries and stick whatever JSON-compatible JavaScript object into your (NoSQL) database. But this is not recommended unless you fully understand what you lose / risk in doing so.
I might also argue that, the authenticate method has no place being in your model and should instead exist in a position previous to any model/database interaction (e.g. in a controller or the equivalent if you're not following MVC conventions.)


text:
Q: When deriving a WPF control, can it be guaranteed that the control's event handler handles the event first? I'm deriving a WPF TextBox control to create a control that only accepts a US currency value as an input.  I'm aware that this has been done before and that there are existing libraries I could use, but this is more of a learning exercise borne from a failed attempt to use one of those existing library controls -- it didn't suit my requirements.
In doing this, I'm trying to prevent the textbox from accepting text that does not fit the US currency format (i.e. optional leading currency symbol, decimal numbers, optional group separators, optional fractional component).  I'm aware that there is the PreviewTextInput event.  Many sources I googled suggested (with much approbation from the community) that one can simply handle this event and reject unwanted input by setting e.Handled = true (setting aside for the moment that this won't work for copy/pasted text, an updated data binding, or a design-time XAML value, to name a few).
I have been wondering whether this approach works all the time.  Given that the order that event handlers are called is not guaranteed, how do I know that my control's event handler is called first?  Put another way: how do I know that someone's event handler doesn't run first and do something else with the value that allows the format I'm trying to disallow and then sets the e.Handled = true?  What about the OnPreviewTextInput method?  I believe that suffers from a similar concern, does it not?

A: It is indeed very good question.As you pointed it is ordered by how you registered the eventhandlers.If you manipulate via reflection at runtime and change the handlers order,it could work as it is expected.I prepared a scenerio just as you told above.
here I defined an attribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomAttribute : Attribute
{
    private int _value;

    public int Value
    {
        get { return _value; }
        set { _value = value; }
    }

    private string _eventName;

    public string EventName
    {
        get { return _eventName; }
        set { _eventName = value; }
    }

    public CustomAttribute()
    {

    }
}

andI created a custom box extended from TextBox
public class CustomBox : TextBox
{
    public CustomBox()
    {
        this.PreviewTextInput += CustomBox_TextChanged;
        this.PreviewTextInput += CustomBox_PreviewTextInput;
    }

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        foreach (var item in typeof(CustomBox).GetRuntimeMethods().ToList())
        {
            var a = item.GetCustomAttributes();

            // unsubscribe
            foreach (var i in a)
            {
                if (i.GetType() == typeof(CustomAttribute))
                {
                    if (((CustomAttribute)i).Value > 0)
                    {
                        RemoveEvent(((CustomAttribute)i).EventName, item.Name);
                    }
                }
            }
        }
        // subscribe according to your order
        var methods = typeof(CustomBox).GetRuntimeMethods()
                  .Where(m => m.GetCustomAttributes(typeof(CustomAttribute), false).Length > 0)
                  .ToList();

        foreach (var item in methods.OrderBy(m => ((CustomAttribute)m.GetCustomAttribute(typeof(CustomAttribute))).Value))
        {
            AddEvent(((CustomAttribute)item.GetCustomAttribute(typeof(CustomAttribute))).EventName, item.Name);
        }

    }
    private void RemoveEvent(string eventName, string methodName)
    {
        EventInfo ev = this.GetType().GetEvent(eventName);
        Type tDelegate = ev.EventHandlerType;
        MethodInfo miHandler = typeof(CustomBox).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
        Delegate d = Delegate.CreateDelegate(tDelegate, this, miHandler);
        ev.RemoveEventHandler(this, d);
    }

    private void AddEvent(string eventName,string methodName)
    {
        EventInfo ev = this.GetType().GetEvent(eventName);
        Type tDelegate = ev.EventHandlerType;
        MethodInfo miHandler = typeof(CustomBox).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
        Delegate d = Delegate.CreateDelegate(tDelegate, this, miHandler);
        ev.AddEventHandler(this,d);
    }

    [CustomAttribute(EventName = "PreviewTextInput",Value = 2)]
    private void CustomBox_TextChanged(object sender, TextCompositionEventArgs e)
    {
        this.Text = e.Text;
        e.Handled = true;
    }

    [CustomAttribute(EventName = "PreviewTextInput", Value = 1)]
    private void CustomBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if (e.Text.Contains("e"))
        {
            e.Handled = true;
        }
        else e.Handled = false;
    }
}

Above, even if someone creates
this.PreviewTextInput += CustomBox_TextChanged;
handler that manipulates
textbox text and change it to unwilling text and blocks another event by e.handle = true;
just before this.PreviewTextInput += CustomBox_PreviewTextInput; is created,
Reflection changes their orders according to how you define.


text:
Q: I need advice how to structure database for storehouse management with C# MySQL Server This question is focused on getting an idea how to structure my database. So there is not going to be any code posted. Please don't mark this questions as "too broad" since my case is specific and I need answer for my specific case.
I am trying to make software for managing stores. Lets say I have a storehouse that can keep lots of products from different types. Lets focus for now on types Tech (laptops, mobile phones, PCs) and Clothes ( jackets, dresses, shoes).
I also have different sections in my storehouse for storing Tech products and Clothes. Since I have lots of different types of products and I think that one table wont satisfy my needs. However if I was to create new table for every type then I would need to hold this products location. This means that I will have lots of tables to check for products when collecting data for the storehouse and doesnot seem as the best solution.
If I was to use MongoDB I could create one table product and not worry about it since I can add properties as I wish and have another collection called storehouse with sections which have products. However in MySQL database I don't think that having big tables with lots of properties is the best solution.
The biggest problem is that I have full freedom to create the database as I see fit as long as it is with MySQL Server. I don't have physical storehouse. This is a project for my uni where we need to create the software as if we had one. Meaning I can have as many sections as I wish and as many product types as I wish. This freedom means there are lots of options for me to create the database but none seem to be effective.
Should I create different tables for every category and store the products there? Should I have one table with the basic information (picture, name, description, price) and in others based on the id to hold the rest of the information? Should I have different sections as individual tables and one table storehouse which will hold every section? Should I create less tables but more compacted or separate everything into lots and lots of tables and relations between them?
What I am looking for is advice on how to make it good following the best practices. Thank you in advance!
And for last - please don't mark it as too broad because I think it isn't. If you however do - please leave a comment to explain why you think that is.

A: I'm going to share some insight even though my first instinct was to vote to close the question. Stackoverflow isn't really the place to get help with conceptualizing your system. Strictly speaking, you should have all of this kind of stuff worked out before you come and ask here, and even then, codereview would be a better place once you have some code written up.
So the way I see it, you'll want at least 3 tables (Categories, Subcategories, Products).

*

*Categories table will be for "Clothes", "Tech", etc.

*Subcategories table will be for "Jackets, Dresses, Shoes" etc".

*Products will be the actual product detail.

To link the data, you'll have a column to reference a record in the other table similar to this:
Categories Table:
    Integer column "Id" - Primary Key, does not allow nulls
    varchar column "Name" - does not allow nulls

Subcategories Table:
    Integer column "Id" - Primary Key, does not allow nulls
    Integer column "CategoryId" Foreign Key references Categories.Id, does not allow nulls
    varchar column "Name" - does not allow nulls

Products Table:
    Integer Column "Id" - Primary Key, does not allow nulls
    Integer Column "SubcategoryId" Foreign Key references Subcategories.Id, does not allow nulls
    <the rest of your product information goes here>

You could add a Category column to your Products table as well but you should always specify a Subcategory. This will allow you to filter products by Category and Subcategory both.
This approach is about as simple as you can get but please next time actually try to do something before you ask.

A: SQL is just not a good way to do this, you could hide it all behind an ORM which would give you the polymorphism you want from the code end.
Optimising and using the database directly will be painful though.
There's an entity attribute value scheme, but very few have enjoyed the results of that...
A compromise design is multiple tables, but only for the extra information. Make anything you want to query cross product category on, e.g. price or quantity generic, put the extras in their own table (or an xml snippet, or serialised name value or some such). This is pretty much what an ORM would do.
Too hard to advise you from here, there are a lot of ways to skin this cat. Also whatever design you come up with, I guarantee the one you choose will end up looking a poor one when some future requirement comes in.
ORM route for me, and plan on always accessing the data via it.


text:
Q: JSON parsing error with CouchDB design document: unclosed string due to indentation whitespaces? I use the following CouchDB design document for testing purposes. I use carriage return \n and tabs \t to indent my Javascript code. As far as I understand JSON, I think that whitespaces in those places are OK. But Ruby couchrest fails parsing that and JSLint too. I have to strip the \n and \t out of the design document before parsing it. Why is that ?
The JSON introduction page on json.org mentions that "Whitespace can be inserted between any pair of tokens. "
It is a little bit difficult to render tabs here so I have included a parsed string with \n and \t.
{
"_id": "_design/test",
"views": {
    "all": {
        "map": "function(doc) {
            if (doc.nom) emit(doc._id, doc);
            }"
        },
    "asin_doc": {
        "map": "function(doc) {
            if (doc.category) emit(doc.asin, doc);
            }"
        },
    "asin": {
        "map": "function(doc) {
            if (doc.category) emit(doc.asin, null);
            }"
        }
    }
    }

The same document in a long string (Ruby):
"{\n\t\"_id\": \"_design/test\",\n\t\"views\": {\n\t\t\"all\": {\n\t\t\t\"map\": \"function(doc) {\n\t\t\t\tif (doc.nom) emit(doc._id, doc);\n\t\t\t}\"\n\t\t},\n\t\t\"asin_doc\": {\n\t\t\t\"map\": \"function(doc) {\n\t\t\t\tif (doc.category) emit(doc.asin, doc);\n\t\t\t}\"\n\t\t},\n\t\t\"asin\": {\n\t\t\t\"map\": \"function(doc) {\n\t\t\t\tif (doc.category) emit(doc.asin, null);\n\t\t\t}\"\n\t\t}\n\t}\n}\n"

JSLint tells me that there is a problem at line 5 character 20.
Problem at line 5 character 20: Unclosed string.
"map": "function(doc) {
Problem at line 5 character 20: Stopping. (25% scanned).
JSON: bad.

I can't see where the string is not properly closed. Any idea ?

A: Newline and tab are not allowed in a string. See the JSON RFC, specifically:
unescaped = %x20-21 / %x23-5B / %x5D-10FFFF

EDIT: What json.org is talking about, I think, is this:

Insignificant whitespace is allowed before or after any of the six structural characters.

The "structural characters" are: [ ] { } : ,


text:
Q: Doing an Access Query with PS Script over VB and writing output in HTA Textbox I am new to PowerShell and got the following Task.
I have to Create a HTA GUI where you can write the Name to search for in the Access Query.
The VB Script in the HTA File starts the PS Script and passes the Parameter of the user Input in the HTA TextBox. After that the PowerShell Script does a Access Query with the user Input to get some results. These results should somehow get back to the VB/HTA File so it can Output every single result in an other TextBox.
Is this even possible to do? If yes, i would appreciate some solution ideas.
EDIT:
VB/HTA
VB/HTA
Wrong Format, should be like a table

A: You have strLine in the HTA code that reads the text file. Your code is reading the text file and taking 1 line and putting it in a text input box.  In order to show the results as a table you need to create the table HTML and pass that HTML to a div element.
strLine = "
"
Do While Not strLines.AtEndOfStream
   strLine = strLine & "
" & strLines.ReadLine() & "
"
Loop
strLine = strLine & "
"
Weiterleitung_div.innerHTML = strLine

You will need to change Weiterleitung_id.value = strLine and instead pass the strLine HTML to a  element in the body.  Add  to the body and then

A: Yes it is possible.  Try the code below with an access database that has 3 fields first_name, last_name, email
Save the file as Employees.mdb (you can use .accdb but you'll have to change the name in code) MAKE SURE THE ACCESS FILE IS IN THE SAME FOLDER AS THE HTA.
I copied in some data from www.mockaroo.com to test it out (I don't get paid to say that it's just very useful)
This is a very basic example but it is possible to create a nicer GUI in an HTA than in Access.
<title>Employee Directory</title>

<HTA:APPLICATION
ID="EMPDIR"
APPLICATIONNAME="Employee Directory"
SINGLEINSTANCE="YES"
>

<meta http-equiv="x-ua-compatible" content="IE=9"/>

<input type="text" id="searchbox" style="font-size:16pt; margin:10px;"/> <input type="button" value="search" name="submitsearch" style="font-size:16pt;" onclick="getEmployeeList" language="vbscript">

-


text:
Q: What hardware profile tool exists for RHEL 5.x similar to `lscfg` or `system_profiler`? I am looking for an equivalent tool or command to dump connected hardware (and optionally software) to a text or XML file for documenting system configuration on RHEL 5.8 specifically.
I am used to lscfg on AIX to dump status of all connected hardware. On Mac, I have system_profiler which dumps both hardware and software details.
Is there a similar tool to these on Red Hat Enterprise Linux that dumps connected hardware information for inventory and discovery purposes?

A: There should be a utility called dmidecode in the path, that sounds like it provides what you are looking for. Some details can be found on the RHEL documentation here.


text:
Q: Python json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) with Spaces in path name I am uploading a file to a REST API with a Python 3 script via the windows command line.  The filename is an argument passed in to the script.  Everything works fine unless there is a space in the path name.  i.e. c:\temp\myFolder\1.jpg works, but c:\temp\my Folder\1.jpg throws an error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The code up until the error is as follows:
def upload_photo(filename):
    f = open(filename, "rb")
    data = f.read()
    data_md5 = hashlib.md5(data).hexdigest()
    f.close()
    r = requests.put('https://upload.mysite.com/{}'.format(filename), data=data)
    response = json.loads(r.text)

I'm not sure how to fix it.  Thanks for the help.
--Edit--
    Full traceback
c:\>python test.py "c:/temp/my folder/1.jpg"

Traceback (most recent call last):

File "test.py", line 144, in <module>
print(test(sys.argv[1]))
File "test.py", line 132, in upload_photo
response = json.loads(r.text)
File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Default\Default\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

A: You need to encode the link properly; escaping the invalid character(s). You can do that with urllib.
>>> import urllib
>>> filename = urllib.parse.quote('c:\temp\my Folder\1.jpg')
>>> 'https://upload.mysite.com/' + filename
'https://upload.mysite.com/c%3A%09emp%5Cmy%20Folder%01.jpg'


text:
Q: variable en 'String' Quiero poner un trozo de codigo html en un return pero dentro del codigo una variable y me salta el siguiente error por consola:

Uncaught SyntaxError: Unexpected identifier

la variable que quiero introducir es sumMinutos, y ya esta declarada e inicializada
$("#canjeador").append(function() {

            return '

<input type="checkbox" value="240" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Factoría Digital: Industria 4.0 (240 mins)

<input type="checkbox" value="270" onclick="contadorTiempoRestante()" class="checkboxTiempo""> Transformación Digital - ERP Inteligente (270 mins)

<input type="checkbox" value="180" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Cómo Potenciar el Liderazgo (180 mins)

<input type="checkbox" value="225" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Encuentro de empresas andaluzas (225 mins)

<input type="checkbox" value="240" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Oportunidades del Entorno Digital (240 mins)

<input type="checkbox" value="240" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Costes transporte marítimo internacional (240 mins)

<input type="checkbox" value="120" onclick="contadorTiempoRestante()" class="checkboxTiempo"> FP Sector Aeroespacial (120 mins)

<input type="checkbox" value="180" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Presentación Tactiómetro 2019 (180 mins)

<input type="checkbox" value="180" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Gemelo Digital (180 mins)

<input type="checkbox" value="90" onclick="contadorTiempoRestante()" class="checkboxTiempo"> Cómo ganar dinero con tu blog y redes (90 mins)
 Tiempo disponible:  <button type="button" id="btnActividades"> 'sumMinutos' 0 H 0 ´ </button> <button type="button">CANJEA TU TIEMPO </button>
'

        });

A: Para poner variables en cadenas se debe usar el backtick `` en lugar de comillas y la variable va entre ${}

let variable = 'hola';
let cadena = `texto en cadena más variable ${variable}`;
console.log(cadena);

A: ¡Si bien te recomiendo usar los Template Literal  `` como lo indica la respuesta anterior, tambien puedes hacer lo siguiente

let variable = 'Hola mundo !!';
let cadena = 'Hola voy a añadir la siguiente variable: '+variable+' ¡Listo quedo añadida!';
console.log(cadena);


text:
Q: systemctl enable fails with cryptic error message I have the following systemd unit file for a Python server using Gunicorn, located at /etc/systemd/system/gunicorn-fizzbuzz.service:
[Unit]
Description=Gunicorn server for FizzBuzz

[Service]
Restart=on-failure
User=deploy
WorkingDirectory=/home/deploy/current/fizzbuzz
EnvironmentFile=/home/deploy/current/fizzbuzz/env/env-fizzbuzz

ExecStart=/home/deploy/current/fizzbuzz/.venv/bin/gunicorn \
    --bind unix:/tmp/fizzbuzz.socket \
    fizzbuzz.wsgi:application

[Install]
WantedBy=multi-user.target

When I try to enable this service with systemctl daemon-reload && systemctl enable gunicorn-fizzbuzz.service, I get the error Failed to lookup unit file state: Invalid argument. Apparently this is a generic systemd error message indicating that something is wrong with my unit file.
I have checked

*

*that a user named deploy exists

*that /home/deploy/current/fizzbuzz exists

*that /home/deploy/current/fizzbuzz/env/env-fizzbuzz exists

*that the ExecStart command works

Can anyone see how this unit file is incorrect? I am running Ubuntu 18.04 with version 4.15.0-144-generic of the Linux kernel.


text:
Q: issue vector layer and marker not plot on both side of dateline at same time Please Help Me vector layer and markers not plot both side of dateline at same time .please check below issue occur same.
 For Vector layer
https://gis.stackexchange.com/questions/20981/openlayers-vector-layer-polygons-not-displaying-properly-with-osm
for marker
i am using openlayer 2 and i am using kml for world map and i show markers with animation cluster
http://acuriousanimal.com/code/animatedCluster/
marker plot same as
http://i.stack.imgur.com/GJR9B.gif