text:
Q: Remove scientific notation formatting for Float values in kotlin android I am trying to set the float value to an edit text. For this I am using a binding adapter like this below.
@BindingAdapter("android:text")
@JvmStatic
fun setAmount(editText: EditText, currency: Float?) {
    if (currency!= null && currency!=0.0f) {

       editText.setText(""+Math.round(currency))
    }else{
        editText.setText("")
    }
}

Model Class
class OpportunityModel : BaseObservable(), Serializable {

var accountName = ""
var accountGuid: String? = null
var amount = 0.0
var potentialAmount:Float = 0.0f
get() = field
set(value) {field=value}
var contactPersonName = ""
var fieldOne = ""
var fieldTwo = ""
var fieldThree = ""
var fieldFour = ""
var fieldFive = ""
var opportunityName = ""
var opportunityGuid: String? = null
var opportunityRating = 0
var opportunityReasonGuid: String? = null
var opportunityIntStatus = 2
var opportunityDispStatus = ""
var opportunityNotAvailable = false
var genericFieldUI: GenericFieldDto? = null
@SerializedName("expDateOfClosure")
var dateForServer: String? = null
var expDate = ""
var contactPersonNameGuid: String? = null
var listOfAccountContact = ArrayList<AccountContactPersonModel>()
var listOfReasonMaster = ArrayList<ReasonMasterDto>()}

This shows the value properly in the edit text but when this value is added to the model class via data binding, it gets converted to scientific notation and is showing values like 1E+07. How can I stop this conversion to scientific notation ?

A: You can use String.format, like
@BindingAdapter("android:text")
@JvmStatic
fun setAmount(editText: EditText, currency: Float?) {
    if (currency!= null && currency!=0.0f) {

       editText.setText(String.format("%.8f", currency))
    }else{
        editText.setText("")
    }
}


text:
Q: Marionette async model fetching not working as expected I'm running into a weird issue. I have a Marionette module responsible for fetching data, which is exposed through Backbone.Wreqr Request/Response system. For my projects it looks like this (CoffeeScript):
@App.module 'Entities', (Entities, App, Backbone, Marionette, $, _) ->

    class Entities.Project extends Backbone.Model
        urlRoot: '/api/project'

    class Entities.ProjectsCollection extends Backbone.Collection
        model: Entities.Project
        url: '/api/projects.json'

    API =
        getProjectEntities: ->
            projects = new Entities.ProjectsCollection
            projects.fetch()
            projects

        getProject: (project) ->
            project = new Entities.Project({ id: project });
            project.fetch()
            project

    App.reqres.setHandler 'project:entities', ->
        API.getProjectEntities()

    App.reqres.setHandler 'project:entity', (project) ->
        API.getProject(project)

For the collection this works entirely as expected. Data is fetched, and when I pass it to a Marionette.CompositeView the view is rendered just fine.
I'm fleshing out a detail-page for these projects now, and all is not well. When I request a specific model by instantiating a new model currentProject = App.request 'project:entity', project, and then pass it on to a Marionette.ItemView, the ItemView parses its template before the model is fetched, causing an Uncaught reference error because the variables in my template haven't been declared yet... Any idea what's going on here?
My template is for now extremely simple:

Edit: Ok, apparently I'm doing more things wrong here, because when I log out this model to the console, all it has attribute-wise is its id. If someone could set me in the right direction that'd be great.

A: You're calling fetch and then immediately returning the project object, without waiting for the async fetch to complete.
Instead of returning the project object, return project.fetch() as this will return a promise. Then you can .then the value, ensuring it is available:

@App.module 'Entities', (Entities, App, Backbone, Marionette, $, _) ->

    class Entities.Project extends Backbone.Model
        urlRoot: '/api/project'

    class Entities.ProjectsCollection extends Backbone.Collection
        model: Entities.Project
        url: '/api/projects.json'

    API =
        getProjectEntities: ->
            projects = new Entities.ProjectsCollection
            projects.fetch()

        getProject: (project) ->
            project = new Entities.Project({ id: project });
            project.fetch()

    App.reqres.setHandler 'project:entities', ->
        API.getProjectEntities()

    App.reqres.setHandler 'project:entity', (project) ->
        API.getProject(project)

When making the call through reqres, you'll get a promise back.

