text:
Q: docker-compose spec says cpus option is deprecated but docker run says use --cpus Reading docker-compose spec (https://github.com/compose-spec/compose-spec/blob/master/spec.md#cpus) it says that cpus option is DEPRECATED, so even if it still works when I use it, I think it is not a great idea.

cpus
DEPRECATED: use deploy.reservations.cpus
cpus define the number of (potentially virtual) CPUs to allocate to service containers. This is a fractional number. 0.000 means no limit.

On the other hand, docker run docs says (https://docs.docker.com/config/containers/resource_constraints/#configure-the-default-cfs-scheduler) that --cpus option is more convenient.

Specify the CPU CFS scheduler period, which is used alongside --cpu-quota. Defaults to 100000 microseconds (100 milliseconds). Most users do not change this from the default. For most use-cases, --cpus is a more convenient alternative.

So I'm very confused: should or shouldn't i use cpus in docker-compose? if don't, how do I efficiently control a service cpu usage?
I'm using docker without swarm.
Context
$ docker version
Client:
 Version:           20.10.2
 API version:       1.41
 Go version:        go1.13.8
 Git commit:        20.10.2-0ubuntu1~20.04.2
 Built:             Tue Mar 30 21:24:57 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server:
 Engine:
  Version:          20.10.2
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.8
  Git commit:       20.10.2-0ubuntu1~20.04.2
  Built:            Mon Mar 29 19:10:09 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.3.3-0ubuntu2.3
  GitCommit:
 runc:
  Version:          spec: 1.0.2-dev
  GitCommit:
 docker-init:
  Version:          0.19.0
  GitCommit:

$ docker-compose version
docker-compose version 1.29.2, build 5becea4c
docker-py version: 5.0.0
CPython version: 3.7.10
OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019

A: you should use deploy.reservations.cpus as the warning suggests, example:
https://github.com/compose-spec/compose-spec/blob/master/deploy.md#cpus
services:
  frontend:
    image: awesome/webapp
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 50M
        reservations:
          cpus: '0.25'
          memory: 20M

so what it means is cpus should be under reservations, under deploy.


text:
Q: wordpress query posts by meta date value I am trying to query a custom post type by a custom field that contains a date. My query looks like this:
query_posts(
    array(
    'showposts' => 500,
    'post_type' =>  'holidays',
    'post_status' => 'publish',
    'order' => 'desc',
    'orderby' => 'meta_value',
    'meta_query'   => array
                    (
                        array
                        (
                            'key'     => 'from_date',
                            'value'   => array( '01-01-2012', '31-12-2014' ),
                            'type'    => 'DATE', // TRIED: DATE, SIGNED, NUMBER
                            'compare' => 'BETWEEN'
                        )
                    ),

    ));

My custom fields store the date like this: 19-11-2013
When i run the query no results are shown, although dates within the range exist.
Am i approaching this is the correct manor, or am i missing something?

A: I can confirm Dan White's answer is correct, when querying by a date range the required format needs to be 'YYYY-mm-dd'. Your final code should look like this:
query_posts(
    array(
    'showposts' => 500,
    'post_type' =>  'holidays',
    'post_status' => 'publish',
    'order' => 'desc',
    'orderby' => 'meta_value',
    'meta_query'   => array
                    (
                        array
                        (
                            'key'     => 'from_date',
                            'value'   => array( '2012-01-01', '2014-12-31' ),
                            'type'    => 'DATE',
                            'compare' => 'BETWEEN'
                        )
                    ),

    ));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot delete a key value pair from js object I am receiving a js object from mongodb query and I want to remove a key value pair from object using delete optr but is not deleting and isFollowing value is not setting but the code in if part is running successfully. (using nodeJS)
I have already tried to delete using delete optr.... however it works with undefined but the value i am setting to isFollowing is not reflected in object.
baseData.numFollowers = baseData.followers.length;
    baseData.numFollowing = baseData.following.length;
    if(forWhom === 'self'){
        delete baseData.following;
        delete baseData.followers;
    }else
    if(forWhom === 'other'){
        const selfUID = req.body.self_id;
        baseData.isFollowing = baseData.followers.includes(selfUID);
        delete baseData.followers;
        delete baseData.following;

    }

    let toSend = {success:true, basic:baseData};

Getting result:
{
  following: [],
  followers: [],
  numFollowers: 0,
  numFollowing: 0
 }

Expected Result:
{
  numFollowers: 0,
  numFollowing: 0,
  isFollowing: true (or false)
}

A: To use delete you would need to convert the model document into a plain JavaScript object by calling toObject so that you can freely manipulate it like this:
const base = baseData.toObject();

base.numFollowers = base.followers.length;
    base.numFollowing = base.following.length;
    if(forWhom === 'self'){
        delete base.following;
        delete base.followers;
    }else
    if(forWhom === 'other'){
        const selfUID = req.body.self_id;
        base.isFollowing = base.followers.includes(selfUID);
        delete base.followers;
        delete base.following;

    }

    let toSend = {success:true, basic:base};


text:
Q: Spacing around itemize in tabular I'm working off of a resume template from writelatex.com. I'd like to use bullet points in my descriptions, rather than flowing text. However, it adds a bit to the separating line, as seen in item 1. How do I get the line to only be the length of the itemized text, similar to item 2?
Line is too long

Line is just right

\documentclass[a4paper,10pt]{article}

\usepackage{enumitem}
\setlist[itemize]{leftmargin=*,topsep=0ex,parsep=0pt}

\usepackage{marvosym}
\usepackage{fontspec}                   %for loading fonts
\usepackage{xunicode,xltxtra,url,parskip}   %other packages for formatting
\RequirePackage{color,graphicx}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[big]{layaureo}              %better formatting of the A4 page
% an alternative to Layaureo can be ** \usepackage{fullpage} **
\usepackage{supertabular}               %for Grades
\usepackage{titlesec}                   %custom \section

%Setup hyperref package, and colours for links
\usepackage{hyperref}
\definecolor{linkcolour}{rgb}{0,0.2,0.6}
\hypersetup{colorlinks,breaklinks,urlcolor=linkcolour, linkcolor=linkcolour}

\titleformat{\section}{\Large\scshape\raggedright}{}{0em}{}[\titlerule]
\titlespacing{\section}{0pt}{3pt}{3pt}

%--------------------BEGIN DOCUMENT----------------------
\begin{document}

\pagestyle{empty} % non-numbered pages

\font\fb=''[cmr10]'' %for use with \LaTeX command

%--------------------TITLE-------------
\par{\centering
        {\Huge Adam \textsc{G}
    }\bigskip\par}

%--------------------SECTIONS-----------------------------------

\section{Work Experience}
\begin{tabular}{r|p{11cm}}
 \emph{Current - } & Research Assistant \\\textsc{June 2012}&\emph{Speech Lab @ Queens College}\\&
 \footnotesize{
 \begin{itemize}
 \item DARPA-funded initiative to identify "cognitive fingerprints" (unique typing patterns) based on linguistic biometrics
 \item Develop, test and implement a series of linguistic feature-sets, to create unique user profiles
 \end{itemize}}\\\multicolumn{2}{c}{} \\

 \textsc{Jul-Oct 2008} & 1\textsuperscript{st} year Analyst at \textsc{Lehman Brothers}, London \\&\emph{Commodities Structured Trading}\\&\footnotesize{Developed spreadsheets for risk analysis on exotic derivatives on a wide array of commodities (\textit{ags, oils, precious} and \textit{base metals}), managed blotter and secondary trades on structured notes, liaised with Middle Office, Sales and Structuring for bookkeeping.}\\\multicolumn{2}{c}{} \\
\end{tabular}

\end{document}

A: Add after=\vspace{-\baselineskip} to
\setlist[itemize]{leftmargin=*,topsep=0ex,parsep=0pt}

Code:
\documentclass[a4paper,10pt]{article}

\usepackage{enumitem}
\setlist[itemize]{leftmargin=*,topsep=0ex,parsep=0pt,after=\vspace{-\baselineskip}}

\usepackage{marvosym}
\usepackage{fontspec}                   %for loading fonts
\usepackage{xunicode,xltxtra,url,parskip}   %other packages for formatting
\RequirePackage{color,graphicx}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[big]{layaureo}              %better formatting of the A4 page
% an alternative to Layaureo can be ** \usepackage{fullpage} **
\usepackage{supertabular}               %for Grades
\usepackage{titlesec}                   %custom \section

%Setup hyperref package, and colours for links
\usepackage{hyperref}
\definecolor{linkcolour}{rgb}{0,0.2,0.6}
\hypersetup{colorlinks,breaklinks,urlcolor=linkcolour, linkcolor=linkcolour}

\titleformat{\section}{\Large\scshape\raggedright}{}{0em}{}[\titlerule]
\titlespacing{\section}{0pt}{3pt}{3pt}

%--------------------BEGIN DOCUMENT----------------------
\begin{document}

\pagestyle{empty} % non-numbered pages

\font\fb=''[cmr10]'' %for use with \LaTeX command

%--------------------TITLE-------------
\par{\centering
        {\Huge Adam \textsc{G}
    }\bigskip\par}

%--------------------SECTIONS-----------------------------------

\section{Work Experience}
\begin{tabular}{r|p{11cm}}
 \emph{Current - } & Research Assistant \\\textsc{June 2012}&\emph{Speech Lab @ Queens College}\\&
 \footnotesize{
 \begin{itemize}
 \item DARPA-funded initiative to identify "cognitive fingerprints" (unique typing patterns) based on linguistic biometrics
 \item Develop, test and implement a series of linguistic feature-sets, to create unique user profiles
 \end{itemize}}\\\multicolumn{2}{c}{} \\

 \textsc{Jul-Oct 2008} & 1\textsuperscript{st} year Analyst at \textsc{Lehman Brothers}, London \\&\emph{Commodities Structured Trading}\\&\footnotesize{Developed spreadsheets for risk analysis on exotic derivatives on a wide array of commodities (\textit{ags, oils, precious} and \textit{base metals}), managed blotter and secondary trades on structured notes, liaised with Middle Office, Sales and Structuring for bookkeeping.}\\\multicolumn{2}{c}{} \\
\end{tabular}

\end{document}

A better setting would be
\setlist[itemize]{leftmargin=*,nosep,after=\vspace{-\baselineskip},before=\vspace*{-0.75\baselineskip}}

If you want to retain the regular itemize environment, define a new list:
\usepackage{enumitem}
\newlist{myitemize}{itemize}{1}
\setlist[myitemize]{label=\textbullet,leftmargin=*,topsep=0ex,
    parsep=0pt,after=\vspace{-\baselineskip},before=\vspace{-0.75\baselineskip}}

and use it:
\begin{myitemize}
 \item DARPA-funded initiative to identify "cognitive fingerprints" (unique typing patterns) based on linguistic biometrics
 \item Develop, test and implement a series of linguistic feature-sets, to create unique user profiles
 \end{myitemize}}


text:
Q: If he had or had he
If he hadn't/Had he not cheated,he wouldn't have won the first prize.

I have always wondered if there is any  difference between the two ways of using the conditional.i searched Google but unable to find the topic.
Can you point out any nuance in above two ways, if any?
Don't be bound to only above given example, it's more of a general question,feel free to give other examples as well.

A: There is no difference in meaning between the two forms.
The "If he hadn't.." form is a lot more likely to be used in spoken English and in informal written English.  It is considered inappropriate to use short forms (hadn't, wouldn't) in formal written English, and this may be one of the reasons the other form is used in formal written English.
According to this NGram, up until 1970, "Had he not" dominated in written English, but written English has become progressively less formal over the years, and "Had he not" is now used rarely apart from in literary, period and formal writing.

Whether Clifford Beers would have made a name for himself had he not become mentally ill in 1900, or, given that, had he afterwards buried his psychiatric history and pursued his youthful goal of business success, is hard to say. Clifford W. Beers: Advocate for the Insane


text:
Q: How to use Pandas to do a conditional VLOOKUP using two columns as an index for the VLOOKUP? I'm pretty new to Pandas and Python, and I simply cannot figure out how to do something that is very easily done in Excel.  I was hoping to get a bit of help from the community.
Assume I have the following, which is a df relating to fantasy football that has three columns - 'Name', 'Year', and 'FantasyPts'. Code below.
import pandas as pd

df = pd.DataFrame({'Name': ['Tom Brady', 'Tom Brady', 'Tom Brady', 'Patrick Mahomes', 'Patrick Mahomes', 'Patrick Mahomes'],
                   'Year': [2019, 2018, 2017, 2019, 2018, 2017],
                   'FantasyPts': [300, 350, 400, 500, 400, 50],
                   })

I want to add another column to the table called 'FantasyPtsPreviousYear' but am having a ton of difficulty figuring out how to do so in Pandas / Python.
What I want to do is:

*

*For each row in the table, have python / pandas check the name and year in that row of the df.

*Look up the fantasy points scored by the same player in the previous year (i.e., Year - 1)

*Populate that number in a new row of the df called 'FantasyPtsPreviousYear' or, if there is no data for the previous year for that player, enter 0.

In Excel, I would simply create new columns and use those columns with VLOOKUPs.  The closest thing I have been able to find to VLOOKUP in Pandas is merge but that doesn't seem to work here (or at least I can't figure out how to make it work with this specific application).  After trying to find the answer, I think it might have something to do with the loc() function and a For loop, but I can't get it to work.
Thanks for any help you can provide!  I greatly appreciate it and think this community is awesome for all of the assistance it provides!

