text:
Q: Object reference not set to instance of object in mvc[Null Reference Exception] I am creating an MVC application.I am getting an error of Null Reference Exception on change password form functionality.
My Model class code
public partial class tblUser
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Please Enter Your Email Id")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please Enter Your Password")]
    [DataType(DataType.Password)]
    [StringLength(18, ErrorMessage = "The password must be atleast 3 characters long", MinimumLength = 3)]
    public string Password { get; set; }

    [Required(ErrorMessage = "Please Enter Your Password")]
    [DataType(DataType.Password)]
    [StringLength(18, ErrorMessage = "The password must be atleast 3 characters long", MinimumLength = 3)]
    public string NewPassword { get; set; }
}

My view(Changepassword.cshtml)
@model MvcWebApplication1.Models.tblUser

            @Html.ActionLink("Log Out", "Login", "Home")

CHANGE PASSWORD

        @using (Html.BeginForm("Changepassword", "Home", FormMethod.Post))
        {

                        Old Password

                            @Html.EditorFor(pass => pass.Password)

                        @Html.ValidationMessageFor(pass => pass.Password)

                        New Password

                            @Html.EditorFor(pass => pass.NewPassword)

                        @Html.ValidationMessageFor(pass => pass.NewPassword)

                            <input type="submit" value="Change Password" />

@ViewBag.Message

        }

When I click on change password submit button I am getting a NullReferenceException in action method on line userDetail.Password = login.NewPassword;
[HttpPost]
public ActionResult Changepassword(tblUser login)
{
    UserDetailsEntities db = new UserDetailsEntities();
    var detail = db.tblUsers.Where(log => log.Password == login.Password).FirstOrDefault();
    if (detail != null)
    {
        var userDetail = db.tblUsers.FirstOrDefault(c => c.Email == login.Email);
        userDetail.Password = login.NewPassword;

        db.SaveChanges();
        ViewBag.Message = "Record Inserted Successfully!";
    }
    else
    {
        ViewBag.Message = "Password not Updated!";
    }
    return View(login);
}

A: [HttpPost]
public ActionResult Changepassword(tblUser login)
{
    UserDetailsEntities db = new UserDetailsEntities();
    var detail = db.tblUsers.Where(log => log.Password == login.Password).FirstOrDefault();

    // ADDED NULL CHECK HERE
    if (detail != null)
    {
        var userDetail = db.tblUsers.FirstOrDefault(c => c.Email == login.Email);
         if(userDetail !=null)
         {
              userDetail.Password = login.NewPassword;

              db.SaveChanges();
              ViewBag.Message = "Record Inserted Successfully!";
         }
    }
    else
    {
        ViewBag.Message = "Password not Updated!";
    }
    return View(login);
}

A: Check ur db. It's either closing before you read from it or it's connecting to some other table.


text:
Q: Remove port from URL - Django Apache2 Gunicorn I would like to know how to omit the port number from my URL.
I currently host a website on an Apache Ubuntu server on port 443 and redirect any http traffic to the https version of the site.
(www.mycompany.com)
However, I also run a Django server on the same Apache VPS using Gunicorn, currently on port 8000 and would like to achieve the URL of www.mycompany.com/blog
My current situation for the URL is www.mycompany.com:8000/blog
I have tried altering the ports that the Django server runs on to 443 and 80, but quickly realised the firewall won't allow that.
I am not sure what to do. Do I have to do a reverse proxy?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Protractor - Chromedriver error in azure devops pipeline I am getting the following error in Azure Devops pipeline when running the protractor tests.
How can i fix this ?
enter image description here

A: You should comment the selenium address in your config file. Then it will work.
// seleniumAddress: 'http://localhost:4444/wd/hub', It is connecting to the local connection hence not working


text:
Q: iText 7.1.8 can't read some pdf file when i open some PDF files,stuck in new PdfDocument(reader)

pdf file:
https://drive.google.com/open?id=1AVda9qst-DiVbz4QFQh8iIv2aLn-uXRR

can someone help me fix it?
var reader = new PdfReader(file);
var doc = new PdfDocument(reader); // stuck
// some code


text:
Q: How can i show beauty url with htaccess? I'm using MVC with PHP and, for example, I have this URL:
domain.com/{modue}/{action}

This will make it look like:
domain.com/user/join

I want it to show
domain.com/join

instead.
Can anyone help me?
I tried this with an .htaccess file, but I couldn't. This is my code:
RewriteEngine On
RewriteRule ^$ ./controller.php [L]
RewriteRule ^([a-zA-Z_0-9-]+)/$ /$1? [R=301,L]
RewriteRule ^([a-zA-Z_0-9-]+)$ /controller.php?modulo=$1&%{QUERY_STRING} [L]
RewriteRule ^([a-zA-Z_0-9-]+)/([a-zA-Z_0-9-]+)/$ /$1/$2? [R=301,L]
RewriteRule ^([a-zA-Z_0-9-]+)/([a-zA-Z_0-9-]+)$ ./controller.php?modulo=$1&action=$2&%{QUERY_STRING} [L]

A: Try this if you have just one controller -
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond $1
RewriteRule ^(.*)$ user/$1 [L]

</IfModule>


text:
Q: How to save RDD data into json files, not folders I am receiving the streaming data myDStream (DStream[String]) that I want to save in S3 (basically, for this question, it doesn't matter where exactly do I want to save the outputs, but I am mentioning it just in case).
The following code works well, but it saves folders with the names like jsonFile-19-45-46.json, and then inside the folders it saves files _SUCCESS and part-00000.
Is it possible to save each RDD[String] (these are JSON strings) data into the JSON files, not the folders? I thought that repartition(1) had to make this trick, but it didn't.
    myDStream.foreachRDD { rdd =>
       // datetimeString = ....
       rdd.repartition(1).saveAsTextFile("s3n://mybucket/keys/jsonFile-"+datetimeString+".json")
    }

A: AFAIK there is no option to save it as a file. Because it's a distributed processing framework and it's not a good practice write on single file rather than each partition writes it's own files in the specified path.

We can pass only output directory where we wanted to save the data. OutputWriter will create file(s)(depends on partitions) inside specified path with part- file name prefix.

A: As an alternative to rdd.collect.mkString("\n") you can use hadoop Filesystem library to cleanup output by moving part-00000 file into it's place. Below code works perfectly on local filesystem and HDFS, but I'm unable to test it with S3:
val outputPath = "path/to/some/file.json"
rdd.saveAsTextFile(outputPath + "-tmp")

import org.apache.hadoop.fs.Path
val fs = org.apache.hadoop.fs.FileSystem.get(spark.sparkContext.hadoopConfiguration)
fs.rename(new Path(outputPath + "-tmp/part-00000"), new Path(outputPath))
fs.delete(new Path(outputPath  + "-tmp"), true)

A: For JAVA I implemented this one. Hope it helps:
    val fs = FileSystem.get(spark.sparkContext().hadoopConfiguration());
    File dir = new File(System.getProperty("user.dir") + "/my.csv/");
    File[] files = dir.listFiles((d, name) -> name.endsWith(".csv"));
    fs.rename(new Path(files[0].toURI()), new Path(System.getProperty("user.dir") + "/csvDirectory/newData.csv"));
    fs.delete(new Path(System.getProperty("user.dir") + "/my.csv/"), true);


text:
Q: How to determine if daylight saving time is active in C? I have a C application running on cross platforms. In this program, I need to write a function which determines if the given date is DST or not.
Actually, i try to find DST begin-DST end dates in pure C. Is there any simple and standard way to do this?

A: time.h provides tm structs with a tm_isdst flag. Use time to get the current time, localtime to get a tm struct with the time adjusted to the current locale and read the tm_isdst flag.
From the manpage:
tm_isdst  A flag that indicates whether daylight saving time is in effect at the
time described.  The value is positive if daylight saving time is in effect, zero
if it is not, and negative if the information is not available.

A: The code is:
time_t rawtime;
struct tm timeinfo;  // get date and time info
time(&rawtime);
localtime_s(&timeinfo, &rawtime);
int isdaylighttime = timeinfo.tm_isdst;

A: Implementation is not allowed to assume that tm_isdst is always 0.
It must provide correct data.
If implementation cannot provide tm_isdst which is consistent with rules set in a country than it should set tm_isdst to negative value as specified in 7.23.1/4 in the same Standard.


text:
Q: How to select items containing any word in a string using Entity Framework 6? I've a table that contains details of Members.
The Name field will be having values like "John Antony", "Sarah Ann Mathew", "Josh John".
How do I select all members who are having names containing any of the words in "John, Ann, Mathew".
I've tried implementations like db.members.Where(m=>names.Contains(m.Name)); but the issue is that I am trying to match any word in m.Name.
Thanks in advance.

A: If you make names a collection of strings, like this {"John", "Ann", "Mathew"}, you can rewrite your query as follows:
var res = db.members.Where(m=>names.Any(n => m.Name.Contains(n)));


text:
Q: Validar si un integer tiene un valor nulo Trabajo con C#, Visual Studio 2019
Tengo un método de filtros condicionales tengo un problema uno de los parámetros recibe un valor int si no he puesto un valor debo mandarle un nulo, pero los tipos int no admiten nulos por lo que se trabaja con HasValue y Value pero no puedo implementarlo.
var filter = new CriteriaOrdenVenta()
        {
            ClienteId = string.IsNullOrEmpty(txtClienteId.Text) ? 0 : Convert.ToInt32(txtClienteId.Text),
            Codigo = txtCodigo.Text,
            FechaEmision = chkFechaEmision.Checked ? (DateTime?)dtpFechaEmision.Value : null,
            FechaCaducidad = chkFechaCaducidad.Checked ? (DateTime?)dtpFechaCaducidad.Value : null,
        };

¿Como debo implementar correctamente en esta linea de código?
ClienteId = string.IsNullOrEmpty(txtClienteId.Text) ? 0 : Convert.ToInt32(txtClienteId.Text),

Clase Criteria
public class CriteriaOrdenVenta
{
    public int? ClienteId { get; set; }
    public string Codigo { get; set; }
    public DateTime? FechaEmision { get; set; }
    public DateTime? FechaCaducidad { get; set; }
}

A: Creo que lo que buscas es esto:
ClienteId = string.IsNullOrEmpty(txtClienteId.Text) ? (int ?)null : Convert.ToInt32(txtClienteId.Text);

Tan sólo que hay que tener cuidado porque si el texto no viene validado como numérico podría lanzar una excepción al intentar convertirlo.
Un saludo.

A: Puedes usar TryParse, para que solo se asigne el valor cuando se pueda convertir:
//C#7
if (int.TryParse(txtClienteId.Text, out var result))
{
     filter.ClienteId = result;
}


text:
Q: How to animate scroll position of div with overflow: auto? I'm trying to create a function which scrolls given div or body to an element's location within. Currently it looks like:
function scrollTo($elem, offset, delay, $context){
    delay = delay || 800;
    offset = offset || 0;
    $context = $context || $('html, body');
    $context.animate({
        scrollTop: $elem.offset().top-offset
    }, delay);
}

It works fine on body, however, when I give it $context the first call works as intended, but all the consecutive calls are scrolling to a wrong position.
Why is this behavior and how to fix it?
FIDDLE

A: The offset().top measures the distance from the top of the page to the element.

*

*When you click .1, the offset distance to the top of the page is 300.

*Once .large which is now -300 is scrolled to that position, .1 offset becomes 0, .2 becomes 300, .3 becomes 600.

*so you need to minus the offset of .large to get the real position.

Code
function scrollTo($elem, offset, delay, $context){
    delay = delay || 800;
    offset = offset || 0;
    $context = $context || $('html, body');
    var a = $context.find('.large'); //need this
    $context.animate({
        scrollTop: $elem.offset().top - a.offset().top
    }, delay);
}

Here is the jsfiddle https://jsfiddle.net/a8jc5q6r/4/


text:
Q: Synchronised data across all clients A few weeks ago I watched a demo video of a framework that could synchronize data between clients. It showed 2 browsers that displayed a list of data. When a new item was inserted into one, it would also appear on the second.
I forgot to bookmark this website. I don't quite know the language it was written in, but I suspect node. Now I would like to investigate this mechanism of synchronizing data, but can't find this framework again.
Can anyone recall such a framework or comparable "technology"?

A: You probably saw this screencast of Meteor:
http://www.meteor.com/screencast
Just a wild guess :)