App.request("project:entity", someId, function (promise){

  // wait for the project to finish loading

  $.when(promise).then(function(project){
    // do stuff with your project, here
  });

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run deployed app in Docker for Windows? Based on this article I was trying to deploy ASP.NET 4.5 application using Docker for Windows.
I have done everthing and I have checked container IP using docker inspect Container_ID.
I've put this IP to my browser and it opens only default IIS page.
So it seems that IIS server works, but how am I suppouse to open my application?
http://172.30.169.6 and http://172.30.169.6:80 - both of them displaying default IIS site.

A: To deploy an ASP.NET web application to a Docker container you can use the following procedure.
Publish Preset
Create a publish preset using the File System publish method. The resulting .pubxml file should look something like this:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <publishUrl>C:\Websites\DockerDeploy\</publishUrl>
    <DeleteExistingFiles>False</DeleteExistingFiles>
</PropertyGroup>
</Project>

Docker Image
Pull the official ASP.NET image from Microsoft:
docker pull microsoft/aspnet

Dockerfile
Since the publish profile from above writes the application to C:\Websites\DockerDeploy\, the dockerfile must be saved under C:\Websites\.
FROM microsoft/aspnet
COPY ./DockerDeploy/ /inetpub/wwwroot/

Custom Image
docker build -t mywebapplication .

Run the Container
docker run -p 80:80 mywebapplication


text:
Q: How do I print colored output to the terminal in Python? Is there a Python equivalent of Perl's
print color 'red';
print <something>;
print color 'reset';

available?
I am using this approach:
"\x1b[1;%dm" % (<color code>) + "ERROR: log file does not exist" + "\x1b[0m"

what I want is I should be able to set color for all print messages like,
print color 'red'
function_print_something(<some message>)
print color 'reset'

Here 'function_print_something' is my python function which will print some formatted log messages on to the screen.

A: A side note: Windows users should run os.system('color') first, otherwise you would see some ANSI escape sequences rather than a colored output.

A: There are a few libraries that help out here. For cmdline tools I sometimes use colorama.
e.g.
from colorama import init, Fore, Back, Style
init()

def cprint(msg, foreground = "black", background = "white"):
    fground = foreground.upper()
    bground = background.upper()
    style = getattr(Fore, fground) + getattr(Back, bground)
    print(style + msg + Style.RESET_ALL)

cprint("colorful output, wohoo", "red", "black")

But instead of using strings, you might want to use an enum and/or add a few checks. Not the prettiest solution, but works on osx/linux and windows and is easy to use.
Other threads about this topic and cross-platform support: e.g. here.

A: I suggest sty. It's similar to colorama, but less verbose and it supports 8bit and 24bit colors. You can also extend the color register with your own colors.
Examples:
from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

Demo:

A: For python 3.6.1 and above I would recommend using Rich. To install Rich and try it out, type the following in the terminal
pip3 install rich
python -m rich

If you don't want to use Rich,
you can try this with python 3:
from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

If you are using the Windows operating system, the above code may not work for you. Then you can try this code:
from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Hope that helps.

A: Compared to the methods listed here, I prefer the method that comes with the system.
Here, I provide a better method without third-party libraries.
class colors: # You may need to change color settings
    RED = '\033[31m'
    ENDC = '\033[m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'

print(colors.RED + "something you want to print in red color" + colors.ENDC)
print(colors.GREEN + "something you want to print in green color" + colors.ENDC)
print("something you want to print in system default color")

More color code , ref to : Printing Colored Text in Python
Enjoy yourself!

A: Would the Python termcolor module do? This would be a rough equivalent for some uses.
from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

The example is right from this post, which has a lot more.  Here is a part of the example from docs
import sys
from termcolor import colored, cprint

text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')

A specific requirement was to set the color, and presumably other terminal attributes, so that all following prints are that way. While I stated in the original post that this is possible with this module I now don't think so. See the last section for a way to do that.
However, most of the time we print short segments of text in color, a line or two.  So the interface in these examples may be a better fit than to 'turn on' a color, print, and then turn it off. (Like in the Perl example shown.)  Perhaphs you can add optional argument(s) to your print function for coloring the output as well, and in the function use module's functions to color the text. This also makes it easier to resolve occasional conflicts between formatting and coloring.  Just a thought.

Here is a basic approach to set the terminal so that all following prints are rendered with a given color, attributes, or mode.
Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way.  Thus if we want all text printed to this terminal in the future to be bright/bold red, print ESC[ followed by the codes for "bright" attribute (1) and red color (31), followed by m
# print "\033[1;31m"   # this would emit a new line as well
import sys
sys.stdout.write("\033[1;31m")
print "All following prints will be red ..."

To turn off any previously set attributes use 0 for attribute, \033[0;35m (magenta).
To suppress a new line in python 3 use print('...', end="").  The rest of the job is about packaging this for modular use (and for easier digestion).
File colors.py
RED   = "\033[1;31m"
BLUE  = "\033[1;34m"
CYAN  = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD    = "\033[;1m"
REVERSE = "\033[;7m"

I recommend a quick read through some references on codes. Colors and attributes can be combined and one can put together a nice list in this package. A script
import sys
from colors import *

sys.stdout.write(RED)
print "All following prints rendered in red, until changed"

sys.stdout.write(REVERSE + CYAN)
print "From now on change to cyan, in reverse mode"
print "NOTE: 'CYAN + REVERSE' wouldn't work"

sys.stdout.write(RESET)
print "'REVERSE' and similar modes need be reset explicitly"
print "For color alone this is not needed; just change to new color"
print "All normal prints after 'RESET' above."

If the constant use of sys.stdout.write() is a bother it can be be wrapped in a tiny function, or the package turned into a class with methods that set terminal behavior (print ANSI codes).
Some of the above is more of a suggestion to look it up, like combining reverse mode and color.  (This is available in the Perl module used in the question, and is also sensitive to order and similar.)

A convenient list of escape codes is surprisingly hard to find, while there are many references on terminal behavior and how to control it. The Wiki page on ANSI escape codes has all information but requires a little work to bring it together. Pages on Bash prompt have a lot of specific useful information.  Here is another page with straight tables of codes.
There is much more out there.
This can be used alongside a module like termocolor.

A: What about the ansicolors library? You can simple do:
from colors import color, red, blue

# common colors
print(red('This is red'))
print(blue('This is blue'))

# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))

A: Color_Console library is comparatively easier to use. Install this library and the following code would help you.
from Color_Console import *
ctext("This will be printed" , "white" , "blue")
The first argument is the string to be printed, The second argument is the color of
the text and the last one is the background color.

The latest version of Color_Console allows you to pass a list or dictionary of colors which would change after a specified delay time.
Also, they have good documentation on all of their functions.
Visit https://pypi.org/project/Color-Console/ to know more.


text:
Q: How to Access TemplateField in Code Behind <asp:DetailsView...
    <asp:TemplateField HeaderText="My CheckBox" SortExpression="DataID" >
         <InsertItemTemplate>
                <asp:CheckBox ID="T01cbx" runat="server" Visible ="false" Checked='<%# Bind("DataID") %>' AutoPostBack="True" " />
         </InsertItemTemplate>
    </asp:TemplateField>

I want give an ID or Name for the above TemplateField and access it from the code behind. Is there anyway to find the TemplateField by giving and ID or Name? This is inside a DetailView.

A: You could use LINQ to get a TemplateField by it's HeaderText:
TemplateField cbField = DetailsView1.Fields.OfType<TemplateField>()
                       .Where(f => f.HeaderText == "My CheckBox")
                       .FirstOrDefault();

A: I've tried to do this in the past, but never found a better way than writing a function that loops all columns and find the one i want to modify by it's SortExpression.
This is the function i used to hide/show columns by their SortExpression:
public void ShowHideGridColumnBySortExpression(string sortExpression, bool show)
{
    for (int i = 0; i < gvProducts.Columns.Count; i++)
    {
        if (gvProducts.Columns[i].SortExpression != null && gvProducts.Columns[i].SortExpression == sortExpression)
        {
            gvProducts.Columns[i].Visible = show;
            break;
        }
    }
}


text:
Q: Why does affine scaling UIWebview gives strange results? I have a game in HTML5 I wish to enclose inside a UIWebview.
I first rotated the view with an affine transform, but it was then off the mark and badly sized. I decided to set the frame to the enclosing view's frame. It was not a good solution, as others have found. So I followed  the concatenation suggestion, and I got into the curious problem that after rotating and translating, the game displays fine, but as soon as I wish to scale, the game starts misbehaving (I get psychedelic colors...), which is not of course the intended result.
CGAffineTransform rot = CGAffineTransformMakeRotation( M_PI/2.0);
CGAffineTransform tran = CGAffineTransformMakeTranslation(0, [self statusBarFrameViewRect:self.view].size.height );
CGAffineTransform tranAndRot = CGAffineTransformConcat(rot, tran);

CGAffineTransform scale = CGAffineTransformMakeScale(self.view.frame.size.height, self.view.frame.size.width);
webView.transform = CGAffineTransformConcat(tranAndRot, scale);
// [webView setScalesPageToFit:YES]; // this line seems to do strictly nothing useful to me, whether on or off.
//I hoped it would help the contents of the view to eventually size to the scaled view, if needed.

Does anyone has a pointer to what I'm doing that's stupid?

A: In the end, I never found the core issue, which is probably linked to the tools used by the game designers (Unity).
Hence my solution was to do the whole UI in landscape mode and drop the rotate/translate part entirely.


text:
Q: Ghost tab at the end of navbar page within shiny context As shown in the below image, I have a problem with a ghost tab that appears at the end of my navbar page.
The ghost tab disappears when the code below at the end of ui is deleted. The code is related to the loading sign. How can I fix this?
hidden(
div(
  id = "app-content"
  #p("")
)

)

A: I fixed this by moving the mentioned code to right after ui <- fluidPage(.
    ui <- fluidPage(
  hidden(
    div(
      id = "app-content"
      #p("")
    )
  ),


text:
Q: gotoAndStop(label) fails with error 2109 I have two movie clips:
mov1 has frames with labels in such sequence ("item"," btn", "win", "loose")
mov2 has frames with labels in such sequence (" ", "item", "win", "loose")

This is two standardized movie clips, which are ruled by one class MovItem.
In constructor of MovItem I init:
public function MovItem(item_mc:MovieClip )
        {
            this.item_mc.addEventListener( MouseEvent.CLICK, dispatchEvent );

            //this.item_mc.gotoAndStop('btn');
            this.item_mc.gotoAndStop(1);
        }

In web version all works correctly, but in AIR 2.6 for Android it fails with error:
Error #2109: Frame label btw not found.

on gotoAndStop('btn'); on element which don't have such label.
And when I'm gotoAndStop(1); on this item all works fine.
All should be great, but 'btw' label on second movie clip is situated on second frame.
How can I fix it easily without total rework in .fla resources? Why does it works on web application, but on AIR fails? Thanx for you time.

A: This is actually happening in both the web version and the AIR version because mov2 has no frame called btn.
On the web version you will get a compiler warning but instead of quitting the application it just ignores the gotoAndStop(). However when compiling to AIR the compiler is in strict mode which converts compiler warnings to errors and won't allow you to compile until they are fixed.
It is bad practice anyway to call a function that you know is erronous (especially in a constructor method) so you should ether pass the frame to the constructor as a parameter (if they are going to different frame numbers) or explicitly give it the frame number e.g. gotoAndStop(2) (if they all go to the same frame number).
Also check you haven't misspelt the frame as you refer to the frame as both btn and btw in your question.


text:
Q: Computing $A=\sum_{k=0}^{\infty}\frac{\alpha(\alpha+k\beta)^{k-1}e^{-(\alpha+k\beta)}}{k!}f^{k}$ I'm working on a problem in order statistics. I am hoping to obtain a closed form solution for the following infinite sum:
$$A=\sum_{k=0}^{\infty}\frac{\alpha(\alpha+k\beta)^{k-1}e^{-(\alpha+k\beta)}}{k!}f^{k}$$
where $$\alpha=1$$ and $$\beta=0.5.$$
This is the probability generating function for a so-called Generalized Poisson distribution. I have plugged the equation into Mathematica, but it simply returns back the sum. I would like to work out this specific case first, and then proceed to the more general case.
Please note that this particular case must converge. For example, if we compute this for a large maximum value of $k$ say $100$, you get a sensible numerical answer (which is between $0$ and $1$ as this is a probability if $f$ is between $0$ and $1$).

A: The answer can be expressed in terms of the Lambert $W$-function.
Let $\color{blue}{L(z)=-W_0(-z)/z}$ for $|z|<1/e$; then, for any complex $\lambda$, we have $$L(z)^\lambda=\sum_{n=0}^\infty\lambda(n+\lambda)^{n-1}\frac{z^n}{n!},$$ so that $\color{blue}{A=e^{-\alpha}L(\beta e^{-\beta}f)^{\alpha/\beta}}$ under obvious conditions.
A possible proof of the above is to deal with $\lambda\in\mathbb{Z}_{>0}$ (and then extend to the general case by the observation that the coefficients of both power series are polynomials in $\lambda$) using Lagrange–Bürmann formula which states that, given analytic functions $\phi$ and $\psi$ with $\phi(0)\neq 0$, if we let $f(w)=w/\phi(w)$ then, using the "coefficient-of" notation, $$[z^n]\psi\big(f^{-1}(z)\big)=\frac1n[w^{n-1}]\big(\psi'(w)\phi(w)^n\big).$$ We apply this to $\phi(w)=e^w$ and $\psi(w)=w^\lambda$. Then $f^{-1}(z)=zL(z)$ and, for $n\geqslant\lambda$, $$[z^n]\big(zL(z)\big)^\lambda=\frac1n[w^{n-1}]\big(\lambda w^{\lambda-1}e^{nw}\big)=\frac{\lambda n^{n-\lambda-1}}{(n-\lambda)!}.$$ This is equivalent to $[z^n]L(z)^\lambda=\lambda(n+\lambda)^{n-1}/n!$, exactly as needed.
Other ideas can be seen in Concrete mathematics [Graham & Knuth & Patashnik] ($2$nd edition, section $5.4$ etc) and The Art of Computer Programming vol. $2$ ($3$rd edition, exercise $4.7.22$).


text:
Q: Select based on another select using php Not working Select based on another select using PHP not working only when a new row is added.
For demo visit here (See steps for demo)

*

*There are two rows when the page is loaded, they are working as wanted. (Service option is as per item option)

*Click on the Add Row button, one more row will be added

*The newly inserted row is not working. (Service select is not giving any options, as first two gives)

What I tried:
<?php require_once '../home.php' ?>
<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
        ob_clean();

        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        if( $action && $id && !is_nan( $id ) ){

            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmt->bindParam(':irn',$id);
            $stmt->execute();
            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmtin->bindParam(':irn',$id);
            $stmtin->execute();
            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );

            if( $stmt->rowCount() > 0 ){
                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
                 }
            }
        }
        exit();
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<form method="post" action="invoice_form.php" id="item_sel">

      <input type="text" name="customer" value="" placeholder="Customer Name">

    Item
    Service
    Qty

      <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
            <?php

                //$sql='select * from `item` order by `Sr` asc;';
                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select>

      <select class="country" name="service1">
</select>
<input type="text" name="qty1" value="" placeholder="Quantity">

      <select name='item2' class='country'>
            <option>Select Item</option>
            <?php

                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select>

      <select class="country" name="service2">
</select>
<input type="text" name="qty2" value="" placeholder="Quantity">

        <button type="submit" name="btnsave" class="btn btn-default">
           Save
        </button>

    <input type="button" class="add-row" value="Add Row">
</form>

        <select name="nameitem" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>

        <select class="country" name="namewhat"></select>

        <input type="text" name="nameqty" value="" placeholder="Quantity" />

A: Your problem is because of this error - Uncaught TypeError: Cannot set property 'onchange' of null at HTMLDocument.bindEvents on line 243. You can see the same in inspect elements. This is because you are defining the function bindEvents for item3, which has not yet been added. Also this will work only in case of a single row being added. Changed your logic and used jquery a lot. I have commented out php part in your code and hard coded that stuff. Also created a php file that sends ajax response on select box change.
    <?php // require_once '../home.php' ?>
    <?php

    foreach($_POST as $key => $val) {
        echo "$key => $val
";
    }

        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
            echo "here
";
            ob_clean();
    //
    //        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
    //        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
    //        if( $action && $id && !is_nan( $id ) ){
    //
    //            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
    //            $stmt->bindParam(':irn',$id);
    //            $stmt->execute();
    //            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
    //            $stmtin->bindParam(':irn',$id);
    //            $stmtin->execute();
    //            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );
    //
    //            if( $stmt->rowCount() > 0 ){
    //                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
    //                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
    //                 }
    //            }
    //        }
            echo "<option value='Select Service'>Select Service (Pant)</option>";
            echo "<option value='12121211'>Iron</option>";
            exit();
        }
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <form method="post" action="invoice_form.php" id="item_sel">

          <input type="text" name="customer" value="" placeholder="Customer Name">

        Item
        Service
        Qty

          <select name='item1' class='country'>
                <option value="Select Item">Select Item</option>
                <?php

    //                //$sql='select * from `item` order by `Sr` asc;';
    //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                $stmt->execute();
    //
    //                if( $stmt->rowCount() > 0 ){
    //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                    }
    //                }

                ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>

    </select>

          <select class="country" name="service1">
    </select>
    <input type="text" name="qty1" value="" placeholder="Quantity">

          <select name='item2' class='country'>
                <option>Select Item</option>
                <?php

    //
    //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                $stmt->execute();
    //
    //                if( $stmt->rowCount() > 0 ){
    //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                    }
    //                }

                ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>
    </select>

          <select class="country" name="service2">
    </select>
    <input type="text" name="qty2" value="" placeholder="Quantity">

            <button type="submit" name="btnsave" class="btn btn-default">
               Save
            </button>

        <input type="button" class="add-row" value="Add Row">
    </form>

            <select name="nameitem" class="country">
                        <option>Select Item</option>
                        <?php
    //                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                        $stmt->execute();
    //
    //                        if( $stmt->rowCount() > 0 ){
    //                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                            }
    //                        }
                        ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>
                    </select>

            <select class="country" name="namewhat"></select>

            <input type="text" name="nameqty" value="" placeholder="Quantity" />

And ajax.php
    <?php
    echo "<option value='Select Service'>Select Service (Pant)</option>";
    echo "<option value='12121211'>Iron</option>";

    ?>

A: In your code above you are running the same query twice which I presume is a copy/paste mistake?
What follows is based upon previous question and help already offered.
mysql> describe irn_item;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| irn   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50)      | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+

mysql> select * from irn_item;
+-----+------------+
| irn | name       |
+-----+------------+
|   1 | Shirt      |
|   2 | Trousers   |
|   3 | Jacket     |
|   4 | Socks      |
|   5 | Underpants |
|   6 | Hat        |
+-----+------------+

mysql> describe irn_service;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| srn         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| irn         | int(10) unsigned | NO   | MUL | 1       |                |
| instruction | varchar(50)      | NO   |     | 1       |                |
+-------------+------------------+------+-----+---------+----------------+

mysql> select * from irn_service;
+-----+-----+-----------------------+
| srn | irn | instruction           |
+-----+-----+-----------------------+
|   1 |   2 | Iron                  |
|   2 |   1 | Dry Clean Only        |
|   3 |   3 | Hi-Pressure dry clean |
|   4 |   4 | Steam Clean           |
|   5 |   5 | Decontaminate         |
|   6 |   6 | Waterproof            |
+-----+-----+-----------------------+

Without knowing the schema of the database I made up a quick example database based upon some of the columns seen in the sql in the original code. The code below uses mysqli rather than PDO simply because for my testing it is much quicker to write so please ignore the fact that it does not follow exactly. The important aspect that you are having troubles with, I believe, is that newly added rows do not copy the event handler which triggers the ajax request. I did make mention yesterday that when cloning nodes any event handlers assigned using addEventListener will NOT be copied/cloned - so to ensure that event handlers are copied/cloned you need to use inline event handlers ~ ie: <select onchange='evtselect(event)'>...</select>
<?php

    $dbhost =   'localhost';
    $dbuser =   'root';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';
    $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){

        ob_clean();

        try{
            $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );

            if( $id && !empty( $id ) ){

                $html=array();

                $sql='select `srn`,`instruction` from `irn_service` where `irn` = ? order by `srn` asc';
                $stmt=$db->prepare( $sql );

                if( $stmt ){
                    $stmt->bind_param( 's', $id );
                    $stmt->execute();
                    $stmt->store_result();
                    $stmt->bind_result( $srn, $instruction );

                    while( $stmt->fetch() ){
                        $html[]="<option value='{$srn}'>{$instruction}";
                    }
                    $stmt->close();
                }

                header('Content-Type: text/html');
                echo implode( PHP_EOL, $html );
            }
        }catch( Exception $e ){
            echo $e->getMessage();
        }
        exit();
    }
?>
<!doctype html>

        <title>Dependent / Chained SELECT menus</title>

Chained select menus using basic ajax

        <form method='post' id='item_sel'>

                    Item
                    Service
                    Qty

                        <select name='item' class='country' onchange='evtselect(event)'>
                            <option value=null>Please Select
                        <?php
                            $sql='select * from `irn_item` order by `irn`;';
                            $result=$db->query( $sql );
                            $html=array();
                            if( $result ){
                                while( $rs=$result->fetch_object() ){
                                    $html[]="<option value='{$rs->irn}'>{$rs->name}";
                                }
                                echo implode( PHP_EOL, $html );
                            }
                        ?>
                        </select>

                    <select name='service' class='country'></select>
                    <input type='number' name='qty' min=0 max=1000 />

                        <button type='submit' name='btnsave' class='btn btn-default'>
                               Save
                        </button>

            <input name='add' type='button' class='add-row' value='Add Row' />
        </form>

With this code I took the trouble of renaming newly added elements - this is probably not strictly necessary as you could instead use array syntax for the element names - viz: <select name='item[]' onchange='evtselect(event)> or <input type='number' name='qty[]' /> etc then access the appropriate values in PHP in the usual manner. It should be mentioned that if you decide upon that approach (ie array syntax ) then you would need to look at the various selectors used in the javascript and edit the names appropriately.
I trust that with this new insight into the use of inline event handlers that you should be able to nail the problem you have - you can, with a little minor editing of this code, run it for yourself to see the application working correctly. You should edit the table names (irn_item -> item, irn_service -> service ) and add suitable db/pwd details... Good luck

A: You've really to change the logic here, I'm sorry but dealing with dynamic content statically will not work in this case... what if we have line 4 and 5 and 10.. you need really to give all set of elements a common class then attach the event using the event delegation on() so the new elements added dynamically will also binded.
Example, change country class to item in the item columns, and country class to service in the service column :
$('body').on('change', '.item', function(){
   //You're ajax logic here
   //Try to use `$.post()` instead
   //Target the related service list like
   var related_service_select = $(this).closest('tr').find('.service');
   //Now you can fill it with the server side response
});

Hope this helps.


text:
Q: ruby syntax error 'require_relative' So when I run ruby server.rb, I get this error:

server.rb:3:in `require_relative': /Users//Desktop/ruby/route.rb:9: syntax error, unexpected ')', expecting keyword_then or ';' or '\n' (SyntaxError)
  nv["REQUEST_METHOD"] == "GET")
/Users//Desktop/ruby/route.rb:17: syntax error, unexpected keyword_end, expecting end-of-input
      from server.rb:3:in `'

Not sure exactly what is asking. maybe some of you more experienced with ruby and or programming can shed some light.
server.rb
require 'rack'
require_relative 'view'
require_relative 'route'

class App

  PAGES = %w{ /home /admin}

  def call(env)
    response_headers = {}

    ### cookies
    request_cookies = Rack::Utils.parse_cookies(env)

    # set the session identifier if one doesn't already exist
    unless request_cookies["session_key"]
      Rack::Utils.set_cookie_header!(response_headers, "session_key", Time.now.to_f)
    end

    # count the number of page visits:
    # nil.to_i returns 0, so if this cookie isn't set, the count will be 0:

    count = request_cookies["session_count"].to_i
    count += 1

    Rack::Utils.set_cookie_header!(response_headers, "session_count", count)

    ### routing
    route_name = Route.new(env).name

    # get the template
    pages = Pages.new(route_name, visit_count: count)

    ### return the response object
    [status, response_headers, [pages.render]]
  end
end

Rack::Handler::WEBrick.run App.new

view.rb
class View
  def initialize(page, data = {})
    @data = data
    @page = page
    file = File.join(File.dirname(__FILE__), "./pages/#{page}.html.erb")
    @page = File.read(file)
  end

  def visit_count
    @data[:visit_count]
  end

  def render
    ERB.new(@page).result(binding)
  end
end

route.rb
class Route

  ROUTES = {
    "/home" => :home,
    "/admin" => :admin
  }

  def initialize(env)
    if env["REQUEST_METHOD"] == "GET")
      @name = ROUTES[env["PATH_INFO"]]
    end
  end

  def name
    @name || "404"
  end