A: I believe this can be achieved with a combination of where() and shift(). However, this requires the data to be previously sorted. Here is the code given the data you provide:
df = df.sort_values(['Name','Year'],ascending=[True,True])
df['FantasyPtsPreviousYear'] = df['FantasyPts'].shift().where(df['Name'].eq(df['Name'].shift())).fillna(0)
print(df)

This outputs:
              Name  Year  FantasyPts  FantasyPtsPreviousYear
5  Patrick Mahomes  2017          50                     0.0
4  Patrick Mahomes  2018         400                    50.0
3  Patrick Mahomes  2019         500                   400.0
2        Tom Brady  2017         400                     0.0
1        Tom Brady  2018         350                   400.0
0        Tom Brady  2019         300                   350.0

A: Let us try groupby with shift
df = df.sort_values(['Name','Year'],ascending=[True,True])
df['FantasyPtsPreviousYear'] = df['FantasyPts'].groupby(df['Name']).shift().fillna(0)

A: merge the DataFrame with itself where you add 1 to the year. This explicitly defines the match on Year -> Year-1 for each player
(Be careful with shift, unless you are certain you have a row for every year. Without explicitly reindexing to all years a shift within group will give you the last year you have data for, regardless of whether that is 1 year ago or 10 years ago (if missing data))

df = df.merge((df.assign(Year=df['Year']+1)
                 .rename(columns={'FantasyPts': 'FantasyPts_prev'})),
              how='left', on=['Name', 'Year'])
df['FantasyPts_prev'] = df['FantasyPts_prev'].fillna(0, downcast='infer')

              Name  Year  FantasyPts  FantasyPts_prev
0        Tom Brady  2019         300              350
1        Tom Brady  2018         350              400
2        Tom Brady  2017         400                0
3  Patrick Mahomes  2019         500              400
4  Patrick Mahomes  2018         400               50
5  Patrick Mahomes  2017          50                0


text:
Q: Change viewport width and height for a specific div I have a configurator application where you can build a website. I have an angular component which builds the website and this uses the viewport width and height for a bunch of media queries to be mobile and desktop responsive.
I want to be able to show my user a preview of what the website looks like in a mobile view.
To paint a picture, in my configurator I have a menu on the left side with basic options, a menu on top with display settings to switch between mobile view and desktop view and a menu on the right to show some more options. In the middle of the page I have my preview which contains an angular component.
Is it possible for me without using an iframe to tell this preview div that to act as if its a viewport with 400px by 800px? And then all the content inside of it will think its inside 400px by 800px?


text:
Q: Pass values between PHP files called by SH script i'm trying to call a PHP script from a SH script.
It's easy, i receive the values from SH, but nothing is passed when i try to pass values from first PHP to other PHP using OOP.
Here's the first PHP, it receive a simple call from a SH file than pass values by URL:
$controller = $_GET['c'];
$metodo     = $_GET['m'];
$uniqueid       = $_GET['uniqueid'];

$url = '../controllers/'.ucfirst($controller).'.controller.php';

include_once($url);

$controller = ucfirst($controller)."Controller";

$objeto = new $controller;
$dados = $_POST;

$objeto->dados = $dados;

$objeto->uniqueid = $uniqueid;

//CALL THE FUNCTION
$result = $objeto->$metodo($uniqueid);

//RETURN THE RESPONSE
echo  $result;