text:
Q: Error Handling java program import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Asterisks
{
    public static void main(String[] args)
    {
        try
        {
            File dataFile = new File("Asterisks.txt"); \\ this file says "S 3"
            Scanner in = new Scanner(dataFile);
            String shapeType = in.next();
            int Dim = in.nextInt();

            if (shapeType.equals("S"))
            {
                for(int loop = 0; loop < 4; loop ++)
                {
                    for (int line = 0; line < Dim; line ++)
                    {
                        for(int elt = 0; elt < Dim; elt ++)
                        {
                            System.out.println(" *");
                        }
                        System.out.println(" ");
                    }
                 }
            }
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Data file not found.");
        }
    }
}

(first time putting it on here so please write on the comments what i can do to make it better)
So this is my file and what I don't get is that why this program does not run.
this file has to print out
      * * *
      * * *
      * * *

the output im getting right now is
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Asterisks.main(Asterisks.java:15)

Thank for your help in advance.

A: What is happening is that Scanner.nextInt() is not finding an integer when it reads the file, so it is throwing an InputMismatchException.

A: Your code works on my machine, so I can only conclude that your version of the Asterix.txt file is bad. Make sure it is correct, and try referencing it with the full path to make sure you're using the correct one. e.g. new File("C:\\Temp\\asterix.txt");
Also a few points:

*

*The line for (int loop = 0; loop < 4; loop++) should be removed to achieve the output you listed.

*You should close your scanner object.

*Don't start your variable names with a capital (Dim should be dim).


text:
Q: How to play a wav (loaded from a URL) in React/html5? I want to include an audio player that plays a wav file that is loaded from a URL in a React component. Although this should work straight forward with the HTML5 <audio> element, I cannot get it to play (I just see the control elements).
I tried to play a .mp3 with the same code, which works. I checked in Chrome and Safari which are supposed to support .wav - it works in neither of them. I tried to replace the <audio> element with a react-audio-player, a react-player and a react-sound element - none of them works.
When I open the URL, the sound is downloaded as an attachment.
    render() {

        const wavUrl = config.fileServer+this.props.values.id+".wav";

        return (
            <audio controls>
                <source src={wavUrl} type="audio/wav" />
                Your browser does not support the audio element.
            </audio>
        );
    }

I expect to see an audio controller that starts playing the sound when I press play. Instead, I see an audio controller that does nothing when I press play, and that claims that the audio file is 0 seconds long. I checked the URL - it is correct if I past it as URL in my browser directly.

A: If you are using create-react-app you have to import the audio file.
import wavUrl from './path/to/file';

// ... rest of code here

A: As mentioned Kitanga, you can use import to load files from public (instead of full URL access), example:
import somefile from '../public/assets/mp3/test1.mp3'

then
Play extends Component {
...
}

render(
  <Play file=somefile>
)