end

I've been stuck on this for some time now and I still can't figure out the solution. I would appreciate the help.

A:
server.rb:3:in `require_relative': /Users//Desktop/ruby/route.rb:9: syntax error, unexpected ')'

The error says, that there's a syntax error on the 9th line of route.rb file. Let's inspect it:
if env["REQUEST_METHOD"] == "GET")

It's not a valid syntax, since we have only one parenthesis, but the valid ones are either:
if(env["REQUEST_METHOD"] == "GET")

Or
if env["REQUEST_METHOD"] == "GET"

So the solution is either remove the parenthesis at the end of line, or add one before env["REQUEST_METHOD"] == "GET")


text:
Q: Gmaps.NET MapProvider.TryGetProvider return null I'm trying to use MapProvider.TryGetProvider(int guid) and it always return null for all of the maps.
When I create the map object and initial it with any provider the map load  successfully without any problem but when I use TryGetProvider for the same provider it return null.
Thank you for your help
Map.MapProvider = MapProvider.TryGetProvider(value.GetType().GUID)
UPDATE:
I did success to reload the map provider by the next code line:
_selectedMapProvider = value; var assemblyType = Assembly.Load("GMap.NET.Core"); Map.MapProvider = (GMapProvider)assemblyType.GetType($"GMap.NET.MapProviders.{SelectedMapProvider.GetType().Name}").GetField("Instance").GetValue(null); Map.ReloadMap();
But I'm trying to use something more fast then use reflection, like the TryGetProvider


text:
Q: Is it possible to wrap a flow type in an immutable container? For example, given the following record:
type UserRecord = {
  id: string;
  name: ?string;
  age: number;
}

Is there some way to do the equivalent of the following:
/* @flow */

import { List, Map } from 'immutable'

const users: List<Map<UserRecord>> = List();
let user: Map<UserRecord>;

user = Map({ id: '666', age: 30 });
users.push(user);

Otherwise I end up simply using something like Map<string, any> which I think takes away from using Immutable.js with the Flow type system.

A: In general this is not possible since records and maps have very different semantics. Map type is parameterized with types of of key and value, so when you call .get you will get the same type for all keys.
There is a way around, though:
declare class Map<T, K1=null, V1=null, K2=null, V2=null> {

  constructor(val: T): void;

  get(key: K1 & $Keys<T>): V1;
  get(key: K2 & $Keys<T>): V2;
  // etc
}

const m: Map<{ foo: string, bar: number }, 'foo', string, 'bar', number> = new Map({
  'foo': 'foo',
  bar: 42
});

m.get('foo') // string
m.get('bar') // number
m.get('baz') // error

It's probably a good idea to generate such declaration with some sort of script to support desired amount of key-value pairs.
Such declaration is a a bit verbose, but safe if you don't mess up type parameters. A couple of comments:

*

*we use recent Flow feature that allows us to declare default type parameter, so that we could use a single declaration for any number of key-value pairs;

*K1 & $Keys<T> ensures that we can only use actual keys of type T to retrieve values; this helps with consistency to some degree, unfortunately, I found no way to verify consistency of value types, so you have to be careful with those.


text:
Q: PHP using jquery to create multiple image upload and multiple textbox I want to use jquery to create multiple image upload with multiple textbox function. But the problem is how to pass to value of the textarea to database. Upload Image can work, but the description cannot pass into database
Can anyone help me to solve this problem ?
//main.php

<form method="post" action="upload-photo-action.php" autocomplte="off" enctype="multipart/form-data">
    <input type="text"  name="counter" id="counter" />

                <button type="button" class="close" data-dismiss="modal">×</button>

Adding description

                <input type="file" style="display:none" id="upload1" name="image_file_photo[]" multiple>
                <button type="button" class="btn btn-upload" id="upload-image1" onclick="upload_photo();">Upload Photos From File</button>

                <input type="submit" name="upload_pho" id="upload_pho" class="btn btn-save" value="Save">

///
////upload-photo-action.php
if(isset($_POST['upload_pho'])){
    $errors= array();
    foreach($_FILES['image_file_photo']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['image_file_photo']['name'][$key];
        $file_size = $_FILES['image_file_photo']['size'][$key];
        $file_tmp = $_FILES['image_file_photo']['tmp_name'][$key];
        $file_type = $_FILES['image_file_photo']['type'][$key];
        $image_desc = $_POST['img_desc'];

        //if($file_size > 2097152){
            //$errors[]='File size must be less than 2 MB';
        //}

        $query = mysql_query("INSERT INTO mt_image SET image_name = '".$file_name."',
                                                       image_size = '".$file_size."',
                                                       image_tmp = '".$file_tmp."',
                                                       image_desc = '".$image_desc."',
                                                       image_type = '".$file_type."'")or die(mysql_error());
        $desired_dir = "img_upload";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
        }
        if(is_dir("$desired_dir/".$file_name)==false){
            move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
        }else{                                  // rename the file if another one exist
            $new_dir="$desired_dir/".$file_name.time();
                rename($file_tmp,$new_dir) ;
        }
            mysql_query($query);
        }else{
            print_r($errors);
        }
    }

}

A: try below code.
1. textarea should be an array.
//main.php

    <form method="post" action="upload-photo-action.php" autocomplte="off" enctype="multipart/form-data">
        <input type="text"  name="counter" id="counter" />

                    <button type="button" class="close" data-dismiss="modal">×</button>

Adding description

                    <input type="file" style="display:none" id="upload1" name="image_file_photo[]" multiple>
                    <button type="button" class="btn btn-upload" id="upload-image1" onclick="upload_photo();">Upload Photos From File</button>

                    <input type="submit" name="upload_pho" id="upload_pho" class="btn btn-save" value="Save">

    ///
    ////upload-photo-action.php
    if(isset($_POST['upload_pho'])){
        $errors= array();
        foreach($_FILES['image_file_photo']['tmp_name'] as $key => $tmp_name ){
            $file_name = $key.$_FILES['image_file_photo']['name'][$key];
            $file_size = $_FILES['image_file_photo']['size'][$key];
            $file_tmp = $_FILES['image_file_photo']['tmp_name'][$key];
            $file_type = $_FILES['image_file_photo']['type'][$key];
            $image_desc = $_POST['img_desc'][$key];

            //if($file_size > 2097152){
                //$errors[]='File size must be less than 2 MB';
            //}

            $query = mysql_query("INSERT INTO mt_image SET image_name = '".$file_name."',
                                                           image_size = '".$file_size."',
                                                           image_tmp = '".$file_tmp."',
                                                           image_desc = '".$image_desc."',
                                                           image_type = '".$file_type."'")or die(mysql_error());
            $desired_dir = "img_upload";
            if(empty($errors)==true){
                if(is_dir($desired_dir)==false){
                    mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                    rename($file_tmp,$new_dir) ;
            }
                mysql_query($query);
            }else{
                print_r($errors);
            }
        }

    }

A: You can try this.
Jquery:

Upload.php
<?php
 $result = '';
 if(is_array($_FILES))
 {
 foreach ($_FILES['files']['name'] as $name => $value)
 {
 $my_file_name = explode(".", $_FILES['files']['name'][$name]);
 $extension_name = array("jpg", "jpeg", "png", "gif");
 if(in_array($my_file_name[1], $extension_name))
 {
 $NewImageName = md5(rand()) . '.' . $my_file_name[1];
 $SourcePath = $_FILES['files']['tmp_name'][$name];
 $TargetPath = "upload/".$NewImageName;
 if(move_uploaded_file($SourcePath, $TargetPath))
 {
 $result .= '

';
 }
 }
 }
 echo $result;
 }
 ?>


text:
Q: Shared Source CLI 4.0? Microsoft released the Shared Source Common Language Infrastructure (the code previously known as ROTOR) some years ago basically as a reference implementation of the .NET runtime. While the actual .NET runtime (mscorlib, mscoree, mscorjit, etc.) aren't compiled from the SSCLI, debugging them shows that they are remarkably similar and at a minimum share much of the same memory structures.
This has been an invaluable resource when debugging tricky system behavior with .NET 2.0 compiled assemblies. Now that 4.0 has been released with major changes to the runtime I'd love to find the reference source for that as well. Microsoft has changed names for the source in the past so I'm either searching for the wrong thing, or it hasn't been released. Is there reference source for a .NET 4.0 compatible runtime?

A: It looks like Microsoft really wants you to download the source through Visual Studio 2008 but it looks like it's still possible to download if you know where to look.
Available Source Code Components
Okay nevermind if you are interested in ROTOR it's dead AFAICT that's why you aren't finding anything newer:
"Sadly, I can report that I corresponded directly with one of the authors of the Rotor book and he confirmed that it has gone the way of the dodo.  He referred to it as a an example of the Law of 2 Feet in action...nobody cared enough about Rotor to keep it alive, so it died."

A: For CLR/CLI 4.0 the .NET Micro Framework is open sourced, I guess it's the successor of ROTOR in a sense. I found it from the link ('its dead') posted by daveangel. Maybe it provides enough insight into the runtime internals for you.
quote from the Micro Framework site:

Several months ago at the Microsoft
  Professional Developers Conference,
  .NET Micro Framework 4.0 (PDC Session
  Video) was released in open source
  under the Apache 2.0 license. This
  means that users can now access the
  productivity improvements offered by
  this rich development environment with
  all the flexibility you need for small
  devices. The code for the libraries
  and even the CLR itself is available
  for you to morph as you need.

A: There is a SSCLI 2.0 patch here for Visual Studio 2010 and I can confirm it builds on Windows 8 with the 7.1A SDK.
and here is further information.
also Codeplex now hosts the .NET Micro Framework.


text:
Q: Issues with 2 motors in series I have two motors in series that are connected to a 36v speed controller. They are identical motors, 12vdc, 30000RPM.
My problem is when applying power, 1 motor slowly drops in voltage until it reaches zero. At the same time, the other motor slowly speeds up.
If I apply full power, the motor that went to zero will then spin but no where near the same speed of the other motor. My DMM confirms the smaller voltage at full power on the slower motor.
I've also tried another motor to replace the slow one but still same result.
What could be happening here?
Could it be that the faster motor is actually different in some way?
EDIT:
I've now wired the motors in parallel and they work perfectly but now I have another thing I'm confused about...
In parallel, the motors should now see the full voltage of the battery which is around 31.5v (8s lipo at 50% charge) but both see half that?? what is going on now?
EDIT:
Attached is a crude drawing of the current setup.

For clarification, both motors now work at the same speed and the shifter works perfectly in so far as i can change the polarity with a flip of the switch. The problem now is both motors only see half the voltage each from the battery.
I've confirmed that when disconnecting 1 motor, the other motor reaches the correct voltage....as soon as I reconnect the other motor, both motors go back to a voltage of 15.5. could this be a current limiting issue?
The controller can handle around 25a and the battery, 90a.
Both relays are also rated at 40a @ 12vdc. At 31.5v it should handle around 15a.
Both motors were pulling around 4a @ 15.5v.
EDIT:
sorry for all the edits, I'm learning more crap all the time!
I've found another symptom/issue...Not only does the voltage half for each motor but it slowly drops!? Now i'm more confused than ever!. i've uploaded 2 videos showing this issue. 1 video shows 2 motors running together and the other, just 1 motor running. DMM is connected to the same motor on both videos.
https://www.youtube.com/watch?v=4M-1r9IBKuU (parallel motors)
https://www.youtube.com/watch?v=uO_2VKqxTaA (single motor)

A:
Could it be that the faster motor is actually different in some way?

Yes. Due to manufacturing tolerances and process variations, no two motors are identical. If one motor draws slightly more current for any reason (higher brush or bearing friction, greater load etc.) the other motor will speed up and produce more voltage, causing the 'greedier' motor to slow down.
It can work if the motors are well matched and the loads increase greatly with rpm (eg. propellers), or they share a common load (eg. coupled to the same gearbox, individual wheels on a road vehicle).

A: it seems I may have the answer...The speed controller is rated at 36v with a low voltage cutoff of 31.5v. These controller aren't made with lipo batteries in mind! I charged the batteries last night. Fully charged they're at 33.6v. Now both motors run at around 25v which is pretty close considering voltage drop under load.
As the batteries were reaching below that threshold, although the controller should have simply switched off, it didn't (it's a cheap one) but clearly limited the voltage going out! In conclusion, I need a Li-ion battery which I've actually ordered 2 weeks ago anyway.
Any thoughts are more than welcome and thanks for all the feedback and help!


text:
Q: Summing Contingency Tables in R with first column as character My sales dataset includes 3 columns:  Countries, Sales Type/Method, Total Quarterly Revenue.  Here's a display of the first few rows for a better idea:
   Retailer.country Order.method.type    Qtr.Rev
         <fctr>            <fctr>      <dbl>
 1        Australia            E-mail  171407.28
 2        Australia       Sales visit 2013909.18
 3        Australia           Special  158795.34
 4        Australia         Telephone 2289201.87
 5        Australia               Web 1738303.59
 6          Austria       Sales visit   66926.18
 7          Austria         Telephone 1671887.40
 8          Austria               Web 7050164.50
 9          Belgium       Sales visit 1655507.05
10          Belgium               Web 6222440.26
etc.........

Here's the dput of this data:
    structure(list(Retailer.country = structure(c(1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 7L,
7L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L, 11L, 11L,
11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 14L,
14L, 14L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 17L, 17L, 17L,
17L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 20L, 20L, 20L, 20L, 20L,
21L, 21L, 21L, 21L, 21L, 21L), .Label = c("Australia", "Austria",
"Belgium", "Brazil", "Canada", "China", "Denmark", "Finland",
"France", "Germany", "Italy", "Japan", "Korea", "Mexico",
"Netherlands",
"Singapore", "Spain", "Sweden", "Switzerland", "United Kingdom",
"United States"), class = "factor"), Order.method.type =
structure(c(1L,
4L, 5L, 6L, 7L, 4L, 6L, 7L, 4L, 7L, 7L, 1L, 2L, 4L, 7L, 2L, 4L,
6L, 7L, 4L, 7L, 4L, 7L, 2L, 4L, 6L, 7L, 1L, 3L, 4L, 7L, 1L, 2L,
4L, 5L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 4L, 6L, 7L, 4L, 5L, 7L,
2L, 3L, 6L, 7L, 2L, 5L, 6L, 7L, 2L, 3L, 6L, 7L, 1L, 7L, 2L, 4L,
5L, 6L, 7L, 1L, 2L, 4L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 7L), .Label =
c("E-mail",
"Fax", "Mail", "Sales visit", "Special", "Telephone", "Web"), class =
"factor"),
    Qtr.Rev = c(171407.28, 2013909.18, 158795.34, 2289201.87,
    1738303.59, 66926.18, 1671887.4, 7050164.5, 1655507.05,
    6222440.26,
    7746789.52, 6864270.12, 195549.5, 450628.79, 12376528.53,
    415128.31, 1453194.14, 2735416.3, 15777880.11, 413978.16,
    3776833.13, 308638.6, 12328172.97, 709194.65, 1304167.86,
    5897377.14, 11048160.97, 1546079.43, 1247170.05, 2373591.15,
    12102240.99, 2461322.51, 165800.42, 1397604.56, 198705.05,
    7413833.64, 2662351.94, 289704.5, 680467.87, 87186.72, 343708.86,
    1802166.73, 16990817.52, 2821127.32, 431860.34, 10144353.75,
    5063353.42, 1725508.54, 3571760.87, 593828.88, 1074860.66,
    2981026.86, 5254137.56, 469627.61, 908725.05, 1625096.56,
    9677070.09, 88788.41, 337710.73, 254360.21, 7835117.44,
    1292812.39,
    4818848.86, 217936.39, 792168.42, 790344.28, 109161.04,
    4565896.64,
    697619.35, 264500.2, 189218.02, 2022968.96, 13756025.4,
    1357389.56,
    2352483.29, 2842600.85, 685752.21, 13437403.28, 29573813.7
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-79L), .Names = c("Retailer.country", "Order.method.type", "Qtr.Rev"
))

I'm creating a contingency table in R that shows the quarterly revenue generated by each sales method for each country.  The final output should look similar to this:
Retailer.country     E-mail        Fax      Mail Sales visit   Special  Telephone       Web  TOTAL.cn
1         Australia   171407.3       0.00       0.0  2013909.18  158795.3  2289201.9   1738304   6371617
2           Austria        0.0       0.00       0.0    66926.18       0.0  1671887.4   7050164   8788978
3           Belgium        0.0       0.00       0.0  1655507.05       0.0        0.0   6222440   7877947
4            Brazil        0.0       0.00       0.0        0.00       0.0        0.0   7746790   7746790
5            Canada  6864270.1  195549.50       0.0   450628.79       0.0        0.0  12376529  19886977
6             China        0.0  415128.31       0.0  1453194.14       0.0  2735416.3  15777880  20381619
7           Denmark        0.0       0.00       0.0   413978.16
...
20   United Kingdom   697619.3  264500.20       0.0   189218.02       0.0  2022969.0  13756025  16930332
21    United States        0.0 1357389.56 2352483.3  2842600.85  685752.2 13437403.3  29573814  50249443
22       TOTAL.type 15695863.0 4767448.43 5692692.6 23233800.42 4811539.3 35257926.7 203769190 293228461

The cast() function from the reshape library gets most of the job done, and only leaves the summary column and row for all values to be computed.
cast(sales.by.country, Retailer.country ~ Order.method.type,
fill=0) -> sales.by.country

Summing the rows into a new column named "TOTAL.cn" is pretty simple:
sales.by.country$TOTAL.cn <- rowSums(sales.by.country[,c(2:8)])

But summing the columns become a major headache, because the first component of that last row must either be a factor or character.  I converted the first column "Retailer.country" to the character type, because it really serves as nothing more than a visual label.
After fussing around with several functions, this is the best code I was able to create to achieve the intended row summation:
# Sum the numeric columns, which is everything *except* column 1
total.by.ordertype <- (colSums(sales.by.country[,-1]))

# Create the Total by Order row
total.by.ordertype.row <- list("TOTAL.type", total.by.ordertype[1],
total.by.ordertype[2], total.by.ordertype[3], total.by.ordertype[4],
total.by.ordertype[5], total.by.ordertype[6], total.by.ordertype[7],
total.by.ordertype[8])

# Add the Total by Order row to the bottom of the table
sales.by.country[22, ] <- total.by.ordertype.row

It works and maintains the proper data types among all columns... BUT I figure there has to be a more efficient way, perhaps by using the apply family of functions, something from dplyr, etc. Maybe the only way is to write my own function?
For example, future datasets may have 50+ different sales methods.  When creating the list for the "Total by Order" row (above), I had to call out every single cell within the vector, separated by commas, in order to successfully add this to my existing table. Other efforts converted the data types of all the other columns to characters, which messes everything up.
I don't mind copying/pasting "total.by.ordertype" 8 times so much. But what happens when I'm dealing with 50-100 order types?  Is there a cleaner method to reproduce any of this?
Thank you!

A: The cast() function from the reshape library can do the whole job. With the parameter margin = TRUE, all row and column totals will be computed:
reshape::cast(sales.by.country, Retailer.country ~ Order.method.type, fun.aggregate = sum,
     fill = 0, margins = TRUE)

   Retailer.country     E-mail        Fax      Mail Sales visit   Special  Telephone       Web     (all)
1         Australia   171407.3       0.00       0.0  2013909.18  158795.3  2289201.9   1738304   6371617
2           Austria        0.0       0.00       0.0    66926.18       0.0  1671887.4   7050164   8788978
3           Belgium        0.0       0.00       0.0  1655507.05       0.0        0.0   6222440   7877947
4            Brazil        0.0       0.00       0.0        0.00       0.0        0.0   7746790   7746790
5            Canada  6864270.1  195549.50       0.0   450628.79       0.0        0.0  12376529  19886977
6             China        0.0  415128.31       0.0  1453194.14       0.0  2735416.3  15777880  20381619
7           Denmark        0.0       0.00       0.0   413978.16       0.0        0.0   3776833   4190811
8           Finland        0.0       0.00       0.0   308638.60       0.0        0.0  12328173  12636812
9            France        0.0  709194.65       0.0  1304167.86       0.0  5897377.1  11048161  18958901
10          Germany  1546079.4       0.00 1247170.1  2373591.15       0.0        0.0  12102241  17269082
11            Italy  2461322.5  165800.42       0.0  1397604.56  198705.0        0.0   7413834  11637266
12            Japan  2662351.9  289704.50  680467.9    87186.72  343708.9  1802166.7  16990818  22856404
13            Korea        0.0       0.00       0.0  2821127.32       0.0   431860.3  10144354  13397341
14           Mexico        0.0       0.00       0.0  5063353.42 1725508.5        0.0   3571761  10360623
15      Netherlands        0.0  593828.88 1074860.7        0.00       0.0  2981026.9   5254138   9903854
16        Singapore        0.0  469627.61       0.0        0.00  908725.1  1625096.6   9677070  12680519
17            Spain        0.0   88788.41  337710.7        0.00       0.0   254360.2   7835117   8515977
18           Sweden  1292812.4       0.00       0.0        0.00       0.0        0.0   4818849   6111661
19      Switzerland        0.0  217936.39       0.0   792168.42  790344.3   109161.0   4565897   6475507
20   United Kingdom   697619.3  264500.20       0.0   189218.02       0.0  2022969.0  13756025  16930332
21    United States        0.0 1357389.56 2352483.3  2842600.85  685752.2 13437403.3  29573814  50249443
22            (all) 15695863.0 4767448.43 5692692.6 23233800.42 4811539.3 35257926.7 203769190 293228461

Of course, fun.aggregate has to be specified as well.

The same functionality is also available from the reshape2 package, the successor of reshape, but about 4 times faster for this small sample size.
reshape2::dcast(sales.by.country, Retailer.country ~ Order.method.type, fun.aggregate = sum,
                fill = 0, margins = TRUE)

dcast() is also available from the data.table package which claims to be faster than reshape2::dcast(). Unfortunately, the margins parameter hasn't been implemented yet (current CRAN version 1.10.4). Therefore, the margins have to be computed separately and combined with the original data:
DT2 <- rbind(
  DT,
  DT[, .(Qtr.Rev = sum(Qtr.Rev)), by = Retailer.country],
  DT[, .(Qtr.Rev = sum(Qtr.Rev)), by = Order.method.type],
  DT[, .(Qtr.Rev = sum(Qtr.Rev))],
  fill = TRUE
)
dcast(DT2, Retailer.country ~ Order.method.type, fill = 0)

    Retailer.country     E-mail        Fax      Mail Sales visit   Special  Telephone       Web        NA
 1:        Australia   171407.3       0.00       0.0  2013909.18  158795.3  2289201.9   1738304   6371617
 2:          Austria        0.0       0.00       0.0    66926.18       0.0  1671887.4   7050164   8788978
 3:          Belgium        0.0       0.00       0.0  1655507.05       0.0        0.0   6222440   7877947
 4:           Brazil        0.0       0.00       0.0        0.00       0.0        0.0   7746790   7746790
 5:           Canada  6864270.1  195549.50       0.0   450628.79       0.0        0.0  12376529  19886977
 6:            China        0.0  415128.31       0.0  1453194.14       0.0  2735416.3  15777880  20381619
 7:          Denmark        0.0       0.00       0.0   413978.16       0.0        0.0   3776833   4190811
 8:          Finland        0.0       0.00       0.0   308638.60       0.0        0.0  12328173  12636812
 9:           France        0.0  709194.65       0.0  1304167.86       0.0  5897377.1  11048161  18958901
10:          Germany  1546079.4       0.00 1247170.1  2373591.15       0.0        0.0  12102241  17269082
11:            Italy  2461322.5  165800.42       0.0  1397604.56  198705.0        0.0   7413834  11637266
12:            Japan  2662351.9  289704.50  680467.9    87186.72  343708.9  1802166.7  16990818  22856404
13:            Korea        0.0       0.00       0.0  2821127.32       0.0   431860.3  10144354  13397341
14:           Mexico        0.0       0.00       0.0  5063353.42 1725508.5        0.0   3571761  10360623
15:      Netherlands        0.0  593828.88 1074860.7        0.00       0.0  2981026.9   5254138   9903854
16:        Singapore        0.0  469627.61       0.0        0.00  908725.1  1625096.6   9677070  12680519
17:            Spain        0.0   88788.41  337710.7        0.00       0.0   254360.2   7835117   8515977
18:           Sweden  1292812.4       0.00       0.0        0.00       0.0        0.0   4818849   6111661
19:      Switzerland        0.0  217936.39       0.0   792168.42  790344.3   109161.0   4565897   6475507
20:   United Kingdom   697619.3  264500.20       0.0   189218.02       0.0  2022969.0  13756025  16930332
21:    United States        0.0 1357389.56 2352483.3  2842600.85  685752.2 13437403.3  29573814  50249443
22:               NA 15695863.0 4767448.43 5692692.6 23233800.42 4811539.3 35257926.7 203769190 293228461
    Retailer.country     E-mail        Fax      Mail Sales visit   Special  Telephone       Web        NA

A: A solution using functions from dplyr and tidyr. dt4 is the final output. Notice the use of summarise_if. It is useful when we only want to apply a function for columns that fit a pre-determined condition. In this case, we can apply the sum function only to columns that are numeric.
# Create example data frame
library(dplyr)
library(tidyr)

# sales.by.country is created by OP's dput dataset
dt2 <- sales.by.country %>%
  mutate(Retailer.country = as.character(Retailer.country)) %>%
  # Spread the data frame
  spread(Order.method.type, Qtr.Rev, fill = 0) %>%
  # Calcualte Total.cn by rowSums
  mutate(TOTAL.cn = rowSums(.[, 2:ncol(.)]))

# Calculate the sum of each column if it is numeric
dt3 <- dt2 %>% summarise_if(is.numeric, sum)

# Combine dt3 (the summary) to dt2
dt4 <- dt2 %>%
  bind_rows(dt3) %>%
  # Replace the na in Retailer.country to be "TOTAL.type"
  replace_na(list(Retailer.country = "TOTAL.type"))

A: Use tidyr to spread and janitor to add totals column & row:
library(janitor)
library(tidyr)
sales.by.country %>%
  spread(Order.method.type, Qtr.Rev, fill = 0) %>%
  adorn_totals(c("row", "col"))


text:
Q: Failed to load config "next/babel" to extend from eslintrc.json When I'm trying to build the Next.Js app then the below error is coming with a successful build. This error is showing when I deploy the app in Vercel.
error - ESLint: Failed to load config "next/babel" to extend from. Referenced from: /vercel/path0/.eslintrc.json

This is my .eslintrc.json
{
  "extends": ["next/babel","next/core-web-vitals"]
}

I've also added .babelrc
{
  "presets": ["next/babel"],
  "plugins": []
}

I also found a solution when I change the eslintrc.json file like below:
{
  "extends": ["next","next/core-web-vitals"]
}

then no error is showing while building the app. But there is another problem showing when I use the above solution and the problem is:
Parsing error: Cannot find module 'next/babel'

This is shown in all the imports with red marks.
I tried to search the solution but did not found any solution for this.

A: my problem has been solved by this code. just copy and paste it into the eslintrc.json file.
{
  "extends": ["next/babel","next/core-web-vitals"]
}

A: I think, this might have to do with this weird hackfix that is being touted in a bunch of places that tells you to place next/babel in your eslint config file for some reason (e.g. here).
It probably was a hackfix for an old bug in older next.js versions. But as of (at least) summer 2022, it makes little sense to do so, considering that next/babel is a babel preset, not an eslint preset. Instead, in recent next.js versions, just reset your .eslintrc.json:
{
  "extends": [
    "next"
  ]
}

With this setup, things don't error out, as of next@12.2.*.
You also might want to take a look next's eslint customization options. For example, some people might be confused why eslint is seemingly not working.
In that case, consider this solution and the next.js docs on eslint.
If you have this problem, but you did not copy+paste your .eslintrc.json from the interwebz, then you might need to describe your situation in more detail.

A: Or just replace "next" and "next/core-web-vitals" to
"plugin:@next/next/recommended"
https://nextjs.org/docs/basic-features/eslint

A: Same Turborepo issue using pnpm. This solved it for me: https://github.com/vercel/next.js/issues/40687#issuecomment-1275184829
Essentially add this to your settings.json
// .vscode/settings.json

{
  "eslint.workingDirectories": [
    { "pattern": "apps/*/" },
    { "pattern": "packages/*/" }
  ]
}

A: I had this issue when working with TurboRepo. The solution for me was to add next as a devDependency in the root of the monorepo.


text:
Q: Giving a different object name for the content of the returned list of purrr::map2() I'm trying to conduct a certain a calculation using purrr::map2() taking two different arguments.
purrr::map2(
  .x = c(1, 3),
  .y = c(10, 20),
  function(.x, .y)rnorm(1, .x, .y)
)

purrr::map2() returns a list, but I want to assign a distinct object name to each content within the list. For example, I want to name the first list [[1]] [1] -5.962716 as model1 and [[2]] [1] -29.58825 as model2. In other words, I'd like to automate the object naming like model* <- purrr::map2[[*]]. Would anybody tell me a better way?
> purrr::map2(
+ .x = c(1, 3),
+ .y = c(10, 20),
+ function(.x, .y)rnorm(1, .x, .y)
+ )
[[1]]
[1] -5.962716
[[2]]
[1] -29.58825

This question is similar to this, though note that I need the results of the calculation in separate objects for my purpose.

A: You could assign the name to the result using setNames :
result <- purrr::map2(
  .x = c(1, 3),
  .y = c(10, 20),
  function(.x, .y)rnorm(1, .x, .y)
) %>%
  setNames(paste0('model', seq_along(.)))

Now you can access each individual objects like :
result$model1
#[1] 6.032297

If you want them as separate objects and not a part of a list you can use list2env.
list2env(result, .GlobalEnv)


text:
Q: Reactsj and d3v4 integration -- Table and Pie chart application with jest testing I am trying to create a basic integration example of react, d3 with jest testing. I've created a pie chart and table component - and I am keen to push data through from the main application into both the table and pie chart components. The pie chart should only become populated when the user has clicked on the table.
-- sandbox
https://codesandbox.io/s/react-d3-pie-chart-2-ezq6y?file=/src/index.js - I've come up with this example

9th June - current integration.
data will look a little like this
[
    {
      "Country": "Afghanistan",
      "TotalConfirmed": 20917,
      "TotalDeaths": 369,
      "TotalRecovered": 2171,
    },
    {
      "Country": "Albania",
      "TotalConfirmed": 1263,
      "TotalDeaths": 34,
      "TotalRecovered": 945,
    },
    {
      "Country": "Algeria",
      "TotalConfirmed": 10265,
      "TotalDeaths": 715,
      "TotalRecovered": 6799,
    }
]

*

*I am having issues with reparsing the data from the props. I will have to refactor the pie chart data into a label,value format -- but I am also unsure on the jest testing aspects for this.

//App.js
import React from 'react';

import Pie from './Pie/Pie';
import Table from './Table/Table';
import './App.css';

class App extends React.Component {
  componentDidMount() {
    //get data
  }

  render() {

    const data = [
      {
        "Country": "Afghanistan",
        "TotalConfirmed": 20917,
        "TotalDeaths": 369,
        "TotalRecovered": 2171,
      },
      {
        "Country": "Albania",
        "TotalConfirmed": 1263,
        "TotalDeaths": 34,
        "TotalRecovered": 945,
      },
      {
        "Country": "Algeria",
        "TotalConfirmed": 10265,
        "TotalDeaths": 715,
        "TotalRecovered": 6799,
      }
  ];

    const piedata =[
            {
                label: 'Jam',
                value: 50,
            },
            {
                label: 'Coconut',
                value: 10,
            },
            {
                label: 'Nutmeg',
                value: 20,
            },
            {
                label: 'Tumeric',
                value: 20,
            },
        ];

    return (

            <Pie
              data={piedata}
              width="300"
              height="300"
              r="110"
              ir="0"
            />

    );
  }
}

export default App;

//Pie.js
import React from 'react';
import * as d3 from "d3";
import ReactDOM from 'react-dom';
import $ from 'jquery';
import './Pie.css';

class Pie extends React.Component {

    constructor(props) {
        super(props);
        this.myRef = React.createRef();
    }

    componentDidMount() {

                var $this = $(this.myRef.current);

                const data  = this.props.data;

                const width = parseInt(this.props.width,10),
                    height = parseInt(this.props.height,10),
                    radius = parseInt(this.props.r,10),
                    innerradius = parseInt(this.props.ir,10);

                var color = d3.scaleOrdinal().range(["#f0cf85", "#e7f0c3", "#a4d4ae", "#32afa9"]);

                var arc = d3.arc()
                    .outerRadius(radius - 10)
                    .innerRadius(innerradius);

                data.forEach(function(d) {
                    d.total = +d.value;
                });

                var pie = d3.pie()
                    .sort(null)
                    .value(function(d) { return d.total; });

                var svg = d3.select($this[0])
                    .append("svg")
                    .attr("width", width)
                    .attr("height", height)
                    .append("g")
                    .attr('class', 'piechart')
                    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

                var segments = svg.append('g').attr('class', 'segments');

                var slices = segments.selectAll(".arc")
                    .data(pie(data))
                    .enter().append("g")
                    .attr("class", "arc");

                slices.append("path")
                    .attr("d", arc)
                    .attr('fill', function(d, i) {
                        return color(i);
                    })

    }

    render() {

        return (

        );
    }
}
export default Pie;

//Table.js
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import './Table.css';

class Table extends React.Component {

    constructor(props) {
        super(props);
        this.myRef = React.createRef();
    }

    componentDidMount() {
        var $this = $(this.myRef.current);
    }

    rows(data) {
        return  (data.map((listValue, index) => {
          return (

              {listValue.Country}
              {listValue.TotalConfirmed}
              {listValue.TotalDeaths}
              {listValue.TotalRecovered}

          );
        }));
    }

    render() {
        return (

                    {Object.keys(this.props.data[0]).map((key, index) => {
                        return ({key}	);
                    })}

             {this.rows(this.props.data)}

        );
    }
}
export default Table;

are these tests correct?
App.test.js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
import Table from './Table/Table';
import Pie from './Pie/Pie';
import allData from './data.json';

fetch = jest.fn().mockImplementation(() => {
    const data = allData;

    data.json = jest.fn().mockImplementation(() => Promise.resolve(data));
    return Promise.resolve(data);
});
describe('App', () => {
    const wrapper = shallow(<App />);

    it('initial render', () => {
        expect(wrapper.find(Table).prop('cols')).toHaveLength(4);

        expect(wrapper.find(Pie).prop('data')).toEqual([
            {
                label: '',
                value: 100,
            },
        ]);
    });

    it('should update pie data when row is selected', () => {
        const row = wrapper.state('data')[0];
        const pieDataRefactor = wrapper.instance().pieDataRefactor(row);
        console.log(pieDataRefactor);
        wrapper.instance().rowSelected(row);

        expect(wrapper.find(Pie).prop('data')).toEqual(pieDataRefactor);
    });
});

Table.test.js
import React from 'react';
import Table from './Table';
import allData from '../data.json';
import { shallow } from 'enzyme';

const columns = [
    'Country',
    'CountryCode',
    'Slug',
    'NewConfirmed',
    'TotalConfirmed',
    'NewDeaths',
    'TotalDeaths',
    'NewRecovered',
    'TotalRecovered',
    'Date',
];
describe('Table', () => {
    const defaultProps = {
        cols: columns,
        data: allData.Countries,
        rowSelected: jest.fn(),
    };

    const wrapper = shallow(
);

    it('should render table', () => {
        expect(wrapper.find('.Table th')).toHaveLength(10);
        expect(wrapper.find('.Table tbody tr')).toHaveLength(allData.Countries.length);
    });

    it('should call rowSelected', () => {
        const row = wrapper.find('.Table tbody tr').at(0);

        row.simulate('click');

        expect(defaultProps.rowSelected).toHaveBeenCalled();
        expect(defaultProps.rowSelected).toHaveBeenCalledWith(allData.Countries[0]);
    });
});

Pie.test.js
import React from 'react';
import Pie from './Pie';
import $ from 'jquery';
import * as d3 from 'd3';
import { mount } from 'enzyme';
describe('Pie', () => {
    const defaultProps = {
        data: [
            { label: 'TotalConfirmed', value: 20917 },
            { label: 'TotalDeaths', value: 369 },
            { label: 'TotalRecovered', value: 2171 },
        ],
        height: 200,
        width: 200,
        r: 30,
        ir: 10,
    };

    // const wrapper = mount(<Pie {...defaultProps} />);

    it('should render Pie', () => {
        const arcSpy = jest.spyOn(d3, 'arc');
        const selectSpy = jest.spyOn(d3, 'select');
        const scaleOrdinalSpy = jest.spyOn(d3, 'scaleOrdinal');
        const pieSpy = jest.spyOn(d3, 'pie');

        const wrapper = mount(<Pie {...defaultProps} />);
        expect(wrapper.find('.Pie')).toHaveLength(1);

        expect(arcSpy).toHaveBeenCalled();
        expect(pieSpy).toHaveBeenCalled();
        expect(selectSpy).toHaveBeenCalled();
        expect(scaleOrdinalSpy).toHaveBeenCalled();
    });
});

A: You forgot to use didUpdate listener, that's why the pie chart didn't update correctly. One should also clear d3-related stuff container (in this case) before each redraw.
https://codesandbox.io/s/react-d3-pie-chart-2-qezz7?file=/src/Pie/Pie.js


text:
Q: Saving values set in Frontend to Django Database I have a website which allows Users to pick a few hobbies they enjoy. Currently the website loads these hobbies from a Model and lists them with a Checkbox. What I want to do is when a User saves the form, it should also save these Checkbox values to the database - i.e if they tick Football, the database should save the fact that this User enjoys football. I am new to Django and Python so not too sure how to accomplish this. Here is the code I am using. This is the Models.py file for the Hobbies:
TYPES = (
        ("Football", "Football"),
        ("Cricket", "Cricket"),
        ("Swimming", "Swimming"),
        ("Cycling", "Cycling")
        )

class Hobby(models.Model):
    myfield = models.CharField(max_length=50, choices = TYPES, default=TYPES[0], null=True)
    football = models.BooleanField(default = False)
    cricket = models.BooleanField(default = False)
    swimming = models.BooleanField(default = False)
    cycling = models.BooleanField(default = False)

This is the relevant views.py file:
def profile(request, user):
    # use this for debugging:
    # import pdb; pdb.set_trace()
    if 'email' in request.POST:
        email = request.POST['email']
        gender = request.POST['gender']
        dob = request.POST['dob']
##        hobby = request.POST['hobby']
        if user.profile:
            user.profile.email = email
            user.profile.gender = gender
            user.profile.dob = dob
##            user.profile.hobby = hobby
            user.profile.save()
        else:
            profile = Profile(email=email, gender=gender, dob=dob)
            profile.save()
            user.profile = profile
        user.save()
    context = {
        'appname': appname,
        'username': user.username,
        'profile' : user.profile,
        'all_hobbies': [hobby[0] for hobby in TYPES],
        'loggedin': True
    }
    return render(request, 'mainapp/profile.html', context)

And lastly the HTML/JS code to display the information:
Hobbies
        {% for hobby in all_hobbies %}

                <input type="checkbox" name={{hobby}} value={{hobby}}> {{hobby}}

        {% endfor %}

<input type='submit' value='Save'>

What I want is a way to check whether the checkboxes have been ticked, and if so to change the value of the BooleanField in the database/model to either True or False. However, I am not sure where to do this, in the views or the JS code. Can someone help me out here? Many thanks.

A: For this case to list all hobbies and update them again. You need to use a Form Class. Example. I just want to mention a single thing, the code below its just a guideline of what you should do. Because Its kind of confusing the logic you want to approach. Since you are not handleing a user as a session but just a plain key.
model.py
my_choices = (
    (0, "None"),
    (1, "Football"),
    (2, "Cricket"),
    (3, "Swimming"),
    (4, "Cycling"),
)
class Hobby(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.DO_NOTHING)
    field = models.integerField(choices=my_choices, default=0)

forms.py
class HobbyForm(ModelForm):
    class Meta:
        model = Hobby
        fields = ["field"]

views.py
def profile(request,user):

    try:
        profile_object = Profile.get(id=user)

        if request.method.POST:
            form = HobbyForm(request.POST)
            if form.is_valid():
                profile_object.field = form.cleaned_data["field"]
                profile_object.save()

                context = {
                        "form": form,
                        "profile": profile_object,
                    }
                return render(request, 'mainapp/profile.html', context)

            else:
                context = {
                        "form": form,
                        "profile": profile_object,
                    }
                return render(request, 'mainapp/profile.html', context)
        else:
            context = {
                        "form": form,
                        "profile": profile_object,
                    }
            return render(request, 'mainapp/profile.html', context)

    except Profile.DoesNotExists:
        context = {
            "form": form,
            "profile": profile_object,
        }
        return render(request, 'mainapp/profile.html', context)

profile.html
<form action="myurl/{{profile.id}}/" method="post">
{% csrf_token %}
{% form.as_p %}
<input type="submit" value="OK">
</form>


text:
Q: How do you grow as a developer when you're the only one in a given technology at your company? I am not the only programmer, but I'm the only .NET developer, everyone else works with Perl, Ext JS, and related technologies.  I'm primarily self taught, using Codeproject heavily to learn new techniques.
Without any mentors at my company specifically knowledgeable in .NET, I'm unsure whether classes, or online tutorials, books, or perhaps some other avenue might be most effective at helping me to become a better developer.
My goal, optimistically, is to become a developer capable of managing the next .NET developer we hire, or at least to integrate well with him/her.
I'm currently taking on the task of documenting my programs in such a way as to receive review from the more experienced developers at my company regardless of them not knowing .NET, and I expect this will be rather general, but hopefully still beneficial.
Does anyone have suggestions or advice for how to most effectively learn good practices without direct oversight?

A: Without mentors around, there are several things you can do to improve your skills:

*

*Take classes...especially if your employer will pay for them.

*Read books. They're the next best thing to a class.

*Read developer blogs. They may not teach you best practices, but they'll keep you abreast of what's new in the development world. That'll help you keep from falling behind.

*Courtesy of the Community Listen to Podcasts (Hanselminutes, Stackoverflow, etc.) and watch Screencasts (Dimecasts has tons of good content).

*Participate in the community. We may seem harsh at times, but you'll hear the most about best practices, coding techniques, design patterns, etc. and different ways to apply everything.

A: I have always worked like that. My ways to improve are:

*

*Reading high-quality blogs

*Applying what these high-quality blogs recommend (whenever it fits your project and when time allows, of course)

*Reading high-quality open source project's source code

*Writing as much code as you can, always keeping in mind what you've learned and always trying to raise the quality bar. Practice does not make perfect. Only perfect practice makes perfect.

*Keep an eye on stuff that's unrelated to your own line of work. For example, if your main job is coding ASP.NET in C#, read stuff about functional programming, F#, Haskell, other web frameworks like django, Ruby on Rails, etc. I'm not saying that you learn them, just see how things can be done differently. It will broaden your perspective.

*When you gain some self-confidence: contribute to open source projects, write a blog.

About books: IMHO the books that are highly-technical (i.e. "Buzzword 2.0 in Action!") aren't worth your time. Everything happens so fast that they'll probably become obsolete 6 months after their release. The only books worth buying are those that deal with the underlying CS or architecture issues.
About classes: it's very hard to find high-quality non-university classes that aren't a waste of time/money. Most of the time you can learn faster by yourself. (UPDATE: fast-forward to 2013, MOOCs are an amazing, high-quality, free learning resource)
Also be wary of codeproject, there are lots of articles there with errors and/or general bad advice.

A: I am in the same situation you are in. I learn mostly from

*

*previous projects/mistakes, especially when you take over an old project from someone else (50%)

*google (25%)

*forum/stackoverflow (25%)

A: Change employers.  I'm not trying to be a jerk, seriously. The most growth your going to have as a developer is by working every day with someone significantly better than you.

A: Join some OSS project which works with .NET to get feedback on your code from experienced .NET developers. In addition looking at other people's code is a great way to learn new things - just as you have been doing. I also agree with Justin also that reading blogs like Eric Lippert's is very rewarding

A: Take advantage of the chance to learn the languages and technologies being used by by your colleagues.
They'll introduce you not just to syntax, but more importantly to techniques, idioms, and paradigms that you won't find in .Net, but that will challenge you to think about how you could apply or build those thing in .Net, or why .Net doesn't have or shouldn't use those things.
Why is Perl weakly typed (or is it)? What's Perl better at than .Net? What is .Net great at the Perl is just terrible at? Why do these differences exist? How might you implement a Perl interpreter in .Net? Why might you want to?
Why's everything in a JavaScript a hash? How does .Net class inheritance compare to JavaScript prototypes? Are JavaScript's first-class functions a great tool or a source of obscurantist abuse, compared to .Net's strongly and statically typed classes?
What are the fundamental data structures in each language? For each language, why are those types fundamental to that language? What were the different design decisions (or lack of decisions) that motivated and informed each language's design and implementation? Can you discern any common "ancestral" languages among the languages used at your workplace? Why don't we have "One Language To Rule Them All"? Should we?
Finally, excellence at any one language is really great to have, but unless you're sitting on that language's Standard Committee or writing compilers/interpreters for that language, a broader knowledge of the underlying algorithms and data structures and patterns that are common across languages is probably more important to your development as a programmer -- and certainly to managing programmers, if that's your goal.

A: Look for local .NET user groups.  In most cities, you are likely to find at least one.  User groups are a great place to develop contacts, ask questions about the technology and basically get answers to problems you may be experiencing.  If there are no user groups in your area, try looking online.

A: If you are free to choose how you develop, and you get new projects fairly often, pick a new technology you're not familiar with to use on each project. Of course, do your research first and make sure it makes sense for the project.
At my last company, I was pretty free to use whatever I wanted as long as it made sense and worked. I always tried to use something new on each project. The last project I worked on, I used NHibernate. No one told me to learn NHibernate, but I took it upon myself to use it to expand my knowledge. Of course, I made sure NHibernate was acceptable first.
The best way to learn something is to use it. Classes and books are good, but nothing will make it stick more than using it in a real project.

A:
My goal, optimistically, is to become
  a developer capable of managing the
  next .NET developer we hire ...

In that case, you should be looking to expand or improve your people/project management skills as well as developing your technical programming and design skills in your chosen technology.
I also subscribe to the view that it is not a good idea to focus too much on a particular technology; e.g. .NET.  Too much specialization tends to limit your career prospects.

A: A year ago I was pretty much in the same boat and it's interesting when I look back at the things I wasn't so good at. Awareness of the technology you are using is an important one, many people have suggested reading books/blogs etc which are good.
One thing that may help you, is to look at the MCTS material, starting with a foundation exam (I'm working toward 70-536 .NET 2.0 Framework exam) to make sure you have a good base. One of the advantages of this is one that it is credited by Microsoft so you can add it to your CV for the future and it gives you a more structured approach than just reading books.
Secondly read up on design practises, or even design principles (such as Gang Of Four). Do your best to not cut corners, and develop your code in the best re-usable way. This keeps you thinking about design and maintainability which is extremely important.
Finally I'd probably suggest trying to ensure you're not doing the same thing over and over. Don't just work with databases, or UI's etc... Try to get a mixture of things to try new techniques and learn new stuff.


text:
Q: Get SQL Insert to work when PK is supplied or NOT I have the following stored procedure:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
    @ServerEnvironmentName varchar(50),
    @ServerEnvironmentDescription varchar(1000),
    @UserCreatedId uniqueidentifier,
    @ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
    -- Stores the ServerEnvironmentId.
    DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)

    -- Insert the data into the table.
    INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
    (
        ServerEnvironmentName,
        ServerEnvironmentDescription,
        DateCreated,
        UserCreatedId
    )
    OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
    VALUES
    (
        @ServerEnvironmentName,
        @ServerEnvironmentDescription,
        GETDATE(),
        @UserCreatedId
    )

    -- If @ServerEnvironmentId was not supplied.
    IF (@ServerEnvironmentId IS NULL)
    BEGIN
        -- Get the ServerEnvironmentId.
        SELECT @ServerEnvironmentId = ServerEnvironmentId
        FROM @APPL_ServerEnvironment
    END

The ServerEnvironmentId column is a primary key with a default set on it, which is (newsequentialid()).
I need this stored procedure to work for 2 scenarios:

*

*Value supplied for ServerEnvironmentId - WORKS.

*Value not supplied for ServerEnvironmentId - DOES NOT WORK - CANNOT INSERT NULL VALUE. I thought by setting a default on this column this would be fine.

Someone please help to ammend this procedure so that it may work for both scenarios. Solution needs to have minimal changes as all sp's currently following this trend.

A: Default values are only applied on inserts if the column is not included in the INSERT list. I'd recommend the following not entirely trivial change (I've commented out the lines to be removed):
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
    @ServerEnvironmentName varchar(50),
    @ServerEnvironmentDescription varchar(1000),
    @UserCreatedId uniqueidentifier,
    @ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
    ---- Stores the ServerEnvironmentId.
    --DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)

    IF @ServerEnvironmentName is null
        SET @ServerEnvironmentName = newid()

    -- Insert the data into the table.
    INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
    (
        ServerEnvironmentName,
        ServerEnvironmentDescription,
        DateCreated,
        UserCreatedId
    )
    --OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
    VALUES
    (
        @ServerEnvironmentName,
        @ServerEnvironmentDescription,
        GETDATE(),
        @UserCreatedId
    )

    ---- If @ServerEnvironmentId was not supplied.
    --IF (@ServerEnvironmentId IS NULL)
    --BEGIN
    --    -- Get the ServerEnvironmentId.
    --    SELECT @ServerEnvironmentId = ServerEnvironmentId
    --    FROM @APPL_ServerEnvironment
    --END

The default constraint will not be used by this procedure, but you can leave it in place if there are other places where rows may be added to the table.

A: (My first answer was long and so it this one, so I'm posting a second answer.)
I missed that you were using NewSequentialId. Again, if a column is specified within the insert statement, any DEFAULT values assigned to that column will not be used [unless you use the DEFAULT keyword in the INSERT statement, but that's still all or nothing--you can't say "if @Var is null then DEFAULT"]. I think you are stuck with simple branching and semi-redundant code, along the lines of:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
    @ServerEnvironmentName varchar(50),
    @ServerEnvironmentDescription varchar(1000),
    @UserCreatedId uniqueidentifier,
    @ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
    -- Stores the ServerEnvironmentId.
    DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)

    IF @ServerEnvironmentId is null
     BEGIN
        --  ServerEnvironmentId not provided by user, generate during the insert
        INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
        (
            ServerEnvironmentName,
            ServerEnvironmentDescription,
            DateCreated,
            UserCreatedId
        )
        OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
        VALUES
        (
            @ServerEnvironmentName,
            @ServerEnvironmentDescription,
            GETDATE(),
            @UserCreatedId
        )

        -- Get the new ServerEnvironmentId
        SELECT @ServerEnvironmentId = ServerEnvironmentId
        FROM @APPL_ServerEnvironment
     END

    ELSE
     BEGIN
        --  ServerEnvironmentId is provided by user
        INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
        (
            ServerEnvironmentName,
            ServerEnvironmentDescription,
            DateCreated,
            UserCreatedId,
            ServerEnvironmentId
        )
        OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
        VALUES
        (
            @ServerEnvironmentName,
            @ServerEnvironmentDescription,
            GETDATE(),
            @UserCreatedId,
            @ServerEnvironmentId
        )
     END

(Why lock the entire table during the insert?)

A: Help to Simplify SQL Insert which uses NEWSEQUNETIALID() column default