And here i receive values passed to object:
(Here's the problem, the values are empty)
include('../classes/Tarifacao.class.php');
class TarifacaoController{
    public function Tarifa($uniqueid){
        $obj_tarif = new Tarifacao;
        $bilhete = $obj_tarif->BuscaUltimoBilhete($uniqueid);
        echo $this->Imprime($bilhete,'BILHETE');

        $uniqueid = $bilhete['uniqueid'];
        echo $this->Imprime($uniqueid,'UNIQUEID');

        intval($duracao = $bilhete['billsec']);
        echo $this->Imprime($duracao,'DURAÇÃO');
        ...

Sorry, my english is so poor.

A: If you execute PHP from the command line, you cannot pass values like that.
You need to use the $argv reserved variable: http://www.php.net/manual/en/reserved.variables.argv.php
You can try something like this:
$controller = $argv[1];
$metodo     = $argv[2];
$uniqueid   = $argv[3];

And execute the script like this from the shell:
$ php script.php <c> <m> <uniqueid>


text:
Q: CSS Counters - used with the content property only? According to the spec, can/will CSS counters only be used in conjunction with the content property?
* { content: counter(mycounter) "! "; counter-increment: mycounter }

Or can/will they also be used with other properties, such as (random example) padding?
/*
    is this possible?
    is this supposed to be possible?
*/
* { padding:counter(mycounter)px; }

Lastly, if that is a feature of CSS, to what extent is it implemented in browsers?

A: In CSS2.1, the counter() function is indeed defined for use with the content property only; you cannot use counters to specify numeric values for other properties.


text:
Q: SwiftyJSON not working with WebSocket message I have a socket response that is this:
{"op":0,"d":{"author":{"id":"6699457769390473216","name":"Test","verified":false},"unixTime":1597277057132,"id":"6699465549836976128","group":"64632423765273287342","content":"Yo","_id":"5f34838198980c0023fa49e3"},"t":"MESSAGE"}

and I need to access the "d" object, I've tried doing
print(JSON(data)["d"])

and it just Returns null every time.

A: If data is of type String, you are probably using the wrong init method to initialize the JSON object. Try using init(parseJSON:) like this:
let jsonString = """
{
    "op": 0,
    "d": {
        "author": {
            "id": "6699457769390473216",
            "name": "Test",
            "verified": false
        },
        "unixTime": 1597277057132,
        "id": "6699465549836976128",
        "group": "64632423765273287342",
        "content": "Yo",
        "_id": "5f34838198980c0023fa49e3"
    },
    "t": "MESSAGE"
}
"""
let json = JSON(parseJSON: jsonString)

print(json["d"])


text:
Q: Composition of two Riemann integrable functions Suppose $f,g$ are two Riemann  Integrable functions .Is it true that $f\circ g$ is also Riemann  Integrable?
Trying this for a long time but not getting the answer

A: A function on a bounded interval is Riemann-integrable iff it is bounded and almost everywhere continuous. So the functions
$$
f(x) = \begin{cases} 1 & \text{ for }x \ne 0 \\ 0 & \text{ for } x = 0  \end{cases}
\quad \text{ and } \quad
g(x) = \begin{cases} 1/q & \text{ for }x=p/q \\ 0 & \text{ for } x \notin \mathbb{Q}  \end{cases}
$$
are Riemann-integrable over any bounded interval, since $f$ is continuous everywhere except at $0$, and $g$ is continuous at every irrational $x$. (In the definition $x=p/q$ is the unique representation of rational $x$ with $p$ and $q$ relatively prime integers and $q>0$.)
The composition of these functions is
$$
f(g(x)) = \begin{cases} 1 & \text{ for }x \in \mathbb{Q} \\ 0 & \text{ for } x \notin \mathbb{Q}  \end{cases}
$$
which is nowhere continuous, so not Riemann-integrable over any interval.


text:
Q: PDB inconsistently recognizing variables foo
(Pdb) *** NameError: name 'foo' is not defined
foo = 'foo'
(Pdb) print(foo)
(Pdb) *** NameError: name 'foo' is not defined
foo
(Pdb) 27

(note:  in a previous pdb session, I defined foo as 27)
Continuing:
foo = "foo"
(Pdb) foo
(Pdb) *** NameError: name 'foo' is not defined
print(foo)
(Pdb) *** NameError: name 'foo' is not defined
foo
(Pdb) *** NameError: name 'foo' is not defined
foo
(Pdb) 'foo'
foo
(Pdb) *** NameError: name 'foo' is not defined

A: My site was running with threads on.  Running it without threading fixed the issue.


text:
Q: how to download file in fixtures/Downloads folder cypress This will download in in cypress\downloads folder which i not want to download , i need to change the download location in fixtures
cy.readFile("cypress\downloads" + fileName + ".csv").should("exist");

A: You can change the location of downloads in cypress.json like this:
{
  "viewportHeight": 880,
  "viewportWidth": 1280,
  "downloadsFolder": "yourPathHere"
}

In the code below, the property "downloadsFolder" is responsible to change the location of downloads. More information here.


text:
Q: Test angular directive - angular.element.css I want write test for angular directive method in jasmine. How to test toHaveBeenCalled for .css method in the following code?
I try to create spy for this method but always got Expected spy css to have been called.. Is it good idea to test css method call?
Directive method to test:
scope.contentPadding = () => {
  const bars = angular.element(element[0].querySelectorAll('.intro'));
  if (bars.length > 0) {
    const bar = angular.element(bars[bars.length - 1]);
    bar.parent().css('padding-top', `${bar[0].offsetHeight - 10}px`);
  }
};

My test implementation:
describe('test', function() {
  var $rootScope,
      $compile,
      $scope,
      $window,
      element;

  function compileDirective() {
    var html = angular.element(`

`);

      element = $compile(html)($scope);
      $scope.$digest();
    }

    beforeEach(function() {
      angular.mock.module('my-directive-name');

      inject(function(_$rootScope_, _$compile_, _$window_) {
        $rootScope = _$rootScope_;
        $compile = _$compile_;
        $window = _$window_;

        $scope = $rootScope.$new();
        compileDirective();
      });
    });

  describe('padding', function() {
    it('adds top padding', function() {
      var el = angular.element(element[0].querySelector('.section'));
      spyOn(el, 'css');
      $scope.contentPadding();
      $scope.$digest();
      expect(el.css).toHaveBeenCalled();
    });
  });
});

A: Be sure you're spying on the angular element:
it('adds top padding' function () {
   var element = angular.element(....);

    spyOn(element, 'css');

    // Trigger padding here

    expect(element.css).toHaveBeenCalled();
});


text:
Q: Add new object to array based on list with new key and value I have a checkbox to make a selection of objects from a list. To make the selection recognizable i want to add a new keyvalue to the selected objects with the label of the selected value.
I tried the following:
var checkCheckboxOnOff = [{"fieldName":"Categorie__c","picklistValue":"Techniek"},{"fieldName":"Regio__c","picklistValue":"Midden"}]

I loop trough checkCheckboxOnOff where I select objects from a list:
opleidingfilter = serverList.filter(function(item) { return item[checkCheckboxOnOff[i].fieldName] == checkCheckboxOnOff[i].picklistValue});

While looping trough the list I add a key and value to the selected objects and push them into a filter array:
    opleidingfilter.forEach(function(n) {n.arrayPicklist = checkCheckboxOnOff.fieldName});
 Array.prototype.push.apply(filter,opleidingfilter[i]);

My problem is that when I select a an object twice I end up with both selected objects being updated with the last Key and value. My expectation is when having selected 1 object twice I end up with 2 different values.
Example:
1st selection:
[{"Id":"120"},{"Id":"121"}]

2nd Selection
[{"Id":"123"},{"Id":"121"}]

Expected:
[{"Id":"120","arrayPicklist":"Categorie__c"},
{"Id":"121","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"},
{"Id":"121","arrayPicklist":"Regio__c"}]

Current result
[{"Id":"120","arrayPicklist":"Categorie__c"},
    {"Id":"121","arrayPicklist":"Regio__c"},{"Id":"123","arrayPicklist":"Regio__c"},
    {"Id":"121","arrayPicklist":"Regio__c"}]

Seem to get undefined for the value in fiddle see:https://jsfiddle.net/Lcg1qca3/18/

A: Your problem is in
n.arrayPicklist = checkCheckboxOnOff.fieldName

You're trying to access a fieldname property on an array, instead of an index in the checkCheckboxOnOff array.
Replace that line with this
opleidingfilter.forEach(function(n,i) {n.arrayPicklist = checkCheckboxOnOff[i].fieldName});

This way you have access to the index property in your iterator, and can access every item in your checkCheckboxOnOff array.


text:
Q: Shortest Path on Chessboard , Python I have NxN chessboard. I have a pawn that can move 1 box up,down,right,left. There is a random exit point. What I want to do is calculate the shortest path from pawn location to exit location.

*

*Pawn is located at random place

*Obstacles are located at random place

*Exit place is located at random place

I already created adjaceny array for chessboard. I did it with 2D array. For instance, obstacles are 0 where others are 1. It looks like 2D array. R is pawn. O is obstacle. X are ways that robot can go. E is exit point.
E   X   X   O   O
X   X   X   X   X
X   X   R   O   X
X   X   X   X   X
X   X   X   X   X
Array representation is
1  1  1  0  0
1  1  1  1  1
1  1  1  0  1
1  1  1  1  1
1  1  1  1  1
My question is should I traverse from R to E and create Tree implementation then calculate the minimum path (DFS, BFS) ? If so how should I do it ?. Or is there another method for that ? For instance using graphs ?

A: You are right, you should use BFS (Breadth-first Search). It is easy to see that DFS (Depth-first Search) would not necessarily return the shortest.  However, it will still tell you whether there exists a path between your pawn and the exit.
To apply the BFS algorithm you should think of your problem as a graph without changing the actual representation of the problem:

*

*vertices of the graphs are all tuples (x, y) that are in your 2D list and are not obstacles

*two vertices are connected by an edge if they are "neighbors" in the 2D array

Here's a standard implementation of BFS in which we replace the vertices and edges as explained above.
def BFS(board, start):
  queue = list()
  queue.append(start)
  visited = set()

  # this keeps track of where did we get to each vertex from
  # so that after we find the exit we can get back
  parents = dict()
  parents[start] = None

  while queue:
    v = queue[0]
    if board[v[0]][v[1]] == 'E':
      break
    queue = queue[1:]   # this is inefficient, an actual queue should be used
    visited.add(v)
    for u in neighbors(board, v):
      if u not in visited:
        parents[u] = v
        queue.append(u)

  # we found the exit, now we have to go through the parents
  # up to the start vertex to return the path
  path = list()
  while v != None:
    path.append(v)
    v = parents[v]

  # the path is in the reversed order so we reverse it
  path = reverse(path)
  return path

def neighbors(board, v):
  diff = [(0, 1), (0, -1), (1, 0), (-1, 0)]
  retval = list()
  for d in diff:
    newr = d[0] + v[0]
    newc = d[1] + v[1]
    if newr < 0 or newr >= len(board) or newc < 0 or newc >= len(board[0]):
      continue
    if board[newr][newc] == 'X':
      continue
    retval.append((newr, newc))
  return retval


text:
Q: Problem while installing vlc player I can't install vlc player on my Ubuntu(14.04).
I have read this and try to run the commands, but while I run this command:
sudo apt-get install vlc

I got something like this:
    Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 vlc : Depends: vlc-nox (= 2.1.4+git20150226+r54594+19+11~ubuntu14.04.1) but 2.1.6-0ubuntu14.04.1 is to be installed
       Recommends: vlc-plugin-notify (= 2.1.4+git20150226+r54594+19+11~ubuntu14.04.1) but 2.1.6-0ubuntu14.04.1 is to be installed
       Recommends: vlc-plugin-pulse (= 2.1.4+git20150226+r54594+19+11~ubuntu14.04.1) but 2.1.6-0ubuntu14.04.1 is to be installed
E: Unable to correct problems, you have held broken packages.

What is the problem? Have you any Idea to solve this or Could you please tell me the right procedure by which I can install vlc media player?

Update:
After removing the PPA, this is the output of apt-cache policy vlc:
vlc:
  Installed:  (none)
  Candidate:  2.1.2-2build2
    Version table:
      2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
      2.1.2-2build2 0
        500 archive.ubuntu.com/ubuntu trusty/universe i386 Packages
      2.0.1-4 0
        500 archive.ubuntu.com/ubuntu precise/universe i386 Packages

And The command:
apt-cache policy vlc-nox vlc-plugin-notify vlc-plugin-pulse

gives me the following results:
vlc-nox:
  Installed: 2.1.6-0ubuntu14.04.1
  Candidate: 2.1.6-0ubuntu14.04.1
  Version table:
 *** 2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages
vlc-plugin-notify:
  Installed: 2.1.6-0ubuntu14.04.1
  Candidate: 2.1.6-0ubuntu14.04.1
  Version table:
 *** 2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages
vlc-plugin-pulse:
  Installed: 2.1.6-0ubuntu14.04.1
  Candidate: 2.1.6-0ubuntu14.04.1
  Version table:
 *** 2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages

A: Don't use the PPA, install vlc from the Ubuntu repositories.

*

*Remove the PPA you have installed:
sudo add-apt-repository --remove ppa:videolan/stable-daily

*Empty the package cache:
sudo apt-get clean

*Update your package lists:
sudo apt-get update

*Downgrade/install all vlc packages to/in the repository version:
sudo apt-get install --reinstall vlc=2.1.2-2build2 vlc-data=2.1.2-2build2 vlc-nox=2.1.2-2build2 vlc-plugin-notify=2.1.2-2build2 vlc-plugin-pulse=2.1.2-2build2

Depending on your Ubuntu version, you might currently (Nov 20, 2015) get a VLC version up to 2.2.1-3 on Wily (15.10). Older Ubuntu versions might have older VLC versions in their repositories.
You check the versions available for you with the command:
apt-cache policy vlc

An example output on my 15.10 64bit system would be:
vlc:
  Installed: (none)
  Candidate: 2.2.1-3
  Version table:
     2.2.1-3 0
        500 http://[YOUR REPOSITORY SERVER URL]/ wily/universe amd64 Packages


text:
Q: Loading a DTD from text using libxml2 for python I am currently limited to using libxml2 (instead of lxml) for parsing on QNX 6.5.  I want to validate my xml using a DTD loaded from a string, instead of from a file.
lxml lets you do this:
import lxml
from lxml import etree
from StringIO import StringIO

dtd_string = """
<!ELEMENT page (title)>
<!ELEMENT title (#PCDATA)>
"""

xml = """
<page>
  <title>Hello</title>
 </page>
 """

dtd = etree.DTD(StringIO(dtd_string))
root = etree.fromstring(xml)
is_valid = dtd.validate(root)

I would like to do the same using libxml2.  I can load the DTD from file, but don't know and can't find the syntax to load it from string:
import libxml2
dtd = libxml2.parseDTD(None, dtd_file)  #How to parse DTD from a string??
ctxt = libxml2.newValidCtxt()
doc = libxml2.parseDoc(xml)
is_valid = doc.validateDtd(ctxt, dtd)
#cleanup omitted

Does anyone happen to know how to do this in libxml2?

A: Enh, I broke down and just read the xml to a string, and appended the dtd to it.
I'm still open to any better solutions.
import libxml2

doc = None
dtd = None
ctxt = None

try:

    xml = MY_DTD + filehandle.read().replace('\n', '')

    ctxt = libxml2.newValidCtxt()

    doc = libxml2.parseDoc(xml)

    if not doc.validateDocument(ctxt):
        return

    root = doc.children

    ...


text:
Q: Search Customer by custom field in Netsuite I was able to make the api work in php and search customer by internal id.
However i have a scenario, where i'll be searching a customer by a custom field.
Under Customer and it has a custom tab contains multiple domain name and domain details.
For example :
Main search criteria : Domain Name
How is this possible in netsuite php api? Much appreciated for any help. im only newbie to NetSuite.
How will i modify this sample code to search by custom field?
$service = new NetSuiteService();
$request = new GetRequest();
$request->baseRef = new RecordRef();
$request->baseRef->internalId = "1780";
$request->baseRef->type = "customer";
$getResponse = $service->get($request);

if (!$getResponse->readResponse->status->isSuccess) {
    echo "GET ERROR";
} else {
    $customer = $getResponse->readResponse->record;
    //var_dump($customer);
    echo "GET SUCCESS, customer:";
    echo "\nCompany name: ". $customer->companyName;
    echo "\nInternal Id: ". $customer->internalId;
    echo "\nEmail: ". $customer->email;
    echo "\nCustomerID: ". $customer->firstName;
}

OK, I'm trying to get the custom record of all domains base from egrubaugh360.
$service = new NetSuiteService();
$request = new GetRequest();

$request->baseRef = new CustomRecordRef();
$request->baseRef->internalId = "47";
//$request->baseRef->externalId = "xxxx";
$request->baseRef->typeId = "custom_list_domains";

$getResponse = $service->get($request);

var_dump($getResponse);

if (!$getResponse->readResponse->status->isSuccess) {
    echo "GET ERROR";
} else {
    var_dump($getResponse->readResponse->record);
    echo "GET SUCCESS";
}

I'm not sure what to put in "typeId", what exactly is the type to put? It gives me error "Invalid custom record type key"
object(GetResponse)#8 (1) { ["readResponse"]=> object(ReadResponse)#9 (2) { ["status"]=> object(Status)#10 (2) { ["statusDetail"]=> array(1) { [0]=> object(StatusDetail)#11 (3) { ["code"]=> string(26) "INVALID_CSTM_RCRD_TYPE_KEY" ["message"]=> string(31) "Invalid custom record type key." ["type"]=> string(5) "ERROR" } } ["isSuccess"]=> bool(false) } ["record"]=> NULL } }

A: Here is a general example of searching for a customer by a custom field.
You can modify to fit your need.
$NSservice = new NetSuiteService();
$NSservice->setSearchPreferences(false, 10);

$cs = new CustomerSearch();
$csb = new CustomerSearchBasic();

$domain = new SearchCustomStringField();
$domain->internalId = 'yourcustomfieldinternalid';
$domain->searchValue = 'text you are searching for';
$domain->operator = 'is';

$scfl = new SearchCustomFieldList();
$scfl->customField = array($domain);
$csb->customFieldList = $scfl;
$cs->basic = $csb;

$request = new SearchRequest();
$request->searchRecord = $cs;

$searchResponse = $NSservice->search($request);

A: Instead of doing a GetRequest, you will want to do a SearchRequest. Your $request should become a CustomerSearchBasic object. You can then use $request->customFieldList to add a list of SearchCustom*Field filters. Build a new SearchCustomStringField, for instance, if the custom field you're filtering on is a text field. Then you will use $service->search($request); to execute the search. See here for the full PHP Toolkit docs.
It sounds like your domain names may actually be a custom sublist, not just a custom field. If this is the case, you will want to be doing a search of the custom Domain record instead of the Customer record. Then you can look for all Domains where the Customer is 1780, along with any other filters you might want.

A: As per previews ans code customer Search by custom field just 1 issue below line.
$domain = new SearchCustomStringField();
replace:
$domain = new SearchStringCustomField();


text:
Q: Dropdown Materialize atributos data Estou utilizando o materialize em um projeto e ao criar um menu com dropdown não consigo utilizar as opções disponíveis na documentação do materialize para personalizar o dropdown.
Opções como:
data-hover="true"
data-beloworigin="true"
data-cosntrainwidth="false"
Ainda sim o dropdown não é exibido ao passar o mouse e continua abrindo em cima do item clicado.
O código do item do menu configurado com o dropdown é o seguinte:
`

    Prefeitura
     arrow_drop_down

`

Se souberem me ajudar por favor a entender porque essas opções do data não funcionam.

A: Cara vc está usando as propriedades da forma errada acredito. A customização deve ser feita com atributos no script do componente como no exemplo abaixo.
$('.dropdown-trigger').dropdown({ suas opções aqui });

Vc pode consultar a documentação oficial que vc vai ver quais opções vc pode usar. constrainWidth coverTrigger e hover https://materializecss.com/dropdown.html
Repare que agora ao fazer o hover o dropdown já aparece abaixo...

$('.dropdown-trigger').dropdown({
  hover: true,
  inDuration: 1500,
  coverTrigger: false,
  constrainWidth: true
});
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">

  Meu Dropdown

one

two

three

view_modulefour

cloudfive


text:
Q: How to install pip in python 3.8 (through Spyder)? I am trying to install pip in spyder, running python version 3.8.
I have saved the file from https://bootstrap.pypa.io/get-pip.py and set my working directory to the folder that the file is in.
I run python3 get-pip.py  but it gives me the following error: invalid syntax
I also tried ipython get-pip.py, python get-pip.py, ipython3 get-pip.py, but all of them are incorrect syntaxes.
I have checked if pip was not installed already and it says 'No module named pip'
Could anyone help me solve this issue? Thanks in advance!

A: try running:
conda install pip


text:
Q: Getting large braces in MathJax In answering this question on math.se I used the expression {{{|}|}|} and wanted to enlarge the outer braces to show the pairing.  I tried \left \{ \left \{ \{ | \} \right \} \right \}  (with backslashes on the braces that don't appear here) but the outer ones did not enlarge.  I found that \Bigl \{\bigl\{\{ | \}|\bigr \}|\Bigr\} worked.  Generally I like \left and \right as it stays nice if  change the contents.  Why doesn't it enlarge the outer braces here?

A: The pair \left \right takes parentheses big enough to enclose a box inside. Here the boxes are of the same height, so braces are the same.
However your version on math.stackexchange works very well. \Bigl, \Bigr and so on are sometimes the only acceptable solution, as in this case.
If you really need enlarging braces, you can change \delimiterfactor to a value greater than 1000, as in the following example (LaTeX, not working in MathJax, at least the version on math.se):
\documentclass{article}
 \begin{document}

$\left \{ \left \{ \{ | \} \right \} \right \}$

\delimiterfactor1100
$\left \{ \left \{ \{ | \} \right \} \right \}$

\end{document}


text:
Q: php parse error in arrays I have an html form in which I want to use the inputs in a SQL query. Instead of the first php code, I want to use the alternative php code below, but I receive php parse error for the line including ${$key} = $value in alternative php code. maybe this syntax has been removed in newer versions of php. I appreciate if anyone could help me correct the syntax or suggest a different code to do me the same thing. Thanks in advance.
The error I receive:
Parse error: "syntax error, unexpected '$', expecting case (T_CASE) or default (T_DEFAULT) or '}' "
html code:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<select name="my_input1">
<option value="val1">a</option>
<option value="val2">b</option>
<option value="val3">c</option>
</select>
<select name="my_input2">
<option value="val4">d</option>
<option value="val5">e</option>
</select>
</form>

main php code:
$inputs = array();
$queries = array();
foreach($inputs as $key => $value){
    array_push($queries,"table_name.column1 = $_POST['my_input1']");
    array_push($queries,"table_name.column2 = $_POST['my_input2']");
}

Alternative php code:
$inputs = array();
$queries = array();
foreach($inputs as $key => $value){
    ${$key} = $value;
    array_push($queries,"table_name.column1 = $my_input1");
    array_push($queries,"table_name.column2 = $my_input2");
}


text:
Q: If a series diverges, dividing it by the sequence of partial sums preserves divergence Let $x_n $ be positive, $s_n = \sum_{i=1}^{n} x_i $         and  the series $\sum x_n$ diverges.
I'm trying to see how we can prove the following two propositions withouth using anything related to Cauchy ( Cauchy criteria for series and notion of cauchy sequences ) or too advanced but i can't seem to suceed in finding a way.
The propositions are :
a) $\sum_{i=1}^{k} \frac{x_{n+i}}{s_{n +i}}   \geq  1 -  \frac{s_n}{s_{n+k}}$
b) The series $\sum_{n=1}^{\infty} \frac{x_n}{s_n} $ diverges
Thanks in advance

A: For problem $(a)$, notice that $s_{n+k}\geq s_{n+i}$  for $0\leq i\leq k$, so that $$\sum_{i=1}^{k}\frac{x_{n+i}}{s_{n+i}}\geq\sum_{i=1}^{k}\frac{x_{n+i}}{s_{n+k}}=\frac{1}{s_{n+k}}\sum_{i=1}^{k}x_{n+i}=\frac{1}{s_{n+k}}\left(s_{n+k}-s_{n}\right)=1-\frac{s_{n}}{s_{n+k}}.$$
Hint: Try to use part $(a)$ to solve part $(b)$.


text:
Q: Use selected value in postgis function How can I use the selected value from a SELECT statement in a PostGIS function.
e.g.
using the geom_way from
SELECT geom_way FROM osm_2po_4pgr ORDER BY ST_Distance(ST_GeomFromText('POINT(21.323329 39.948928)', 4326), geom_way) ASC LIMIT 1;
in
SELECT  ST_Line_Interpolate_Point(geom_way, ST_GeomFromText('POINT(21.323329 39.948928)'));
EDIT: I know this has errors, but what I really want to know is how I could refactor a super long statement like this:
SELECT ST_AsText(ST_Line_Interpolate_Point((SELECT geom_way FROM osm_2po_4pgr ORDER BY ST_Distance(ST_GeomFromText('POINT(39.948928 21.323329)', 4326), geom_way) ASC LIMIT 1), ST_Line_Locate_Point((SELECT geom_way FROM osm_2po_4pgr ORDER BY ST_Distance(ST_GeomFromText('POINT(39.948928 21.323329)', 4326), geom_way) ASC LIMIT 1), ST_GeomFromText('POINT(21.323329 39.948928)',4326))));
To be manageable enough to fit into a Java PreparedStatement

A: It's just a simple subquery:
SELECT ST_Line_Interpolate_Point(q.geom_way, ST_GeomFromText('POINT(21.323329 39.948928)'))
FROM
  (SELECT geom_way
  FROM osm_2po_4pgr
  ORDER BY ST_Distance(ST_GeomFromText('POINT(21.323329 39.948928)', 4326), geom_way) ASC
  LIMIT 1)
 AS q


text:
Q: "Segmentation Fault" : when using xlsx npm module in node.js app on linode I'm running a node.js app on linode server(Cent Os 7).
My app is using xlsx npm module for excel conversion and is giving  Segmentation Fault when my code reaches :
var xlsx = XLSX.read(file.data, {type: "binary"});

A: You're probably running node.js v0.10.31 or higher.
I was getting this problem when switching my workplace from my macbook to a Ubuntu desktop. And after some hours searching around, I found this github issue on another repository: https://github.com/SheetJS/j/issues/4.
And it's exactly the same problem of js-xlsx.
I've downgraded my node.js to v0.10.30 and everything worked fine.
Hope this get fixed soon.
EDIT: the issue came from https://github.com/joyent/node/issues/8208, which was fixed in node v0.10.32


text:
Q: Slim PHP REST API not fetching data in production server, works in localhost I have a simple Slim PHP REST api which works great on my local server, but when I pushed it to a shared hosting server it does not fetch the data. My limited plan does not give me SSH access to the database so it is difficult to run tests, but this is what I have tracked so far...
Here is a test api endpoint:
$app->get('/test', function() use($app) {
    $app->response->setStatus(200);
    if($db = getDB()){
      echo "connected
";
    } else{
      echo "not connected
";
    }
    $sql = "SELECT * FROM artists";
    $stmt = $db->prepare($sql);
    if($stmt){
      echo "statement true
";
    } else{
    echo "statement not true
";
    }
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    if($stmt->fetch()){
      echo "executed";
    }else{
      echo "not executed";
    }
});

This gives me an output of:
'connected'
'statement true'
'not executed'.
I am able to run queries from the phpMyAdmin dashboard successfully. In the webpage, the rest api is working fine and returning a 'No match found' message implying that the functions are working, but the data set is empty. I do not know which direction to look to find why no records are being returned?
In the complete data functions:
    $error = array('error' => 'No match found');

    // fetch data into array
    $i = 0;
    while($row = $stmt->fetch()) {
        $data[$i] = $row;
        $i++;
    }

    // return data
    if($data) {
        $app->response->setStatus(200);
        $app->response()->headers->set('Content-Type', 'application/json');
        echo json_encode($data, JSON_PRETTY_PRINT);
    } else {
        $app->response->setStatus(200);
        $app->response()->headers->set('Content-Type', 'application/json');
        echo json_encode($error);
    }

I am new to PHP so any advice on how to trouble shoot, log, or otherwise trace the issue would be appreciated.

A: Ahhhh... I found it! The problem was not with the php, but with the sql. Apparently, sql statements are case insensitive on my local machine (mac), but case sensitive on Linux servers. In the DB the table name is Artists where in the code above I had artists.
So the correction is:
$sql = "SELECT * FROM artists";

Becomes:
$sql = "SELECT * FROM Artists";


text:
Q: When does the browser decide to wrap a flexbox container? In the following code, will the browser decide whether to wrap the #container element into new lines based on whether the initial sizes exceed the width of the cross axis or the main axis?

#container {
  display: flex;
  flex-wrap: wrap;
  width: 500px;
  height: 500px;
}

#container div {
  flex-basis: 200px;
}