But if you found webpack error message at start: "You may need an appropriate loader to handle this file type..." then seems you need to load appropriate extension npm package to read it and configure webpack.config.js, example:
 ...
 module: {
   rules: [
     {
       test: /\.mp3$/,
       loader: "file-loader"
     },
     ...
   ]
   ...
 ...

if "file-loader" not installed then use example:
 npm install --save file-loader


text:
Q: Imagebutton clickable area is bigger than the image I have multiple imagebutton shaped like a trapezoid, but the clickable area is a transparent square all around them (bigger than the image).  I want only the trapezoid to be clickable because the trapezoids overlaps because the square shape. Thank u!
<ImageButton
    android:id="@+id/btnAgua"
    android:layout_width="93dp"
    android:layout_height="170dp"
    android:layout_marginStart="28dp"
    android:layout_marginLeft="28dp"
    android:adjustViewBounds="true"
    android:background="@null"
    android:scaleType="centerInside"
    android:src="@drawable/agua"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

Screenshot of my problem:
https://i.stack.imgur.com/gM4IN.png


text:
Q: Sniff/intercept and change http(s) request data A few days ago I've been researching how I can listen for https requests in my browser and overwrite some data (headers, body) from the request before it reaches the final destination (site).
I tried many times. I came to use the modules
mockttp, web-sniffer, hoxy, among others.
As the application I'm developing is with selenium, I tried to create a proxy server with the modules mentioned above and make them go through my application before being "dispatched", however, none of them were successful.
Note: I was able to listen to requests, change their response, and other things. But I didn't get what I really wanted: change the request data before it was sent to the site. Something similar to the breakpoint functionality present in Fiddler, Charles, HTTP Tool Kit and others applications.
What do I really hope?
I'd like to hear my browser's requests -> pause HTTPS requests (breakpoint), change something anyway -> forward/follow/dispatch with/the request.
One of the failed attempts:
The new header is not really inserted in the request! (browser was configured with proxy server and I could see the requests being shown in the console)
import mockttp from "mockttp";
import fs from "fs";
import * as Sniffer from "web-proxy-sniffer";

(async () => {
  // Create a proxy server with a self-signed HTTPS CA certificate:
  const https = await mockttp.generateCACertificate();

  fs.writeFile("key.pem", https.key, console.log);
  fs.writeFile("cert.pem", https.cert, console.log);
  const proxy = Sniffer.createServer({
    certAuthority: {
      key: fs.readFileSync(`./key.pem`),
      cert: fs.readFileSync(`./cert.pem`),
    },
  });

  proxy.intercept(
    {
      // Intercept before the request is sent
      phase: "request",
    },
    (request, response) => {
      request.headers.test = "a simple test";

      return request;
    }
  );

  proxy.listen(8001);
})();

Would this be possible with NodeJS?
(Sorry for this "rude" english)


text:
Q: Why is the pronunciation of the O in "move" different from in "bone"? I have read about the silent "e" rule. So, in the word "bone", it seems to work with "o" having its letter sound. But, we say "move" as in "moov". Why this difference? Is it historical or due to some rule?

A: I think it's safe to say that there's no rule (like the silent E is a rule).
I recommend thinking of move as being some sort of exception.

A: One of the curious exceptions to the "silent e" rule is essentially a matter of syntax. In general, English words do not end with the letter "v" or "u", and the presence of the "e" is merely a reconciliation of that fact without affecting the pronunciation of the intervening vowel.

A: English spelling is rarely based upon true phonetics, but rather upon word roots and etymology. The disjointed pronunciation and spelling of the word "move" in comparison to its similarly suffixed counterparts is likely due to such factors.
The online etymology dictionary suggests a French influence for the word, with possible provenance reaching as far back as Indo-European roots, which both have spelling construction that hint at the modern pronunciation in English, whereas the Latin root of the French word informs its current English orthography. It is notable that the French root from which English inherits its spelling has been modified in Modern French and provides better phonetic guidance to today's French reader, unlike English.

late 13c., from Anglo-French mover, Old French movoir "to move, get moving, set out; set in motion; introduce" (Modern French mouvoir), from Latin movere "move, set in motion; remove; disturb" (past participle motus, frequentative motare), from PIE root *meue- "to push away" (cognates: Sanskrit kama-muta "moved by love" and probably mivati "pushes, moves;" Lithuanian mauti "push on;" Greek ameusasthai "to surpass," amyno "push away").

A: It is due to the Great Vowel Shift between 1350-1700's. Many of the words we commonly use have changed pronunciation while keeping the spelling.
SPELLING
The spelling of "move" was of course based on the Latin movere: mov(e) - movie, movable etc.
The "e" is there because English words don't end in v (or u).
PRONUNCIATION (using IPA and simple diacritic)
So many words were changed in pronunciation during the Great Vowel Shift (see PHY117 - The Great Vowel Shift by Prof. Jürgen Handke 6:32).
In stage 2 of the Shift [o:] changed to to [u:]. He uses the example of "food" previously pronounced [fo:d] or /fŏd/ (or a sound between /ŏ/ and /ä/) and shifted to [fu:d] or /food/.
So - "move" would have been pronounced by its spelling [mo:v] then shifted to [mu:v] ( /mŏv/ to /moov/ ).
Other explanations of pronunciation is the spelling indicated the pronunciation differently to today - "blood" for example has double 'o' to indicate a long o /ō/ instead of the "magic e" - /b-l-ō-d/ NOT /b-l-oo-d/. Then the Great Vowel Shift changed many of the pronunciations from /ō/ to /ŭ/. (as opposed to "flood" which derived from the German Flut /floot/, which changed pronunciation possibly due to the same reason for how it was spelled -  from /oo/ to be read as /ō/ and then had the same change from /ō/ to /ŭ/). So it's almost like they found a middle ground for the sound.
Remember that the pronunciation of vowels can be changed significantly due to the letters that come before and after as they distort the sound, especially using a schwa due to lesser significance in a sentence. So even if you think you pronounce a pure vowel sound, it may actually sound like another in the area of the mouth too, and not lose meaning within the sentence. It could even be due to class - if an English person from say South London says "move" they may actually be saying /mōv/ and be correct due to accent, while if a North American or Australian said it that way, it would be mispronunciation.


text:
Q: How to add a timer in an animation.FuncAnimation (), using pandas/Geopandas? I am creating an animation by using GeoPandas and everything is going well but I'd like to include a timer, in order to know the time corresponding to my visualization.
I think the way is by means of set_text, but I think everything is lost in the update done by Geopandas to plot (ax=ax).
So, the instruction time_text is the one that is not working on my code. Please any help/suggestion/idea? Thanks in advance!!
Here the important part of my code:
import numpy as np

from matplotlib import pyplot as plt

from matplotlib import animation

import geopandas as gpd

import pandas as pd

from shapely.geometry import Point

fig = plt.figure()

ax = plt.axes(xlim=(2.5, 7), ylim=(48, 52))

time_text = ax.text(2.8, 50.,"",transform = ax.transAxes, ha="right")

ax.legend()

t=0

bel = gpd.read_file('....')

def init():

    global inicio

    inicio = bel.plot( ax=ax, color='black', markersize=5)

    time_text.set_text("")

    return inicio, time_text

data = pd.read_csv('.....')

legend = plt.legend(loc='lower left',prop={'size': 7})

def animate(i):

  global inu, iterar, t

  t += 1

  ax.clear()

  inu = bel.plot( ax=ax, color='lightgray', linewidth=1., edgecolor='black')

  cond = geo_data[ geo_data['newdate'].dt.minute == i]

  iterar = cond.plot(ax=ax,marker='s',color='yellow', markersize=7.,alpha=0.3,label='Max >= 60 Tonne');

  legend = plt.legend(loc='lower left',prop={'size': 7})

  time_text.set_text("time = "+str(t))

  return iterar,inu,time_text

anim = animation.FuncAnimation(fig, animate, init_func=init,frames=60, interval=500, blit=False)

plt.show()


text:
Q: jQuery Store data variable from previous click I have a click function which occurs when the user presses a 'player' in my game. I'm trying to code a substitution between two players. The function first checks to see whether another player has already been selected, if so, it checks to see whether they are on the bench or not. If they're on the bench then it stores the second players data information.
The problem is with storing the first players data information. When I alert 'pid' it comes up as undefined. Is there anyway of storing pid so that the next time a user clicks on another player, the information stored under 'pid' remains? I realise that 'pid' is being declared within the function, I have tried declaring it first outside the function but this is still not working.
var pid;

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

    event.preventDefault();

    var start = $(this).data("start");

    if ($(".show2")[0]){
      // Player has already been selected

      if ($(this).children('.show2').length) {
        // User has selected same player, toggle off select image and return

        $(this).children('.player-select').toggleClass('show2');
        return;
      }

      if(start == 'FirstEleven'){
        $(".message-alert").css("display", "block");
        $(".message").html('You must substitute a player from the bench');
        $(".overlay2").css("opacity", "0.5");
        $(".overlay2").css("display", "block");
        $(".container2").css("pointer-events", "all");
      }

      if(start == "Bench"){
        var pid2 = $(this).data("id");
        var element2 = $(this).data("element");

        alert(pid);
        alert(pid2);
      }

    } else {
      // First player to be selected

      if(start == 'Bench'){
        // If player selected is on the bench
        $(".message-alert").css("display", "block");
        $(".message").html('You must select a player from the starting lineup first');
        $(".overlay2").css("opacity", "0.5");
        $(".overlay2").css("display", "block");
        $(".container2").css("pointer-events", "all");
        return;
      }

      $(this).children('.player-select').toggleClass('show2');

      var pid = $(this).data("id");
      var element = $(this).data("element");

    }

  });

A: You can use sessionStorage for this kind of use case. It will be clean once windows close. Or you can clean programmatically.
sessionStorage.setItem("players1", "deepak")

console.log(sessionStorage.getItem("players1"))


text:
Q: Deny CloudTrail from logging my S3 bucket In my company we have an AWS account and I have a bucket that holds personal information about workers of the company. As the names of the files sometimes disclose information about the workers, I don't want the files to be listable to anyone. The bucket policy I used blocks all access to the bucket to anyone but me but CloudTrail still logs the names of the files, in PutObject or GetObject events for example, and so anyone with CloudTrail access (which I don't control) may see the file names and who accesses them. Is there a way to deny CloudTrail from logging this bucket? I want to make sure it is not logging what happens to the files there and who accesses the bucket.

A: The events you mentioned like GetObject and PutObject are data events
From docs

CloudTrail supports logging Amazon S3 object-level API operations such as GetObject, DeleteObject, and PutObject. These events are called data events.

which means your organization has enabled Data events and since you dont control the cloudtrail, you cannot disable.
according to docs

To disable CloudTrail data events logging for objects in an S3 bucket

To disable object-level logging for the bucket, you must open the CloudTrail console and remove the bucket name from the trail's Data events.


text:
Q: transform Collection to Collection I trying to implement functionally similar to CollectionUtils transform (Apache Commons Collections)
class CollectionUtils {

    public static void transformerModifier(Collection<MyClass> myCollection) {
        // How should I implement this method in order that
        // output from the line 1 and line 2 will be the same ?
    }

    public static List<String> transform(Collection<MyClass> myCollection) {
        List<String> strCollection = new LinkedList<>();
        for (MyClass item : myCollection) {
            strCollection.add(item.getName());
        }
        return strCollection;
    }
}

class myClass {
    private String name;
    private int value;

    myClass( String name, int value) {
        this.name = name ;
        this.value = value;
    }

    public String toString(){
        return new String(name+ ":" + value ) ;
    }
}

class MyClassCollection{
    private List<myClass> list ;

    myClassCollection(List<myClass> list){
        this.list = list;
    }

    List<myClass> collection(){
        return list.clone();
    }

}

public class TestClass{

