text:
Q: Send parameters to control defined in XAML Is it possible to send parameters to a control defined in a XAML?
For example if I have this XAML:
<UserControl x:Class="Controls.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d">
    <UserControl.Resources>
        <ResourceDictionary Source="..\Colors.xaml" />
    </UserControl.Resources>
    <Grid>
        <Polygon x:Name="plgPoly" Points="0,0 100,0 100,100 0,0" />

    </Grid>
</UserControl>

But when I construct my "Polygon" I want to give it coordinates which depend on the control which contain it (like : this.Height, this.Width, etc...) or on other controls defined in the parent control.
Is it possible? how?

A: If the property that should reference another is a dependency property that can easily be done via a Binding (with RelativeSource), otherwise you may need to construct your own MarkupExtension that fetches the value once (rather than binding it).

A: If you want to use only a simple value or bind to a custom property of owner control, use dependency property mechanism as suggested by H.B.. It is, however, probable, that you would need to convert a value from another type to appropriate one (i.e. PointCollection). In this case, I would suggest using a binding and a value converter to do it. More on value converters can be found here: http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx.


text:
Q: Nginx default_server not working I'm running nginx 1.2.1 with a couple of services. They all use their on domain and listen on 443 only.
I want to lock out people who IP scan my server and don't know the domain. If there is no domain no site should reply. I'm not sure if that's possible because a domain is just a human readable IP?
I've tried a lot but did not get it working.
# Default server
server {
    listen [::]:443 ssl default_server;
    server_name _; # also tried to leave this out
    return 404;
}

If I enable this, none of my other services will reply. Regardless if this is the first or last site (alphabetically). They don't reply neither via IP nor via domain name.
What would be the correct way to reach this?
Edit: More Info
I've six sites defined, including the default catch all site which does not work:
etherpad, nagios, openmediavault-nginx, openmediavault-webgui, owncloud9, zzz-default.

openmediavault-nginx contains only on site, a Piwik instance.
Each site has a server_name assigned. Two sites (nagios and webgui) share an internal server name but have different port numbers. All sites reachable from outsite have te same port (443) but different domain names.
I use dynDNS and CNAME to get my domains working.
When I enter https://<my ip>, I get my owncloud instance. There is a warning, that this domain is not trusted , but it's owncloud.
Here my owncloud listen line
listen [::]:443 ssl ipv6only=off deferred;

The rest of the config is mainly default as linked in the comments.
The question is: Why is owncloud responding even if there is no default or default_site option in it's config?
I've disabled everything except default-catch-all-site and owncloud.
Behavior is the same, if ddefault site is enabled, ownclud would not work.
Default site config is listed above, I added the ssl option.
Owncloud config is:
upstream php-handler {
 # server 127.0.0.1:9000;
  server unix:/var/run/php5-fpm-owncloud.sock;
}

server {
  listen [::]:443 ssl;
  server_name owncloud.mydomain.com
  ssl_certificate /etc/ssl/certs/openmediavault-7e8ef610-4ac4-4e47-9774-453fee8878bf.crt;
  ssl_certificate_key /etc/ssl/private/openmediavault-7e8ef610-4ac4-4e47-9774-453fee8878bf.key;

  # Add headers to serve security related headers
  add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
  add_header X-Content-Type-Options nosniff;
  add_header X-Frame-Options "SAMEORIGIN";
  add_header X-XSS-Protection "1; mode=block";
  add_header X-Robots-Tag none;
  add_header X-Download-Options noopen;
  add_header X-Permitted-Cross-Domain-Policies none;

  # Path to the root of your installation
  root /var/www/owncloud9/;
  # set max upload size
  client_max_body_size 10G;
  fastcgi_buffers 64 4K;

  # Disable gzip to avoid the removal of the ETag header
  gzip off;

  # Uncomment if your server is build with the ngx_pagespeed module
  # This module is currently not supported.
  #pagespeed off;

  #  security settings to reach A+
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_prefer_server_ciphers on;
  ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
  ssl_dhparam /etc/ssl/private/dhparams.pem;
  server_tokens off;

  index index.php;
  error_page 403 /core/templates/403.php;
  error_page 404 /core/templates/404.php;

  rewrite ^/.well-known/carddav /remote.php/dav/ permanent;
  rewrite ^/.well-known/caldav /remote.php/dav/ permanent;

  # The following 2 rules are only needed for the user_webfinger app.
  # Uncomment it if you're planning to use this app.
  #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
  #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;

  # Logging - important for fail2ban
 error_log /var/log/nginx/owncloud_error.log error;
  access_log /var/log/nginx/owncloud_access.log combined;

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  location ~ ^/(build|tests|config|lib|3rdparty|templates|data)/ {
    deny all;
  }

  location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
    deny all;
  }

  location / {

    rewrite ^/remote/(.*) /remote.php last;

    rewrite ^(/core/doc/[^\/]+/)$ $1/index.html;

    try_files $uri $uri/ =404;
  }
location ~ \.php(?:$|/) {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param HTTPS on;
    fastcgi_param modHeadersAvailable true; #Avoid sending the security headers twice
    fastcgi_pass php-handler;
    fastcgi_intercept_errors on;
  }

  # Adding the cache control header for js and css files
  # Make sure it is BELOW the location ~ \.php(?:$|/) { block
  location ~* \.(?:css|js)$ {
    add_header Cache-Control "public, max-age=7200";
    # Add headers to serve security related headers
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;
    # Optional: Don't log access to assets
    access_log off;
  }

A: I use this which seems to work for me. It looks very similar to yours, I wonder if something else in your configuration is causing a problem. Please post the configuration for another server.
# This just prevents Nginx picking a random default server if it doesn't know which
# server block to send a request to
server {
  listen      80 default_server; # add 443 / SSL if you like
  server_name _;
  return      444; # This means "go away", effectively
  access_log off; log_not_found off; # Optional
}

A: The default server config you have shown us is trying to use SSL, but you've provided no SSL certificate. That on its own should be a massive red flag.
My personal experience is that under certain conditions, the default server is relegated to lower in an alphabetic search list of domains (or more specifically config files - I name mine to match the domain name). I was able to remedy this by renaming the file as "_default".

redpajama_set_name: RedPajamaStackExchange


text:
Q: git lfs tracking file of type where size is above So i am using git lfs in my unity project.
Now in unity, a file called .asset doesn't necessarily mean that it is huge but it can grow to a huge amount over time.
my question is:
is it possible to track .asset files that has a size above 50mb ?

A: The git lfs road map (https://github.com/git-lfs/git-lfs/blob/master/ROADMAP.md) lists this as a possible feature; so as of now, that appears to be a no.

A: How about find + git lfs?
find "*.asset" -type f -size +50M -exec git lfs track {} \;


text:
Q: Any way to make terminal control sequences portable? I'm currently in the process of planning out a custom Vim-like editor. It's going to be written in C and I want it to be as portable as possible between as many types of systems as possible.
I'm aware of curses (ncurses, I suppose), the tput command, and how terminals use control sequence (Esc-[ and the CSI character) to change backgrounds, move the cursor, etc.
Of the options above, it seems like ncurses would be the most recommended way of printing for the editor. BUT ncurses also has a LOT of stuff that I rather wouldn't use, and if it's reasonably feasible I'd rather make my own system. I'm not against using it, but .. anyways.
So, my question is: Is there any way to use control sequences in the vast majority of terminals without using a library? Whether through tput or another method?
Thanks!

A: tput(1) uses the terminfo(5) (or older termcap(5)) database, which provides the mapping from abstract commands such as move cursor to x,y to escape sequences for different terminals. When you run a command such as
$ tput cup 10 3 # move cursor to row/column 10/3

, the terminfo database is queried to find the correct string for your terminal, which is then simply written to stdout. To find the available commands (e.g., cup), look at the cap-name column in terminfo(5). tput determines what terminal you are using by looking at the TERM environment variable.
(This means that you can check what escape characters are being generated by simply doing $ tput [command] > [file] and opening [file] in some editor that can show control characters, which can be handy for exploration. The infocmp(1) command can also be used for this.)
If you use tput (or the underlying tputs(3)), your program is hence automatically portable to different terminals. This is what Vim uses by the way.
However -- in the modern world, pretty much all terminals (or terminal emulators rather) use ANSI escape codes, along with some extensions (see XTerm Control Sequences). I believe the escapes supported by xterm and their behavior have become something of a de facto standard at this point, with other terminal emulators simply copying xterm's behavior. Some text-based UI libraries like termbox seem to do away with support for non-ANSI terminals altogether, and output ANSI escapes directly.
Besides the already-mentioned termbox, there's also S-Lang, which includes a terminal handling component. I believe those are the two most popular "ncurses replacements". I'd give ncurses some time first though.


text:
Q: Error in passing arraylist in another activity Here is my declaration
List lstProfilePicture = new ArrayList();
This is my code for calling another activity
Intent i = new Intent(LogoActivity.this, MenuActivity.class);
i.putExtra("Profile", (Serializable) lstProfilePicture);
This is my Profile Class
public class Profile implements Serializable
{
private Long employeeCode;
private Bitmap employeePicture;

public Profile() {
}

public Profile(Long employeeCode, Bitmap employeePicture) {
    this.employeeCode = employeeCode;
    this.employeePicture = employeePicture;
}

public Long getEmployeeCode() {
    return employeeCode;
}
public void setEmployeeCode(Long employeeCode) {
    this.employeeCode = employeeCode;
}
public Bitmap getEmployeePicture() {
    return employeePicture;
}
public void setEmployeePicture(Bitmap employeePicture) {
    this.employeePicture = employeePicture;
}

}
Here is my error message
/AndroidRuntime: FATAL EXCEPTION: main
Process: oras.liv.com.oras, PID: 21484
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
How to I pass with a bitmap in class? Is there another way?

A: Convert it to a Byte array
Activity 1:
try {
    //Write file
    String filename = "bitmap.png";
    FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

    //Cleanup
    stream.close();
    bmp.recycle();

    //Pop intent
    Intent in1 = new Intent(this, Activity2.class);
    in1.putExtra("image", filename);
    startActivity(in1);
} catch (Exception e) {
    e.printStackTrace();
}

In Activity 2, load up the bitmap:
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
    FileInputStream is = this.openFileInput(filename);
    bmp = BitmapFactory.decodeStream(is);
    is.close();
} catch (Exception e) {
    e.printStackTrace();
}


text:
Q: RavenDb. Sorting syntax in Lucene query using Index I am trying to write Lucene query in RavenDB Index which will return results sorted by some field.
But still no success.
The Query looks like:

Language:EN AND Key:*car* AND sort=KEY

Question:
Is it possible at all to add sorting statement in query?
If yes, how the sorting syntax looks like?

A: No. The sort parameter is passed along with the query, but not within the query. If you're using the C# client API you'll have an operator OrderBy, otherwise you're most likely using the REST API, in which the sort parameter is being passed as an additional URL parameter


text:
Q: Hibernate_sequence table is generated I have id column with generated strategy AUTO, I'm wondering, why MySql generate hibernate_sequence table? I supposed that hibernate will pick IDENTITY id generating strategy
<mapped-superclass class="com.cl.xlp.model.data.Identity">
    <attributes>
        <id name="id">
            <column name="id" />
            <generated-value strategy="AUTO" />
        </id>
    </attributes>
</mapped-superclass>

Hibernate properties
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update

Mysql connector version
version.mysql.connector>5.1.39</version.mysql.connector>

Mysql server version is 5.6.12

A: The way Hibernate interprets AUTO generation type has changed starting with Hibernate version 5.0.
When using Hibernate v 4.0 and Generation Type as AUTO, specifically for MySql, Hibernate would choose the IDENTITY strategy (and thus use the AUTO_INCREMENT feature) for generating IDs for the table in question.
Starting with version 5.0 when Generation Type is selected as AUTO, Hibernate uses SequenceStyleGenerator regardless of the database.  In case of MySql Hibernate emulates a sequence using a table and is why you are seeing the hibernate_sequence table.  MySql doesn't support the standard sequence type natively.
References

*

*http://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-auto

*https://www.thoughts-on-java.org/5-things-you-need-to-know-when-using-hibernate-with-mysql/

A: If you use strategy="AUTO", Hibernate will generate a table called hibernate_sequence to provide the next number for the ID sequence. You may have forgotten to add the AutoIncrement feature to your table's PK.
You may use generation strategy strategy="IDENTITY" to enforce using the AutoIncrement feature available in MySql and avoid creating a table.


text: Q: Sharing an Github ssh key I'm trying to share the ssh I created on two machines, one my work laptop and the other my personal laptop in order to be able to make changes and commit to my repos, and also update the activity on my Github timeline. I don't want to create to ssh keys on separate machines if I'm working on two laptops for the same Github account. I came across this post on where to find the key and what to send, but I'm not sure if I can simply use just the rsa.pub file (the public key) by itself and share this same key on both machines, or if I need to copy the entire .ssh folder with it's contents: id_ed25519, id_ed25529.pub and known_hosts files. The ssh was created on my old laptop, which I'm still using, but I'm not sure where to put the key on my new laptop and where it goes.  I'm assuming a .ssh folder at the root?


text:
Q: Mask_RCNN inside a flask server Hello I'm trying to build a simple api to receive an image and return some inference values.
My filesystem is the following:
Mask_RCNN
   |-MaskDetector.py
        |-FireDetector(class)
fire_app
   |-server.py
   |-saved_img

If I open python console and run this:
import sys
sys.path.insert(0, '../Mask_RCNN')
new FireDetector.FireDetector('../trained_weights')
fire_detector.detect('/home/fctmasterthesis/fire_app/saved_img/image7.jpg')

It returns the expected result of inference:
({'rois': array([[ 238,  170,  988, 1359], (...)

But if I run it inside Flask server.py like this:
 from flask import Flask
from flask import render_template
from flask import request, flash, redirect
from werkzeug.utils import secure_filename
import os
import sys
sys.path.insert(0, '../Mask_RCNN')

from MaskDetector import FireDetector
fire_detector = FireDetector('../trained_weights')

UPLOAD_FOLDER = 'saved_img'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
    return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/',methods=['GET', 'POST'])
def hello():
    if request.method == 'POST':
        if 'fire_image' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['fire_image']
        if file.filename == '':
            flash('No selected file')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return fire_detector.detect('/home/fctmasterthesis/fire_app/saved_img/'+'/'+filename)
    return render_template('upload.html')

app.run(host='0.0.0.0',port='80')

While running It gives a code 500 with the following error:
ValueError: Tensor Tensor("mrcnn_detection/Reshape_1:0", shape=(1, 100, 6), dtype=float32) is not an element of this graph.

A: Just run
model.keras_model._make_predict_function()

right after
model.loadweights(...)


text:
Q: Equivalent of brew cleanup in pip I've been looking around for the equivalent of brew cleanup or npm prune for pip (the package manager for python users), but ain't able to find one.
cleanup and prune have done me a huge favor of detecting and removing extraneous and outdated packages on Mac, and the closest I get so far for pip is pip list --outdated --not-required, which only indicates the outdated and no-longer-required packages.
Does such function exist for pip? or has it already been built in some subcommands of pip? If not, can anyone point me to any third-party script that does this?


text:
Q: deb package fails while postinst bash script executing Im making a bash script for nagios custom plugins & configuration
i use equivs for its simplicity
here'is my control file.
in Files: section , i tell files to copy themselves to their right path.
Files: check_cpu_loadx /usr/lib/nagios/plugins
 check_ipmi_sensors /usr/lib/nagios/plugins
 check_libreoffice_count /usr/lib/nagios/plugins
 check_ram_per_user /usr/lib/nagios/plugins
 check_ram_usage2 /usr/lib/nagios/plugins
 check_ram_usage_percentage /usr/lib/nagios/plugins
 check_tcptraffic /usr/lib/nagios/plugins
 nrpe_custom.cfg /etc/nagios

in the postinst section , it's a bash script that is used for post-install
 File: postinst
     #!/bin/bash -e
     set -x
     echo 'configuring nrpe.conf file.'
     mv /etc/nagios/nrpe.cfg /etc/nagios/nrpe.original.backup
     mv /etc/nagios/nrpe_custom.cfg /etc/nagios/nrpe.cfg
     chmod -R +x /usr/lib/nagios/plugins
     echo 'Installing tcp-ip addon..'
     FLAG=0
     Interfaces=`ifconfig -a | grep -o -e "[a-z][a-z]*[0-9]*[ ]*Link" | perl -pe "s|^([a-z]*[0-9]*)[ ]*Link|\1|"`
     for Interface in $Interfaces; do
        INET=`ifconfig $Interface | grep -o -e "inet addr:[^ ]*" | grep -o -e "[^:]*$"`
        MASK=`ifconfig $Interface | grep -o -e "Mask:[^ ]*"      | grep -o -e "[^:]*$"`
        STATUS="up"
        #loopback
        if [ "$Interface" == "lo" ]; then
            continue
        fi
        #if eth is down
        if [ -z "$INET" ]; then
            continue
        fi
         #if eth ip not starts with 10. or 192.
        if [[ "$INET" == 10.* ]]
        then
            ActiveEth=$Interface;
            break
        elif [[ "$INET" == 192.* ]]
        then
        ActiveEth=$Interface;
            break
        else
            echo "Ethernet Selection Failed!Configure nrpe.cfg manually.Change tcp_traffic plugin paramethers according to your current ethernet.";
            FLAG=1
            break
        fi
     done
     if [[ "$FLAG" == 0 ]]
     then
         echo 'Selected Ethernet :'$ActiveEth
         sed -i -e "s/eth0/$ActiveEth/g" /etc/nagios/nrpe.cfg
     fi
     echo 'nrpe.conf changed.'
     echo 'Nagios-nrpe-server restarting.'
     service nagios-nrpe-server restart
     echo 'IPMI modules are loading.'
     modprobe ipmi_devintf
     modprobe ipmi_msghandler
     echo "IPMI modules are added to startup."
     #echo "ipmi_si" >> /etc/modules
     echo "ipmi_devintf" >> /etc/modules
     echo "ipmi_msghandler" >> /etc/modules

the problem here , when i compile it to deb package i got "subprocess installed post-installation script return error exit status 1"
then i added set -x for debugging.the problem is for configuring tcp-ip addon , there are some machines that have more then one ethernet card.So i need to choose with the one that has a ip that starts with 10.* or 192.*
in the second section , there is a line
INET=ifconfig $Interface | grep -o -e "inet addr:[^ ]*" | grep -o -e "[^:]*$"
when a ethernet device has no ip , grep returns null and INET variable becomes null , that why the process exit status is 1.
after that line , when i enter "$?" , it says 1
so the problem here is , when i run dpkg -i to install that package , bash script quits after it sees that INET becomes null ..
any help would be appreciated. Im new to this bash thing.

A: if you want to make sure that a bash command always succeeds, even if the last program gives a non-null return value, just add a "very last" command that will succeed.
something like
INET=$(/sbin/ifconfig eth0 | grep -o -e "inet addr:[^ ]*" | grep -o -e "[^:]*$" || true)

here we call true (a small program that always succeeds), whenever grep fails (|| means OR and is a way to chain programs depending on the exit state of the previous one)
however, your script has a number of flaws:

*

*your grep expression "inet addr:" will only give correct results in an english locale; e.g. when running in a german environment (LANG=de) you could get strings like inet Adresse: 192.168.7.10 (sic!)

*you are unconditionally moving files around; what happens if these files are not there?

*you are unconditionally moving files in /etc. /etc is the place where the sysadmin adjust the system to their needs; you shall not delete or revert the configuration of the sysadmin. you should rather document how to properly configure the system (so the sysadmins can do it themselves); if you insist in "helping" by automatically configuring the system, you should use something like debconf

*you assume that a lot of software is installed, and that this software is in your path. you should probably use fully qualified paths to the binaries you are using, e.g. /sbin/ifconfig rather than just ifconfig


text:
Q: Trying to set a span element equal to a variable value in a JS Rock, Paper, Scissors Game I'm writing a program to play rock, paper, scissors. As I was coding, everything was going fine until I added the:
userScore_span.InnerHTML = userScore;

line. When testing out the win function, I added a console.log('you win'); and it worked fine, but as soon as I added the line from above I got an error when I pressed any one of the three buttons.
I'm trying to relay the result from userScore to userScore_span given that userScore increases after a game is won
userScore++;
userScore_span.innerHTML = userScore;

However, when I press any of the buttons I get an error of:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at lose (app.js:34)
at game (app.js:58)

I am not sure what the chrome Dev tools means by this. How can this be fixed?

let userScore = 0;
let computerScore = 0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById('r');
const paper_div = document.getElementById('p');
const scissors_div = document.getElementById('s');

function getComputerChoice() {
  const choices = ['r', 'p', 's'];
  const randomNumber = (Math.floor(Math.random() * 3));
  return choices[randomNumber];
}

function convertToWord(letter) {
  if (letter === "r") return "Rock";
  if (letter === "p") return "Paper";
  return "Scissors";
}

function win(userChoice, computerChoice) {
  userScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} beats ${convertToWord(computerChoice)}${smallCompWord}. You win!`;
}

function lose(userChoice, computerChoice) {
  computerScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} loses to ${convertToWord(computerChoice)}${smallCompWord}. You lost!`;
}

function draw(userChoice, computerChoice) {
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} equals ${convertToWord(computerChoice)}${smallCompWord}. It's a draw`;
}

function game(userChoice) {
  const computerChoice = getComputerChoice();
  switch (userChoice + computerChoice) {
    case "rs":
    case "pr":
    case "sp":
      win(userChoice, computerChoice);
      break;
    case 'rp':
    case 'ps':
    case 'sr':
      lose(userChoice, computerChoice);
      break;
    case 'rr':
    case 'pp':
    case 'ss':
      draw(userChoice, computerChoice);
      break;
  }
}

function main() {
  rock_div.addEventListener('click', function() {
    game('r');
  })
  paper_div.addEventListener('click', function() {
    game('p');
  })
  scissors_div.addEventListener('click', function() {
    game('s');
  })
};

main();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #24272E;
  font-family: avenir;
}

header {
  background: white;
  padding: 20px;
}

/*header each one*/

header>h1 {
  color: #24272E;
  text-align: center;
}

.score-board {
  border: 3px solid white;
  border-radius: 4px;
  width: 200px;
  margin: 20px auto;
  /*20px (top/bottom) & center (left/right) */
  color: white;
  padding: 15px 20px;
  text-align: center;
  font-size: 46px;
  position: relative;
}

.badge {
  background: #E2584D;
  font-size: 14px;
  padding: 2px 10px;
}

#user-label {
  position: absolute;
  top: 30px;
  left: -25px;
}