A: For flex items, they will always depend on the main axis space to decide where to break into new line.
The main axis can be horizontal (default) or vertical, depend on flex-direction
Here is an example, items will break into new row when the total width of items in the current row exceeds 600px

#container {
  display: flex;
  flex-wrap: wrap;
  width: 600px;
  height: 500px;
}

#container div {
  flex-basis: 200px;
  background-color: red;
  border: 1px solid black;
  box-sizing: border-box;
  font-size: 50px;
}

1

2

3

4

5

6

7

If you change flex-direction to column, now the main axis becomes vertical, and flex-basis now defines the initial height of the items (instead of width).
And if the total height of items in the current column exceeds 600px, items will break into new column

#container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  width: 500px;
  height: 600px;
}

#container div {
  flex-basis: 200px;
  box-sizing: border-box;
  border: 1px solid black;
  background-color: red;
  font-size: 50px;
}

1

2

3

4

5

6

7


text:
Q: Designing a table with multiple column types and different foreign keys I have a table item in which different columns are filled depending on the template type of item that it is e.g.
|item_id|template_id|brand|model|heading|usp_1|usp_2|icon_1_asset_id|icon_2_asset_id|
|-------|-----------|-----|-----|-------|-----|-----|---------------|---------------|
| 1     | 1         | ABC | xyz |       | ddd |     | 1             | 2             |
| 2     | 1         | ABC | xyy |       | eee |     | 3             | 4             |
| 3     | 2         | BCD | ghj | opqrs |     |     | 2             |               |
| 4     | 3         | FGH | stu |       | jjj | kkk |               |               |