    public static void main (String[] args) {

        List<MyClass> list = new ArrayList<>();
        list.add(new myClass("John", 12);
        list.add(new myClass("Mike", 16);
        list.add(new myClass("Eric", 13);
        list.add(new myClass("Mark", 142);
        list.add(new myClass("Alex", 112);

        MyClassCollection myOjb = new MyClassCollection(list );
        CollectionUtils.transformerModifier(myObj.collection() );
        List<MyClass> myList = CollectionUtils.transform(myObj.collection());
        System.out.println(Arrays.toString(myObj.collection().toArray)); // line 1
        System.out.println(Arrays.toString(myList.toArray));            // line 2
    }

}

output: [John,Mike,Eric,Mark,Alex] // output after line 1
output: [John,Mike,Eric,Mark,Alex] // should be output after line 2

My question is it possible to implement method transformerModifier in the way that it will change collection of the object myObj so that myObj.collection() return not the List<myClass> but the List of List<String> ( where string is the data from private String name data member of myClass ) ?
My guess is that the solution should be through anonymous class. However, I didn't understand yet how should I implement it.

A: If you are using Java 8, you could make use of streams and map() to do something like this:
List<MyClass> myClassList = new ArrayList<>();
//add your items to myClassList here

List<String> names = myClassList.stream().map(MyClass::getName).collect(Collectors.toList());
//names will now consist of a List of all the names associated with
//each of the MyClass objects within myClassList in the same order

This solution makes use of Method Reference as well MyClass::getName.  This calls the getName method on each object in the stream mapping it to its respective spot in the transformed stream using .map().
Next it uses .collect() to bring it back from a stream to a list using Collectors.toList().
If you are working with a lot of objects within myClassList, this process can be sped up using .parallelStream() instead of .stream(), but if you are not working with a large amount of data, you may see a reduction in performance with .parallelStream().  It all depends on how many objects you expect to be present within the List.

A: public interface Converter<I, O> {

    void tranformer(List list);

    O retriever(I obj);
}

_
  public static <I, O> void transform(Converter<I, O> converter, List inputList) {
        Iterator<I> it = inputList.iterator();
        List list = new LinkedList<>();
        while (it.hasNext()) {
            list.add(converter.retriever(it.next()));
        }
        converter.tranformer(list);
    }

_
    public static void main(String[] args) {
       List<MyClass> list = new ArrayList<>();
        list.add(new myClass("John", 12);
        list.add(new myClass("Mike", 16);
        list.add(new myClass("Eric", 13);
        list.add(new myClass("Mark", 142);
        list.add(new myClass("Alex", 112);

        MyClassCollection myclasscollection = new MyClassCollection(list);
        final List collectionList = myclasscollection.collection();
        CollectionUtils.transform(new Converter<myClass, String>() {
            @Override
            public void tranformer(List list) {
                employeeList.clear();
                employeeList.addAll(list);
            }

            @Override
            public String retriever(myClass obj) {
                return obj.name; // make the data member public or add getter
            }
        }, collectionList);

 collectionList.get(0).toString.toLowerCase();

}

This isn't fully what you need but I bet this isn't bad alternative. Please, notice that could output collection collectionList will be collection of objects ( not String ), however, you can access to methods of the String data type   just to right like this  collectionList.get(0).toString.toLowerCase(); Hope this help.


text:
Q: Custom RoleProvider in a MultiTenant MVC App I need to develop a custom RoleProvider for a MultiTenant web app.
At the DB level, we have a table that relates Users with Roles with Tenants.

My problem is that RoleProvider gets user roles just passing the User as parameter, and we need to take the Tenant into account.
In RoleProvider implementation we have:
public override string[] GetRolesForUser(string username)
{
    //Code to retrieve roles from repo
}

As the roles are for a user in an specific Tenant, we need:
public override string[] GetRolesForUser(string username, int tenantId)
{
    //Code to retrieve roles from repo
}

The current tenant is stored in the ControllerBase class (the one that all controllers inhereted from).
The Membership and Role Providers are in a separate project, so I don't see a way to use the current Tenant. I think I could create my custom RoleProvider in the web app project.
Any idea on how to implement the RoleProvider interface taking the Tenant as part of the input ?

A: Well, just to inform you what I did in my case:
As our routes are in the form of  http://[tenantName].[domain]/[App]/[Area] we ended up getting the [tenantName] from the Request, since it is unique, and with the Tenant and the UserName that came as a parameter I can do my select on our UsersInTenants' table.
The very same can be done using cookies as a way to pass aditional information.
So you can access the request, with the cookies, but for what I research the Session is not yet initialized in most cases.
Hope it helps!


text:
Q: tortoisesvn slow Windows 10 After upgrading to Windows 10, a colleague and I, have huge problems using Tortoisesvn, especially the repository browser.
When navigating around in the directories, depending on the content, and amount of files, it usually hangs for about a minute or two.
We diden't have these kind of issues using Windows 7, and the latest version of tortiose.
What we've tried so far is:
Look through all applications that is related to file extentions, this would be a known error when using the repo browser, and windows would try to fetch the program related to the file extention.
Disable IPV6 this would cause problems on some machines.
Updating Windows 10 fully, an update from MS would also solve this cause.
When using the DebugView and enabling debug mode in Tortoise, I can see that the application hangs in the List command, and ReadProperties commands.
We've also tried disabling the firewall, antivirus and so fourth.
When browsing the repository using a browser, there is no speed issues.


text:
Q: Cocoa Converting RTFD to ASCII and back Is it possible to convert an NSattributedString with attachments (RTFD not RTF) to ASCII, edit the stream, and convert it back? So far I am able to convert an RTFD to a String stream. But turning it back into an NSData object does not work. Here's the code I'm using in a playground.
import Cocoa

func stream(attr: NSAttributedString) -> String? {
    if let d = attr.rtfd(from: NSMakeRange(0, attr.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType]) {
        if let str = String(data: d, encoding: .ascii) { return str }
        else {
            print("Unable to produce RTFD string")
            return nil
        }
    }
    print("Unable to produce RTFD data stream")
    return nil
}

if let im = NSImage(named: "image.png") {
    let a = NSTextAttachment()
    a.image = im

    let s = NSAttributedString(attachment: a)

    if let str = stream(attr: s) {
        print("\(str)\n") //prints a string, which contains RTF code combined with NSTextAttachment string representation

        if let data = str.data(using: .ascii) { //this is where things stop working
            if let newRTF = NSAttributedString(rtfd: data as Data, documentAttributes: nil) {
                print(newRTF)
            }
            else { print("rtfd was not created") }
        }
        else { print("could not make data") }
    }
}

What am I missing? Or is my entire concept wrong here? I am doing this to get around a limitation of the way OS X handles images attached in RTF documents.
Edit:
The limitation I am trying to address is to set the size of an image in an RTF stream. The text handling system requires that we use NSTextAttachment. Whenever an image is pasted from that, it automatically sizes the image to whatever the pixel height and width are. Unfortunately there is no way to control this property. I have tried here and also using all the techniques here.
As far as the ASCII stream, I'm not trying to edit the image attachment itself. When the stream is printed, the actual RTF code is visible and editable. This works and would be a good workaround for this limitation. All I need is to edit the RTF code and change the \width and \height properties that Apple uses.

A: After your edit I can see what you are trying to do, interesting idea, but it won't work - at least not easily.
Take a look at the value of d, it is not an ASCII string stored as a value of type Data (or NSData). It is a serialised representation of multiple items; the RTF stream (text), the image data (binary). If you convert this to an ASCII string and back again it is not going to work, you can't represent arbitrary binary data as ASCII unless you encode it (e.g. something like base 64 encoding).
Now you could attempt what you are trying a slightly different way, skip the conversion to ASCII and edit the Data value directly. That is certainly possible, but as you are editing a format you don't know (the serialised representation) you would have to be careful... And even if you succeed in editing the representation there is no guarantee that converting back to an NSAttributedString with an NSTextAttachment will preserve your edits.
I suggest you tackle this another way. You have an NSAttributedString and you don't like the RTF produced after you write this to a file. So edit the RTF after it is written, e.g. open up the RTFD package, open the contained RTF file (TXT.rtf), edit it, write it back.
HTH


text:
Q: Change button style on focus change using pure CSS or dynamically, New to coding and I'm trying to make it so you click on a button and it changes the color of that button, then when you click on the button right next to it, that button changes color and the previous button goes back to its original color. After pressing the left button the focus should shift to the left button again. I've tried many, many different things, but this is what I have right now.
const [buttonOneOn, setButtonOneOn] = useState(false)
const [buttonTwoOn, setButtonTwoOn] = useState(false)

  function onChangeForFilter(e) {
    setButtonOneOn(prevButtonOn=>!prevButtonOn)
    if(buttonOneOn===true){
      e.target.style.color = "grey"
    }
    else{e.target.style.color='blue'}
    if(buttonTwoOn===true){
      setButtonOneOn(false)
    }
  }

  function onChangeForFilter2(e) {
    setButtonTwoOn(prevButtonOn=>!prevButtonOn)
    if(buttonTwoOn===true){
      e.target.style.color='grey'
    }
    else{e.target.style.color='blue'}
    if(buttonOneOn===true){
      setButtonOneOn(false)
    }
  }

Obviously, this code doesn't do what I want to at all. Couldn't find any answers online. If anyone has any resources it would be appreciated.

A: You can really attain that purely in css. heres some sample you can play. Let me know if this is what you mean.

button {
  background-color: white;
  border-radius: 10px;
  color: black;

}

button:focus  {
  background-color: red;
  border-radius: 10px;
  color: white;
}

  <button>My button 1</button>
  <button>My button 2</button>
  <button>My button 3</button>

A: My approach uses state and template literals to play with className
import './css.css'

export default function Buttonsso() {
    const [buttonOne, setButtonOne] = useState(false);
    const [buttonTwo, setButtonTwo] = useState(false);

    function eForBtn1() {
        setButtonOne(buttonOne=>!buttonOne);
    }

    function eForBtn2() {
        if(buttonOne === true & buttonTwo=== false) {
            setButtonOne(false);
            setButtonTwo(true);
        }
    }

  return (

      <button className={`${buttonOne ? "purple" : ""}`} onClick={() => eForBtn1()}>btn1</button>
      <button className={`${buttonTwo ? "orange" : ""}`} onClick={() => eForBtn2()}>btn2</button>

  )
}

The css.css file looks like
.purple {
    background-color: purple;
}

.orange {
    background-color: orange;
}

I do not have your render function so could not work on your code. But my solution works for sure.


text:
Q: Why The up button has been added in all activities while i enabled it only in one activity? I followed the Google documentation for adding the up button , here is the link https://developer.android.com/training/implementing-navigation/ancestral?utm_source=udacity&utm_medium=course&utm_campaign=android_basics , so first i modified my manifest file so it looks like :
?xml version="1.0" encoding="utf-8"?><!--
 Copyright (C) 2016 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
}});}}
          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".PhrasesActivity"
            android:label="@string/category_phrases"
            android:parentActivityName="com.example.android.miwok.MainActivity" />
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.android.miwok.MainActivity" />/>

        <activity android:name=".NumbersActivity"
            android:label="@string/category_numbers"
            android:parentActivityName="com.example.android.miwok.MainActivity" />
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.android.miwok.MainActivity" />/>

        <activity android:name=".FamilyActivity"
            android:label="@string/category_family"
            android:parentActivityName="com.example.android.miwok.MainActivity" />
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.android.miwok.MainActivity" />
        <activity android:name=".ColorsActivity"
            android:label="@string/category_colors"
            android:parentActivityName="com.example.android.miwok.MainActivity" />
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.android.miwok.MainActivity" />/>
    </application>

</manifest>

As , you can see i have 4 child activities , after that randomly I've chosen the NumbersActivity to test the up button , by adding this line of code in it's java file :
@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

What i couldn't understand is why the up button has been being enabled in all other child activities without updating theirs java file ??

A: These statements in the manifest:
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.android.miwok.MainActivity" />

android:parentActivityName="com.example.android.miwok.MainActivity"

makes the up button available to all child activities in order to return to the parent activity.
Note: this way of returning back to the parent activity, always recreates the parent activity and this may not be what you want.
So to avoid the recreation of the parent activity add in the manifest this line for MainActivity:
android:launchMode="singleTop"


text:
Q: Python How to use pointer in function I have a simple question how can i send pointer of boolean varible with function?
example :
condition = True
def set_false(con):
    con = False
set_false (condition)
print(condition)

and i want to output is false.

A: You need to return:
condition = True
def set_false(con):
   return False
condition = condset_false(condition)
print(condition)

Output:
False

A: Try:
condition = True
def set_false(con):
    con = False
    return con
condition = set_false(condition)
print(condition)

OR
condition = True
def set_false():
    global condition
    condition = False
set_false()
print(condition)


text:
Q: What could be solution for this? I am not finding the solution for the following problem . Any help?

A: Try the following:

*

*Add this to your gradle compile 'com.android.support:appcompat-v7:22.1.1'

*Go to Build -> Clean Project.

*Go to File -> Invalidate Caches/Restart.


text:
Q: How can we make list-group horizontal with Bootstrap 4 With Bootstrap 4, the list-group component is very rich with design aesthetics, such as with borders, background colors, rounded corners, etc..
With my following list...

item 1

item 2

item 3

item 4

...how can I make it look fancy like the following....

item 1

item 2

item 3

item 4

...and still keep it horizontal.

A: So the options you have to get it done involve overriding the styles in the classes with other classes, or using a different component that looks more like what you need like Button Group here you can see what I mean.
In the case you use flex-row to change the direction of the list-group, you would have to adjust the borders of each item so it looks as you need. In this case the list-group will flex horizontally on larger screens, but stack on smaller ones

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

item 1

item 2

item 3

item 4

  <button type="button" class="btn btn-link">Left</button>
  <button type="button" class="btn btn-link">Middle</button>
  <button type="button" class="btn btn-link">Right</button>

A: One approach would be using classes d-flex and flex-row on the list-group. If you want the items to stack on smaller screen, you can use the breakpoint classes of bootstrap (SM, MD, LG, **XL*). For example: flex-sm-row

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

item 1

item 2

item 3

item 4


text:
Q: Intellij Idea add Scala support to existing Java project Intellij Idea add Scala support to existing Java project.
Just cannot figure it out How to add Scala worksheet to existing Java project?
It would be just nice to have Scala REPL or worksheet.
But after resiarsh and trying I failed to do that.

A:
To add Scala support to existing module:

*

*Right-click the module in Project View, choose "Add Framework Support…"

*Check "Scala" in technologies list (unavailable if module has Scala facet attached)

*Provide a path to Scala installation (if not detected)

From http://blog.jetbrains.com/scala/2010/09/02/project-configuration-explained/.


text:
Q: Autenticação API bearer Cliente Tenho uma API que retornar token bearer, normal, conforme imagem

A dúvida é o seguinte, tem uma aplicação MVC que consome essa API, e quero colocar [Authorize] nas classes dessa aplicação MVC e que faça autenticação com o token da API, é possível? se sim, como devo fazer?
private async Task<List<string>> GetToken(string UserName, string password)
    {
        List<string> lstResult = new List<string>();
        string[] resultResponse = new string[2];

        var parametros = new Dictionary<string, string>();
        LoginModel param = new LoginModel { UserName = UserName, Password = password};

        IRestResponse restResponse = await APIIdentity.ResponseAPIPostToken_RestSharp("/token", param);

        var token = JToken.Parse(restResponse.Content);
        var obj = JObject.Parse((string)token.ToString());

        int statusCode = (int)restResponse.StatusCode;

        if ((int)statusCode > 200)
        {
            resultResponse[0] = Convert.ToString((int)statusCode);
            resultResponse[1] = obj["error_description"].ToString();
        }
        else
        {
            resultResponse[0] = Convert.ToString((int)statusCode);
            resultResponse[1] = obj["access_token"].ToString();
        }

        lstResult.AddRange(resultResponse);

        return lstResult;
    }

 public static async Task<IRestResponse> ResponseAPIPostToken_RestSharp(string URIResource, LoginModel objParam)
    {
        RestClient restClient = new RestClient(string.Format("{0}", ConfigurationManager.AppSettings["APIUrl"]));
        RestRequest restRequest = new RestRequest("/token", Method.POST);

        string encodedBody = string.Format("grant_type=password&username={0}&password={1}", objParam.UserName, objParam.Password);
        restRequest.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
        restRequest.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);

        return await restClient.ExecuteTaskAsync(restRequest);
    }


text:
Q: Android ActionBar/Toolbar colors different in Light vs Dark themes I am trying to understand why the ActionBar is styled differently in Light vs Dark themes. Below is a simple settings screen that can toggle between Light and Dark themes with identical themes.

values\themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Dark application theme. -->
    <style name="Theme.SettingsApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <item name="colorPrimary">@color/blue_normal</item>
        <item name="colorPrimaryVariant">@color/blue_dark</item>
        <item name="colorOnPrimary">@color/white</item>
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <item name="colorSurface">@color/red</item>
        <item name="colorOnSurface">@color/green</item>
    </style>
</resources>

values-night\themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Dark application theme. -->
    <style name="Theme.SettingsApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <item name="colorPrimary">@color/blue_normal</item>
        <item name="colorPrimaryVariant">@color/blue_dark</item>
        <item name="colorOnPrimary">@color/white</item>
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <item name="colorSurface">@color/red</item>
        <item name="colorOnSurface">@color/green</item>
    </style>
</resources>

values\colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="blue_normal">#FF3F7FBF</color>
    <color name="blue_dark">#FF2F6090</color>
    <color name="white">#FFFFFFFF</color>
    <color name="red">#FF0000</color>
    <color name="green">#00FF00</color>
</resources>

In the Light them, the ActionBar comes across as blue and white, indicating it is using colorPrimary and colorOnPrimary. In the Dark theme it comes across as red and green, indiciating it is using colorSurface and colorOnSurface. Why are these applied differently and how can I get consistent application of colors on the ActionBar?

A:
Why are these applied differently

Quote from the documentation:

large surfaces should not use bright background colors because they can emit too much brightness. When applicable, the Material themes will provide this behavior out-of-the-box, e.g., by having the Light theme default to Widget.MaterialComponents.AppBarLayout.Primary and the Dark theme default to Widget.MaterialComponents.AppBarLayout.Surface.

So, though you have the same colors for both light & dark themes, but the Primary colors are the preferable colors in the light mode, and the surface colors are for the dark mode.

how can I get consistent application of colors on the ActionBar?

This can be concluded from the previous documentation ..
So, you just need to, have values\themes.xml to contain:

*

*colorPrimary & colorSurface to have the same value

*colorOnPrimary & colorOnSurface to have the same value

Applying this to your example
values\themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Dark application theme. -->
    <style name="Theme.SettingsApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <item name="colorPrimary">@color/blue_normal</item>
        <item name="colorOnPrimary">@color/white</item>

        <item name="colorSurface">@color/blue_normal</item>
        <item name="colorOnSurface">@color/white</item>
    </style>
</resources>

For more info, please check documentation.


text:
Q: How, and should I, use KL-divergence to improve a naive Bayes classifier? How, and should I, use KL-divergence to improve a naive Bayes classifier?
I have a Naive Bayes Classifier working on a number of datatypes (real, boolean and categorical). Each variable is weighted identically. But from inspecting my data I know
that some variables contribute more to my overall classification than others.
Should I use KL-divergence (information gain) to weight my probabilities before combining
them to calculate class membership? How would I go about this?
If this is the wrong approach, what other approaches might I try?

A: When estimating the parameters of a naive Bayes classifier, you are effectively optimizing the joint likelihood $p(x, c) = \prod_i p(x_i \mid c) p(c)$ instead of the conditional likelihood $p(c \mid x)$, which is the distribution you are actually interested in.
You can probably get some improvement by directly optimizing the parameters of your model using gradient ascent or something similar with respect to the average conditional log-likelihood, $\left<\log p(c \mid x)\right>$.
If you only want to reweight the probabilities, you could redefine your conditional distribution to something like
$$\log q(c \mid x) = \log p(c) + \sum_i w_i \log p(x_i \mid c) + const$$
and only optimize the weights $w_i$ using gradient ascent. The gradient should be
$$\frac{\partial}{\partial w_j} \left<\log q(c \mid x)\right> = \left<\log p(c \mid x)\right> -\left<\log p(c \mid x)\right>_q,$$
where the first expectation on the right-hand side is with respect to the data and the second is with respect to the data and $q(c \mid x)$.
At least that's what I would try.
I briefly looked at this paper, where they seem to suggest to use mutual information (average information gain, equation 6) for the weights,
$$w_i = I(C, X_i) = \sum_{x_i} p(x_i) D_\text{KL}(p(c \mid x_i) \mid\mid p(c)),$$
but I would have to take a closer look at the paper to tell whether there is a principled motivation behind it or whether it's just a heuristic. Maybe somebody else knows more.
When you optimize the weights directly, at least you know that you're optimizing the right objective function (provided your ultimate goal is to get a good estimate of $p(c \mid x)$ in the Kullback-Leibler sense).


text:
Q: Python Simulation I am using the graphics.py library to generate a simulation of multiple balls falling from the top of the screen. The balls should 'bounce' off the bottom and then resume falling back down. The rate at which the ball falls is determined by its size.
Currently the program generates and drops the balls with appropriate rates but when they 'bounce' the continue upwards indefinitely instead of falling again.
Any ideas would be greatly appreciated.
Code is as follows:
from graphics import *
from random import randint, choice
from time import sleep

# Generate a graphics window and set the 0,0 to the lower left corner.
win= GraphWin("Falling Bubbles!",600,600)
win.setCoords(0,0,600,600)
cornerB1= Point(-100,-100)
cornerB2= Point(700,700)
Background= Rectangle(cornerB1, cornerB2)       #Create a white background
Background.setFill('white')
Background.draw(win)

# Distance function and check function used to determine if two bubbles will be generated overlapping
def dist(p1, p2):
    x1, y1 = p1.getX(), p1.getY()
    x2, y2 = p2.getX(), p2.getY()
    return ((x1-x2)**2+(y1-y2)**2)**.5

def check(center, radius, bubbles):
    overlapping= False
    bubble= [item[0] for item in bubbles]
    for i in bubbles:
        radiSum= radius + bubble[0].getRadius()
        if (dist(center, bubble[0].getCenter())< radiSum):
            overlapping= True

        return overlapping

# This function defines between 3 and 6 Circle objects with a random radius between
#   10 and 35 pixels and stores them in a list with the format [bubble, dx, dy]
def makeBubbles():
    bubbles = []
    colors = ['red','blue','green','pink','yellow','cyan']

    n= randint(3,6)
    for i in range(n):
        center = Point(randint(40,560),randint(540,560))
        radius = randint(10,35)
        while (check(center, radius, bubbles)):
            center= Point(randint(40,560),randint(540,560))

        newbubble = Circle(center,radius)
        newbubble.setFill(choice(colors))
        bubbles.append([newbubble,0,-.6])
    return bubbles

# This function accepts the list of bubbles with their dx, dy values as a parameter
# The function increases the speed of all bubbles in the list with smaller
#   bubbles should increasing proportionally faster than larger bubbles
# The function returns the moddified 'bubbles' list

def speed(bubbles):
    for bubble in bubbles:
        radius= bubble[0].getRadius()
        if radius<=15:
            bubble[2] -= 1.1
        elif 16<=radius<=25:
            bubble[2] -= 1.05
        else:
            bubble[2] -= 1.025
    return bubbles
# This function accepts the list of bubbles with their dx, dy values as a parameter
# The function determines it the bubble is too close to the bottom border of the Graphics window
#   reverses it's dy value and simultaneously reduce it's speed
# The function returns the moddified 'bubbles' list

def sink(bubbles):
    for bubble in bubbles:
        center = bubble[0].getCenter()
        radius= bubble[0].getRadius()
        y= center.getY()
        if y+ bubble[2]< radius:
            bubble[2] *= -.9
        if bubble[2]>0:
            bubble[2]*=.9
        if .7<bubble[2]<-.7:
            bubble[2]= 0
        bubble[0].move(bubble[1], bubble[2])
        time.sleep(.025)

# Main
def main():
    bubbles= makeBubbles()
    n= len(bubbles)
    x= 0
    for bubble in bubbles:
        bubble[0].draw(win)
    while True:
        speed(bubbles)
        sink(bubbles)
        x+= 1

main()

EDIT1: New line added balls slow down to stop when bouncing up
EDIT2: Follow Up Question. I need the generated bubbles to not overlap at all when being generated.
EDIT3: Code added to determine if balls are generated overlapping

A: This is an answer to the follow-up question regarding avoiding bubble overlaps:
Here is a half pseudo-code method for checking if a generated center and radius pair overlaps another bubble in the bubble list. Note that it is indeed pseudocode because I don't know python syntax very well. Also note that you'll need to implement a dist function that takes in two Point objects and calculates the distance between them.
def checkIfOverlapping(center, radius, bubbles):
   overlapping = false;
   for i in range(bubbles.length):
      radiSum = radius + bubbles[i].radius
      if (dist(center, bubbles[i].center) < radiSum):
         overlapping = true

   return overlapping

You can eliminate some of the work done by the for loop by converting it to a while loop and exiting if overlapping is determined to be true as well:
while (i < bubbles.length and !overlapping)

This is what your for loop would now look like when generating the bubbles:
for i in range(n):
   center = Point(randint(40,560),randint(540,560))
   radius = randint(10,35)
   while (checkIfOverlapping(center, radius, bubbles)):
      center = Point(randint(40,560),randint(540,560))

   newbubble = Circle(center,radius)
   newbubble.setFill(choice(colors))
   bubbles.append([newbubble,0,-.6])

The loop now regenerates center points until the bubble is not overlapping with any bubble currently in the list. You might also consider regenerating the radius in that while loop too, in case the original radius is so big that no non-overlapping point exists. This can lead to an infinite loop.


text:
Q: BinaryFormatter in Silverlight I am building a WCF RIA service used for Silverlight application.
I am using BinaryFormatter.Serialize() to serialize my data to binary array before sending back to client side (silver light).
However, Silverlight 4 doesn't support BinaryFormatter yet, could you advise how to deserialize a byte array back to object at client side as BinaryFormatter.Deserialize() does at service side.
Thanks

A: I found some links that might help you:

*

*Check this project out: http://whydoidoit.com/silverlight-serializer/

*Silverlight 3.0 Binary Serialization Support?

*http://www.codeproject.com/KB/silverlight/bin_ser_in_silverlight.aspx

*

*"In Silverlight, there is no choice if you want to use binary serialization. As there is no BinaryFormatter in Silverlight, the only solution is sharpSerializer."


text:
Q: Permalink not work when admin not login I had configured premalink on my wordpress. It works fine when I login in as a admin.
However, if I log out, all of the links cannot be opened. Instead, it gives me a 404 page.
Has anyone met this problem before and tell me how to solve it? Thanks.

A: Double check your page properties. May be it is password protected/private or may be it is not published.
To check page properties:

*

*Login to Dashboard.

*Click Pages on left side.

*Hover on the page which you getting 404 and click Quick Edit
This will show all the details about your page. Check the password field, private and the Status field. The status should be published.
Check it.

A: Try flushing the permalinks cache by going back to the permalink options and clicking save (without changing anything). If that doesn't do the trick, make sure you've cleared your browser cache :P


text:
Q: Using COLLECT STATISTICS in Teradata In Teradata I can use a statement like ...
collect statistics on my_table column(col1)

This will gather stats on the table and store them in DBC views like ColumnStats, IndexStats and MultiColumnStats.  I'm also under the impression that the optimizer (parsing engine) will find the statistics when they are available and use them instead of estimated table cardinality/index value counts to make better decisions on how to execute a query.
This all sounds great, but I have some questions.

*

*are there any disadvantages to using collect stats?

*When is it appropriate/inappropriate to use collect statistics in your SQL scripting?

*What's the performance benefit to collect statistics on a field that's already indexed?

*How long are statistics stored for (table, volatile tables)?

*Any other comments concerning collect statistics would be appreciated.

A: 1>are there any disadvantages to using collect stats?
Yes, collect stats itself is time consuming, it actually locate data from AMPS and insert the stats in dictionary tables.
Suppose you have a table definition like:
ct t1(x1 int,y1 int, z1 int);
The table contains millions of rows and z1 is never used in the ST/Join conditions, then it is not worth to collect stats on z1.
2>When is it appropriate/inappropriate to use collect statistics in your SQL scripting?
Already answered above. If a column is going to be used as ST/Join condition .i.e in where or on clause, you must collect stats, otherwise not needed.
3>What's the performance benefit to collect statistics on a field that's already indexed?
ct t1(x1 int,y1 int) primary index(x1);
for a simple query like sel * from t1 where x1 = 5;
will demonstrate the usefulness of collect stats.
How?
the optimizer can correctly estimate how many rows this query will select and if t1 is going to be joined with say t2, a efficient join will be chosen by optimizer.
4>How long are statistics stored for (table, volatile tables)?
Table : permanently.
volatile tables: till session expires.
5>Any other comments concerning collect statistics would be appreciated.
Nothing has been discussed about multicolumn stats.
Say, the query is like:
sel * from t1 join t2 on y1=y2 and x1=2;
then collecting multi-column stats on (x1,y1) would be quite helpful in optimization.
Also, if table demography has been changed (increased number of rows) you must consider re-collecting the stats


text:
Q: How can two algorithms one with O(n^2) the other Ω(n) has about the same run time? How can two algorithms

*

*one with O(n²)

*the other with Ω(n)
have the same practical run time, when testing the algorithms with a large number?

A: O(f(n)) is a set of functions that grow proportionally to f(n) or slower.
Ω(f(n)) is a set of functions that grow proportionally to f(n) or faster.
There are many functions that grow at least as fast as n, but not faster than n^2. For example: n, n*log n, n^1.5, n^2.


text:
Q: Parent-child dimension in Analysis Services from Server2008 Someone know some interesting and complete tutorial about how to create a Parent-Child dimension in Server2008?
I found a brief introduction in Server2005, but a lot of step are changed.
thanks in advance.

A: Yup, it changed (whether it is better is debatable) but I found this blog very useful.
http://www.brustblog.com/archive/2008/06/22/analysis-services-2008-wizards-is-the-magic-gone.aspx
Good luck!


text:
Q: Good way to restructure a table I have a number of tables in an existing database that i would like to migrate to a new database but with a little different structure.
For example if a current table has columns like below:
table1
id, a1, a2, a3, a4, b1, b2, b3, b4

And the new structure would be something like:
table1, table2 (new table)
table1 (patient names)
id, a1, a2, a3, a4, bfk

table2 (doctor names)
id, b1, b2, b3, b4

EDIT:
Adding hypothetical scenario of patients and doctors.
Lets say that the original table had 4 rows for 4 patients so
it would look like
 row1   id, pat1fname, pat1lname, pat1address...., doc1fname, doc1lname,....
 row2   id, pat2fname, pat2lname, pat2address...., doc2fname, doc2lname,....
 row3   id, pat3fname, pat3lname, pat3address...., doc1fname, doc1lname,....
 row4   id, pat4fname, pat4lname, pat4address...., doc1fname, doc1lname,....

Lets say that we only have two doctors and we want to put them in their own table 'Doctors'
so the tables would look like this
Original table structure
     row1   id, pat1fname, pat1lname, pat1address...., doc1fname, doc1lname,....
     row2   id, pat2fname, pat2lname, pat2address...., doc2fname, doc2lname,....
     row3   id, pat3fname, pat3lname, pat3address...., doc1fname, doc1lname,....
     row4   id, pat4fname, pat4lname, pat4address...., doc1fname, doc1lname,....

New table structure
'Patients' table
    row1    id, pat1fname, pat1lname, pat1address, 1, ....,
    row2    id, pat2fname, pat2lname, pat2address, 2, ....,
    row3    id, pat3fname, pat3lname, pat3address, 1, ....,
    row4   id, pat4fname, pat4lname, pat4address, 1, ....,
'Doctors' table
    row1    1, doc1fname, doc1lname,....
    row2    2, doc2fname, doc2lname,....

What would be a good way of linking these two new tables and converting each row from one-table-structure above to the two-table-structure i mentioned.

A: Methods of Linking:
1. Logically just left join doctors table and get doctor ID during patients data insert as showed below
2. Physically add foreign key constraint and during insert left join doctors table and get doctor ID during patients data insert
 /* Supposed your OriginalTable is with following structure */

    create table #OriginalTable
    (
    ID int,
    patfname varchar(100),
    patlname varchar(100),
    pataddress1 varchar(100),
    pataddress2 varchar(100),
    patcity varchar(40),
    patstate varchar(4),
    Patzipcode varchar(20),
    Docfname varchar(100),
    Doclname varchar(100),
    Docaddress1 varchar(100),
    Docaddress2 varchar(100),
    Doccity varchar(40),
    Docstate varchar(4),
    Doczipcode varchar(20),
    DocNPI varchar(40)
    )

    /*Dumpy data insert*/
    insert into #OriginalTable
    select '1', 'pat1fname','pat1lname','pat1address1','pat1address2','Pat1City','p1S','pt1zip'
    ,'doc1firstname','doc1lastname','doc1address1' ,'doc1address2' ,'doc1City','d1S','dt1zip','000001'
    union all
    select '2', 'pat2fname','pat2lname','pat2address2','pat2address2','Pat2City','p2S','pt2zip'
    ,'doc2firstname','doc2lastname','doc2address1' ,'doc2address2' ,'doc2City','d2S','dt2zip','000002'
    union all
    select '3', 'pat3fname','pat3lname','pat3address3','pat3address2','Pat3City','p3S','pt3zip'
    ,'doc1firstname','doc1lastname','doc1address1' ,'doc1address2' ,'doc1City','d1S','dt1zip','000001'
    union all
    select '4', 'pat4fname','pat4lname','pat4address4','pat4address2','Pat4City','p4S','pt4zip'
    ,'doc1firstname','doc1lastname','doc1address1' ,'doc1address2' ,'doc1City','d1S','dt1zip','000001'

    /* create patients table with all required fields*/
    create table Patients
    (
    ID int identity(1,1),
    FirstName Varchar(100),
    LastName Varchar(100),
    Adress1 Varchar(100),
    Adress2 Varchar(100),
    City Varchar(50),
    [State] Varchar(4),
    ZipCode varchar(20),
    DoctorID Int
    )

    /* create Doctors table with all required fields*/
    create table Doctors
    (
    ID int identity(1,1),
    FirstName Varchar(100),
    LastName Varchar(100),
    Address1 Varchar(100),
    Address2 Varchar(100),
    City Varchar(50),
    [State] Varchar(4),
    ZipCode varchar(20),
    NPI varchar(40)
    )

    /*Remove existing data from patients and doctors table*/
    delete from Doctors
    delete from patients

    /* insert all distinct doctors data from Orginal table */
    insert into Doctors( FirstName ,LastName ,Address1 ,Address2 ,City ,[State] ,ZipCode ,NPI )
    select distinct docfname,doclname,docAddress1,docAddress2, docCity, docState, docZipcode, docNPI
    from #OriginalTable

    /* Set Identity insert On to add OLD unique ID values as they are in #OriginalTable */

    SET IDENTITY_INSERT Patients ON

    insert into  Patients( ID , FirstName ,LastName ,Adress1 ,Adress2 ,City ,[State] ,ZipCode ,DoctorID )
    select old.ID ,old.patfname ,old.patlname ,old.pataddress1 ,old.pataddress2 ,old.patcity ,old.patstate ,old.Patzipcode ,doc.ID
    from #OriginalTable old left outer join Doctors doc
    on old.Docfname=doc.FirstName
    and old.Doclname=doc.LastName
    and old.Docaddress1=doc.Address1
    and old.Docaddress2=doc.Address2
    and old.Doccity=doc.City
    and old.Docstate=doc.[State]
    and old.Doczipcode=doc.ZipCode
    and old.DocNPI=doc.NPI

    /*Set Identity insert off */
    SET IDENTITY_INSERT Patients OFF

    /* Query table to verify inserted data*/
    select * from #OriginalTable
    select * from Patients
    select * from Doctors

    DROP Table #OriginalTable

A: Either use a SELECT INTO or generate your tables and do an INSERT INTO SELECT
USE NewDatabase
GO

SELECT id, a1, a2, a3, a4, <some calc here> AS bfk
      INTO NewTable1 -- Generates the new table
FROM OldDatabase.schema.Table1

SELECT id, b1, b2, b3, b4
      INTO NewTable2 -- Generates the new table
FROM OldDatabase.schema.Table1

OR
USE NewDatabase
GO

CREATE TABLE NewTable1 (id int, a1 ......)
CREATE TABLE NewTable2 (id int, b1 ......)

INSERT INTO NewTable1
SELECT id, a1, a2, a3, a4, <some calc here> AS bfk
FROM OldDatabase.schema.Table1

INSERT INTO NewTable2
SELECT id, b1, b2, b3, b4
FROM OldDatabase.schema.Table1

The first method is of course much easier but the second gives you quite a bit more control over the structure.  For example if the id column is an identity then the id columns in both NewTable1 and NewTable2 will be identity columns.
EDIT:
Based on the edit here is what I would do.  You can still do it a number of ways, this is just one example.
CREATE TABLE Table1 (id int, patfname varchar(50), patlname varchar(50),
                        pataddress varchar(50), docfname varchar(50),
                        doclname varchar(50))

INSERT INTO Table1 VALUES
     (1, 'pat1fname', 'pat1lname', 'pat1address', 'doc1fname', 'doc1lname'),
     (2, 'pat2fname', 'pat2lname', 'pat2address', 'doc2fname', 'doc2lname'),
     (3, 'pat3fname', 'pat3lname', 'pat3address', 'doc1fname', 'doc1lname'),
     (4, 'pat4fname', 'pat4lname', 'pat4address', 'doc1fname', 'doc1lname')

CREATE TABLE Doctor (docid int NOT NULL IDENTITY(1,1),
                    docfname varchar(50), doclname varchar(50))

INSERT INTO Doctor
SELECT docfname, doclname
FROM Table1
GROUP BY docfname, doclname

CREATE TABLE Patients (id int, patfname varchar(50), patlname varchar(50),
                        pataddress varchar(50), docid int)

INSERT INTO Patients
SELECT Table1.id, Table1.patfname, Table1.patlname, Table1.pataddress, Doctor.docid
FROM Table1
INNER JOIN Doctor
    ON Table1.docfname = Doctor.docfname
    AND Table1.doclname = Doctor.doclname


text:
Q: Make Google Sheets remember data Currently, I'm working with large databases in which we store information on assets. It also contains a monthly inspection section in which one can sign off if some inspection has been conducted.
Until now I've made a new file every year in which only the inspection section is the part that differs from the previous file.
What I'd like to do is to have the inspection section (some collection of columns and rows) to show all the signed months from some year (in essence needing sheets to remember the previous years.)
So basically if I'd select 2020, I'd expect an empty array. But if I'd select 2019 in a drop-down menu, I'd like to see all the signed off months within the one and same array.
I already tried copy pasting the results in separate tabs and just copy paste but that would make for a huge file.
What I'd expect (x meaning it's signed off):
2020
A     B      C
-     -      -
2019
A     B      C
x     x      x

I'd like to switch between those years within the same sheet and within the same set of cells.


text:
Q: Creating nice GUI I'm seeking graphic advice on how to have your interface look better.
So far I've been focusing on usability but its starting to look like a Jakob Nielsen kind of interface.
I'm searching for tutorials on how to pimp up my windows forms application or at least general guidelines on how to do so
edit :
thank you for the info. I was looking for something more oriented toward pure graphic considerations instead of usability documentation.
This question refered me to this site which is very nice. It is the kind of page which says "hey, to look nice your application should have rounded corners". Very useful, lots of different gotcha I'll look for

A: Don't Make Me Think is a classic and must-read:
http://www.amazon.com/exec/obidos/ASIN/0789723107/ref=nosim/joelonsoftware/
From Amazon.com:

Product Description
People won't use your web site if they
  can't find their way around it.
  Whether you call it usability,
  ease-of-use, or just good design,
  companies staking their fortunes and
  their futures on their Web sites are
  starting to recognize that it's a
  bottom-line issue. In Don't Make Me
  Think, usability expert Steve Krug
  distills his years of experience and
  observation into clear, practical--and
  often amusing--common sense advice for
  the people in the trenches (the
  designers, programmers, writers,
  editors, and Webmasters), the people
  who tell them what to do (project
  managers, business planners, and
  marketing people), and even the people
  who sign the checks.
Krug's clearly explained, easily
  absorbed principles will help you
  sleep better at night knowing that all
  the hard work going into your site is
  producing something that people will
  actually want to use.

A: 37signals has a blog with numerous articles. Though they are focused on web development, the same principles of simplicity and usability could be applied to WinForms.
http://www.37signals.com/svn/

A: Everyone is different, but i think it's always safe to go clean and simple, and not to over do it.
Try not to throw loads of different things together even if individually they look great!
Have a look at 101 Places To Get Design Inspiration for inspiration :)

A: A good book:  User Interface Design for Programmers by Joel Spolsky.  Somewhat old (2001) but still relevant.

A: If you need help in the layout of your GUI applications to make them more effective, this site is a great resource: http://designingwebinterfaces.com/designing-web-interfaces-12-screen-patterns


text:
Q: Using the result of an AJAX call in JavaScript function I realise this question was already asked on StackOverflow but the answer is mostly focused on jQuery.
How do I return the response from an asynchronous call?
I have a JavaScript function that allows people on the website to vote. However they can only vote once a day. So I am trying to call another JS function which is doing an AJAX call. This in turn calls a PHP page, which is doing a query in the database to check whether the caller voted in the last 24H.
function can_vote(user_id)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "rating.php?&user_id=" + user_id, true);
    xmlhttp.send();
    var result = true;
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            console.log("answer: " + xmlhttp.responseText);