#computer-label {
  position: absolute;
  top: 30px;
  right: -30px;
}

.result {
  font-size: 40px;
  color: white;
}

.result>p {
  text-align: center;
  font-weight: bold;
}

.choices {
  text-align: center;
  margin-top: 50px;
}

.choice {
  display: inline-block;
  border: 4px solid white;
  border-radius: 50%;
  padding: 10px;
  margin: 0 20px;
  transition: all 0.3s ease;
}

.choice:hover {
  cursor: pointer;
  background: darkblue;
}

img {
  height: 100px;
  width: 100px;
}

#action-message {
  text-align: center;
  color: white;
  font-weight: bold;
  font-size: 20px;
  margin-top: 20px
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Rock Paper Scissors</title>
  <meta name="description" content="DESCRIPTION">
  <link rel="stylesheet" href="styles.css">

Rock Paper Scissors

user

comp

    0:0

Paper cover rock. You win!

Make your move

A: Beside your typo idea= / id= ...
you could drastically minify your game logic and code by using indexes integers.
Game of integers

*

*Use data-* attribute for user buttons. The attributes should hold numerical values 0, 1, 2. On click, the value will represents the player choice.

*The AI should play numbers too: const AI = ~~(Math.random() * 3) // 0, 1, 2
Now that you know AI and Player both use integers (instead of strange letters combinations), you can store the Move names into an array  const moves = ["Rock", "Paper", "Scissors"]; (where 0 is Rock... etc)
Rock Paper Scissors Logic
The game has three possible round resolutions, PL wins, AI wins, Draw.
Let's convert those "human" values to integers, in the same order:

*

*0 = PL win

*1 = AI win

*2 = Draw

Here's how to calculate those:
Draw
To calculate a Draw is the simplest. It's when both AI and PL integers are equal. Let's return 2
result = PL === AI ? 2

Player wins
To calculate Player win, simply increment AI choice by 1 and do a modulo 3. If the result of this operation is equal to player's choice, than Player must have won! Let's return 0
AI wins
Else, since our game has only 3 possible states, it's not a draw, and it's not a player win, than must be AI win! And let's return 1
const result = PL===AI ? 2 : (AI+1)%3 === PL? 0 : 1; // Possible results: 0, 1, 2

The cool thing in having a game result index based too is that now you can use also an array of messages like messages = ["You won!", "AI won", "it's a draw!", ] and get the desired message by the result index!. And bonus! You can also increment the score array values, 0 being the player's index and 1 being AIs!

const moves = ["Rock", "Paper", "Scissors"],
  messages  = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
  score     = [0, 0, 0],                              // [PL, AI, draw]
  EL = sel => document.querySelector(sel),
  EL_result  = EL("#result"),
  EL_PLScore = EL("#PLScore"),
  EL_AIScore = EL("#AIScore");

function game() {
  const PL = +this.dataset.playermove;  // Get dataset value as integer
  const AI = ~~(Math.random() * 3);     // All you need: 0, 1, 2
  const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw

  score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
  EL_result.innerHTML = `You: ${moves[PL]}<br>AI: ${moves[AI]}<br>${messages[result]}`;
  EL_PLScore.textContent = score[0];
  EL_AIScore.textContent = score[1];
}

// EVENTS:
document.querySelectorAll("[data-playermove]")
  .forEach(el => el.addEventListener("click", game));
<button data-playermove="0">ROCK</button>
<button data-playermove="1">PAPER</button>
<button data-playermove="2">SCISSORS</button>

YOU | 0:0 | AI

A: Typo: idea <> id
Change this:
0:0

to
0:0

let userScore = 0;
let computerScore = 0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById('r');
const paper_div = document.getElementById('p');
const scissors_div = document.getElementById('s');

function getComputerChoice() {
  const choices = ['r', 'p', 's'];
  const randomNumber = (Math.floor(Math.random() * 3));
  return choices[randomNumber];
}

function convertToWord(letter) {
  if (letter === "r") return "Rock";
  if (letter === "p") return "Paper";
  return "Scissors";
}

function win(userChoice, computerChoice) {
  userScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} beats ${convertToWord(computerChoice)}${smallCompWord}. You win!`;
}

function lose(userChoice, computerChoice) {
  computerScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} loses to ${convertToWord(computerChoice)}${smallCompWord}. You lost!`;
}

function draw(userChoice, computerChoice) {
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} equals ${convertToWord(computerChoice)}${smallCompWord}. It's a draw`;
}

function game(userChoice) {
  const computerChoice = getComputerChoice();
  switch (userChoice + computerChoice) {
    case "rs":
    case "pr":
    case "sp":
      win(userChoice, computerChoice);
      break;
    case 'rp':
    case 'ps':
    case 'sr':
      lose(userChoice, computerChoice);
      break;
    case 'rr':
    case 'pp':
    case 'ss':
      draw(userChoice, computerChoice);
      break;
  }
}

function main() {
  rock_div.addEventListener('click', function() {
    game('r');
  })
  paper_div.addEventListener('click', function() {
    game('p');
  })
  scissors_div.addEventListener('click', function() {
    game('s');
  })
};

main();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #24272E;
  font-family: avenir;
}

header {
  background: white;
  padding: 20px;
}

/*header each one*/

header>h1 {
  color: #24272E;
  text-align: center;
}

.score-board {
  border: 3px solid white;
  border-radius: 4px;
  width: 200px;
  margin: 20px auto;
  /*20px (top/bottom) & center (left/right) */
  color: white;
  padding: 15px 20px;
  text-align: center;
  font-size: 46px;
  position: relative;
}

.badge {
  background: #E2584D;
  font-size: 14px;
  padding: 2px 10px;
}

#user-label {
  position: absolute;
  top: 30px;
  left: -25px;
}

#computer-label {
  position: absolute;
  top: 30px;
  right: -30px;
}

.result {
  font-size: 40px;
  color: white;
}

.result>p {
  text-align: center;
  font-weight: bold;
}

.choices {
  text-align: center;
  margin-top: 50px;
}

.choice {
  display: inline-block;
  border: 4px solid white;
  border-radius: 50%;
  padding: 10px;
  margin: 0 20px;
  transition: all 0.3s ease;
}

.choice:hover {
  cursor: pointer;
  background: darkblue;
}

img {
  height: 100px;
  width: 100px;
}

#action-message {
  text-align: center;
  color: white;
  font-weight: bold;
  font-size: 20px;
  margin-top: 20px
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Rock Paper Scissors</title>
  <meta name="description" content="DESCRIPTION">
  <link rel="stylesheet" href="styles.css">

Rock Paper Scissors

user

comp

    0:0

Paper cover rock. You win!

Make your move


text:
Q: Prove the associativity property for orientation-preserving isometries of the Euclidean plane I just started learning group theory and I have to prove the following theorem:

If $\mathrm{I}_{+}(\mathbf{E})$ is the set of all complex functions of the form $f(z)=az+b$ where $a,b,z\in\mathbb{C}$ and $|a|=1$, then
$$\forall a,b,c\in\mathrm{I}_{+}(\mathbf{E}):\, a*(b*c)=(a*b)*c$$
where $*$ is a functional composition on $\mathrm{I}_{+}(\mathbf{E})$.

What I tried:
I know that functional composition is a binary operation on $\mathrm{I}_{+}(\mathbf{E})$. But I keep getting different results, neither of which seems to lead to the desired result.
Associativity can be represented in the functional notation as follows: $f(f(a, b), c) = f(a, f(b, c))$. So
$$f: a,b\mapsto az+b$$
$$f(f(a,b),z)=f(az+b,z)=(az+b)z+z=az^2+bz+z$$
$$f(a,f(b,z))=f(a,bz+z)=az+bz+z.$$
These are equal iff $z^2=z$, but that means that either $z=0$, or $z=1$. So this approach doesn't seem to be correct.
Since multiplying by $a\in\mathbb{C}$ with $|a|=1$ has the effect of a rotation, I tried to look at it from a different perspective: It says that a translation and then a rotation should have the same effect as a rotation and then translation.
$$\text{Translation, then rotation:}\, z\mapsto z+b\mapsto a(z+b)=az+ab$$
$$\text{Rotation, then translation:}\, z\mapsto az\mapsto az+b$$
These are equal iff $a=1$, so this doesn't seem to be the right way either.

A: $f$ is not the function $\langle a, b\rangle\mapsto az+b$ but rather $z\mapsto az+b$. A better notation would be to use subscripts, i.e. $f_{a,b}(z) = az+b$. So you want to show that $f_{a, b}\circ(f_{c, d}\circ f_{e, f}) = (f_{a, b}\circ f_{c, d})\circ f_{e, f}$ which is true since composition of functions is associative.