In reality, it has about 40 columns.  template_id has a foreign key to the template table, icon_1_asset_id and icon_2_asset_id both have foreign keys to the asset table.  The columns filled depend on the template_id, in this example:

*

*All items have a template_id, brand, model.

*template_id = 1 items have usp_1, icon_1_asset_id, icon_2_asset_id

*template_id = 2 items have heading, icon_1_asset_id

*template_id = 1 items have usp_1, usp_2
As you can see, there is a large amount of wasted space of cells that will never hold data.
I have considered altering the structure to:
Table item
|item_id|template_id|
|-------|-----------|
| 1     | 1         |
| 2     | 1         |
| 3     | 2         |
| 4     | 3         |

Table property_type
|property_type_id| description     |
|----------------|-----------------|
| 1              | brand           |
| 2              | model           |
| 3              | heading         |
| 4              | usp_1           |
| 5              | usp_2           |
| 6              | icon_1_asset_id |
| 7              | icon_2_asset_id |

Table template_property_type
|template_id|property_type_id|
|-----------|----------------|
| 1         | 1              |
| 1         | 2              |
| 1         | 4              |
| 1         | 6              |
| 1         | 7              |
| 2         | 1              |
| 2         | 2              |
| 2         | 3              |
| 2         | 6              |
| 3         | 1              |
| 3         | 2              |
| 3         | 4              |
| 3         | 5              |

Table item_property
|item_property_id|item_id|property_type_id| value |
|----------------|-------|----------------|-------|
| 1              | 1     | 1              | ABC   |
| 2              | 1     | 2              | xyz   |
| 3              | 1     | 4              | ddd   |
| 4              | 1     | 6              | 1     |
| 5              | 1     | 7              | 2     |
| 6              | 2     | 1              | ABC   |
| 7              | 2     | 2              | xyy   |
| 8              | 2     | 4              | eee   |
| 9              | 2     | 6              | 3     |
| 10             | 2     | 7              | 4     |
| 11             | 3     | 1              | BCD   |
| 12             | 3     | 2              | ghj   |
| 13             | 3     | 3              | opqrs |
| 14             | 3     | 6              | 2     |
| 15             | 4     | 1              | FGH   |
| 16             | 4     | 2              | stu   |
| 17             | 4     | 4              | jjj   |
| 18             | 4     | 5              | kkk   |

Although this gives more efficient storage and an amount of database-level control over which properties can be filled, you loose the foreign key constraint on the property value due to the fact that some properties are linking to another table and some are plain text.
Is there a way to put some database-level constraint on the value column - possibly by breaking it out onto another table, or re-working the structure?
Or is there a completely different way to approach this type of data?
I'm using SQL Server, although the fundamental problem is not tied to any specific relational database management system.

A: You can enforce the column nullability based on the template_id by using CHECK CONSTRAINTS, for example:
ALTER TABLE [item] ADD CONSTRAINT CK_Template_Columns
CHECK (
    (template_id = 1 AND usp_1 IS NOT NULL AND icon_1_asset_id IS NOT NULL AND icon_2_asset_id IS NOT NULL AND heading IS NULL AND usp_2 IS NULL)
    OR (template_id = 2 AND heading IS NOT NULL AND icon_1_asset_id IS NOT NULL AND usp_1 IS NULL AND usp_2 IS NULL AND icon_2_asset_id IS NULL)
    OR (template_id = 3 AND usp_1 IS NOT NULL AND usp_2 IS NOT NULL AND heading IS NULL AND icon_asset_1_id IS NULL AND icon_2_asset_id IS NULL)
)

This CHECK CONSTRAINT enforces the columns that cannot be NULL and those that must be NULL based on the chosen template_id. An attempt to fill an invalid column, or leave a valid column blank, for a given template_id would cause the INSERT/UPDATE to fail.
And if you're concerned regarding storage, within SQL Server you have the option of defining SPARSE columns to help reduce storage space for mostly NULL columns. You can also leverage Data Compression and Filtered Indexes to reduce overall space consumption.
For example, a filtered index for each template_id value would allow you to only index the columns that are not null for that template, thereby reducing the number of rows and columns stored in an index.


text:
Q: Error with downloading image as data url So, i was doing a link to download an image from a data url(a LARGE one):
something

However, whenever i try to click in that link i receive an error telling me some net problems.
I have make a fiddle test, but its LARGE(15mb of text) and it will take sometime to load:
https://jsfiddle.net/jjydp1ek/
As the jsfiddle is hard to load, i added a file in mediafire:
http://www.mediafire.com/download/p85y1g442ne9v6m/new++7.html
The test is an image with the same data url value as the link, the image is visible, however i see that the option to open image in a new tab on chrome isn't working.
I do it with canvas in ie 11 and is failing too
Questions:
It is ever possible to make it work with the download link as it is now?
Is there a limit size with the data url to download a file, which is?
How do i do to make the user able to download that image?
Also, ask questions here, or correct any error in the text you see if you think its not understandable.
Thanks.

A: I have a 70Mb broadband and a powerhouse of a PC and that JS fiddle won't even open.
I don't think it's feasible to have a 15MB encoded string, since that has to be downloaded onto the page each time on every visit. I would try the following:

*

*Optimise the image, you could incorporate gulp-imagemin if you have/want to have Gulp for a build system. I think there are alternatives for Grunt if you wanted to go that way.

*Store the file on the server and just place a link to the path, this is the preferred solution.

In response to your questions
The limit:

Length limitations
Although Mozilla supports data URIs of essentially
unlimited length, browsers are not required to support any particular
maximum length of data. For example, the Opera 11 browser limits data
URIs to around 65000 characters.

Source: data URIs - MDN
Downloading
The above suggestion on optimising the image as small as you can get without losing quality if that's a concern. Try it then. If not, it's not a problem to give the user a link to the image / display it on the page. The user can right click and save.
Note
By the time I finished writing this response JSFiddle timed out.


text:
Q: Java Error: java -v command throws errors I am running an Ubuntu 12.04.5 server and am trying to install Java.
Running java -v in console provides this error message:
*Unrecognized option: -v
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.*

A: Execute the command
java -version


text:
Q: How do I delete a branch without an error message if the branch does not exist? I would like to include a command to delete a local Git branch in a script, and I don't want any error message to be shown if the branch does not exist. At the same time, I also don't want a status code indicating a failure from the Git command.
Given the following example:
git branch -D foo

If the branch exists, it is deleted, and the return status of the command is 0, indicating success. If I run the same script again, the branch is no longer there, therefore the command fails, prints
error: branch 'foo' not found.

and the return status of the Git command is >0, indicating an error.
Is there a way to silence the command, so that it does not care whether the branch was there in the first place? Ideally, it would not print an error message and it also would not indicate a failure through a non-zero return status.
I know that I can work around these things using some scripting magic, but I would prefer a simple solution, since I have to do the same thing on Windows (.bat) and for Unix/Linux/Mac (.sh).
Did I miss an option, or am I out of luck?

A: Try this:
branch="${1:?foo}"

if git show-ref --verify --quiet "refs/heads/$branch"; then
echo "Branch exists."
.......

A:
If the branch exists, it is deleted, and the return status .. is 0, ... Is there a way to silence the command, so that it does not care whether the branch was there ... it would not print an error message and it also would not indicate a failure through a non-zero return status.