            return (xmlhttp.responseText == "false") ? false : true; // doesn't work
        }
    }
}

function rating(user_id)
{
    if (can_vote(user_id) == false)
    {
        // display error message
        ...
        return false;
    }
    ...
}

This doesn't work for the reasons explained in the link I provided earlier. I tried to follow the suggestions suggested in this link but I can't make it work (I can only use JavaScript no jQuery). I tried to implement a callback system:
can_vote(callback, user_id)
{
    ...
    xmlhttp.onreadystatechange=function()
    {
        // if we can a positive answer from the rating.php
        // then call the callback function
        callback();
    }
}

function rating(user_id)
{
    var result = false;
    can_vote(function() {
        result = true;
    }, user_id);
    console.log(result); // always false
    ...
}

But while the mechanism works, it doesn't update the variable true, which seems to be "local" to the callback function.
It feels like I am close to the solution, but can't go any further. Passing a variable by reference to the function doesn't work in JS, so I have explored all options I can think of.
Could someone please help and suggest a fix/solution (using JavaScript only)?
EDIT 1:
As suggested earlier, while the answer in How do I return the response from an asynchronous call? is very thorough and informative, it answers the question using jQuery not JavaScript.
EDIT 2 and ANSWER:
I can't answer my own question for whatever reason, but fair enough, because in fact I should have thought twice before asking it. So thanks for all answers.