A: You are not setting up the associative law correctly. What you have to do is to take three elements $f,g,h \in \mathrm{I}_{+}(\mathbf{E})$, each of which has its own formula with its own independent constants:
\begin{align*}
f(z) &= az+b \\
g(z) &= cz+d \\
h(z) &= kz+l
\end{align*}
The operator $*$ is just  function composition:
$$f * g(z) = f(g(z))
$$
Comment: The usual symbol I see for function composition is $f \circ g$, but I'll stick with your symbol $f * g$.
So, work out the formula for $g * h(z)$ and then substitute that for $z$ in the formula for $f(z)$:
$$g * h(z) = c(kz+l)+d = ckz + cl + d
$$
$$f(g * h(z)) = a(ckz + cl + d) + b = ackz + acl + ad + b
$$
Next, work out the formula for $f * g(z)$, and then substitute $h(z)$ for $z$ :
$$a(cz+d) + b = acz + ad + b
$$
and substitute in $h(z)$
$$ac(h(z)) + ad + b = ac(kz+l) + ad + b = ackz + acl + ad + b
$$

A: The statement of the problem seems almost designed to confuse the reader. First they use $a$ and $b$ as elements of $\mathbb C$, when writing $f(z) = az + b$, and then they use them to represent elements of $\mathrm{I}_{+}(\mathbf{E})$ when writing out the condition for associativity. No wonder it's not working.
In particular, $f(f(a, b), c) = f(a, f(b, c))$ doesn't even make sense -- $f\in \mathrm{I}_{+}(\mathbf{E})$ is not a function of two variables. Let's set things up properly and see how that works.
Let's let $f$, $g$, and $h$ be elements of $\mathrm{I}_{+}(\mathbf{E})$. That means that
$$\begin{align}f(z) &= az +b \\
g(z) &= cz + d \\
h(z) &= rz + s
\end{align}$$
where $a,b,c,d,r,s \in \mathbb C$ (and $|a| = |c| = |r| = 1$). Now the question didn't state explicitly what binary operation on $\mathrm{I}_{+}(\mathbf{E})$ you were supposed to use, but as you noticed, when functions are around "composition" is the obvious one to use. So what you have to prove is
$$ (f \circ g) \circ h = f \circ (g \circ h)$$
At this point we can feel a bit silly, because function composition being associative is pretty basic, and we've probably assumed it dozens of times before, but I'd guess they want you to grind it out in this case, so, letting $z$ be a variable that ranges over $\mathbb C$, we have to show that
$$ ((f \circ g) \circ h)(z) = (f \circ (g \circ h))(z)$$
Now, using the definition of function composition and the expressions for $f$, $g$, and $h$ above, you can explicitly compute both sides, and they should end up being equal. (Note: LeeMosher has worked this all out in his answer, but you might want to try writing it out for yourself. You might come across this some time in the future and writing it out should help you recognize it when you see it again.)
Two notes:

*