The following examples will suppress all output, and indicate the success or failure via the exit code:
Linux   $ git branch -D <branch> &>/dev/null
Windows $ git branch -D <branch> 1>nul 2>nul

If you intend to consciously ignore the exit code, simply don't check it, and proceed to the next command in your script.
Or, If you must exit with a zero code then
Linux   $ git branch -D <branch> &>/dev/null || true
Windows $ git branch -D <branch> 1>nul 2>nul || ver>nul

A: Use the core command, after the command runs that ref is gone, so it regards the result as successful:
git update-ref -d refs/heads/$branch

Stuff like this is one of the reasons for the "don't use convenience aka porcelain commands for scripting" rule that's so widely ignored.

A: For Windows powershell, the following command will delete all local branches except the current branch
git branch | %{ $_.Trim() } | ?{ $_ -notmatch '\*' } | %{ git branch -D $_ }


text:
Q: Minimize intro part in eclipse application I have created my own intro in eclipse application as follows:
public class CustomIntro extends IntroPart {
    public void createPartControl(Composite container) {
        //add intro, works perfectly fine
    }

    //override other essential methods
}

The above code works perfectly fine, now I want to minimize this intro programatically. Upon a click of button the intro should be minimized. Actually I want to launch a internal browser upon click of button, and the intro should be minimized and launched internal browser should be visible.
As suggested by @greg-449, I extended the IntroPart than implementing IIntropart. Thanks for that, but my issue still remains. Any help is appreciated.

A: As @greg-449 pointed, you should extends IntroPart abstract class as is explained in the documentation.

A: You can use setPartState().
Use this in your IntroPart:
this.getIntroSite().getPage().setPartState(this.getIntroSite().getPage().getActivePartReference(), IWorkbenchPage.STATE_MINIMIZED);


text:
Q: Sharing (sshfs) a folder with another Linux machine on the same home network via fstab? UBUNTU 20.04 First and foremost let me thank zx81roadkill for his excellent description of how to share a folder with another Linux machine on the same home network using sshfs. Everything has worked great for me except the last step "10. Enable reconnect after reboot" which involves modifying the fstab file.
While I can mount (and un-mount) the remote folder manually,
sudo sshfs vanmetter@192.168.2.4:/home/vanmetter /mnt/HP-2014-home -o allow_other,default_permissions -o identityfile=/home/vanmetter/.ssh/id_rsa

Mounting via the fstab file results in an error when I try to open the remote folder on my local machine.
vanmetter@192.168.2.4:/home/vanmetter/ /mnt/HP-2014-home fuse.sshfs default_permissions,user,delay_connect,reconnect,ServerAliveInterval=15,ServerAliveCountmax=3,allow_other,identityfile=/home/vanmetter/.ssh/id_rsa,idmap=user,uid=1000,gid=1000 0 0

I have even retyped the entire line to insure no 'special' characters were accidentally copied.
Clicking on the mount point for the remote folder results in a reproducible error as followings:
in Nautilus:
**Oops! Something went wrong.**
Unhandled error message: Error when getting information for file "mnt/HP-2014-home": Input/Output error