*

*Apologies, it is indeed a duplicate of the question linked above

*Egg Vans suggested to rethink the problem. This is indeed one way. In fact it's possible in the PHP page creating the rating system, to actually call a PHP function when the user votes. My system requires the user to click on "stars" to vote. Thus, I could set the onclick callback to a PHP function rather than a JS function and bypass AJAX all together.

*however the reason I can't do this is because finding out the number of stars chosen by the user requires some calls to DOM functions.

Now, while I consider myself as an okay programmer, the problem is that in this particular situation, I completely overlooked the code. The original question contains the correct answer for "processing" the result of an AJAX call from within a JS function. So what I have overlooked is that in fact, the actual result of the AJAX call will be "processed" in the callback function. So for example in my case if the user can vote, then I should execute some code within this call back function, and if he/she can't vote, I should execute some other code in the same call back function. In other words:
function can_vote(callback, user_id)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "rating.php?user=" + user_id, false);
    xmlhttp.send();
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
             // pass the result to the callback function and process this result accordingly
             callback(xmlhttpx.responseText);
        }
    }
}

function star_rating(user_id)
{
    ...

    can_vote(function(result)
    {
        if (result == false)
        {
            // you can't vote display error message
        }
        else
        {
            // you can vote do your stuff here, find out what's the rating from the user
            // add it to the db, and update the current rate yet using another
            // AJAX call.
        }
    }, user_id);

    // any code you put after this line will be processed likely before the AJAX call returns
    ...
}