*We have not shown that $\mathrm{I}_{+}(\mathbf{E})$ is closed under $\circ$, i.e. that if $f, g \in \mathrm{I}_{+}(\mathbf{E})$, then $f\circ g \in \mathrm{I}_{+}(\mathbf{E})$. They didn't explicitly ask for that, but they also didn't explicitly say to use function composition. Morally, since we chose to use composition, I feel that we owe the reader a demonstration of that (it's not hard), but it's up to you (and your grader).

*I think there's a super slick way of showing all this by representing your functions as $2 \times  2$ matrices, and showing that function composition is just matrix multiplication, but I'll leave that as an answer for someone else to provide.


text:
Q: Right command for deploy dll Hi I compiled a dll with .netframework 4.6 and want to deploy to a server ,which has sharepoint 2016 and windows server 2016 ,what is the right command and path for deploy this dll to assembly gac folder.
In windows server 2016
I want PowerShell Command for deploy this DLL.
I want to deploy to C:\Windows\assembly folder
when I go to this path C:\Windows\Microsoft.NET\assembly I found three folders, from this which one is the correct path for assemblies
GAC_32
GAC_64
GAC_MSIL

A: You should be able to deploy the dll to GAC with the following powershell commands:
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("FULL PATH TO DLL")

EDIT:
If you want to check if the dll has been deployed, you can do it with the following powershell command (just replace the values for DllName, Version, Culture and PublicKeyToken with your own values):
[reflection.assembly]::Load("DllName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX")


text:
Q: Change swiper-slide background (Swiper.js) when in darkmode, next.js + tailwindcss darkmode I am using next.js with tailwindcss and Swiper js. I have also implemented a darkmode functionallity. So basically I want to change the background-color of all divs with the class of swiper-slide. I have some png images in every swiper slide and when i toggle the darkmode on I need the background of the swiper-slide to change. So I want to add the class of let say dark:bg-blue-900. I have tried grabbing the swiper-slides in useEffect by using querySelector all and then using a for of loop to add the classes, but the classes doesn't seem to be applied at all when I inspect the elements. How can I add the class? Here is my component
export default function VerticalSwiper() {
  const content = [
    { id: 1, img: PizzaImg },
    { id: 2, img: HamburgerImg },
    { id: 3, img: SteakImg },
    { id: 4, img: Salad1Img },
    { id: 5, img: WineImg },
    { id: 6, img: KebabImg },
    { id: 7, img: SodaImg },
    { id: 8, img: BeerImg },
    { id: 9, img: Salad2Img },
  ];

  useEffect(() => {
    const root = window.document.documentElement;
    if (root.classList.value === 'dark') {
      const swiperSlides = document.querySelectorAll('.swiper-slide');
      for (const swiperSlide of swiperSlides) {
        swiperSlide.classList.add('dark:bg-blue-900');
      }
    }
  });

  return (
    <div className="swiper-container">
      <Swiper
        direction={'vertical'}
        autoplay={{
          delay: 3500,
          disableOnInteraction: false,
        }}
        pagination={{
          clickable: true,
        }}
        modules={[Autoplay, Pagination]}
        className="mySwiper"
      >
        {content.map((item) => (
          <SwiperSlide key={item.id}>
            <SwiperContent img={item.img} />
          </SwiperSlide>
        ))}
      </Swiper>
    </div>
  );
}


text:
Q: Newbie Question-- calling multiple .sql scripts into PHP file I have a PHP file that executes multiple sql scripts. I find that the first two scripts execute, but the last two never seem to complete. I tested the last two scripts individually in their own PHP files and the scripts worked, so I'm wondering if it's because of the number of exec() calls I'm making in my PHP script. Any suggestions? Here's the original script:
<?php
session_start();

$host = "localhost";
$user = "user";
$pass = "pass";
$database = "database";

$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");

$query = sprintf("SELECT dbName FROM users where userName='%s'",
   $_SESSION['MM_Username']);
$resultID = mysql_query($query) or die("Data not found.");

list($dbName)= mysql_fetch_row($resultID);

exec("mysql -u user -ppassword ".$dbName." < ../scripts/makeTblFinalAnalysis.sql");
exec("mysql -u user -ppassword ".$dbName." < ../scripts/tblFinalDetailed.sql");
exec("mysql -u user -ppassword ".$dbName." < ../scripts/TblGridViews.sql");
exec("mysql -u user -ppassword ".$dbName." < ../scripts/makeTblGeo.sql");
header( 'Location: dashboards/dashboard.html' ) ;
exit;
?>

A: Might you be running out of execution time? How long are the scripts taking to run?
Look up set_time_limit() in the PHP documentation; if they take a while to run you will want to raise the PHP execution timeout.

A: "but the last two never seem to complete." perhaps because of some locks on the first two scripts, the third script is deadlocked? you can try to execute these scripts all 4 of them together on your sql server to check if it executes successfully and changes are commited. Also posting the sql queries might help.

A: Try to join all execs into shell script and run it. Then try to run it in background. But then PHP will not wait for script return.
exec("nohup sqlRoutines.sh > /dev/null 2>&1 &");

this will detach script from calling process and redirect stdout and stderr to nowhere (or to logfile if you want...).


text:
Q: Show or Hide form based on radio yes or no selection I am trying to use Jquery to show more or less of form based on what the user selects. If the user chooses Yes then more form is displayed. I plan on doing this with many different top level questions and then unlocking more questions based on yes or no.
At this link this shows what I have.
http://jcsites.juniata.edu/students/bookhjr10/flashpoint/test2.html
The problem I am experiencing is that a user needs to check yes twice for the question to disappear but it should close when the user checks no.
Code:
JQuery
$(document).ready(function(){

   $('.show_hide').showHide({
        speed: 1000,  // speed you want the toggle to happen
        easing: '',  // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
        changeText: 0, // if you dont want the button text to change, set this to 0
        showText: 'Yes',// the button text to show when a div is closed
        hideText: 'No' // the button text to show when a div is open

    });

});

</script>

HTML form:
<form class="form-signin" role="form">
 I am having a Cloud My Office log in issue
<input type="radio" name="myofficeissue" id="0" value="No">No
<input type="radio" name="myofficeissue" class="show_hide" rel="#slidingDiv"  id="1" value="Yes">Yes

        I am having a username and password issue.
      <input type="radio" name="passwordissue" id="passwordissue-0" value="No">No
      <input type="radio" name="passwordissue" class="show_hide" rel="#slidingDiv_2" id="passwordissue-1" value="Yes">Yes

    I need to reset my password
      <input type="radio" name="password" id="password-0" value="No" checked="checked" required> No
      <input type="radio" name="password" id="password-1" value="Yes" required>   Yes

        My username needs updated.
      <input type="radio" name="username" id="username-0" value="No" checked="checked" required> No
      <input type="radio" name="username" id="username-1" value="Yes" required> Yes

My account is locked out
<input type="radio" name="locked" id="locked-0" value="No" checked="checked" required> No
      <input type="radio" name="locked" id="locked-1" value="Yes" required> Yes

I am experiencing other problems
      <input type="radio" name="other" id="other-0" value="No" checked="checked" required>No
      <input type="radio" name="other" id="other-1" value="Yes" required>Yes

CSS

My questions are. Is this the best way to do something like this?
Is there a way to make it so that the No option closes the div?
Any help is appreciated.

A: We can achieve your requirement using jquery change event.
http://jsfiddle.net/mail2zam/vQ4Up/
$(document).ready(function(){
$("input:radio").change(function(){
    console.log(this);
    if(this.value == 'Yes' && this.name == 'myofficeissue'){
        $('#slidingDiv').slideDown();
    }else if(this.value == 'No' && this.name == 'myofficeissue'){
        $('#slidingDiv').slideUp();
        $('#slidingDiv_2').slideUp();
    }else if(this.value == 'Yes' && this.name == 'passwordissue'){
        $('#slidingDiv_2').slideDown();
    }else if(this.value == 'No' && this.name == 'passwordissue'){
        $('#slidingDiv_2').slideUp();
    }
});

});

A: I can see your project getting quite complex so I don't think having all the logic in the javascript would be the right way to go about this. So I've created a sort of logic controller in the javascript and separated out the logic requirements into the html with some data attributes.
Here is the code in action. This solution is now very flexible and easy to maintain. All you need to do is wrap the parts that need to appear and disappear in a div and give them an attribute called "data-view-conditions". This attribute can contain mutiple conditions that need to be met in order for it to display.
The conditions are comma separated and contain an input name and a required value. Which are in turn separated by a colon. This supports both radio and checkbox inputs. You can also supply just a name without a value and the condition will "match" if that input is at least checked or selected without caring about the value. Below are some example conditions.
data-view-conditions="name"

data-view-conditions="name:1"

data-view-conditions="name:1,name2:3,name3:test"

data-view-conditions="name4:123,name5"

JavaScript:
jQuery(function($){

  // Prevents errors in old IE.
  if(!window.console || !window.console.log) window.console = {log: function(){}};

  // Enable debugging for complex logic.
  var debug = true;

  function checkConditions(inputs, views){
    views.each(function(){
      var view = $(this);
      var conditions = view.attr('data-view-conditions').split(',');
      var display = true;

      // Loop over all required conditions to be met.
      for(var i = 0; i < conditions.length; i++){
        var name = conditions[i].split(':')[0];
        var value = conditions[i].split(':')[1];
        var input = inputs.filter('[name="' + name + '"]:checked');

        if(debug) console.log('\nRecalculating view conditions.');

        if(!input.length){
          display = false;
          if(debug) console.log('View not show as no :checked input with the name "' + name + '" was found.');
        }else{
          if(value != undefined && input.val() != value){
            display = false;
            if(debug) console.log('View not show as no :checked input with the name "' + name + '" has the value of "' + input.val() + '". Value needed was: "' + value + '".');
          }
        }
      }

      if(display){
        view.css({display: 'block'});
      }else{
        view.css({display: 'none'});
      }

    });
  }

  $('form').each(function(){
    var form = $(this);
    var inputs = form.find('input[type="checkbox"], input[type="radio"]');
    var views = form.find('[data-view-conditions]');

    // Recalculate which views to be shown each time the inputs change.
    inputs.on('change', function(e){
      checkConditions(inputs, views);
    });

    // Check conditions to set up required view state on page load.
    checkConditions(inputs, views);
  });

});

HTML:
<form>

  Input 1
  <input id="i1" type="radio" name="name1" value="1">

  Input 2
  <input id="i2" type="radio" name="name1" value="2">

Hello

    Click me
    <input id="i3" type="checkbox" name="name2">

It works!

</form>

A: Selecting yes for the first question should always show the next question, and no should always hide the next question. Currently yes is toggling between shown and hidden.
Same with selecting yes or no for the second question and showing the subsequent questions.
As far as good user interface goes, using radio inputs the way you currently are doesn't feel right. If you do use radio buttons, wrap both the radio <input> and the text belonging to it in a  tag so that clicking the text selects the radio. This makes a much bigger target for your user to click on. The same applies for checkboxes.
Radio inputs make more sense when you have to pick one option out of three or more. Two works, but with only two possibilities there are usually more suitable input types. For your last set of questions, checkboxes would make more sense than a series of radios.


text:
Q: Bash script using sed with variables in a for loop? I'm trying to write a bash script that takes a few variables and then does a find/replace with a given file search using grep to get the list of files that have the string. I think the issue I'm having is having the variables be seen in sed I'm not sure what else it might be.
if [ "$searchFiles" != "" -a "$oldString" != "" -a "$newString" != "" ]; then
   echo -en "Searching for '$searchFiles' and replacing '$oldString' with '$newString'.\n"
   for i in `grep $oldString $searchFiles |cut -d: -f1|uniq`; do
      sed -i 's/${oldString}/${newString}/g' $i;
   done
   echo -en "Done.\n"
else
   usage
fi

A: Use double quotes so the environmental variables are expanded by the shell before it calls sed:
  sed -i "s/${oldString}/${newString}/g" $i;

Be wary: If either oldString or newString contain slashes or other regexp special characters, they will be interpreted as their special meaning, not as literal strings.

A: use double quotes so the shell can substitute variables.
for i in `grep -l $oldString $searchFiles`; do
  sed -i "s/${oldString}/${newString}/g" $i;
done

if your search or replace string contains special characters you need to escape them: Escape a string for a sed replace pattern


text:
Q: Working with textfiles and arrays(need explanations) I'm busy working on an old grade 11 question paper and my teacher didn't explain the significance of thing such as (ipos -1) can anyone explain why this needs to be done because at the moment i'm struggling to understand what ipos-1 and the copy and delete function does. code is provided below:
procedure TForm1.CreateBookCode1Click(Sender: TObject);
var icount,k,ipos:integer;
begin
  richedit1.Clear;
  richedit1.Lines.Add('Book Title'+#9+'Book Code');
  for k:=1 to icount do
  begin
    ipos := pos(';',arrBooks[k]);
    arrtitle[k]  := copy(arrbooks[k],1,ipos-1);
    delete(arrbooks[k],1,ipos);
    ipos := pos(',',arrbooks[k]);
    arrsurname[k]:= copy(arrbooks[k],1,ipos-1);
    arrcode[k] := copy(arrsurname[k],1,3) +inttostr(k);

    richedit1.Lines.add(arrtitle[k] + #9 + arrcode[k]);
  end;

A: ipos := pos(';',arrBooks[k]);
 arrtitle[k]  := copy(arrbooks[k],1,ipos-1);
This says "set the k'th element of the arrtitle array to be the string of characters that are before the first semicolon in the k'th element of the arrbooks array.
In other words, the title of each element is the first part of the element, the bit before the semicolon.
The reason for subtracting 1 from ipos is that ipos is the position of the semicolon in the k'th element of arrbooks array.  Subtracting one from the copy means that you don't copy the semicolon.
Note that there appears to be at least two problems here:
1) icount does not appear to be initialised.  It should contain the number of elements in the arrbooks array.
2) In the line that sets ipos, arrbooks is mis-typed: it has a capital B
delete(arrbooks[k],1,ipos);
This says "remove all the characters from the k'th element of the arrbooks array from the beginning up to and including the semicolon (because ipos is pointing at the semicolon in the k'th elemet of the arrbooks array).


text:
Q: Can't manage two get page numbers shown at the outside of a twosided PDF I am trying to change the page numbering from being at the footer's center, to a more book like page numbering where the numbers are always located at the outside of a page (odd page nubmer -> left sided, even page number -> right sided).
I am not very familiar with Lyx, so I don't know which code parts of my Lyx file are relevant to attach here.
I tried using fancy but this didn't solve the problem. Using the code below, the page numbers are always displayed at the right lower corner.
My attempt to  fix it using fancy:
\pagestyle{fancy}
\fancyfoot{}
\fancyfoot[LE,RO]{\thepage}

First 85 lines of my Lyx file:
#LyX 2.3 created this file. For more info see http://www.lyx.org/
\lyxformat 544
\begin_document
\begin_header
\save_transient_properties true
\origin unavailable
\textclass book
\options oneside
\use_default_options true
\begin_modules
customHeadersFooters
\end_modules
\maintain_unincluded_children false
\language ngerman
\language_package default
\inputencoding auto
\fontencoding global
\font_roman "default" "default"
\font_sans "default" "default"
\font_typewriter "default" "default"
\font_math "auto" "auto"
\font_default_family sfdefault
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100 100
\font_tt_scale 100 100
\use_microtype false
\use_dash_ligatures false
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize a4paper
\use_geometry true
\use_package amsmath 1
\use_package amssymb 1
\use_package cancel 1
\use_package esint 1
\use_package mathdots 1
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 1
\use_minted 0
\index Index
\shortcut idx
\color #008000
\end_index
\leftmargin 3cm
\topmargin 3cm
\bottommargin 3cm
\secnumdepth 5
\tocdepth 5
\paragraph_separation indent
\paragraph_indentation default
\is_math_indent 0
\math_numbering_side default
\quotes_style polish
\dynamic_quotes 0
\papercolumns 1
\papersides 2
\paperpagestyle fancy
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

If any further code is needed, feel free to ask me! Thanks

A: You are using the book class but with a onside layout:
\textclass book
\options oneside

You will have to change that to twoside (the default for book). I cannt tell you how to do that since I am not a LyX user.


text:
Q: RegDBKeyExists function fails to read in Installshield We have developed MSI package in Installshiled 2008 Premier Edition and project type is Installscript MSI, recently we bought 2011 and upgrdaded our project to 2011.
In earlier version we used to check the registry entries for Microsoft SQL Express and its path is
**HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL**

Now a new require came to create a package for 64 bit O.S., since O.S. is 64-bit but the registry path for SQL Express in 64 bit is
**HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL**

The registry function RegDBKeyExists is to check SQL registry's presence, but function is returning a negative number as -2147483646 and fails to read.
setting the option REGDB_OPTIONS = REGDB_OPTIONS | REGDB_OPTION_WOW64_64KEY will not help because we not reading 64 bit related registry Hive.

A: Don't worry about it so much; Registry Reflection makes this do the right thing without extra code. When a 32-bit app accesses HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL on a 64-bit machine it will be redirected and see HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL (unless it passes the KEY_WOW64_64KEY - equivalent to the REGDB_OPTION_WOW64_64KEY).
If you hardcode the Wow6432Node key into your query, this scenario will tend to see the keys under a path including HKLM\Software\Wow6432Node\Wow6432Node\... and be unable to find the key you meant to find.

A: As a follow up to Michael's answer and my comment (i.e. question), here's an InstallScript function to toggle registry reflection:
prototype void EnableRegistryReflection( BOOL );
///////////////////////////////////////////////////////////////////////////////
//
// Function:  EnableRegistryReflection
//
//  Purpose:  Toogle the automatic conversion of registry keys from 64 to 32 bit equalivents.
//            This is enabled by default.
//
///////////////////////////////////////////////////////////////////////////////
function void EnableRegistryReflection( bEnable )
begin
    if( bEnable ) then
        REGDB_OPTIONS = REGDB_OPTIONS & ~REGDB_OPTION_WOW64_64KEY;
    else
        REGDB_OPTIONS = REGDB_OPTIONS | REGDB_OPTION_WOW64_64KEY;
    endif;
end;


text:
Q: How to pass data from a form to controller in CakePHP? How do I pass data from a form to controller and then pass it on that data to a model
public function registertest()
    {

    if (!empty($this->data)) {

        var_dump($this->data);

        if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['cpassword'])) {
            $this->User->create();

            if($this->User->save($this->data)) {
                $this->Auth->login($this->data);
                $this->redirect(array('action' => 'index'));
            }
        }
    }
    //$this->render('register');
}