in Nemo:
Could not display "/mnt/HP-2014-home".
Error: Error when getting information for file "/mnt/HP-2014-home": Input/Output error
Please select another viewer and try again.
Finally, if the folder is un-mounted, then mounted manually as shown above, everything is working fine (i.e. remote folder opens and all content are accessible).
Any help would be greatly appreciated as I now have a 99% solution to my connectivity needs.
Thanks,
Richard
Here is some further diagnostic information:
fstab contains the line:
vanmetter@192.168.2.4:/home/vanmetter/ /mnt/HP-2014-home fuse.sshfs default_permissions,user,delay_connect,reconnect,ServerAliveInterval=15,ServerAliveCountmax=3,allow_other,identityfile=/home/vanmetter/.ssh/id_rsa,idmap=user,uid=1000,gid=1000 0 0
after boot (access fails with error):
vanmetter@dell-2018:/mnt$ ls -l
ls: cannot access 'HP-2014-home': Input/output error
total 0
d????????? ? ? ? ?            ? HP-2014-home
try manual sshfs mount (fails with error):
vanmetter@dell-2018:/mnt$ sudo sshfs vanmetter@192.168.2.4:/home/vanmetter /mnt/HP-2014-home -o allow_other,default_permissions -o identityfile=/home/vanmetter/.ssh/id_rsa
[sudo] password for vanmetter:
fuse: bad mount point `/mnt/HP-2014-home': Input/output error
manually un-mount (success):
vanmetter@dell-2018:/mnt$ sudo umount HP-2014-home
vanmetter@dell-2018:/mnt$ ls -l
total 4
drwxr-xr-x 2 root root 4096 Sep  6 06:16 HP-2014-home
manual sshfs mount (success)
vanmetter@dell-2018:/mnt$ sudo sshfs vanmetter@192.168.2.4:/home/vanmetter /mnt/HP-2014-home -o allow_other,default_permissions -o identityfile=/home/vanmetter/.ssh/id_rsa
vanmetter@192.168.2.4's password:
vanmetter@dell-2018:/mnt$ ls -l
total 4
drwxrwxrwx 1 vanmetter vanmetter 4096 Sep 10 07:38 HP-2014-home
remote mount "HP-2014-home" now opens successfully in nautilus and nemo.


text:
Q: JQuery acting asynchronous I have Jquery looping through my XML file:
 $(xml).find("category").each(function()
    {
        var title = $(this).find("title").text();
        var i = 0;
        console.log("j:" + j);
        if (j > 0) {
            fillNav("","",i,"final");
        }
        $(this).find('items > item').each(function() {
            var text = $(this).find("text").text();
            console.log("i:" + i);
            fillNav(title,text,i,"text");
            i++
        });

        j++;
    });

where it fills the div:
 function fillNav(title,text,i,final){
    console.log("i:" + i);

        if ((i == 0)&&(final != "final")){
            console.log("title:" + title + "div>

");
            $("#accordionSub").append("
"  + title + "

");
            //$("#output").append("

");
        }
        if (final != "final"){
            console.log("
");
            $("#accordionSub").append("
"  + text + "
");
        }
        if ((i == 0) && (final == "final")){
        console.log("final:" + "/ul>/p>/div>");
        $("#accordionSub").append("

");
        }
}

resulting html:

Accessories

Adaptors,  Bushings,   and Pressure Snubbers

Cables and Accessories   for pH Instruments

Why are the UL tags not surrounding the LI tags?
UPDATE:
    output += "
"  + title + "

";
        output += "

 " ;
        $(this).find('items > item').each(function() {
            var text = $(this).find("text").text();
            var slink = $(this).find("link").text();
            //console.log("i:" + i);
            output += "
"  + text + "
";
        });
        output += "

";

Produces:
<-div><-p><-/p><-ul><-li><-/li><-/ul><-p><-/p>
I have to get the P tags to surround the UL tags
UPDATE*
thanks to all that helped: just posting my final code to help someone else in the future:
$(xml).find("category").each(function()
    {

        var output += '
' +$(this).find("title").text() + '
' ;
        var div = '
';
        output += '
';

        $(this).find('items > item').each(function() {
            var text = $(this).find("text").text();
            var slink = $(this).find("link").text();

            output += "
"  + text + "
";
        });

        output += '
';

    });
    //console.log(output);

    var icons = {
  header: "ui-icon-circle-arrow-e",
  activeHeader: "ui-icon-circle-arrow-s"
};
$('
')
.attr('id','accordionSub')
.html(output)
.appendTo('#accordionSubB').delay(1).queue(function(){
    $( "#accordionSub" ).accordion({
                heightStyle: "content",
                collapsible: true,
                icons: icons
            });
});

A: I had similar problem before. It's better if you store all the generated HTML in a single variable than append. Example:
var output = '
';

for(var i = 0; i < 10; i++){
    output += '

';
}

output += '
';

$(elem).append(output);

Also this method will cost you much less CPU usage. In your solution you're always manipulating the DOM in every cicle. That's a really unefficient way.

A: Append and inner html are two different things - append takes a dom element and inserts it into the parent element..
You could do something like this...
var ul = $('
');
$('
').html("Some Text").appendTo(ul);
$('
').html("More Text").appendTo(ul);

and then when you're ready
$(some container).append(ul);


text:
Q: onNextStep is not a function, functional components I have a parent component with the state which is number, and I'm passing state to RegistrationForm component and setActiveForm to StepperComponent. In the stepper Component, there is a button on which click it should change state. But I'm getting 'onNextStep is not a function'
Parent component:

import React, { useState } from 'react'
import { Box, Divider, Flex } from '@chakra-ui/react'
import Logo from 'components/navigation/Logo'
import Footer from 'components/footer/Footer'
import RegistrationForm from 'components/forms/RegistrationForm'
import StepperComponent from 'components/stepper/StepperComponent'
import Section from 'components/section/Section'
import { SubTitle, Title } from 'components/UI'
import SuccessRegistration from 'components/forms/SuccessRegistration'

const RegisterPage = () => {
    const [activeForm, setActiveForm] = useState<number>(0)
    return (
        <>
            <Box maxWidth="1450px" px={['16px', '43px', '83px']} mx="auto">
                <Logo />
            </Box>
            <Section pt="23px">
                <Box maxWidth="580px" ml={['0', '0', '200px']} mb="25px">
                    <Title value="React Week 2021- Event Registraton Form" mb="8px" />
                    <SubTitle
                        value="React Week talks, classes and workshops will feature advanced topics aimed for junior and medior software developers, and consultants."
                        fontSize="16px"
                    />
                </Box>
                <Divider d={['none', 'none', 'none', 'block', 'block']} />
                <Flex flexDirection={['column', 'column', 'row', 'row']}>
                    <StepperComponent onNextStep={setActiveForm} />
                    <Box>
                        <Divider orientation="vertical" d={['none', 'none', 'none', 'block', 'block']} />
                    </Box>

                    <RegistrationForm activeForm={activeForm} />
                </Flex>
            </Section>
            <Footer />
        </>
    )
}

export default RegisterPage
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

RegistrationForm component:

import React from 'react'
import { Box } from '@chakra-ui/react'
import PersonalInfoForm from './PersonalInfoForm'
import TicketOptionForm from './TicketOptionForm'
import AdditionalInfoForm from './AdditionalInfoForm'
import FormContainer from './FormContainer'
import SuccessRegistration from './SuccessRegistration'

interface Props {
    activeForm: number
}

const RegistrationForm = ({ activeForm }: Props) => {
    const forms = [<PersonalInfoForm />, <TicketOptionForm />, <AdditionalInfoForm />]
    return <FormContainer>{forms[activeForm]}</FormContainer>
}

export default RegistrationForm
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Stepper component:

import React, { useEffect } from 'react'
import { Box, Button } from '@chakra-ui/react'
import { Step, Steps, useSteps } from 'chakra-ui-steps'

interface Props {
    onNextStep: React.Dispatch<React.SetStateAction<number>>
}

const steps = [
    {
        label: 'Step 1',
        description: 'Personal Info',
    },
    {
        label: 'Step 2',
        description: 'Ticket Options',
    },
    {
        label: 'Step 3',
        description: 'Additional Info',
    },
]

const StepperComponent = ({ onNextStep }: Props) => {
    const { nextStep, prevStep, reset, activeStep } = useSteps({
        initialStep: 0,
    })

    useEffect(() => {
        onNextStep(activeStep)
    }, [activeStep])

    return (
        <Box w={['100%', '200px']} mt={['12px', '43px']}>
            <Steps activeStep={activeStep} orientation="vertical" colorScheme="blue" textAlign="center">
                {steps.map(({ label, description }) => (
                    <Step label={label} description={description} key={label}></Step>
                ))}
            </Steps>
            <Button onClick={nextStep}>NextStep</Button>
        </Box>
    )
}

export default StepperComponent
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


text:
Q: javascript giving weird output I have this weird problem with javascript. I wrote a code that checks if the text input from the user is good, and after a while the message saying if it is good or not disappears, any suggestions?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

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

    <title></title>

    <form id="form1" runat="server" onsubmit="return validate()" action="Default2.aspx">

    enter you first name
    <input type="text" id="firstName"  />

     <input type="submit" value="send"/>

    </form>

A: Well,
Please remember as you have mentioned action in the form, the control will transferred to the page mentioned in it when "TRUE" is encountered.
If you still want to see "good", you can remove action.
So to get your code working, you can either change it as below,

OR,
You can use jQuery Validation, which is way better and less time consuming,
jQuery Form Validation example
jQuery Validate Options

A: The submit action refreshes the page that's why you only see that for a moment.
You have to work with async form if you want to stay on that page.
Read this
http://blog.teamtreehouse.com/create-ajax-contact-form
and This https://learn.jquery.com/ajax/ajax-and-forms/


text:
Q: Show that $T(t)$ and $N(t)$ are Orthogonal If $r(t)$ is the smooth parametrization of a curve $C$ in 3-space, then the unit tangent and unit normal vectors are denoted as $T$ and $N$, and are given by:
$$T(t)=\frac{r'(t)}{||r'(t)||},N(t)=\frac{T'(t)}{||T'(t)||}$$
How do I show that $T(t)$ and $N(t)$ are orthogonal for all $t$ at which they are defined. I cannot assume anything about the binormal vector $B$, so I want to know how to do this without assuming so.

A: $$ T(t)\cdot N(t)={1\over\|T'(t)\|}T(t)\cdot T'(t)={1\over2\|T'(t)\|}{d\over dt}\left[ T(t)\cdot T(t)\right]=0$$
Because $T(t)\cdot T(t)={r'(t)\cdot r'(t)\over \|r'(t)\|^2}\equiv 1$


text:
Q: how to get style cop to ignore a specific instance of a violation I have a few instances in my code where Style cop gives out that:
"SA1119: The line contains unnecessary parenthesis."
Now I totally agree with this if I have a line of code that says:
int someValue = (((12 + 3) + 5));

However when I have something more complicated like:
textXpos = ((((float)this.Width - imageoffset) - textsize.Width) / 2);

I understand that I can rewrite this like:
textXpos = (((float)this.Width - imageoffset - textsize.Width) / 2);

And It will evaluate out to the same values, but I find the first one easier to read.  Is there a way to tell styecop to ignore this instance of the error?
Or do I need to work around this by assigning some of the equation to temp variables?
I don't want to wrap this code in an autogenerated region as I do want style cop to evaluate this section of code.
Thanks

Based on the suggestion by ken2k I tried the following:
using System.Diagnostics.CodeAnalysis;

.
.
.
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1119:StatementMustNotUseUnnecessaryParenthesis", Justification = "Better for readability.")]
    public int Testmethod()
    {
        int returnValue = (((5 - 5) - 5) / 2);
        return returnValue;
    }

But this doesn't seem to have any effect?  Am I missing something?

A: You can add the following statement before the header of your method:
[SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1119:StatementMustNotUseUnnecessaryParenthesis", Justification = "Better for readability.")]

But warnings SA1119 will be ignored for the whole method.
EDIT: at least remove the first and last parenthesis:
textXpos = (((float)this.Width - imageoffset) - textsize.Width) / 2;


text:
Q: How can I do a cumulative sum of wins, losses and draws here? I have written the below code for a rock, paper, scissors game as my first bit of independent coding. I've tried every possible solution I can possibly think of to get a cumulative running total of wins, losses and draws, however every time it only shows me the most recent result - i.e. 1 win 0 losses 0 draws even on the 50th game if the most recent game was a win.
Can anybody suggest a way to solve this?
# Rock, Paper, Scissors!

import random
import time

print('Welcome to Rock, Paper, Scissors, a Python recreation of the classic game.')
print('The computer will randomly choose a sign at the start of the run for you to try to beat.')
print('Choose carefully...')

def fullgame():
    compguess = random.randint(1, 3)
    if compguess == 1:
        compsign = 'rock'
    elif compguess == 2:
        compsign = 'paper'
    else:
        compsign = 'scissors'
    playsign = input('Would you like to throw rock, paper or scissors? ')
    while playsign != 'rock' and playsign != 'paper' and playsign != 'scissors':
        print('You need to pick a valid sign!')
        playsign = input('Would you like to throw rock, paper or scissors? ')

    def numberallocator(rps):
        if rps == 'rock':
            return 1
        elif rps == 'paper':
            return 2
        elif rps == 'scissors':
            return 3
        else:
            print('That\'s not a valid sign!')
    playguess = numberallocator(playsign)
    numberallocator(playsign)

    def game(cg, pg):
        print('The computer is deciding...')
        time.sleep(1)
        print('The computer throws ' + compsign + ' and you throw ' + playsign + '...')
        time.sleep(1)
        if cg == pg:
            print('It\'s a draw! You both picked ' + compsign)
            return 'd'
        else:
            if cg == 1:
                if pg == 2:
                    print('You win! Paper beats rock!')
                    return 'w'
                elif pg == 3:
                    print('You lose! Rock beats scissors!')
                    return 'l'
            elif cg == 2:
                if pg == 1:
                    print('You lose! Paper beats rock!')
                    return 'l'
                elif pg == 3:
                    print('You win! Scissors beats paper!')
                    return 'w'
            else:
                if pg == 1:
                    print('You win! Scissors beats rock!')
                    return 'w'
                elif pg == 2:
                    print('You lose! Scissors beats paper!')
                    return 'l'
    game(compguess, playguess)

playagain = 'y'

gamesplayed = 0

while playagain == 'y' or playagain == 'Y':
    fullgame()
    gamesplayed = gamesplayed + 1
    print('You have played ' + str(gamesplayed) + ' games.')
    playagain = input('Play again? y/n: ')
    while playagain != 'y' and playagain != 'n':
        print('You must pick y or n!')
        playagain = input('Play again? y/n: ')

print('Thank you for playing rock, paper, scissors! This has been coded in Python by Ethan Lang!')

Thank you!

A: If you want to save a variable outside of all the functions, and modify it inside a function, you can use the Python global keyword. Otherwise, when you try to modify the variable inside a function, even if you defined it already outside the function, Python will assume you meant to create a brand-new variable, with its scope only function-level, and the variable with global scope won't be modified. To specify that you want to modify the global variable, you can use
global <variable_name>

as the first line in your function. That way, Python knows that any references to variable_name inside your function refer to the "global" variable (outside the function).
Disclaimer: using global variables is generally regarded as a Bad Idea. It makes it more difficult to fix issues with your code, since any code could possibly be modifying your global variables, which makes it harder to keep track of where it could be going wrong. For more info, see Why are global variables evil?
Wherever possible, you should try to find another solution. In this case, the solution in @JNevill's comment is probably a better idea.


text:
Q: JRuby won't install gems in correct path I have issues trying to install gems listed in my gemfile. I had a newer version of JRuby jruby-9.2.19.0 but ended up uninstalling this version and downloading the jruby-9.1.17.0 version and set it as the default interpreter.
After checking the environment/path settings with gem env I can see the following info:
RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.14.1
  - RUBY VERSION: 2.3.3 (2018-04-20 patchlevel 0) [java]
  - INSTALLATION DIRECTORY: C:/jruby-9.1.17.0/lib/ruby/gems/shared
  - USER INSTALLATION DIRECTORY: C:/Users/(my_name)/.gem/jruby/2.3.0
  - RUBY EXECUTABLE: C:/jruby-9.1.17.0/bin/jruby.exe
  - EXECUTABLE DIRECTORY: C:/jruby-9.1.17.0/bin
  - SPEC CACHE DIRECTORY: C:/Users/(my_name)/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: C:/jruby-9.1.17.0/etc

So the installation directory is correct:

C:/jruby-9.1.17.0/lib/ruby/gems/shared

as expected.
BUT when I run:
bundle install the command ends up creating a new directory with the name: jruby-9.2.19.0 and installs the gems into the path: C:\jruby-9.2.19.0\lib\ruby\gems\shared\gems\jruby\2.3.0
I tried Invalidating Caches within RubyMine itself and it didn't help.
What could be causing this issue where JRuby/RubyMine wont install in the correct directory even though the gem environment has the correct path?

A: After trying out for days, I used the bundle config documentation which says to use bundle config list to view the set configs.
Through this, I found that the bundler had set a path for where the gems should be installed.
After deleting the config, everything seems to work normally as it should!


text:
Q: How do I programmatically resize an eclipse ViewPart? I have a ViewPart that is created using a regular plugin extension point with a ratio that defines it's height.  At a later point I have a block of code that is adding some more things to the Canvas for the ViewPart.  The new items are not shown unless the user drags the edge of the ViewPart to make it bigger.  Is there a way to programmatically tell the ViewPart to resize itself either to match it's current contents or to a value I specify?

A: You can make it work, but only for views that are in their own view stack. See the JavaDoc for IViewPart:
As of 3.4, views may optionally adapt to ISizeProvider if they have a
preferred size. The default presentation will make a best effort to
allocate the preferred size to a view if it is the only part in a stack.
If there is more than one part in the stack, the constraints will be
disabled for that stack. The size constraints are adjusted for the size
of the tab and border trim. Note that this is considered to be a hint to
the presentation, and not all presentations may honor size constraints.

To see this in action, check out the UI test project as described here and open the view called "Layout Constraints Test".

A: "The short answer is that you can't always control the size and position of your view."
More at the Eclipse FAQ.

A: If I recall correctly, there is no way to ask a ViewPart to resize itself. We ran into this problem before (in RCP 3.4) and I believe we had to work around it.
I think what we would up doing was adding all possible controls first, then hiding them. However, we were doing this with a wizard, so all we did was show the first page and the controls weren't incredibly dynamic. For instance, we knew the maximum number of controls and nothing was user-modifiable.


text:
Q: Why doesn't boost::hash_value support boost::unordered_set by default? It seems intuitive that one should be able to use sets of sets, and indeed std::set is designed to support such use by default (since lexicographical ordering is implemented by default.) Similarly, it seems reasonable to expect the same feature of boost::unordered_set. Is there a good reason why boost doesn't implement a generalized hash function for boost::unordered_set by default, something like:
// DEFINE A HASH FUNCTION FOR A HASH-SET THAT COMBINES THE HASH VALUES
// OF THE ELEMENTS OF THAT SET
namespace boost {
    template<typename T>
    size_t hash_value(const boost::unordered_set<T> & set) {
        typename boost::unordered_set<T>::const_iterator it, itend;
        size_t seed = 0;
        for ( it = set.begin(), itend = set.end(); it != itend; it++ ){
            boost::hash_combine(seed,boost::hash_value(*it));
        }
        return seed;
    }
}

A: Generally you want hashes to be fast, ideally constant time.
On a string, one thing you can do is get the length and then only sample X times over its length (which, assuming non-pathological input, will be reasonably good at avoiding collisions).
unordered_set lacks a get_nth, which would allow a similar strategy to keep hashing time down to O(1).  Alternatively, unordered_set could keep an xor of its content's hash and use it as its own hash (not hash_combine, as that is order-dependent, and it is hard to remove the 3rd element from the combined hash when there are 100 of them in O(1) time).
Lacking a good O(1) implementation, exposing hash_value by default might seem overly encouraging to the builder of unordered_set<unordered_set<foo>>, when in reality they should be writing unordered_set< my_unordered_set_wrapper<foo> >, where unordered_set_wrapper does the above "xor of contents hashs" to produce O(1) hash_value.  Either that, or extend unordered_set.
As to why boost actually did not include it, you'd have to ask everyone who ever added stuff to boost collectively.  They do not seem to be present.


text:
Q: How to add a back button on a Webview in a fragment I've seen a lot of examples for back button in webview. However, I have a tab layout using fragments and viewpager. I have seen an example that has an activity, but has an inner fragment class and the back button works. However, when I tried that, I got a lot of errors in my TabsPagerAdapter. If anyone has any idea how to do the code for the back button please tell me.
TabFour
public class TabFour extends Fragment {

static WebView webView;
String myBlogAddr = "http://192.168.1.75/Treasuria-v2/";
String myUrl;
Button map;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.activity_tab_four, container, false);

    webView= (WebView)rootView.findViewById(R.id.webView);

    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new MyWebViewClient());
    String title = "Quezon City Guide";
    String desc = "Your Number One City Guide!";
    String image = "http://s22.postimg.org/5t4qidqpt/launcher114x114.png";

    myBlogAddr ="http://www.facebook.com/sharer.php?m2w&s=100&p[title]="+title+"&p[summary]="+desc+"&p[url]=http://www.sample.com&p[images][0]="+image;
    if(myUrl == null){
        myUrl = myBlogAddr;
    }
    webView.loadUrl(myUrl);
    Log.i("URL", myBlogAddr);

    webView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().getActionBar().setSelectedNavigationItem(2);
        }
    });

    map = (Button) rootView.findViewById(R.id.buttonMap);

    map.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            getActivity().getActionBar().setSelectedNavigationItem(2);
        }
    });

    return rootView;

}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        myUrl = url;
        view.loadUrl(url);
        return true;
    }
}

public void onBackPressed() {
    getActivity().getActionBar().setSelectedNavigationItem(2);
}

public void OnCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    getActivity().getActionBar().setSelectedNavigationItem(1);
    map = (Button) rootView.findViewById(R.id.buttonMap);

    map.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            getActivity().getActionBar().setSelectedNavigationItem(2);
        }
    });
}

}

MainActivity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {

public static FragmentManager fragmentManager;
public ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private Integer[] Icons = {R.drawable.homeg,R.drawable.placesg, R.drawable.mapg, R.drawable.reviewg,R.drawable.fbg};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fragmentManager = getSupportFragmentManager();
    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Adding Tabs
    for (Integer tab_icon : Icons) {
        actionBar.addTab(actionBar.newTab().setIcon(tab_icon)
                .setTabListener(this));

    }

    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.synergy88studios.quezoncityguide",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

}


text:
Q: How to extract all footnotes from a MS Word file? Is there a generic (Macro, XML Parser, ...) way to extract all footnotes in a MS Word file and also keep the corresponding number from the original text?

A: You might use Elod Pal Czirmaz's macro as a starting point.  I suspect that footnotes don't carry their numbers with them.  When the document is rendered, the numbers are just assigned in order.


text:
Q: Looping through API XML data is not being added to the array correctly Here is the XML. I am looking for the siteid.
<result created="2018-10-13T13:11:18-05:00" host="redacted" status="OK">
<items>
<site>
<siteid>399700</siteid>
<name>
<![CDATA[ Warehouse ]]>
</name>
<connection_ok>1</connection_ok>
</site>
<site>
<siteid>547401</siteid>
<name>
<![CDATA[ Monterey Park ]]>
</name>
<connection_ok>1</connection_ok>
</site>
</items>
</result>

To obtain the data I am looking for, I first need to iterate through the XML for a client id, and then I can use the client id to find the site id for each client. Some clients have multiple sites.
While the clients are obtained correctly the sites are, for the lack of a better term, compressed.
Results:

ClientID: 12345
SiteID: 9876543210

The Site ID should be two individual numbers: 98765 43210
Here are the two functions I am working with:
$ClientsIDs = @()
$SiteIDs = @()

function Get-Clients() {
    $clientdata = Invoke-RestMethod -Uri ($baseurl + $lc)
    $clientid = $clientdata.result.items.client.clientid
    $Script:ClientsIDs += $clientid
    Write-Output("Client ID: " + $ClientsIDs)
}

function Get-Sites() {
    foreach ($id in $Global:ClientsIDs) {
        $sitedata = Invoke-RestMethod -Uri ($baseurl + $ls + $id)
        $siteid = $sitedata.result.items.site.siteid
        $SiteIDs += $siteid
    }
    Write-Output("Site ID: " + $SiteIDs)
}

Get-Clients
Get-Sites

(Only the URLs are not shown. The Write-Outputs are only for my benefit to make sure the data is being collected correctly. They will eventually be removed.)
How can I get the $sitedid to properly be saved in the array?

A: tl;dr
I suggest refactoring your code, which avoids your problem, and is both more efficient and provides better encapsulation:
function Get-Sites() {
    # Note: Also consider passing the parent-scope
    #       $ClientsIDs, $baseurl, $ls variables as *parameters* instead.
    foreach ($id in $ClientsIDs){
        $sitedata = Invoke-RestMethod -Uri ($baseurl + $ls + $id)
        # Implicitly output each site ID, which by
        # virtue of being inside a foreach loop outputs
        # all of them as an array.
        $sitedata.result.items.site.siteid
    }
}

# If you wanted to interpret the IDs as *numbers*, you
# could use type [int[]], for instance
[array] $SiteIDs = Get-Sites

As for what you tried:
By assigning to $SiteIDs without scope modifier script ($script:SiteIDs), you're mistakenly creating a local $SiteIDs variable inside your Get-Sites function.
Given that scopes see - but cannot directly assign to - variables from parent scopes, the local copy of $SiteIDs that is being created by the assignment inherits the type (and value) of a variable of the same name from a parent scope (see this answer to learn more about scoping in PowerShell).
If $SiteIDs were truly an array in your script scope, your local copy would also create an array - but that still wouldn't modify the original array in the script scope.
The fact that $SiteIDs in your case ended up containing the string concatenation of your site IDs suggests that your actual code either does not create a $SiteIDs variable in the script scope, or it is string-typed there, not an array (@()), because applying += with a string as the RHS to a variable that is [string]-typed or didn't previously exist performs simple string concatenation (appends the RHS directly to the existing value, which defaults to the empty string, if the variable didn't exist).
The immediate fix would be:

*

*Be sure that $SiteIDs = @() is truly defined in the script scope, that is, as an array.

*Change $SiteIDs += $siteid to $script:SiteIDs += $siteid so as to modify the script-scope variable directly, as intended.
That said, it's generally better to avoid referencing variables across scope boundaries - use parameters and local variables for better encapsulation, as demonstrated at the top.

A: [array]$SiteIDs += $siteid

# or

function Get-Sites() {
    $SiteIDs=@()
    foreach ($id in $Global:ClientsIDs){
        ...
        $SiteIDs += $siteid

# or; for better performance

function Get-Sites() {
    $SiteIDs=New-Object System.Collections.ArrayList
    foreach ($id in $Global:ClientsIDs){
        ...
        $SiteIDs.add($siteid)


text:
Q: Although 8086 is a 16 bit processor, yet it deals with 8 bit memory. Why? Is it because of segmentation? If yes, then how? I don't see any problem using any 16-bit memory.

A: When the 8088/86 came out, 8 bit memories were the norm and affordable.  To have a 16 bit bus you needed two parts, so it cost you more in some way, half sized parts but two of them or same size parts and two of them would be twice the cost.  So the design allows for the 8088 to use 8 bit parts and do two bus transfers or the 8086 and is capable of one transfer.
External and internal are not related.  Many/most of the instructions from the 8086 are present today where the busses are much wider.  And from edge of the processor core to the now dram (then sram) goes through a number of busses and transfer size changes, etc.   The dram can be implemented using x8, x16, x32 parts.  Typically 72 bits wide on a full sized motherboard, sometimes 64, so if you have say 8 or 9 parts on one side of the dimm then they are 8 bit wide parts, if both sides populated with 8 or 9 still 8 bit wide parts, but two ranks.   4 or 5 parts on a side then x16, etc.   Because of the nature of the number of busses, the external geometry then as now doesnt matter so long as it confirms to the bus interface that the memory is connected to.  It doesnt define what the internals are in any way shape or form.
As new DDR tech comes out, DDR2, DDR3, DDR4, etc. you often find them starting with x8 parts being the most affordable, then x16 not long after and so on.  density vs yield.
now phone memory lpddr4, etc those busses are like 16 bits wide and you just do more transfers per cache line than you would with a 64/72 bit wide bus.   same instruction set inside, "byte addressable"
Kinda similar but the same house you live in could be a on a one way single lane road, a two way road, two way with a median, four lane, four lane with a median, could be strictly next to a big parking lot and not on a road, etc.  Does not in any way affect the sheets on your bed or use of towels in the bathroom.  The two things are not related, the overall system design is such that it tries to get affordable memory in quantity that is not horribly slow for the processor in question.

A: The 8086 had a dual memory structure to allow for 16-bit rams or 8-bit rams. (The 8088 only had an 8-bit data bus and could only use 8-bit rams) If the 16-bit rams were used, it was divided up into two banks of 8 bits. 16-bits allowed for newer rams, 8-bits allowed the architecture to be somewhat compatible with other chips and older rams.

Source: www.sbcecarni.org/sbadmin/admin/downloading/uploads/57887-8086-architecture.pdf

A: Many processors treat memory as byte-addressable, even if the physical data bus is much wider. This is because programmers find it useful to be able to manipulate data in 8-bit chunks.
This means that 16-bit memory attached to an 8086 needs to have the ability to write to only one byte at a time, controlled by the BHE and BLE signals. Newer members of the family have similar control signals.