Thanks again everything for your patience. Hope though that this concrete example will help others.

A: The A in AJAX stands for asynchronous. That means that your JS is not going to wait for the AJAX to finish before moving on to the next thing (in other words it doesn't "block" the script).
This is why you have a callback function that executes when the call is complete. The callback is triggered only when you have the data you need.

A: I believe you should move console.log inside of your callback function:
 function rating(user_id) {
     var result = false;
     can_vote(function(result) {
         result = true;
         console.log(result);
     }, user_id); }

You always have "false" result because you are using asynchronous callback.
UPD:
Maybe i didn't catch your problem. If you need to process the result of callback just call your processing method from callback function body:
     can_vote(function(result) {
        processCanVoteResult(result); //call result processing
     }, user_id); }


text:
Q: how do I show up a SSP page in Suitecommerce Denali? I follow the training step,

*

*new a SSP application

*set application folder (include setting applications publisher)

*check the folder in /SSP applications

*build a XXX.ssp in there. (used eclipse IDE, and upload it)

*show up the XXX.ssp file  -->  used

http://shopping.na1.netsuite.com/c.TSTDRV0000000//XXX.ssp?n=1
but, still show up "page not found"
what did I miss?

A: You need to include the path to your ssp folder. It's not the file cabinet folder but the path you set up in the SSP Application definition.
e.g. http://shopping.na1.netsuite.com/c.TSTDRV0000000/path-to-ssp/XXX.ssp