A: Use this Code
 public function registertest()
    {
    if ($this->request->is('post')) {
       $this->data['User']['password'] == $this->Auth->password($this->data['User']['cpassword']);
       $this->User->create();

        if($this->User->save($this->request->data['User'])) {
            $this->Auth->login($this->request->data['User']);

            $msg = '<div class="alert alert-success">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <strong> User Created succeesfully </strong>
            </div>';
            $this->Session->setFlash($msg);
            $this->redirect(array('action' => 'index'));
        }

        }
}


text:
Q: Matrix decomposition dimensions diagram What's the easiest way of making diagrams depicting matrix dimensions such as the following?

I can do it with simple subscripts, but I like the visual effect that these diagrams give.

A: Here is a way to do it "manually."
\documentclass{article}
\usepackage{amsbsy}
\newcommand*{\clap}[1]{\hbox to 0pt{\hss#1\hss}}
\newcommand*{\mat}[1]{\boldsymbol{\mathrm{#1}}}
\newcommand*{\subdims}[3]{\clap{\raisebox{#1}[0pt][0pt]{$\scriptstyle(#2 \times #3)$}}}
\fboxrule=1pt

\begin{document}
\Huge
\[
\framebox[2.5cm]{\clap{\raisebox{0pt}[1.5cm][1.5cm]{$\mat X$}}\subdims{-2.5cm} I J} =
\framebox[1.5cm]{\clap{\raisebox{0pt}[1.5cm][1.5cm]{$\mat T$}}\subdims{-2.5cm} I R} \
\framebox[2.5cm]{\clap{\raisebox{5mm}[1.5cm]{$\mat P^T$}}     \subdims{-1cm} R J} +
\framebox[2.5cm]{\clap{\raisebox{0pt}[1.5cm][1.5cm]{$\mat E$}}\subdims{-2.5cm} I J}
\]

\end{document}

Result:

Obviously this doesn't compare to Mr. Segletes's powerful and general answer! It does use more basic commands, however, which could have the benefits that it's quicker to compile on a slow machine, and it will work even with a smaller installation that's lacking in packages. Or perhaps you just like getting your hands dirty. The drawback, of course, is that you have to determine all the widths, heights, and depths yourself.
Note: if you use mathtools or any other package that provides a \clap command, it will conflict with the definition. In this case, just omit this definition and use the \clap provided.

A: This is one possible solution via amsmath package.

Code
\documentclass[12pt]{article}
\usepackage[margin=1cm,paper size={20cm,5cm}]{geometry}
\usepackage{amsmath,amssymb}

\thispagestyle{empty}
\begin{document}
\[
{\begin{pmatrix}
  &    & \\
  & X &\\
  &     &
\end{pmatrix}
\mkern-10mu}_{I \times J}=
{\begin{pmatrix}
\phantom{T}\\
\makebox[20pt][c]{$T$}\\
\phantom{T}
\end{pmatrix}
\mkern-10mu}_{I \times R}
{\begin{pmatrix}
  &    & \\
  & \raisebox{10pt}{$P^T$} &\\
\end{pmatrix}\mkern-10mu}_{R \times J}+
{\begin{pmatrix}
  &    & \\
  & E &\\
  &    &
\end{pmatrix}
\mkern-10mu}_{I \times J}
\]

\end{document}

A: Here I do it with stacks, setting the indices below the boxes.  The primary macro is
\matbox{rows}{columns}{row index}{column index}{matrix name}.
A helper macro is \raiserows, which is like a \raisebox, except that the "length" is specified in rows, not actual length.  Note that in the MWE, because X has 7 rows, while P^T only has 2 rows, P^T must be lifted (7-2)/2 = 2.5 rows.
I introduce the factor \matscale to scale your box sizes.  By default, each row and column of the box size will occupy a square of size \baselineskip on a side.  The factor \matscale (which defaults to 1) will scale that value.
EDITED to set array indices in \scriptstyle
\documentclass{article}
\usepackage{stackengine}
\stackMath
\newlength\matfield
\newlength\tmplength
\def\matscale{1.}
\newcommand\dimbox[3]{%
  \setlength\matfield{\matscale\baselineskip}%
  \setbox0=\hbox{\vphantom{X}\smash{#3}}%
  \setlength{\tmplength}{#1\matfield-\ht0-\dp0}%
  \fboxrule=1pt\fboxsep=-\fboxrule\relax%
  \fbox{\makebox[#2\matfield]{\addstackgap[.5\tmplength]{\box0}}}%
}
\newcommand\raiserows[2]{%
   \setlength\matfield{\matscale\baselineskip}%
   \raisebox{#1\matfield}{#2}%
}
\newcommand\matbox[5]{
  \stackunder{\dimbox{#1}{#2}{$\mathbf{#5}$}}{\scriptstyle(#3\times #4)}%
}
\parskip 1em
\begin{document}
$\renewcommand\matscale{.6}
\matbox{7}{4}{I}{J}{X} =
\matbox{7}{2}{I}{R}{T} \raiserows{2.5}{\matbox{2}{4}{R}{J}{P^T}} +
\matbox{7}{4}{I}{J}{E}$
\end{document}

Just to clarify, in case it wasn't clear.  One can use actual (very large) matrix dimensions, as long as one scales suitably small.  For example, the following works::
$\renewcommand\matscale{.05}
\matbox{300}{75}{I}{J}{X} =
\matbox{300}{25}{I}{R}{T} \raiserows{137.5}{\matbox{25}{75}{R}{J}{P^T}} +
\matbox{300}{75}{I}{J}{E}$


text:
Q: How to write C++ template functions to call multiple C functions internally? I wish to write a C++ template function which in turn uses some "C" functions and exploits function overloading.
For example, I need to write a function myAbs using templates which make appropriate calls to fabs or abs defined in math.h, based on the input parameter type. How to do this?
#include <math.h>
template<typename T>
T abs(T x)
{
   // I need to write an efficient code here!
   // If it is 'double' and 'float' I may be able to compare  the
   // sizeof(Type) and call 'return fabs(x)' or 'return abs(x)'.
   // But this is not a good solution as two types can be of same size!

}

Note: I simply used it as an example to explain my question. I already know that such a function "abs" is already available in <cmath>.

A: Templates might not be the answer here.  Consider just overloading:
inline float myAbs(float x) { return fabsf(x); }
inline double myAbs(double x) { return fabs(x); }

A: C++17 solution (mostly just for fun), which guarantees that the branch is taken at compile time:
template <typename T>
T my_abs(T x)
{
    if constexpr(std::is_same<T, double>{})
    {
        return std::fabs(x);
    }
    else if constexpr(std::is_same<T, float>{})
    {
        return std::abs(x);
    }
    else
    {
        // Produces a compiler error:
        struct invalid_type;
        return invalid_type{};
    }
}

on wandbox

A: You could use C++11 type traits:
#include <math.h>
#include <type_traits>
template<typename T>
T abs(T x)
{
    if(std::is_same<T,double>::value)
    {
        //do double stuff
    }
    else if(std::is_same<T,float>::value)
    {
        //do float stuff
    }
    else
    {
        //deal with unsupported type
    }
}

Hope that helps.

A: You can explicitly specialize the function templates:
template<>
double abs<double>(double x) {
    return fabs(x);
}

If you want to overengineer more, you can employ tag-dispatch to cut down on the repetition and make up for it in tag selection.


text:
Q: Adding values to Enum in runtime I have enum :
public enum ConsoleMessageType
{
    Error, Info, BackInfo, Success
}

i want to add values to it in runtime, is this possible?

A: No. You should use a dictionary for that.

A: No, this isn't possible.
C# is an strongly-typed language and its nature prevents from supporting such things.
Check this article about expando objects, which is a possible solution for your problem:

*

*http://msdn.microsoft.com/en-us/magazine/ff796227.aspx


text:
Q: Submitting a form to two different locations using JavaScript then validating with jQuery I have a form called #summaryforms, a user can book now or book later.
Here are my buttons:

   <input type="hidden" name="bookingid" value="<?php echo $bookingid; ?>" />
   <input type="button" class="button" value="Book Now" onClick="this.form.action='payment.php';this.form.submit()">
   <input type="button" class="button" value="Book Later" onClick="this.form.action='poa.php';this.form.submit()">

However whenever I try to use jQuery Validation such as:
$("#summaryforms").validate();

It doesn't work and I get no errors, I suspect it is because it submits before the jQuery is called, is there a way around this while still maintaining the option to submit to two different locations?

A: Remove the inline onClick handlers from your button elements.  You're using jQuery which negates any need for inline JavaScript.  Secondly, since the jQuery Validate plugin already has the submit event handler built-in, you'll need to place your buttons outside of the <form></form> and capture their click events separately.
I removed the inline onclick handlers and added id attributes.  I also self-closed your input tags with a />.
HTML:
<form id="summaryforms">
    ...
</form>

   <input type="hidden" name="bookingid" value="<?php echo $bookingid; ?>" />
   <input type="button" class="button" value="Book Now" id="now" />
   <input type="button" class="button" value="Book Later" id="later" />

jQuery:
$(document).ready(function() {

    $('.button').each(function () {
        $(this).on('click', function () {
            var action;
            if ($(this).attr('id') == "now") {
                action = 'payment.php';
            } else {
                action = 'poa.php';
            }
            $('#summaryforms').attr('action', action).submit();
        });
    });

    $('#summaryforms').validate({ // initialize the plugin
        // any options and/or rules
    });

});

DEMO: http://jsfiddle.net/a9zAh/

EDIT:
Quote OP:

"... I suspect it is because it submits before the jQuery is called ..."

It should not.  Calling a submit() should only trigger the validation since the plugin has a submit event listener built-in.  There may be another problem in your code you have not shown us in your OP.  Perhaps there is a problem with how you've defined your rules.  Also, your id is summaryforms; why is that plural?  id's should be unique and if you have more than one form, or any element, on the page sharing an id="summaryforms", that will cause problems.
Follow my working code and jsFiddle demo above as your model and ask questions if you get stuck.

A: Absolutely. You want to "capture" the normal submit, prevent it from happening, then do your validation.
To stop the form from submitting, make sure it has an ID (which it seems like you do), and use something like this:
// on DOM load...
jQuery(function () {
    // attach a handler to the SUBMIT of your form
    jQuery('#summaryforms').submit( function () {
       // do validation or whatever, and if it passes, return true
       // to submit
       if (myFormIsValid) {
           return true;
       }
       // otherwise, prevent it from submitting "normally"
       return false;
    });
});

A: Problem is combining both javascript and jQuery. In General, javascript is take precedence than jQuery. If you are doing this, Some browser like IE produce unexpected result. And try as follows,
Edited Script:
In jQuery,
 $(document).ready(function(){

    $("#summaryforms").validate();

   $("#summaryforms input.button").click(function(e){
     var action = '';
     if($(e.target).val() === 'Book Now'){
       action = 'payment.php';
     }else if($(e.target).val() === 'Book Later'){
       action = 'poa.php';
     }
     $("#summaryforms").attr('action', action);
     $("#summaryforms").submit();
   })

  });

In HTML,

   <input type="hidden" name="bookingid" value="<?php echo $bookingid; ?>" />
   <input name="booknw" type="button" class="button" value="Book Now" >
   <input name="booklater" type="button" class="button" value="Book Later" >


text:
Q: No 'Access-Control-Allow-Origin' header is present on the requested resource not solved with Php header I want to get a URL with Ajax like this:
$.ajax({url: "http://techparty.ir/e.php", success: function(result){
        $("#div1").html(result);
    }});

The error is this:
XMLHttpRequest cannot load http://techparty.ir/e.php?_=1437826051819. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.com' is therefore not allowed access.

As I've tried to search about this problem. But I couldn't, for example these links:
https://www.daniweb.com/web-development/php/threads/461902/php-header-is-not-working-for-access-control-allow-origin
No 'Access-Control-Allow-Origin' header is present on the requested resource error
Recommends that place this code on top of Php file:
header("Access-Control-Allow-Origin: *");

But not worked. this is my source code(e.php):
<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Credentials: true ");
    header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
    header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size,
        X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
    echo "ehsan";
    ?>

How to solve this problem?

A: Simply add this code to .htaccess file:
<IfModule mod_headers.c>
   Header set Access-Control-Allow-Origin "*"
 </IfModule>


text:
Q: Преобразование из строки в число на си Есть у меня строка введенная с клавиатуры. Нужно из этой строки получить число. Число берется вначале строки если строка будит вида 123 вася пупкин то итоговое число 132
Форматы ввода следующие:
0xac
0b1101
123
564.75

Написал следующий код:
char text[256];

memset(text,0,sizeof(text));

popStrCalc(&StrCalc, text); // выгрузка из стека

char * p2=text;

if(*p2 == '0'){
        switch (*(p2+1)) {
            case 'x':
            case 'X':{
                resI = strtol(p2+2,NULL,16);
                    pushMcalcI(&MCALC,resI); // загрузка в стек
                break;
            };
            case 'b':
            case 'B': {
                resI = strtol(p2+2,NULL,2);
                    pushMcalcI(&MCALC,resI);
                break;
            };
        }
}
else{
    resI = strtol(text,NULL,10);
        pushMcalcI(&MCALC,resI);
}

Проблема не могу понять как можно отличить числа float от int. Преобразовать float хочу '(float)strtod(text,NULL);'.

A: Отличить можно по простому признаку - в float есть либо точка либо буква e
if (strchr(text, '.') == NULL && (strchr(text, 'e') == NULL || strchr(text, 'E') == NULL)) {
    puts("it looks like float");
}

но можно заменить на одну функцию
if (strpbrk(text, ".eE") != NULL) {
    puts("it looks like float");
}

и есть ещё один случай - если число слишком длинное. Оно хоть и выглядит как целое, но в 32/64 может не влезть. Тут уже по обстоятельствам.


text:
Q: Cannot set property Id value in EF CORE if property is included in select I am using Entity Framework 2.0.1 and I have having a problem that was working fine in pre 2.x versions of EF.
If I select an object and include a property in the selection and I want to update that property, I must update the object reference, not the Id referencing the object for EF to recognize and save the change.
Here is an example.
Ranking.RankTypeId is a foreign key to RankType.RankTypeId. I select and include the RankType property.
public Ranking GetRankingById(int rankingId)
{
    using (var context = new BestNetDatabaseContext())
    {
        var rankings = context.Rankings.AsQueryable();

        var foundRanking = rankings.Include(x => x.RankType).FirstOrDefault(x => x.RankingId == rankingId);

        if (foundRanking == null)
            throw new RankingNotFoundException();

        return foundRanking;
    }
}

If I want to update the Ranking.RankType, I must select and get an instance of the RankType object and set that.
ranking.RankType = _rankTypeService.GetRankTypeById(1);

What I would like to do (and have been doing for years) is just set the Id.
ranking.RankTypeId = 1;

I am attaching the object to the context and setting the state to dirty before saving changes (this code was working in previous versions of EF CORE).
public void UpdateRanking(Ranking ranking)
{
    using (var context = new MyDatabaseContext())
    {
        context.Rankings.Attach(ranking);
        context.Entry(ranking).State = EntityState.Modified;
        //ranking.RankTypeId IS correctly set to 1 at this point
        context.SaveChanges();
    }
}

If I do not use the include statement, I can set the Id and EF will recognize the change and update the database fine. It just seems to ignore updating the Id when I include the property. Thoughts?


text:
Q: R convert data.frame to json I'm trying to convert a data.frame into json format
my data.frame has the following structure
a   <- rep(c("Mario", "Luigi"), each = 3)
b   <- sample(34:57, size = length(a))
df  <- data.frame(a,b)
> df
      a  b
1 Mario 43
2 Mario 34
3 Mario 36
4 Luigi 45
5 Luigi 52
6 Luigi 35

What I want to create is something like this (to finally print it to a .json file)
[
  {
    "a": "Mario",
    "b": [43, 34, 36]
  },
  {
    "a": "Luigi",
    "b": [45, 52, 35]
  }
]

I've tried different packages handling json format but so far failed to produce this kind of output. I usually end up with something like this
[
  {
   "a":"Mario",
   "b":43
  },
  {
   "a":"Mario",
   "b":34
  },
  {
   "a":"Mario",
   "b":36
  },
  {
   "a":"Luigi",
   "b":45
  },
  {
   "a":"Luigi",
   "b":52
  },
  {
   "a":"Luigi",
   "b":35
  }
]

A: If you nest b as a list column, it will convert correctly:
library(jsonlite)

# converts b to nested list column
df2 <- aggregate(b ~ a, df, list)

df2
##       a          b
## 1 Luigi 49, 42, 37
## 2 Mario 46, 50, 45

toJSON(df2, pretty = TRUE)
## [
##   {
##     "a": "Luigi",
##     "b": [49, 42, 37]
##   },
##   {
##     "a": "Mario",
##     "b": [46, 50, 45]
##   }
## ]

or if you prefer dplyr:
library(dplyr)

df %>% group_by(a) %>%
    summarise(b = list(b)) %>%
    toJSON(pretty = TRUE)

or data.table:
library(data.table)

toJSON(setDT(df)[, .(b = list(b)), by = a], pretty = TRUE)

which both return the same thing.

A: To get the required JSON structure you will want your data in a list, something like:
l <- list(list(a = "Mario",
               b = c(43,34,36)),
          list(a = "Luigi",
               b = c(45,52,35)))

## then can use the library(jsonlite) to convert to JSON

library(jsonlite)

toJSON(l, pretty = T)

[
  {
    "a": ["Mario"],
    "b": [43, 34, 36]
  },
  {
    "a": ["Luigi"],
    "b": [45, 52, 35]
  }
]

So to split your data into this format, you can do
l <- lapply(unique(df$a), function(x) list(a = x, b = df[a == x,"b"])   )

## and then the conversion works
toJSON(l, pretty = T)

[
  {
    "a": ["Mario"],
    "b": [44, 49, 50]
  },
  {
    "a": ["Luigi"],
    "b": [39, 57, 35]
  }
]

This works for the simple case, but if it gets more complex it might be better to re-design how you create your data.frame, and instead create a list(s) to begin with.

Reference
The jsonlite vignette is a very good resource.


text: Q: How should I determine degrees of freedom for t-test in ordinal regression? I consider a proportional odds (ordinal regression) model, as described in Agresti (2002) and estimated by R base package function MASS. The software reports t-values but no p-values in summary. I wonder how I should determine the degrees of freedom for the t-test. In simple linear regression $df=n-2$ where $n$ the sample size. Is this also the case for ordinal linear regression?


text:
Q: Godot engine collision with KinematicBody doesn't work I was fiddling around with the Godot engine and tried a little game.
But I can't seem to get an info on colliding.
if is_colliding():
    print ("Collision with " + get_collider())
    get_node("Sprite").set_texture(walk_cycle_right_1)
    move_state_right = 1
    set_pos(Vector2(get_pos().x -10, get_pos().y))

It always prints false. I'm moving my character (KinematicBody2d -> Sprite/CollisionShape2d) with the set_pos command.

A: For the kinematicbody you need to use move or move_to to trigger the collision.
If you really need to use set_pos, check collisionshape2d.shape and do the collision check yourself.
There is an example on Godot documentation where KinematicBody2D movement and collisiong handling is introduced: http://docs.godotengine.org/en/stable/tutorials/2d/kinematic_character_2d.html
Full definition for KinematicBody2D class is available also at Godot Documentation:
http://docs.godotengine.org/en/stable/classes/class_kinematicbody2d.html?highlight=KinematicBody2D


text:
Q: Django: reverse parametrized url in JavaScript let's say one of my urlpatterns looks like this.

url('^objects/update/(?P<pk>\d+)$', views.UpdateView.as_view(), name = 'update-object'),

I need to redirect user to the update page depending on the selected object (the list of objects is populated using Ajax). So I'd like to pass that named url pattern to the JavaScript, in order to build the actual url on the client side.
Example of what I want to achieve:

*

*pass the name 'update-objects' to the function

*get the actual url pattern, replace (?P<pk>..) with {pk}

*pass the result to the javascript, resulting in : objects/update/{pk}
any tips?
thanks

to make it more clear: at the moment of rendering, I can't do url reverse because the PK is not known yet. I need to make kind of javascript-urlpattern which will later be converted to the real url (i.e. my JS code will replace {pk} part with the actual pk value)

A: The actual URL reversing must happen on the server side.  There are several ways to do this, and the most elegant of these probably depends on how exactly your script and markup are set up for this.  One thing I've done recently is to attach the URL to a logical element using HTML5 data attributes, which are easy to retrieve using jQuery.  If you're not using jQuery, I'll leave it up to you to translate to pure JS.  You haven't provided any code or specifics for your client-side, so I'm kind of shooting in the dark here, but maybe this will give you the idea:
Django HTML template:

 {% for object in objectList %}

object.name

 {% endfor %}

JS:
$('.object-list').on('click', 'li' function () {
  var updateUrl = $(this).data('update-url')
  ...
});

A: It sounds like you need to make an additional ajax call once the object has actually been selected. Don't try and second guess your url.conf by trying to work out the url on the client side - you'd just be making trouble for yourself later. Wait till you can get a pk, then use django's reverse function to give you your url (doing anything else violates DRY).
How about creating a simple view that returns the url -
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest

def get_url(request):
    if request.is_ajax() and request.method == 'POST':
        obj_id = request.POST['obj_id']
        url = reverse('object-update', kwargs{'pk': obj_id})
        return HttpResponse(obj_id)
    return HttpResponseBadRequest()

Then write a javascript function that gets the url using an ajax call to your new view and then redirects. You'd call this function as soon as the object's been selected. I would suggest using JQuery to do this, pure javascript will require you to write more code, and probably write browser specific code (depending on your target). Also it supports dealing with django's csrf protection (you'll need to implement this for ajax calls if you haven't already).
var redirect = function(obj) {
    $.ajax({
        url: '/your-get-url-view/',
        method: 'post',
        data: {'obj_id': obj},
        success: function(url){
            window.location = url;
        }
    });
}

I'm afraid I don't know how you're getting from the selected object to the pk (For simplicity I've assumed it's available to the redirect function) - you may have to do some processing in the view to get there.
I haven't tested the above code, but it should give you an idea of what I'm suggesting.

A: Try this one:
Reverse method for generating Django urls
https://github.com/mlouro/django-js-utils
One more
https://github.com/Dimitri-Gnidash/django-js-utils

A: If you have a URL that only has one PK field in it, you could resolve it with any number (e.g. 0), then substitute the number as required.
In my scenario my URL had a pk then an upload_id, so I had to replace on the right most instance of a 0, with <upload_id>, which the JS would replace this string occurance as required:
detele_url_upload_id_0 = reverse(f'{APP_NAME}:api_upload_delete', args=[pk, 0])
prefix, suffix = detele_url_upload_id_0.rsplit('0', 1)
context['generic_delete_url'] = prefix + '<upload_id>' + suffix

Then in the JS:
const deleteUrl = genericDeleteUrl.replace('<upload_id>', uploadId)


text:
Q: Bind "src" attiribute in audio tag within vue code try to bind src of audio tag invue code bur does not work ..
Note that object (surah) is api json object ..
this is my code :
<audio controls class="audio">
<source :src="'@/data/mp3/' + surah.source" type="audio/mpeg">

عفوًا متصفحك لا يدعم تشغيل الأصوات، قم بتحديثه أو استخدم متصفح آخر.

</audio>

rest of code work will (use api) except for this ..

A: *

*Make sure the surah object is available in component's data

*Make sure if the mp3 files are stored in a data/mp3 folder

*Make shure the source proprety of surah object is a valid string that represents the name of mp3 file (Ex: file_audio.mp3)

*try this example:

template:

<audio controls class="audio">
    <source :src="`@/data/mp3/${surah.source}`" type="audio/mpeg">

عفوًا متصفحك لا يدعم تشغيل الأصوات، قم بتحديثه أو استخدم متصفح آخر.

</audio>

script
export default {
  data() {
    return {
     surah: {
      name: 'يونس',
      Number: 10,
      'Number of Verses': 109,
      'Makki/Madani': 'مكية',
      Theme: 'قصص الأنبياء',
      source: '010.mp3',
     },
    }
  }
}


text:
Q: how to get data from multiple tables in sql using php i have 4 tables in my db
(0)users
user id,user name,password
(1)messages
user id,user name(fk),message,location,time
(2) images
user name(fk),image id,image path,time
(3)videos
user name(fk),video id,video path,location,time
i want to show data from multiple tables
what will be query syntax  to do it
i want to show like
"rana " has upload this image and this video and this messages"
image  should be select from images table video from video tables and message from message table
thanks
sorry if question already asked
thanks please help

A: Your expected mysql query is :
select *from users a
join messages b on a.user_name = b.user_name
join images c on a.user_name = c.user_name
join videos d on a.user_name = d.user_name

Example (MySQLi Procedural) & PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "select *from users a
join messages b on a.user_name = b.user_name
join images c on a.user_name = c.user_name
join videos d on a.user_name = d.user_name";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "User Name: " . $row["user_name"]. "
";
        echo "Message: " . $row["message"]. "
";
        echo "Image Path: " . $row["image_path"]. "
";
        echo "Video  Path: " . $row["video_path"]. "
";
        //you get more data as your wise................
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>


text:
Q: Spring MVC. Ошибка при использвании OkHttp3 Есть контроллер
import airtickets.parser.Example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ExampleController {
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(Model model) {
        try {
            model.addAttribute("body", new Example().getBody("http://square.github.io/okhttp/"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "test";
    }
}

Класс Example
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Example {
    public String getBody(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

test.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${body}
</body>
</html>

И мой стакстрейс
HTTP Status 500 – Internal Server Error

Type Exception Report

Message Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: okhttp3/OkHttpClient

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: okhttp3/OkHttpClient
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:982)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

java.lang.NoClassDefFoundError: okhttp3/OkHttpClient
    airtickets.parser.Example.getBody(Example.java:10)
    airtickets.controller.ExampleController.test(ExampleController.java:15)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/9.0.0.M26


text:
Q: Can't boot on Lenovo Ideapad 110 14ast I tried to install Ubuntu 19.10 alongside dualboot with my Windows 10, I succeded created a bootable usb with Rufus in Windows 10. I did reboot my pc and started boot menu I choosed My USB Flashdisk as primary boot option, after a while the screen show the grub of ubuntu there are some options and I entered Install Ubuntu.
The screen goes black a while and the error messages appeared with "Initramfs unpacking failed: broken padding" in the top of the message.
What is This messages?
How to resolve This?
Thank you.


text:
Q: Wordpress Gallery This website is based on wordpress, I wonder which plugin/theme are they using to customize wordpress into a gallery/download site.
Many thanks for your help!

A: I think you can do this with WordPress' thumbnail feature. You can assign a thumbnail to each post. It looks like that, and some tweaking to the theme in the way the posts are displayed and the download button is included.
Maybe there's a plugin to assign a file to download on each post, that's the only part I find complex in this theme.
Check these links:

*

*http://www.wpzoom.com/design/10-wordpress-themes-designed-for-photo-galleries/

*http://wordpress.org/extend/plugins/search.php?q=download


text:
Q: HTTP requests from Google Compute Engine to Appengine Standard Is it possible to make secure HTTP requests from Google Compute Engine GCE to Google AppEngine GAE, without using service accounts and enabling the endpoints service (proxy) on the GAE service? Most of our backend HTTP handlers don't need the endpoints service proxy enabled, as the requests are all internal and not from the public. Our public API uses the compute engine endpoints service..
handlers:
- url: /securehandler/.*
  script: main.app
  login: admin

https://cloud.google.com/appengine/docs/standard/go/config/appref#handlers_element
"Note: the admin login restriction is also satisfied for internal requests for which App Engine sets appropriate X-Appengine special headers. For example, cron scheduled tasks satisfy the admin restriction, because App Engine sets an HTTP header X-AppEngine-Cron: true on the respective requests. However, the requests would not satisfy the required login restriction, because cron scheduled tasks are not run as any user."
https://cloud.google.com/appengine/docs/standard/go/appidentity/
"Asserting identity to other App Engine apps
If you want to determine the identity of the App Engine app that is making a request to your App Engine app, you can use the request header X-Appengine-Inbound-Appid. This header is added to the request by the URLFetch service and is not user modifiable, so it safely indicates the requesting application's ID, if present.
In your application handler, you can check the incoming ID by reading the X-Appengine-Inbound-Appid header and comparing it to a list of IDs allowed to make requests."
Obviously no X-AppEngine and X-Appengine-Inbound-Appid headers are set when making HTTP requests with the Go client in GCE.
Edit:

*

*url: /securehandler/.*
script: _go_app
login: required
secure: always

Will default service accounts authenticate if login is set to required?

A: If you do an HTTP request from GCE it will not include any credentials, so will not appear as logged-in. GAE does not provide a mechanism for API calls to pass login:required.
GAE does provide authentication as part of Cloud Endpoints. You can use this to authenticate requests from GCE.


text:
Q: Is the difference between "page views" and "visits" in the site analytics tool documented anywhere? The Site Analytics tool, accessible to users with 25k reputation or more, includes a "Traffic" graph that has three curves:

*

*page views

*visits

*new visits

I was not sure what the difference between a "page view" and a "visit" was, so I searched for it on Meta. However, neither the privilege page nor the FAQ nor the feature announcement post seem to contain this information. The announcement post contains the not so helpful sentence

*

*Traffic — Includes the existing "Number of Visits", "Number of New Visits", and "Total Page Views" in one graph. The data series are relabeled "visits", "new visits" and "page views".

I finally found what I think to be the answer by reading about the common meaning of these two concepts on external websites (it seems that a "view" is counted every time someone loads an SE page, and a "visit" is counted only when someone loads a page coming from an external site).
Is this documented anywhere inside the SE network? If not, can it be documented? Something like a hover text on the words "page views" / "visits" would be helpful.
(I could add the explanation myself to the feature announcement post, but for that I would need to be sure that my interpretation of the meaning is correct).

A: These figures are copied directly from the Google Analytics API.

*

*Page view matches what you describe.

*A 'visit' is now called Session; consecutive page views by the same user within 30 minutes count as a single session. (Also, if it's midnight, that will start a new session.) You do not necessarily need to come from an external site to count as a visit. More explanation and a helpful diagram can be found here.

*A 'new visit' (new session) is a visit by a user who hasn't been to the site before (at least not in the last 30 days, it seems).