text:
Q: Why don't xvalues bind to non-const lvalue references? The following does not compile:
#include <iostream>
using namespace std;

int x = 5;
int && f () { return std::move(x); }
int g(int & y) { return y; }

int main() {
    g(f());
    return 0;
}

It's clear to me why prvalues (unnamed temporaries) do not bind to non-const lvalue references -- it does not make sense to modify them, as they will soon disappear. Yet why do xvalues not bind to non-const lvalue references?
If a function returns int &&, the referenced object can't be temporary, otherwise we would get a dangling reference. Hence if an int && is returned, that's, in my understanding, a reference with the additional guarantee that it's safe to move from it.
Edit: Wording corrected: "Values" bind to "references" and not vice versa.
Second edit: The following compiles -- I do not see the conceptual difference, besides y now being an lvalue. Yet it still references x. I understand why this should compile and the above shouldn't, by the language specification. I do not, however, understand the reason behind it. Why does mere aliasing change the picture?
#include <iostream>
using namespace std;

int x = 5;
int && f () { return std::move(x); }
int g(int & y) { return y; }

int main() {
    int && y = f(); // reference!
    g(y); // compiles

    // check that y indeed references x
    y = 7;
    std::cout << x << std::endl; // prints 7, of course
    return 0;
}

Third edit: In short, what's the idea behind not allowing
int && f() { ... }
int g (int & y) { ...}
g(f());

yet allowing
int && f() { ... }
int g (int & y) { ...}
int & k (int && y) { return y; }
g(k(f()));

A: Because that would make a mess.
The whole point of non-const lvalue references is that they are aliases for non-temporary objects whose lifetime is already being managed by some other means. The introduction of rvalue references — and, crucially, std::move — was specifically to create a new "class" of references whose binding signifies that the referent is most likely "safe" to move from.
If these referents also were able to bind to a simple T&, you'd have a slew of ambiguous conversion errors and nobody would know what to do. You could give such conversions a lower rank, but I feel that this would still be extremely confusing.
As such, you're looking at it backwards. Ask yourself instead why xvalues don't bind to non-const lvalue references.


text:
Q: Linking HTML files in a folder with one another using python I have a folder full of html files as follows:
aaa.html
bbb.html
ccc.html
....
......
.........
zzz.html

All these htmls are created using a python script, and hence follow the same template.
Now, I want to link all these html files, for which I already have the placeholders in the html as follows:

Previous

Next

I want to fill these placeholders with the filenames in the folder. For example, bbb.html will have

Previous

Next

and the ccc.html file will contain:

Previous

Next

And so on for rest of the files.
Can this task be done using python? I don't even know how to start with. Any hints, suggestions would be really helpful.

A: You can use the beautifulsoup library to modify html:
from bs4 import BeautifulSoup

file_names = ['bbb.html', 'ccc.html', ... , 'yyy.html']
# we exclude first and last files (not sure what to do with them ?)

for ind, file_name in enumerate(file_names):
    with open(file_name, 'r+') as f:
        soup = BeautifulSoup(f.read(), 'html.parser')
        # we suppose that there is only one link for previous and next
        soup.find_all(class_='previous')[0]['href'] = file_names[ind - 1]
        soup.find_all(class_='next')[0]['href'] = file_names[ind + 1]
        # erase contents and replace with new html
        f.seek(0)
        f.truncate()
        f.write(soup.prettify("utf-8"))  # to get readable HTML

If the filenames aren't as consistent as in your example, and you want to generate the list from the files in the directory, you can use os.walk or glob.glob.

A: You can replace elements from your template by looping over the file list, with list wrapping. Here's an example for aaa.html using aaa,bbb,ccc:
#f = ['aaa.html','bbb.html','ccc.html']
f = sorted(['aaa.html','bbb.html','ccc.html'])  # explicit sorting

t = """

Previous

Next

"""  # sample aaa.html file

for i in xrange(len(f)-1):
    #print f[i]
    t = t.replace('
Previous','
Previous')
    t = t.replace('
Next','
Next')

print t

To do the list-wrapping I use this concept (After zzz comes aaa)
Gives as an output for aaa.html:

Previous

Next

To complete the code, you'd have to loop over *.html files (see glob.glob)


text:
Q: History and origin of sine function I'm doing some research about the beginning of trigonometry. I want to know why and who draw the first time the sine function. Do you have one site or something that can help me ?

A: In the anceint greek time they didn't use the sine, they used the chord instead which has $\text{crd}(\alpha)\in[0,2]$. The indians later took this and improved upon it and started using the sine instead which was roughly translated as "half-chord" because it's half the value of the chords value and half the angle.

A: In Astronomy and maybe in astrological predictions(curved planetary aspect/position). Shlokas had been devised for accurate calculations and used like trig table of values.
AncientSine