text:
Q: ArrayList returned is of size 0 I have an arraylist in my adapter class. I add some items to it in OnLongClick() method . When I print its size using Log inside OnLongClick() method it prints size 1 on adding one item but if I print it inside another method getList() it prints size 0 on adding one item.
Adapter :
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private ArrayList<String> mData;
    private ArrayList<String> mData2;
    private LayoutInflater mInflater;
    private int selected_position ;
    private ItemClickListener mClickListener;
    private ArrayList<String> mSelected = new ArrayList<>();
    ArrayList<Uri> files = new ArrayList<>();
    private static final String TAG = "com.example.dell_1.myapp3.InternalMemory";
    private Context context;

    // data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, ArrayList<String> data, ArrayList<String> data2) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        this.mData2 = data2;
        this.context = context;
    }

    @Override
        public boolean onLongClick(View view) {  //this is the method asked by user902383
            if (mClickListener != null) mClickListener.onLongClick(view, getAdapterPosition());
            selected_position = getAdapterPosition();
            if (mSelected.contains(Integer.toString(selected_position))) {
                mSelected.remove(Integer.toString(selected_position));
                itemView.setBackgroundColor(Color.TRANSPARENT);// remove item from list;
                // update view (v) state here
                // eg: remove highlight
            } else {
                mSelected.add(Integer.toString(selected_position));
                itemView.setBackgroundColor(Color.LTGRAY);
                // add item to list
                // update view (v) state here
                // eg: add highlight
            }
            Log.v(TAG, Integer.toString(mSelected.size()) + " this is size");  //this returns size 1
            return  true;
        }
    }

   protected  ArrayList<String>  getList(){
            Log.v(TAG,Integer.toString(mSelected.size()) + "  final size"); //this returns size 0
            return mSelected;

        }

LOG :
02-16 16:00:52.129 16797-16797/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 0  final size
02-16 16:00:52.130 16797-16797/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 1 this is size

Also, many people are saying I am removing the item after adding it, but selected_position = getAdapterPosition(); which means its value is different onLongClicking different items . I wrote this method to add items on selection and remove on deselection , so I am removing an item already added when I deselect it(Long click again the already selected item).

A: This is because you're removing the item from the list each item you're doing onLongClick():
@Override
public boolean onLongClick(View view) {

  if (mSelected.contains(Integer.toString(selected_position))) {
     mSelected.remove(Integer.toString(selected_position));
     ...
  } else {
     ...
  }
  ...
}

Instead of removing the item from the list, you can make the item view gone with:
itemView.setVisibility(View.GONE);
itemView.setLayoutParams(new RecyclerView.LayoutParams(0, 0));

Read more for the set view gone at https://stackoverflow.com/a/46342024/4758255


text:
Q: Corda Azure Single Ledger Resource - No Cordapp in the web server issue I am new to Corda. I am trying to follow  https://docs.corda.net/releases/release-V2.0/azure-vm.html?highlight=azure to create corda single ledger setup in Azure.
As mentioned in the link, I have copied the .jar file to /opt/corda/plugins
 folder. But still  I am not able to view the Yo cordapp application. I am getting "No installed custom CorDapps." message.
corda runtime version is 2.0
Any suggestion on how to resolve this issue.

A: I did the same. Copied cordapp jar file to /opt/corda/plugins and restarted corda and corda-webserver.
[INFO ] 2019-08-11T14:35:36,768Z [main] internal.Node.registerWithNetworkMapIfConfigured - Node successfully loaded network map data from the database.
[INFO ] 2019-08-11T14:35:36,778Z [main] messaging.NodeMessagingClient.invoke - Network map is complete, so removing filter from P2P consumer.
[INFO ] 2019-08-11T14:35:36,920Z [main] BasicInfo.printBasicNodeInfo - Providing network services              :
[INFO ] 2019-08-11T14:35:36,925Z [main] BasicInfo.printBasicNodeInfo - Loaded CorDapps                         : yo-4, corda-finance-1.0.0, corda-core-1.0.0
Application seems to have loaded.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy textbox value to another - ASP.NET MVC Razor I have the following form within an ASP.NET MVC 5 application
@model ProjectOasis.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

@ViewBag.Title.

@using (Html.BeginForm("Admin", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

Create a new account.

    @Html.ValidationSummary("", new { @class = "text-danger" })

        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label"})

            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label"})

            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })

    //more form stuff

            <input type="submit" class="btn btn-default" value="Create" />

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

How do I make it so that whenever a value is entered into the m.Email textbox that the value is immediately copied into the m.UserName textbox? (I will be making the UserName textbox un-editable after I have this working).
Thanks.

A: So if you want to just display the username, here is an example (vanilla js), something like:

document.getElementById("txt2").onkeyup = function() {
  document.getElementById("txt1").value = this.value;
};
<input type="text" id="txt1" disabled />
<input type="text" id="txt2" />

or here is the jquery version:

$("#txt2").on("keyup", function() {
  $("#txt1").val($(this).val());
});

<input type="text" id="txt1" disabled />
<input type="text" id="txt2" />

I hope this helps.

A: Use javascript. Probably you have already included jQuery in your site scripts. So, all you have to do is to add following script:
$(function(){
    $("#Email").change(function(){
        $("#UserName").val($(this).val());
    });
})

Please ensure about letter casing since I am not sure if Razor camelifies names or not - just preview HTML source in your browser and check the field names spelling.
Here is some working sample for you

A: Option 1
 $("#Email").change(function(){
        $("#UserName").val($(this).val());
 });

Option 2
 $("#Email").focusout(function(){
        $("#UserName").val($(this).val());
 });

and to enforce to use email as username, have this in your username textbox:
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @disabled = "disabled" }


text:
Q: Spring-Data + QueryDSL + JDBC: how to map the query results to the domain objects? I am considering to use Spring-Data + QueryDSL + JDBC to replace (or enhance) the currently used MyBatis.
My reasons are:

*

*Compile-time check of column names

*Compile-time check of SQL tatements and auto-completion from IDE

*Ability to write unit tests on Java Collections against the same code that will work against the actual DB, which is much simpler and faster than pre-populating a DB

*It is more concise than MyBatis – no need for a separate XxxMapper.java and XxxMapper.xml under the DAO layer

Yet I see the following problems:

*

*There is no infrastructure for mapping the query results to domain objects. QueryDSL's QBean and MappingProjection, Spring's BeanPropertyRowMapper and Spring-Data's OneToManyResultSetExtractor seem to be too low level, see below.

*No out of the box session/transaction-level cache which comes for free in MyBatis

*No out of the box SQL statement and result logging which comes for free in MyBatis

Since I am asking a single question let's concentrate on the mapping which I consider the most important problem.
So my question is:
Is there any convenient solution to map the QueryDSL's SQLQuery results to the domain object, similar to what MyBatis or JPA offer? That is, the mapping based on some simple configuration, be it XML, annotations, or simple Java?
In particular, I am interested in the following:

*

*Mapping a column to a custom type, e.g. a String column to an EmailAddress Java object

*Mapping a group of columns to an embedded object, such as e.g. grouping {first_name, last_name} into a FullName Java object

*Supporting one-to-many relationship, such as being able to extract a Customer object(s) containing a list of Addresses.

To summarize, I need an easy way to obtain one or many objects of the following 'Customer' class from the following SQL query:
class Customer {
    EmailAddress emailAddress;
    FullName fullName;
    Set<Address> addresses;
    Set<Comment> selfDescription;
}
class EmailAddress {
    private String address;
    EmailAddress(String address) {this.address = address; }
}
class FullName {
    String firstName, lastName;
}
class Address {
    String street, town, country;
}
class Comment {
    LocalDateTime timeStamp;
    String content;
}

Query:
query.from(qCustomer).
    leftJoin(qCustomer._addressCustomerRef, qAddress)).
    leftJoin(qCustomer._commentCustomerRed).
    getResults(
       qCustomer.email_address, qCustomer.first_name, qCustomer.last_name,
       qAddress.street, qAddress.town, qAddress.country,
       qComment.creation_time_stamp, qComment.content);

The ideal solution for me would be to reuse the MyBatis mapping infrastructure.
Another mapping solution or a custom one is also acceptable.
Note:
I could also accept "negative" answers if you show an alternative that:

*

*Possesses an ease of use and transparency comparable to that of MyBatis - you always know which SQL is executed by simply inspecting the code

*Allows full control over the executed SQL code, in particular, allows to easily write three DAO methods for retrieving 'Customer': without 'addresses' and 'selfDescription' information, just with 'addresses', and with all the fields

*Allows compile-time check of your SQL code

*Does not require hand-coding of mapping of every single domain class from SQL.

The alternative should work well on the example above.
Solutions already considered:

*

*MyBatis 'Builder' class (http://mybatis.github.io/mybatis-3/statement-builders.html): not enough, since the column and table names are still Strings, so it violates requirement (3)

*Spring-data + JPA + QueryDSL: might be an option if you show how the requirements (1) and (2) can be satisfied and if no simpler solution will be provided

A: Lukas Eder gave an excellent answer to a similar question here: Is it possible to combine MyBatis and QueryDSL/jOOQ?
His answer to the mapping question is to use either Java 8 functional style capabilities or a dedicated solution such as modelmapper.
He also mentioned Spring JCache support as a caching solution and this solution to the logging.


text:
Q: how to link flex and bison files output together in GCC -> C I've been learning flex recently (not adobe flex), and I've been using the flex output file with success (just compiling the lex file generated and that's it).
Now I've come across bison, and I've read that bison uses the lex file to get the tokens from the input.
But now I have a problem: I am sitting in front of gcc and I have no idea of how I link the flex file (lex one) and the bison one together.
My question is, how do I link them together in gcc?

A: You just compile both c programs together. Yes, the lex part could generate a .h file, but you only have to care about C files on compilation:
lex example4.l
yacc -d example4.y
gcc lex.yy.c y.tab.c -o example4

You can learn more about lex & yacc, in (for example) here:
http://westes.github.io/flex/manual/
http://www.gnu.org/software/bison/manual/


text:
Q: Chapter content disappears beyond page-layout For some reason my "Languages" chapter is not appearing properly: it's as if parts of it were not respecting my page layout (see A on the screen-capture).
Also, and it's probably related, there's now a blank page right after "Chapter 1" when "chapter 2" should instead appear there  (see B on the screen-capture).
Any help would be appreciated.
Thank you.

% PREAMBLE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[a4paper,oneside,centered]{book}
\special{papersize=210mm,297mm}
\usepackage[top=3cm, bottom=3.2cm, left=2.5cm, right=2.5cm]{geometry}

\usepackage[english]{babel}
\usepackage{newpxtext} % Font for document instead of obsolete Palatino
\usepackage{tocloft} % Customization of TOC LOF LOT
\usepackage[table,xcdraw]{xcolor} % For shading in tables
\usepackage{pdfcolmk}
\usepackage{multirow}
\usepackage{textcomp}
\usepackage{ltablex}
\usepackage{nicefrac} % to write fractions
\usepackage{attrib} % For source of quotations
\usepackage{lettrine} % For NewThought formatting
\usepackage{array} % To define width of columns in long table
\usepackage{booktabs} % Nicer spacing in columns
\usepackage{siunitx} % To write Celsius, etc.
\usepackage{enumitem} % To create item lists
\usepackage{caption} % To change way captions are labelled
\usepackage{scrextend}
\usepackage{threeparttable} % For table notes + To allow footnote material to stay with the tabular environment
\usepackage{etoolbox} % To make table footnote font smaller
\usepackage{threeparttablex}
\appto\TPTnoteSettings{\footnotesize}

% Creating Index
\usepackage{imakeidx}
\makeindex
%\indexsetup{othercode=\small}
%\makeindex[columns=3,title=Index,intoc,options={-s indexstyle.ist}]
%\usepackage{showidx} %To print all index entries in right margin to proofread entries

\usepackage{blindtext}
%\usepackage{showframe}

% Styling Chapter appearance
\usepackage[T1]{fontenc}
\usepackage{titlesec, color}
\definecolor{gray75}{gray}{0.75}
\newcommand{\hsp}{\hspace{20pt}}
\titleformat{\chapter}[hang]{\Huge\bfseries}
{\thechapter\hsp\textcolor{gray75}{|}\hsp}{0pt}{\Huge\bfseries}

\usepackage{hyperref} % Hyperlinks

\usepackage[toc]{glossaries}
\makeglossaries

%%%%%TEST_ZONE%%%%%%

\newglossaryentry{naiive}
{
    name=na\"{\i}ve,
    description={is a French loanword (adjective, form of naïf)
        indicating having or showing a lack of experience,
        understanding or sophistication}
}

%%%%%TEST_ZONE%%%%%%

%Table of Content depth
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{5}
\setlength{\parindent}{15pt}

%Hyperlinks for TOC
\makeatletter
\hypersetup{
    colorlinks,
    citecolor=blue,
    filecolor=blue,
    linkcolor=blue,
    urlcolor=blue
}

\begin{document}

    %\layout

    % FRONTMATTER STARTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    \frontmatter

    \title{The Book of Wonders}
    \maketitle

    \tableofcontents
    \clearpage

    \listoftables
    \clearpage

    \thispagestyle{plain} % To not have "List of Tables appear" at the top of the "Preface" page
    \section*{Preface}
    \blindtext
    \clearpage

    \thispagestyle{plain} % To not have "List of Tables appear" at the top of the "Preface" page
    \section*{Introduction}
    \blindtext
    \clearpage

    % MAINMATTER STARTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    \mainmatter

    \chapter{The Story}

    \section{Data}

    \index{Plants}
    \index{star}
    \index{Mu}
    \index{Sinis}
    \index{Ball}

    \chapter{Languages}

    \section{Pronunciation}

    \section{Scripts}

    \subsection{Tina}

    \subsubsection{Consonants}

    \subsubsection{Vowels}

    \subsubsection{Numerals}

    \subsubsection{Special Symbols}

    \subsection{Anna}

    \subsubsection{Consonants}

    \subsubsection{Vowel Diacritics}

    \subsubsection{Diphthongal Diacritics}

    \subsubsection{Numerals}

    \subsubsection{Special Symbols}

    \subsubsection{Common Determinatives}

    \subsection{Herbert}

    \subsubsection{Consonants}

    \subsubsection{Vowel Diacritics}

    \subsubsection{Consonants}

    \subsubsection{Vowels}

    \subsubsection{Numerals}

    \subsubsection{Special Symbols}

    \subsection{Jennifer}

    \subsubsection{Consonants}

    \subsubsection{Vowel Diacritics}

    \subsubsection{Special Symbols}

    \subsection{Mike}

    \subsubsection{Consonants}

    \subsubsection{Vowel Diacritics}

    \subsubsection{Special Symbols}

    \subsection{Script Samples}

    \backmatter

    \printglossaries
    \printindex

\end{document}

A: Ok, I'll give it a try:
All sectioning commands do not allow a page break right after them to prevent them from standing alone. Once you add text to the corresponding section, a page break will automatically be after the text.
So, adding arbitrary text, or and an \mbox{} as David suggested would solve your problem.

For the background I did some research myself, and will do my best to explain based on the \section command:
The \section command for the book class is defined as
\newcommand\section{\@startsection {section}{1}{\z@}%
                                   {-3.5ex \@plus -1ex \@minus -.2ex}%
                                   {2.3ex \@plus.2ex}%
                                   {\normalfont\Large\bfseries}}

Therein the \@startsection command is actually a low level TeX command:
\def\@startsection#1#2#3#4#5#6{%
  \if@noskipsec \leavevmode \fi
  \par
  \@tempskipa #4\relax
  \@afterindenttrue
  \ifdim \@tempskipa <\z@
    \@tempskipa -\@tempskipa \@afterindentfalse
  \fi
  \if@nobreak
    \everypar{}%
  \else
    \addpenalty\@secpenalty\addvspace\@tempskipa
  \fi
  \@ifstar
    {\@ssect{#3}{#4}{#5}{#6}}%
    {\@dblarg{\@sect{#1}{#2}{#3}{#4}{#5}{#6}}}}

Here we have a \if@nobreak  \everypar{}, which delays a \nobreak command until text has been added, to prevent this text from being separated from the sectioning command (source). Once (La)TeX comes upon the text, the \nobreak is inserted.
Now, to my believe, the original \nobreak is inserted by an \@xsect command, defined in latex.ltx
\def\@xsect#1{%
  \@tempskipa #1\relax
  \ifdim \@tempskipa>\z@
    \par \nobreak
    \vskip \@tempskipa
    \@afterheading
  \else
    \@nobreakfalse
    \global\@noskipsectrue
    \everypar{%
      \if@noskipsec
        \global\@noskipsecfalse
       {\setbox\z@\lastbox}%
        \clubpenalty\@M
        \begingroup \@svsechd \endgroup
        \unskip
        \@tempskipa #1\relax
        \hskip -\@tempskipa
      \else
        \clubpenalty \@clubpenalty
        \everypar{}%
      \fi}%
  \fi
  \ignorespaces}

which again is called by the \@sect macro used in ever @startsection
\def\@sect#1#2#3#4#5#6[#7]#8{%
  \ifnum #2>\c@secnumdepth
    \let\@svsec\@empty
  \else
    \refstepcounter{#1}%
    \protected@edef\@svsec{\@seccntformat{#1}\relax}%
  \fi
  \@tempskipa #5\relax
  \ifdim \@tempskipa>\z@
    \begingroup
      #6{%
        \@hangfrom{\hskip #3\relax\@svsec}%
          \interlinepenalty \@M #8\@@par}%
    \endgroup
    \csname #1mark\endcsname{#7}%
    \addcontentsline{toc}{#1}{%
      \ifnum #2>\c@secnumdepth \else
        \protect\numberline{\csname the#1\endcsname}%
      \fi
      #7}%
  \else
    \def\@svsechd{%
      #6{\hskip #3\relax
      \@svsec #8}%
      \csname #1mark\endcsname{#7}%
      \addcontentsline{toc}{#1}{%
        \ifnum #2>\c@secnumdepth \else
          \protect\numberline{\csname the#1\endcsname}%
        \fi
        #7}}%
  \fi
  \@xsect{#5}}


text:
Q: Why Angular child component ( navbar ) stops updating view after route change? this is my first question on the platform, hope i do it right.
So, i'm working on a social network using MEAN stack and socket.io, and i'm trying to show the number of unviewed notifications and messages next to the icons. All the data is updated in the component by the sockets and i can see that all works fine in the console, data arrives in real time and updates the array which length i'm using to show the numbers on the navbar. Everything works fine and it updates the numbers in the view with no problem, BUT when i change the route (even if i come back to the same url) it stops updating the view, no matter the data still receiving and updating in console.
I've been days stuck with this, doing research, trying but i can't make it work. I've tried:
Using ChangeDetectionStrategy.OnPush combined with ChangeDetectionRef and its methods like markForCheck, detectChanges with async pipe.
Trying to re-render the component on route change without success.
ngZone but honestly i couldnt understand it so well.
So, i'm looking for some short explanation of what is happening and an idea of how can i could fix it. I know there's some very similar questions like this made before, and i'd checked them but couldn't apply them succesfully to my project. I hope someone can help me with this.
This is the navbar component:
import { Component, OnDestroy, OnInit} from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserService } from '../../services/user.service';
import { NotificationService } from '../../services/notification.service';
import { MessageService } from '../../services/message.service';
import { GLOBAL } from '../../services/global';
import { io } from 'socket.io-client';
import { Observable } from 'rxjs';
import { Message } from 'src/app/models/message';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss'],
  providers: [ MessageService ]
})
export class NavbarComponent implements OnInit{
  private socket = io("ws://localhost:3000");
  public identity;
  public token;
  public url:string;
  public newNotifications$: Observable<boolean>;
  public myNotifications;
  public unviewedMessages: Message[];

  constructor(  public user: UserService,
                private _notificationService: NotificationService,
                private _messageService: MessageService,
                private _route: ActivatedRoute,
                private _router: Router
              ) {
                this.identity = user.identity;
                this.unviewedMessages = [];
                this.token = user.getToken();
                this.url = GLOBAL.url;
                this.checkIfNewNotifications();
                this.checkUnviewedMessages();
              }

  ngOnInit(): void {
    this.sockets()
  }

  sockets(){
    this.socket.emit("addUser", this.identity._id);
    this.socket.on("newNotification", newNotification =>{
      this.checkIfNewNotifications();
      console.log("nueva notificacion")
    });
    this.socket.on("getMessage", msg =>{
      this.checkUnviewedMessages();
      console.log("nuevo mensaje")
    })
  }

  logout(){
      localStorage.clear();
      this.identity = null;
      console.log();
      this._router.navigate(['/register']);
  }

  toTop(event){
    window.scroll(0,0);
  }

  seeNotifications(){
    this.newNotifications$ = new Observable(observer=>observer.next(false));
    this.setViewedNotifications(this.token, this.identity._id);
  }

  checkIfNewNotifications(){
    this._notificationService.getNotifications(this.token).subscribe(
      response => {
        this.myNotifications = response.notifications.filter(notification => notification.viewed == false).length;
        console.log(this.myNotifications)
        if(this.myNotifications > 0){
          this.newNotifications$ = new Observable(observer=>observer.next(true));
        }
      },
      error => {
        console.log(<any>error);
      }
    )
  }

  setViewedNotifications(token, id){
    this._notificationService.setViewedNotifications(token, id).subscribe(
      response =>{
        console.log(response);
      },
      error =>{
        console.log(<any>error);
      }
    )
  }

  checkUnviewedMessages(){
    this._messageService.getUnviewedMessages(this.token).subscribe(
      response => {
        this.unviewedMessages = response.unviewed;
      },
      error => {
        console.log(<any>error);
      }
    )
  }

}

This is the navbar component template:

        V a p o r b o x

      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

              Inicio

              Usuarios

              <i class="fa fa-comments fa-lg mx-lg-2" *ngIf="unviewedMessages.length < 1">
              = 1">
                {{unviewedMessages.length}}

              Chat

              Cerrar Sesión

              {{identity.name}}

                Perfil

                Configuración

                Cerrar Sesión

              {{myNotifications}}

A: Try unsubscribing the api calls made in components, in ngOnDestroy method.


text:
Q: Request sent successfully but no response is coming back. I am sending a post request using jquery Ajax to java Restful Webservice. Request is submitted successfully but no response is coming back.
Jquery Code
$.ajax({
    type: "POST",
    url: "http://127.0.0.1:8080/Sampleprj/getData",
    data: "{\"result\": \"Hello\"}",
    crossDomain: true,
    dataType: "json",
    success: function( data, textStatus, jqXHR) {
    },
    error: function(jqXHR, textStatus, errorThrown){
    },
    beforeSend: function(jqXHR, settings){
    },
    complete: function(jqXHR, textStatus){
    }
});

Java Code :-
@RequestMapping(method=RequestMethod.POST, value="/getData")
public @ResponseBody String getRequest(@RequestBody String data) {
    System.out.println(data);
    return "{\"result\": \"Hello\"}";
}

Data coming from jquery is successfully printed to console but no data is returning back to jquery. It is going in error function and showing 200 OK status in firebug console without any response.


text:
Q: Any way to initialize attributes/properties during class creation in python? Any equivalent to this one-line code in Python?
// C# just shows how class looks like
class MyClass {
    public int A {get; set;}
    public int B {get; set;}
}

// This is that one-line code in C#. Any pythonic way to do something like this?
// var x = MyClass() { A=1, B=2 } - "var" syntax sugar, at compile time it's == MyClass
MyClass x = MyClass() { A=1, B=2 }

Edit: Maybe my question wasn't so precise. My main goal is to not pass arguments to constructor.
How to initialize many class members (any combination of them) without passing them to constructor and without constructor with all default values.
Edit: Thx for answers and sorry for confusing question. I just wanted to know answer for question in topic - What is the best way (pythonic way) to initialize class's subset of attributes without explicity writing them in constructor.

A: Actually, I am not aware of C# but looking at your code, I thought this is the one that you are looking at.
def MyClass (object):
    def __init__ (A, B):
        self.A = A
        self.B = B

x = MyClass(A=1, B=2)

Edit:
If you are looking for 100 arguments, use something like **kwargs.

A: I'm not sure what you are trying to achieve but you might want to pass generic arguments to the class constructor like:
class MyClass:
    def __init__(self, **kwargs):
        for key in kwargs:
            setattr(self, key, kwargs[key])

x = MyClass(a='test', b='test2')
# x.a == 'test'
# x.b == 'test2'
y = MyClass(c=123, d='something else')
# y.c = 123
# y.d = 'something else'

A: Well to make a class in Python just do this:
class Name:
    def __init__(self, arg1): # When an instance of a class is made this will be executed.
        self.var1 = 1
        self.var2 = 2
        self.arg1 = arg1

person1 = Name("arg1") # Create instance of the class

I personally don't know if there is a way to do this in one line pythonically as you also need to create the init() method.


text:
Q: How do I prevent Keras from always predicting the underlying distribution of my data? I am training a Deep CNN on a very unbalanced data set for a binary classification problem. I have 90% 0's and 10% 1's. To penalize the misclassification of 1, I am using a class_weight that was determined by sklearn's compute_class_weight(). In the validation tuple passed to the fit_generator(), I am using a sample_weight that was computed by sklearn's compute_sample_weight().
The network seems to be learning fine but the validation accuracy continues to be 90% or 10% after every epoch. How can I solve this data unbalance issue in Keras considering the steps I have already taken to overcome it?
Picture of fit_generator: fit_generator()
Picture of log outputs: log outputs

A: It's ver y strange that your val_accuracy jumps from 0.9 to 0.1 and back. Do you have right learning rate? Try to lower it even more.
And my advice: use f1 metric also.
How did you split the data - train set classes have the same rate in test set?


text:
Q: Beacon Proximity: Is this still a issue from Apple API reference. We are having a issue with iBeacons.
App makes wrong guess sometimes as to which proximity region its in before eventually correcting itself. It sometimes shows Far when the Proximity is Near. And then later it flips back to Near.
The problem actually occurs when we need to fire an event when we are in the Near/Far/Immediate region. This doest happen in that way. App is likely to lose range of beacons for brief instances.
Are there any other way to solve this Issue.

A: It is normal for the Proximity estimate to fluctuate with radio noise, but your experience sounds extreme.  What iBeacon brand are you using?
Make sure you are using an iBeacon with as fast enough transmission rate. Different iBeacons transmit advertisements at different frequencies from 30 times per second to once per second or less. Generally, faster transmission rates give you less noisy distance estimates because they give iOS more radio signal strength measurements to work with.
If an iBeacon transmits less than once per sec, you may get intermittent exit/entry events.
For your testing, Try an iOS-based iBeacon like Locate for iBeacon or EZBeacon to see if it helps. It is known to transmit 30x per second.

A: The proximity issue can be effected by advertising frequency as David has already said. The reason for this is that iOS takes an average of the RSSI readings overtime and uses these to find a final value, if you hold an iOS device in an ideal location, (i.e. clear line of site to the beacon) the result settles down over a few seconds of holding the device still. Apple describes the averaging as: "This value is the average RSSI value of the samples received since the range of the beacon was last reported to your app."
However a bigger factor can be fluctuations in the environment, the RSSI will change dramatically if an obstruction appears between the iBeacon and the iOS device, if the iBeacon and iOS device are both at a low level, this could be a person walking past. I have published some initial results using Estimote iBeacons that show changes in distance based on the device operator rotating 360 degrees. A distance change of +/- 2m is not an uncommon change in this circumstance and could result in the behaviour you observed if the iOS device is near the proximity region boundary.

A: This is Wojtek Borowicz, I'm a community evangelist at Estimote.
Calculating the exact proximity of a Beacon is based solely on the radio waves it's broadcasting an is really hard. You encounter factors like multipath propagation, wave diffraction, absorption or interference. That's exactly why iBeacon standard does not try to calculate the exact distance between a Beacon and the receiving device. Instead, it uses a value called RSSI (received signal strength indicator), which allows to estimate the proximity based on signal power. For calibration purposes, there's also included a metric called Measured Power - but it's nothing more than just RSSI measured 1 meter away from the Beacon. Even calibrated, RSSI might fluctuate heavily, due to the factors mentioned above.
The stability of the Beacon's signal is also based on two main factors. One of them is advertising interval (frequency - the lower, the better signal) and broadcasting power (the higher the better signal). Improving them will allow for much better proximity reading, but will also strongly affect battery life.


text:
Q: $first command is giving null values I have the collection for "article_titles" and there are some title with repetitions involved in it. I want to pick the one that is earliest.
{ "_id" : ObjectId("6375dbf89a70ce15b7c51172"), "title" : "Visualizing Graphs and Clusters as Maps", "year" : 2005, "name" : "amir" }
{ "_id" : ObjectId("6375dbf89a70ce15b7c5118a"), "title" : "Visualizing Dynamic Data with Maps", "year" : 2012, "name" : "amir" }
{ "_id" : ObjectId("6375dbf89a70ce15b7c511ac"), "title" : "Visualizing Cartograms: Goals and Task Taxonomy", "year" : 2015, "name" : "kobourov" }
{ "_id" : ObjectId("6375dbf99a70ce15b7c60293"), "title" : "Upward straight-line embeddings of directed graphs into point sets", "year" : 2008, "name" : "hossain" }
{ "_id" : ObjectId("6375dbf99a70ce15b7c738c7"), "title" : "Upward straight-line embeddings of directed graphs into point sets", "year" : 2010, "name" : "hossain" }

Here the name "hossain" has two same publications but in different years. I am trying to pick the first one,
I am using
db.article_titles.aggregate([{$sort:{year:-1}},{$group:{_id:{title:"$title",name:"$name",year:{$first:"$year"}}}}])

I want to understand what I am doing wrong here?

A: Originally your year: { $first: "$year" } statement was nested too deeply (inside of _id). Then with your second attempt you pulled it out too far. It should be inside of $group but outside of _id:
  {
    $group: {
      _id: {
        title: "$title",
        name: "$name"
      },
      year: {
        $first: "$year"
      }
    }
  }

Playground demonstration here


text:
Q: How to disable edit from kendo editable grid dynamically? I would like to disable edit from only first cell of kendo edit-able grid and I am doing something like below. Actually I am trying to remove a datepicker
from first cell of kendo grid as it is not required to be there. so I am using below and this code removes datepicker from grid but it still shows a text box.
I should be able to remove it completely.
  function onGridEditing(e) {
        var gridbody = $("#EditableGrid").data("kendoGrid");
        var gridData = gridbody.dataSource.view();
        var currentUid = gridData[0].uid;
        var Date = gridData[0].Date;
        var currenRow = gridbody.table.find("tr[data-uid='" + currentUid + "']");
        //var firstCell = currenRow.find('td:not(:empty):first');
        //firstCell.find('.k-select').remove();
        //alert(firstCell.val());
        currenRow.find('.k-select').remove();// this removes the datepicker but it is still showing textbox when user click on the row for edit.
        currenRow.find(".editDate").remove();

ALso I tried to apply a css over there so that it hide datepicker but not working
//$("#EditableGrid").data("kendoGrid")._data[0].addClass('hideMe');
    }

<style>

   .hideMe {
        /*visibility: hidden;*/
        border: none !important;
        background-color: none !important;
    }

</style>

A: You could disable editing of a particular column in the model of the dataSource. For example:
model: {
    fields: {
        ProductID: {
            //this field will not be editable (default value is true)
            editable: false
        }
    }
}

source: Telerik Forums
Edit: To do it dynamically:
var model = $("#EditableGrid").data("kendoGrid").dataSource.getByUid(currentUid);
if (model) {
    model.fields["ProductID"].editable = false;
}


text:
Q: Microsoft Sign-In for ASP.NET MVC 5 web role I have created Azure cloud service and in this cloud service I have a web role serving as a MVC web application. I followed this tutorial to use Microsoft account as the external authentication. When I try with the localhost it works perfectly. However, after I deploy the cloud service, I changed the redirect URL to the site url which is http://109e199cf5864b50ab25ac839f8c151d.cloudapp.net/. But this doesn't work. I can reach the authorization part, but after I login with the Microsoft account I got Error Message: An error occurred while processing your request. What should I do to make it work?
UPDATE:
I tried to remove the [Authorize] tag in my controller so that I don't need to login to see the view. After I deployed again, I got the Error Message directly!!
I didn't login at all! I checked the code this Error Message is actually the Error view from the template in the Shared folder. But there is no change of the code to return me this Error view! What I am missing with the deployment here?

A: In the comments of the blog post you referenced, the author (Ben Day) said there was an update to the redirect URI.

With the latest version of the ASP.NET Identity code, the redirect uri is a different value. So on account.live.com, the redirect url value for your app is now going to be "http://myapp-url/signin-microsoft".

You may want to check that you have the correct values here.


text:
Q: How to drop orig_to using postfix virtual domains? With the virtual domains, the final mailbox receiving the email gets the orig_to email address in its header. Is there a way to prevent this (i.e. address translation without keeping the orig_to)?

A: Maybe you mean X-Original-To header instead orig_to header. String orig_to only appears in maillog. To disable it set parameter enable_original_recipient = no in main.cf
From postconf(5):

enable_original_recipient (default: yes)

Enable support for the X-Original-To message header. This header is needed for multi-recipient mailboxes.
When this parameter is set to yes, the cleanup(8) daemon performs duplicate elimination on distinct pairs of (original recipient, rewritten recipient), and generates non-empty original recipient queue file records.
When this parameter is set to no, the cleanup(8) daemon performs duplicate elimination on the rewritten recipient address only, and generates empty original recipient queue file records.
This feature is available in Postfix 2.1 and later. With Postfix version 2.0, support for the X-Original-To message header is always turned on. Postfix versions before 2.0 have no support for the X-Original-To message header.


text:
Q: apt-get doesn't work on kali linux v2.0 For example, when i type apt-get install tor i get :
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
libpcap0.8-dev : Depends: libpcap0.8 (= 1.3.0-1) but 1.6.2-2 is to be installed
libsqlite3-dev : Depends: libsqlite3-0 (= 3.7.16.2-1~bpo70+1) but 3.8.7.1-1+deb8u1 is to be installed
tor : Depends: libseccomp2 (>= 0.0.0~20120605) but it is not going to be installed
      Recommends: tor-geoipdb but it is not going to be installed
      Recommends: torsocks but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Even when i type apt-get -f install tor i get the same error !

A: It seems that the local repository was out of date, solved after typing :
sudo apt-get clean


text:
Q: What is Dynamic Code Evaluation as mentioned by John Resig In his book "Secrets of the Javascript Ninja", John Resig writes:

Although dynamic code evaluation has been maligned due to its complexity and potential for security issues, without it we wouldn't have had the CoffeeScript programming language.

I was hoping that someone could explain what is Dynamic Code Evaluation?  Also, are there any code examples (or word examples) that would help better explain it?  Furthermore, are there any website examples that use dynamic code evaluation?
Also, if possible, how did dynamic code evaluation bring about the CoffeeScript programming language?

A: Dynamic code evaluation techniques in JavaScript:

*

*eval function

*Function object, created with the Function constructor

Basically you take a string (for example, concatenate it from parts) which contains JavaScript code, and use one of these techniques to parse and run it. The CoffeeScript compiler is actually a transpiler: it takes source code written in CoffeeScript (that is, a string), and translates it into JavaScript source code (another string), which is run using eval.


text:
Q: JDialog fixed height
Possible Duplicate:
JDialog allow user to only change width of the dialog

I have a JDialog that I would like the width to be resizable, but the height not.
This is my current code:
addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent e) {
        setLocation(getLocation().x, getLocation().y + (getHeight() - staticHeight));
        setSize(new Dimension(getWidth(), staticHeight));
        super.componentResized(e);
    }
});

Problem is, that code gets called after the window is resized. Making the window resize and then flicker back.
I would like to make it so when the user trys to drag the height of the window it does nothing.

A: *

*you can't directly stop resizing,

*you can't block basic property of containers,

*container because from Native OS and are built on its properties,

*and limitations for resizing is screen size

*rest are (with code) Resizing Components by @camickr

*there are dirty hack based on AbsoluteLayout, and I don't suggest using that

*block resize if there is any flickering or freeze during resize

A: looks like you cant. there's a setResizable() method but its all-or-nothing.
you could try mitigating this by using a layout inside your JDialog so that your content remains the same height regardless of the JDialog height
or perhaps (a bit more radical) set it as not resizable and implement your own mouse listener for resizing yourself ? that way you could have full control

A: After looking for a while, I could not find any really satisfactory solutions. I think that the resize of the dialog is something that is handled directly at the OS level and therefore you can only say that you want it totally not resizable or totally resizable.
The code below will always prevent the dialog from being bigger, but as the user resize the dialog, the borders of the dialog still move.
The other option, also suggested by radai, would be to prevent resize and set a Custom content pane with a mouse listener that listens for the mouse and resize accordingly. However, I think that this will not feel very native to the user (I don't think that you will be able to catch the events on the border of the dialog).
import java.awt.Frame;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JDialog;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                init();
            }
        });
    }

    public static void init() {
        final int staticHeight = 150;
        final JDialog dialog = new JDialog((Frame) null) {

            @Override
            protected JRootPane createRootPane() {
                JRootPane rp = new JRootPane() {
                    @Override
                    public void reshape(int x, int y, int w, int h) {
                        super.reshape(x, y, w, staticHeight);
                    }
                };
                rp.setOpaque(true);
                return rp;
            }

            @Override
            public void reshape(int x, int y, int width, int height) {
                super.reshape(x, y, width, staticHeight);
            }

        };
        dialog.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                dialog.setSize(dialog.getWidth(), staticHeight);
            }
        });
        dialog.pack();
        dialog.setVisible(true);

    }
}

A: Here try this code example, that's how you set the JDialog to not have vertical Resizing. Though I really doesn't want to take credit for this, the whole credit goes to the creator of this program which is "Darryl Burke" the link to the program is here.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class WidthResizeableDialog {

  Robot robot;
  static final int HEIGHT = 400;
  Point lastLocation;

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {
        new WidthResizeableDialog().makeUI();
      }
    });
  }

  public void makeUI() {
    try {
      robot = new Robot();
    } catch (AWTException ex) {
      ex.printStackTrace();
    }
    final JDialog dialog = new JDialog();
    dialog.setSize(400, HEIGHT);
    dialog.setLocationRelativeTo(null);
    dialog.addWindowListener(new WindowAdapter() {

      @Override
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    dialog.addComponentListener(new ComponentAdapter() {

      @Override
      public void componentMoved(ComponentEvent e) {
        SwingUtilities.invokeLater(new Runnable() {

          @Override
          public void run() {
            lastLocation = dialog.getLocation();
          }
        });
      }
    });
    dialog.getRootPane().addComponentListener(new ComponentAdapter() {

      @Override
      public void componentResized(ComponentEvent e) {
        int height = dialog.getHeight();
        if (robot != null && height != HEIGHT) {
          robot.mouseRelease(InputEvent.BUTTON1_MASK);
          dialog.setLocation(lastLocation);
          dialog.setSize(dialog.getWidth(), HEIGHT);
        }
      }
    });
    dialog.setVisible(true);
  }
}


text:
Q: Циклическая карта мира. Unity3d Unity3d
Есть картинка карты мира и orthographic camera, которую можно двигать по карте, увеличить/ уменьшать. Нужно сделать так , чтобы при достижении края карты, показывалась картинка карты с другого края. Чтобы получилась бесшовная карта, которую можно бесконечно двигать вправо/влево, как это сделано в google maps. Есть у кого-нибудь идеи как это можно реализовать?

A: Есть 2 способа:

*

*Изменять оффсет текстуры плейна и при этом сам плейн размещать всегда на уровне игрока/камеры.

*Создать 2 картинки и просто передвигать одну из них вперед когда камера направлена на вторую.


text:
Q: How can I measure the physical properties of a metallic string? Metallic strings exist in different kinds but I would like to measure for a metallic string:

*

*the section/geometry along its length, to a precision of 1/100 mm

*its elongation when a tension is exerted on it on a measuring system I would construct to apply forces of the order of 1 to 100 daN. I have no clear idea of the order of magnitude of the elongation, so it might be too small to measure with reasonable equipement.
Any ideas, suggestions, theoretical and practical remarks welcome.

A: In a physics laboratory session at university we measured the extension of copper wire with different weights attached.  To do so requires two wires hung vertically, one has the weights attached and is stretched, the other acts a sort of control.  Between them a device is attached, this contains an adjustable spirit level.
Before the weight is applied the spirit level is set to horizontal, after the weights have stretched one string the device can be re-levelled and this 'correction angle' implies a certain extension.
To predict the sort of stretch you might achieve I would suggest looking up Youngs Modulus: http://en.wikipedia.org/wiki/Young%27s_modulus.  (For metal wires and 'safe' loads don't expect very much!).

A: To accurately measure the cross section, assuming you know the material's density, just measure the length, mass and use
$$\sigma = \frac{M}{\rho\;L}$$
If you're interested in the answer (rather than having to measure it), and you know the material's Young's modulus, it's easy to calculate the extension. But I'll assume you don't know this (which strength of a material is a lot harder to predict than its density).
If you're having trouble measuring the extension due to its small amount, then use the following fixture:

The idea is to use leverage so you can measure a smaller change in string length. There are two strings, one with no weight applied, the other stretches slightly. The result is that the blue stick moves quite a lot. (Probably it would be better to have the blue stick set up so that it has equal lengths on either sides of where you attach the strings. I'd use balsa for the stick.)

A: Ah.  Hobby engineering.  You have strayed into an area of intense interest.  Here is a simple Rube Goldberg device which may give you other ideas:
build a short teeter-totter ("TT") with a laser pointer clamped to it, so that the laser points at a wall.  Make sure the TT is fairly level, the fulcrum of the TT is firmly supported and that it is fairly balanced (so as to not add weight to your string).  Attach one end of the TT near the free end of the string.  Turn on the laser, make a pencil mark on the wall where it hits, load the string, and make your second mark.
Call the length from the TT fulcrum to the string = TS.
Call the length from the string to the wall = SW.
Call the length from your first to second wall mark = WW
Call the length of stretch of the string = SS
Then: SS/TS = WW/(TS+SW) --->  SS = (WW)(TS/(TS+SW))
If you build a TT with a 2 inch half-arm (TS), and your wall is 9 feet away, you will get a movement magnification of 110/2 = 55.  This might not be enough.
Another idea would be to mount a small mirror on the TT and hit it with a fixed laser, so that it bounces back to the wall. This would double your sensitivity (movement magnification of 110).  If you made TT for the mirror = 1 inch, you could get approximately double that (218).  If you wanted to add another mirror at the target spot on the wall and make your pencil marks on the opposite wall... well... you do the math.  :-)  As long as you keep the angles small (less than 5 degrees) you can dispense with any trig and just use simple geometry.


text:
Q: How do I remote debug over Serial Port or USB with Eclipse? I'm working on a device that has an unstable wireless connection and therefore requires a serial cable to debug programs that run on it while the Firmware team works on fixing the wireless connections.  This happens often as new devices tend to be unstable at first.  The problem is I can't seem to find out how to remote debug in Eclipse CDT when using a serial port.  I've been doing some searching online and have found lots of info about remote debugging via SSH, FTP and Telnet.  Although, I can't find anything about debugging through the serial port.  I was able to find info on and use a serial terminal in Eclipse but as far as I can tell this doesn't help me debug a program remotely with the serial connection.  I also know that it's possible due to this Eclipse bug:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=257171
Unfortunately that doesn't tell me how to use this new support :(
I also know GDB allows debugging via serial cable, so surely there is a way to do it with the Eclipse debugger.  I was also wondering if there is a way to get the "Remote System Explorer", an Eclipse plugin, to use a serial port as well?  As far as I can tell it doesn't seem to support serial connections.  Is there another plugin like it that does support serial connections?  Any and all help is greatly appreciated.

A: From the comments by the patch it looks like official support is in Eclipse 3.6 (Helios) M7
The supported CDT approach seems to be to use the GDB serial protocol.
http://www.embecosm.com/appnotes/ean4/embecosm-howto-rsp-server-ean4-issue-2.html


text:
Q: Embedding SVG images in Angular application I'm developing an Angular app and I'm trying to figure out the best way to deal with SVGs:

*

*Use them as background-image, src attribute of img tag etc. - I lose the ability to style the SVGs with CSS. On the other hand it's pretty easy to use and I don't have to copy/paste the content

*Use 3rd party app that makes the request for us and puts the SVG inside the container that had the directive - e.g. https://www.npmjs.com/package/ng-inline-svg - it makes the HTTP request that I'd like to avoid. I can, however, style the image with CSS

*Put the SVG directly inside the component template - no additional requests are made and I have full control over the styling. This reduces the code reusability though.
The reason I'd like to avoid the HTTP requests altogether is because we have multiple themes (same SVGs but different colors) and I want to load at most one resource per "image".
Are there any good practices I could use? Any open source code that I could look at?
Is the 3rd option even any good? Maybe I could write an Angular service and group the inline SVGs somehow, but I don't have any idea for now.
Kind regards,
Marcin


text:
Q: Python: array of 2 dim shape (1,1024) is read as 3 dim array In python, I have a list a of arrays, each of shape (1, 1024) and a list b of ints {1,0,0,1…]
Now I want to train a basic SVM with that.
I always receive this error message:
ValueError: Found array with dim 3. Estimator expected <= 2.

But doesnt the shape tell me, that I have a 2 Dim shape?
There is probably something wrong with my array but I don`t understand, what.
I am glad for any help.
clf = svm.SVC(kernel='linear')
clf.fit(lista, listb)

First 10 items of the array:
[array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.03608917,
         0.06382023,  0.02493868]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00363029,
         0.04429551,  0.04517733]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.01848865,
         0.03857033, -0.04184096]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00812042,
        -0.01121382, -0.07293765]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.0026521 ,
        -0.00911874,  0.02558753]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.0128456 ,
        -0.00659914, -0.05465406]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00801555,
        -0.06554729, -0.04112517]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.0015485 ,
        -0.03974668,  0.03871798]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.03571296,
         0.0097717 , -0.02939025]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00178309,
        -0.00751928, -0.00501447]], dtype=float32)]

A: Just think this way:
[(1, 1024),(1, 1024),(1, 1024)...(1, 1024)]
to select a single element here you will need 3 things: position in the list, the n in (n, 1024) and k in (1, k). This is a 3 dimensional data structure.
use np.stack  or convert your list with np.array and  np.reshape(len(list),1024). This way you`ll have a unique array of shape (n, 1024).


text:
Q: What is a patch in Git version control? I am new to both Git and version control so I am trying to figure out what a patch is and how is it different from the rest of activities I do in Git?
When do I apply a patch? Does it happen every time I commit?

A: A patch is a set of differences between one or more files, to show what is different between them. You would typically only generate a patch to show someone what you have changed. An example of when you might do this is when you find and fix a bug in an open source application and then post the fix on their bug tracker.

A: A patch is a small file that indicates the changes made in a repository. It's generally used when someone from outside your team has read-only access but had a good code change available. He then creates a patch and sends it to you. You apply it and push it to the git repository. Everyone then benefits from the updated version, and the author of the patch didn't need read/write access.
It's really mainly a security thing (at least, that's what people use it for).

A: You can see in this blog post how you can create a patch (collection of changes you want to communicate and apply to another repo)

(picture from the 2008 blog post "Bioruby with git: how would that work?", published by Jan AERTS)
See also Contributing to Rails with Git as another concrete example.
Nowadays, the GitHub pull request makes it really easy to apply patches on GitHub repos, which is useful when you aren't a direct contributor (ie you have no right to directly push to a repo).
Actually, fairly recently GitHub introduced "Better Pull Request Emails" to improve the notification of new patches.

A: A patch file represents a single set of changes that can be applied to any branch, in any order. By using patch, you will get differences between one or more files. And later, you can apply the differences (patch) to get the changes on new files. There are many uses for a patch in Git.
If you have uncommitted changes in your working directory, and you need to get that changes to apply somewhere else, just create a patch and apply the patch.
git diff > mypatch.patch

If you have new files in your repository(untracked), then you should stage the file before creating a patch (don't commit), and use the following command
git diff --cached > mypatch.patch

You can later apply the patch:
git apply mypatch.patch

If you want to make some changes to a git repository, that you don't have a write permission, just make the changes and create a patch between both,  and send the patch to someone who has the permission to apply the patch, by this your changes should be added to that git repository.

A: Patch is a Unix program that updates text files according to instructions contained in a separate file, called a patch file.
So, in other words it may mean the file with instructions or a program that processes that file and applies it to something.
Now, what is a patch file? Let's say you have a text file with 2 lines:
This is line A.
This is line B, or otherwise #2.

Then you change the first line, and now your file looks like this:
This is SPARTA.
This is line B, or otherwise #2.

How would you describe the change to the contents of the file? You can say that first line "This is line A." got replaced with "This is SPARTA.", or even the last word "A" of the first line replaced with another word "SPARTA". And that is exactly what diff tells us. Let's say I have two versions of this file, one called file1.txt and another one file2.txt, then I run diff and get this:
$ diff -u file1.txt file2.txt
--- file1.txt   2011-11-26 11:07:03.131010360 -0500
+++ file2.txt   2011-11-26 11:07:13.171010362 -0500
@@ -1,2 +1,2 @@
-This is line A.
+This is SPARTA.
 This is line B, or otherwise #2.

Having a description of changes, you can apply it to a initial content and get a modified content. And those changes, put in unified format that "patch"-like programs can understand, is called a patch file. It's like instead of getting a fish from someone they teach you how to fish, so that you can dig that fish out of the waters yourself. Now, let's apply our patch to file1.txt to make it look exactly like file2.txt:
$ cat file1.txt
This is line A.
This is line B, or otherwise #2.
$ cat file2.txt
This is SPARTA.
This is line B, or otherwise #2.
$ diff -u file1.txt file2.txt > changes.patch
$ cat changes.patch
--- file1.txt   2011-11-26 11:09:38.651010370 -0500
+++ file2.txt   2011-11-26 11:07:13.171010362 -0500
@@ -1,2 +1,2 @@
-This is line A.
+This is SPARTA.
 This is line B, or otherwise #2.
$ patch < changes.patch
patching file file1.txt
$ cat file1.txt
This is SPARTA.
This is line B, or otherwise #2.
$

You may think that it is easier to just have two versions of this file. Well, in this simple case that is true. But when you have a lot of files, and those files are very big, it is a lot more efficient to have a few lines of changes rather than two copies of the whole thing.
When talking in terms of git, patch file still means the same thing, but using diff + patch yourself would be a nightmare. For example, you will always have to have two versions of the file (or even the whole repository) checked out in order to compare them. Doesn't sound that good, does it? So git takes care of all of the hard work for you - it compares your local file with what is there in the repository you are working with, and can show it to you as a "diff", or apply that "diff" as a patch aka commit your changes, or even let you apply some patch file that you have already. Without going deep into details, in this sense git is absolutely the same as other version control systems like SVN, or even CVS or perforce.
Hope it helps!


text:
Q: JavaScript curry / schönfinkeln Lets say I have the following functions declared
function curry(fn) {
    var args = [];
    // push everything but function itself into args
    for (var i = 1; i < arguments.length; ++i) {
        args.push(arguments[i]);
    }
    return function() {
        var args2 = [];
        for (var i = 0; i < arguments.length; i++) {
            args2.push(arguments[i]);
        }
        var argstotal = args.concat(args2);
        return fn.apply(argstotal);
    };
}

function add(a,b){return a + b};

What im trying to do is obvious, I want to curry the add function which works great itself
var addCurry = curry(add);
addCurry(10, 20, 12314) // should deliver 30, gives NaN

Somehow it returns NaN and I dont know what Im doing wrong... Anybody got an idea?

A: You have an off-by-one error here: return fn.apply(argstotal)
The first argument to Function.prototype.apply is a scope, the value of this within the invocation, not the first argument. If you were to print out the arguments from within your curried function, you would see:

function curry(fn) {
  var args = [];
  // push everything but function itself into args
  for (var i = 1; i < arguments.length; ++i) {
    args.push(arguments[i]);
  }
  return function() {
    var args2 = [];
    for (var i = 0; i < arguments.length; i++) {
      args2.push(arguments[i]);
    }
    var argstotal = args.concat(args2);
    return fn.apply(argstotal);
  };
}

function add(a, b) {
  console.log('debug', this, arguments);
  return a + b;
}

var cadd = curry(add, 1);
cadd(2);

You can very easily fix this in two ways:

*

*Pass this through to the curried function

*Ignore this and do not set it for curried functions

The first option is probably better, as it will surprise developers less. You can implement that using:

function curry(fn) {
  var args = [];
  // push everything but function itself into args
  for (var i = 1; i < arguments.length; ++i) {
    args.push(arguments[i]);
  }
  return function() {
    var args2 = [];
    for (var i = 0; i < arguments.length; i++) {
      args2.push(arguments[i]);
    }
    var argstotal = args.concat(args2);
    return fn.apply(this, argstotal); // <-- only change
  };
}

function add(a, b) {
  console.log('debug', /* this, */ arguments);
  return a + b;
}

var cadd = curry(add, 1);
cadd(2);

The second option can be implemented with fn.apply(null, argstotal).


text:
Q: How can I identify the source of calls to Instance Metadata Service Version 1 (IMDSv1)? I want to transition to using the Instance Metadata Service Version 2 (IMDSv2).  I've been following the steps in https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#instance-metadata-transition-to-version-2, which mentions using a CloudWatch metric to see if anything is still calling IMDSv1:

CloudWatch: IMDSv2 uses token-backed sessions, while IMDSv1 does not.
The MetadataNoToken CloudWatch metric tracks the number of calls to
the instance metadata service that are using IMDSv1. By tracking this
metric to zero, you can determine if and when all of your software has
been upgraded to use IMDSv2.

I don't want to guess which instances may still be making calls to IMDSv1, and I don't necessarily want to disable IMDSv1 one-by-one on instances until I find one that breaks.  I want to know where the calls are coming from first. I've heard some CLI actions will call it, but that is a black box to me.  I see the MetadataNoToken metric in CloudWatch, but how can I tell which instances are still making the calls to IMDSv1?

A: I realized in CloudWatch I could find the MetadataNoToken metric under "Per-Instance Metrics," which at least will show the instance ID for each instance.  I was just looking under "Across All Instances" before.  Seems obvious now.
I am still not able to see what specific process/action on the instance is calling IMDSv1, but at least I can identify which instances are making calls:

Also useful: https://blog.appsecco.com/getting-started-with-version-2-of-aws-ec2-instance-metadata-service-imdsv2-2ad03a1f3650


text:
Q: Ubuntu 14.04 32 bit getting "Kernel panic - not syncing" when trying to install on VMware player I am trying to install Ubuntu 14.04 on my work computer. First i had to active VT in bios and now I get this error and cant fix it:

The computer uses i3-4130 CPU with 8GB of brand new RAM.
I already tried setting the processor to Intel VT-x or AMD-v in the Virtualization engine option but i got the same error

A: So the fix was rather simple, the new work computer i got had vmware player preinstalled and ofcourse i though it was the latest version, as it turned out it was not, so i updated it and it worked.

A: What guest os option did you set in vmware for the ubuntu? If you set to a specific guest os option in vmware, please try selecting "Other"
Changing guest os option is best to format the guest again to see if the new option setting works for you.
Please try because such panics are common in virtualization partially due to wrong guest option to ISO / OS type. Happens in Virtualbox and Xen for me.


text:
Q: Do mutable class attributes require a lock when reading or updating? I'm using a couple of class attributes to keep track of aggregate task completion across multiple instances of class. When reading or updating the class attributes do I need to use a lock of some sort?
class ClassAttrExample:

    of_type_list = []
    of_type_int = 0

    def __init__(self, name):
        self.name = name

    def do_task(self):
        # does some stuff
        # do I need a lock context here???
        self.of_type_list.append(self.name)
        self.of_type_int += 1

A: If not threads are involved, no locks are required just because class instances share data. As long as the operations are performed in the same thread, everything is safe.
If threads are involved, you'll want locks.
For the specific case of CPython (the reference interpreter), as an implementation detail, the .append call does not require a lock. The GIL can only be switched out between bytecodes (or when a bytecode calls into C code that explicitly releases it, which list never does), and list.append is effectively atomic as a result (all the work it does occurs within a single CALL_METHOD bytecode which never calls back into Python level code, so the GIL is definitely held the whole time).
By contrast, += involves reading the input operand, then performing the increment, then reassigning the input, and the GIL can be swapped between those operations, leading to missed increments when two threads read the value before either writes back to it.
So if multithreaded access is possible, for the int case, the lock is required. And given you need the lock anyway, you may as well lock around the append call too, ensuring the code remains portable to GIL-free Python interpreters.
A fully portable thread-safe version of your class would look something like:
import threading

class ClassAttrExample:
    _lock = threading.Lock()
    of_type_list = []
    of_type_int = 0

    def __init__(self, name):
        self.name = name

    def do_task(self):
        # does some stuff
        with self._lock:
            # Can't use bare name to refer to class attribute, must access
            # through class or instance thereof
            self.of_type_list.append(self.name)  # Load-only access to of_type_list
                                                 # can use self directly
            type(self).of_type_int += 1  # Must use type(self) to avoid creating
                                         # instance attribute that shadows class
                                         # attribute on store


text:
Q: C++ fstream multiple input files I am writing a simple program to take in two files.  The terminal command line looks like this.
./fileIO foo.code foo.encode

When it runs, the second file is not read in.  When I enter
./fileIO foo.code foo.code

it works.  I can't seem to figure out why the second one is not opening.  Any ideas?  Thanks!
#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;

int main( int argc, char *argv[] )
{
  // convert the C-style command line parameter to a C++-style string,
  // so that we can do concatenation on it
  assert( argc == 3 );
  const string code = argv[1];
  const string encode = argv[2];
  string firstTextFile = code;
  string secondTextFile = encode;

  //manipulate the first infile
  ifstream firstFile( firstTextFile.c_str(), ios::in );
  if( !firstFile )
  {
    cerr << "Cannot open text file for input" << endl;
    return 1;
  }

  string lineIn;
  string codeSubstring;
  string hexSubstring;
  while( getline( firstFile, lineIn ) )
  {
    hexSubstring = lineIn.substr(0, 2);
    codeSubstring = lineIn.substr(4, lineIn.length() );
    cout << hexSubstring << ", " << codeSubstring << endl;
  }

  //manipulate the second infile
  ifstream secondFile( secondTextFile.c_str(), ios::in );
  if( !secondFile )
  {
    cerr << "Cannot open text file for input" << endl;
    return 1;
  }

  char characterIn;
  while( secondFile.get( characterIn ) )
  {
    cout << characterIn << endl;
  }

  return 0;
}

A: One thing you might want to try is adding the close() call as is standard procedure after you're done using files. Sometimes issues arise with re-opening files if they were not closed properly in a previous run.
firstFile.close();
secondFile.close();

Also, you may try restarting the computer if there is some lingering file handle that hasn't been released.


text:
Q: Loop through SQL to get count, if value of all inputs are 0, disable submit button My products are split up into variable and fixed pricing. Based on ajax when clicked on plus or minus inputs to add or delete items to the sidebar. Its coded to make the disabled submit button enabled when the price in the sidebar is more then 0 etc. That's fine and works. However on the refresh regardless of the amount of items added, the submit button will go back to disabled. The inputs value change from 0 to the item amount.
We need to validate the submit button that if any of those values are higher then 0, then the button should be enabled. It only becomes enabled again once you add or delete an item. Here is the markup.
<div class="select-price">
<?php
    $order_id   = $_SESSION['orderid'];
    $addonID    = get_the_id();
    if($_SESSION['currenttrip']>1){
        $order_item_amount  = 0;
    }else{
        $qty = $wpdb->get_row("SELECT order_item_total, order_item_name, order_item_amount FROM fcb_order_item WHERE order_id=$order_id AND order_item_addon_id=$addonID");
        $order_item_amount  = ($qty->order_item_amount) ? $qty->order_item_amount : 0;
    }

    if(get_post_meta(get_the_ID(), 'fcb_addon_pricing_type', true) == 'fixed')
    {
        $max     = get_post_meta(get_the_ID(), 'fcb_addon_max_amount', true);
        $options = array_fill(1, $max, 'option');

        echo '<input data-addon-id="'.get_the_id().'" data-price="'.$price.'" type="button" value="-" class="qtyminus new-add-item add-service-item plus left '.$addonID.'" data-type="minus" field="quantity" />';
        echo '<input class="airport-value qty qty-'.get_the_id().'" type="number" name="quantity" value="'.$order_item_amount.'" />';
        echo '<input data-addon-id="'.get_the_id().'" data-price="'.$price.'" type="button" value="+" class="qtyplus new-add-item add-service-item minus right '.$addonID.'" data-type="plus" field="quantity" />';

    } elseif (get_post_meta(get_the_ID(), 'fcb_addon_pricing_type', true) == 'variable') {

        $options = get_post_meta(get_the_ID(), 'fcb_variable', true);

        echo '<input data-addon-id="'.get_the_id().'" data-price="'.$options[0]['price'].'" type="button" value="-" class="qtyminus new-add-item add-service-item plus left '.$addonID.'" data-type="minus" field="quantity" />';
        echo '<input class="airport-value qty qty-'.get_the_id().'" type="number" name="quantity" value="'.$order_item_amount.'" />';
        echo '<input data-addon-id="'.get_the_id().'" data-price="'.$options[0]['price'].'" type="button" value="+" class="qtyplus new-add-item add-service-item minus right '.$addonID.'" data-type="plus" field="quantity" />';

    }
?>
</div>

using something on the lines of
foreach ($_GET as $key => $value) { }

but not sure how to loop through two different sets of options being variable and fixed. If they all are 0 then disable the submit button. If any one has a value of 1 then enable it and let the customer continue to payment
EDIT
here is the ajax that adds and deletes the items to the sidebar and the price etc.
//Arrival First Track suvarnabhumi
if(addonid==126){
    if($quantity.val()>0){
        $('.plus218').removeClass('add-service-item');
        $('.minus218').removeClass('add-service-item');
    }else{
        $('.plus218').addClass('add-service-item');
        $('.minus218').addClass('add-service-item');
    }
}

//Depeature First Track suvarnabhumi
if(addonid==283){
    if($quantity.val()>0){
        $('.plus1597').removeClass('add-service-item');
        $('.minus1597').removeClass('add-service-item');
    }else{
        $('.plus1597').addClass('add-service-item');
        $('.minus1597').addClass('add-service-item');
    }
}

//Arrival First Track don muang airport
if(addonid==216){

    if($quantity.val()>0){
        $('.plus218').removeClass('add-service-item');
        $('.minus218').removeClass('add-service-item');
    }else{
        $('.plus218').addClass('add-service-item');
        $('.minus218').addClass('add-service-item');
    }

}

var amount = parseInt($quantity.val());
var total = parseInt($(this).attr('data-price')) * amount;

if (total > 0) {
    $('.main-amount-' + addonid).html('');
    $('.main-amount-' + addonid).html(total);
}

console.log(addonid+'-'+amount+'-'+total)

$('.spinner').html('loading');
$('.addon-list').hide();
jQuery.ajax({
    type: 'post',
    url: myAjax.ajaxurl,
    data: {
        action: 'fcb_add_item_to_order',
        addonid: addonid,
        amount: amount,
        total: total,
        option: option
    },
    beforeSend: function () {
    },
    success: function (response){

        //var price = data.split('~');
        if(response>0){
            $('.return-total-save').html(response);
            $('.payment-for-airport').prop('disabled', true );
        }

        jQuery.ajax({
            type: 'post',
            url: myAjax.ajaxurl,
            data: {
                action: 'get_sidebar_addons', // get Items for SB
            },
            beforeSend: function () {
            },
            success: function (data) {

                var $content = $('#acc-' + tripcount + ' .addon-list')
                $content.html(data);

                jQuery.ajax({
                    type: 'post',
                    url : myAjax.ajaxurl,
                    data: {
                        action: 'get_sidebar_total', // get total for SB
                    },
                    beforeSend: function () {
                    },
                    success: function (data) {

                        $('.spinner').html('');
                        $('.addon-list').show();
                        var $content = $('.total-main-price span');
                        $content.html(data);
                        $('#currency').trigger('change');

                        if (total > 0) {
                            alert("price has increased lets make a payment");
                            $('.payment-for-airport').prop('disabled', false);
                        }
                        if (data == 0) {
                            alert("price is 0");
                            $('.payment-for-airport').prop('disabled', true );
                        }

                    }
                });

            }
        });

    }
});
});


text:
Q: Rspec expect raise_error ObjectDisabledException throws NameError exception I have been using the watirspec-master files as examples to write my own RSpec tests. I recently encountered a situation in which I need to test for an exception thrown by a click or set event. I wrote the following test based on code in the checkbox_spec.rb file. I just changed the original from the lambda syntax to expect syntax.
el4 = browser.checkbox(:id, "category_8")
expect { el4.set }.to raise_error(ObjectDisabledException)

When executed, this code complains about an uninitialized constant ObjectDisabledException. The lambda syntax produces the same error. The full error response is below.
Failure/Error: lambda { el4.set }.should raise_error(ObjectDisabledException)
NameError:
   uninitialized constant RSpec::Core::ExampleGroup::Nested_1::Nested_2::Nested_2::Nested_1::Nested_1::Nested_1::ObjectDisabledException
Shared Example Group: "SF Categories tab" called from ./cf-manage/spec/_suite_sf_abusive_dev_spec.rb:135
# ./cf-manage/spec/_shared_sf_categories.rb:122:in `block (4 levels) in <top (required)>'

I have looked for some documentation on the raise_error method but came up empty. My first thought was that ObjectDisabledException was the wrong value to use. But that value is used repeatedly in the watirspec-master files. Any ideas what is wrong?

A: The ObjectDisabledException (and other Watir exceptions) are custom exceptions that are defined in the Watir::Exception module.
To use them in your specs, you need to specify the exceptions full name:
expect { el4.set }.to raise_error(Watir::Exception::ObjectDisabledException)

Alternatively, if you are doing a lot of exception testing, you should include the Watir::Exception module by adding (some point after requiring watir):
include Watir::Exception

You can see this in the watir-classic gem's implementation.rb and watir-webdriver's spec_helper.rb.


text:
Q: Meta: Why are there no custom class based views? It seems like such an obvious pattern that would be extremely useful, and help developers to conform to DRY. Eg, define a certain context that can be passed to each view. As far as I am aware, there is no way of doing this.

A: All the generic class-based views can be extended and their methods overridden, as defined in the documentation. For example, if you wanted extra context variables defined in addition to the ones the view defines itself, just add them using the get_context_data method:
class CustomDetailView(DetailView):
    model = MyModel
    def get_context_data(self, **kwargs):
        context = super(CustomDetailView, self).get_context_data(**kwargs)
        context.update({
            "foo": "bar",
            "baz": 999,
        })
        return context

Alternatively, you may want to define a certain mixin which would be included in every view as needed.


text:
Q: Jquery window.load not working $("#footer_privacy_policy").click(function(){

    window.location = "aboutus.php";

    $(window).load(function(){

              alert("window is loaded");

             $(".about").load("./about/privacy_policy.txt");
     });
});

So I loaded the page "aboutus.php" when I perform a click on the id,
but the alert never pops up.
Any one could help with this problem?

A: As soon as you set the url with window.location, the page is reloaded so the $(window).load() never happens as it is inside the click event callback.
Is there a reason you are using window.location instead of relying on the href attribute and linking to a page with the content already inside?

A: When you set window.location, the browser immediately navigates to that page. No further code on the current page is executed after that point. In fact, any event handlers or callbacks that you've set on the current page are wiped out.


text:
Q: Can't Install mysql- for Python / Django (Windows) I'm trying to download through pip the MySql-python connector as following, however im getting an  error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).
C:\Users\yschellekens.INTRANET\Desktop\Django project\general>pip install MySQL-
python
You are using pip version 7.1.0, however version 7.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.
Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python
  Complete output from command C:\Python33\python.exe -c "import setuptools;__fi
le__='c:\\users\\yschel~1.int\\appdata\\local\\temp\\pip-build-wc92bo\\MySQL-pyt
hon\\setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file_
_, 'exec'))" bdist_wheel -d c:\users\yschel~1.int\appdata\local\temp\tmpc71e54pi
p-wheel-:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win32-3.3
  copying _mysql_exceptions.py -> build\lib.win32-3.3
  creating build\lib.win32-3.3\MySQLdb
  copying MySQLdb\__init__.py -> build\lib.win32-3.3\MySQLdb
  copying MySQLdb\converters.py -> build\lib.win32-3.3\MySQLdb
  copying MySQLdb\connections.py -> build\lib.win32-3.3\MySQLdb
  copying MySQLdb\cursors.py -> build\lib.win32-3.3\MySQLdb
  copying MySQLdb\release.py -> build\lib.win32-3.3\MySQLdb
  copying MySQLdb\times.py -> build\lib.win32-3.3\MySQLdb
  creating build\lib.win32-3.3\MySQLdb\constants
  copying MySQLdb\constants\__init__.py -> build\lib.win32-3.3\MySQLdb\constants

  copying MySQLdb\constants\CR.py -> build\lib.win32-3.3\MySQLdb\constants
  copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.3\MySQLdb\constan
ts
  copying MySQLdb\constants\ER.py -> build\lib.win32-3.3\MySQLdb\constants
  copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.3\MySQLdb\constants
  copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.3\MySQLdb\constants
  copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.3\MySQLdb\constants
  running build_ext
  building '_mysql' extension
  error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).

  ----------------------------------------
  Failed building wheel for MySQL-python
Failed to build MySQL-python
Installing collected packages: MySQL-python
  Running setup.py install for MySQL-python
    Complete output from command C:\Python33\python.exe -c "import setuptools, t
okenize;__file__='c:\\users\\yschel~1.int\\appdata\\local\\temp\\pip-build-wc92b
o\\MySQL-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__
).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\ys
chel~1.int\appdata\local\temp\pip-ckxp_c-record\install-record.txt --single-vers
ion-externally-managed --compile:
    running install
    running build
    running build_py
    running build_ext
    building '_mysql' extension
    error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).

    ----------------------------------------
Command "C:\Python33\python.exe -c "import setuptools, tokenize;__file__='c:\\us
ers\\yschel~1.int\\appdata\\local\\temp\\pip-build-wc92bo\\MySQL-python\\setup.p
y';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n',
 '\n'), __file__, 'exec'))" install --record c:\users\yschel~1.int\appdata\local
\temp\pip-ckxp_c-record\install-record.txt --single-version-externally-managed -
-compile" failed with error code 1 in c:\users\yschel~1.int\appdata\local\temp\p
ip-build-wc92bo\MySQL-python

I found this wonderful question, which was very helpful:
Install mysql-python (Windows)
But im still running into issues, i know that i can download Visual Studio 2010 but i saw people who mention that its not necessary, and i prefer not to download it.
Here are my PYTHONPATH + PATH
PATH:
C:\Tools\OpenVPN\bin;C:\Python33\;C:\Program Files\Java\jdk1.7.0_15\bin;C:\Program Files\Java\jdk1.7.0_15\jre\bin\server;C:\Python33\Lib\site-packages;C:\Python33\Lib;C:\Python33\DLLs;C:\Python33\Lib\lib-tk;C:\Python33\Scripts;C:\Windows\System32;C:\Program Files\MySQL\MySQL Server 5.6\bin

PYTHONPATH
C:\Python33;C:\Python33\Lib\site-packages;C:\Python33\Lib;C:\Python33\DLLs;C:\Python33\Lib\lib-tk;C:\Python33\Scripts

Did i miss anything?
Any help in that would be great!

A: What you need is to have Microsoft Visual C++ 10.0 compiler (and as far as I remember version 10.0 doesn't necessarily mean Visual Studio 2010) installed on your system and vcvarsall.bat accessible from PATH environment variable.
However, it is usual for Windows to have enormous amount of blocking issues connected with compiling python extensions via pip (or it's just me?), so my usual workaround of the error you get is to google some Windows binary installers (mysql-python for 2.7 for instance) or .whl files. Both have python extensions compiled for a particular Python and architecture thus eliminating the need in having C or C++ compiler installed.


text:
Q: How to resolve Anypoint studion 7 errors? I have just installed anypoint studio 7.3.4
When i create a new mule project i got two default errors

I have dependency file as below
<dependencies>
        <dependency>
            <groupId>org.mule.connectors</groupId>
            <artifactId>mule-http-connector</artifactId>
            <version>1.3.2</version>
            <classifier>mule-plugin</classifier>
        </dependency>
        <dependency>
            <groupId>org.mule.connectors</groupId>
            <artifactId>mule-sockets-connector</artifactId>
            <version>1.1.2</version>
            <classifier>mule-plugin</classifier>
        </dependency>
<dependencies>

I'm completely struct, How to proceed ?
Please help

A: Go to Windows -> Preferences -> General -> Network Connections --> Change "Active Providers" from Native to Direct then restart the workspace.


text:
Q: Align left and right elements contained in a parent div I want the text Immunization coverage with a purple background to be on the left, while the text HIT and the switch are aligned to the right.
Also I would like the switch to be on the left of HIT.
How can I do?

#legendRectContainer {
 border: 1px solid black;
}

 /* The switch - the box around the slider */
.switch {
 position: relative;
 display: inline-block;
 width: 26px;
 height: 15px;
 background-color: lime;
 margin-top: 3.5px;
}

/* Hide default HTML checkbox */
.switch input {
 display: none;
}

/* The slider */
.slider {
 position: absolute;
 cursor: pointer;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background-color: #ccc;
 -webkit-transition: .4s;
 transition: .4s;
}

.slider:before {
 position: absolute;
 content: "";
 height: 11px;
 width: 11px;
 left: 2px;
 bottom: 2px;
 background-color: white;
 -webkit-transition: .4s;
 transition: .4s;
}

input:checked + .slider {
 background-color: #2196F3;
}

input:focus + .slider {
 box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
 -webkit-transform: translateX(11px);
 -ms-transform: translateX(11px);
 transform: translateX(11px);
}

/* Rounded sliders */
.slider.round {
 border-radius: 15px;
}

.slider.round:before {
 border-radius: 50%;
}

#legendRectRow {
 background-color: yellow;
 display: flex;
 align-items: center;
}
#titleLegendRectRow {
 float: left;
}
#switchTitleLegendRectRow {
 background-color: orange;
 float: right;
}
#switchLegendRectRow {
 text-align: right;
 float: right;
}
#switchAndHit {
 border: 1px solid green;
}

#svgLegendRectRect text {
 font-size: 7pt;
 font-weight: 100;
}

.legendLinAxis path, .legendLinAxis line {
 fill: none;
 stroke: none;
 shape-rendering: crispEdges;
}

.legendLinG .tick line {
 stroke: black;
 stroke-width: 1px;
}

.chartTitle {
 font-weight: 500;
 margin: 0;
 background-color: DeepPink;
 padding: 5px;
}

Immunization coverage

HIT

        <input type="checkbox" id='legendRectSwitchButton' autocomplete='off'>

A: The problem is you should not use floats along with flexbox:
#legendRectRow {
  background-color: yellow;
  display: block;
  overflow: hidden;
}

#legendRectContainer {
  border: 1px solid black;
}

/* The switch - the box around the slider */

.switch {
  position: relative;
  display: inline-block;
  width: 26px;
  height: 15px;
  background-color: lime;
  margin-top: 3.5px;
}

/* Hide default HTML checkbox */

.switch input {
  display: none;
}

/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 11px;
  width: 11px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #2196F3;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(11px);
  -ms-transform: translateX(11px);
  transform: translateX(11px);
}

/* Rounded sliders */

.slider.round {
  border-radius: 15px;
}

.slider.round:before {
  border-radius: 50%;
}

#legendRectRow {
  background-color: yellow;
  display: block;
  overflow: hidden;
}

#titleLegendRectRow {
  float: left;
}

#switchTitleLegendRectRow {
  background-color: orange;
  float: right;
  padding: 5px;
}

#switchLegendRectRow {
  text-align: right;
  float: right;
}

#switchAndHit {
  border: 1px solid green;
}

#svgLegendRectRect text {
  font-size: 7pt;
  font-weight: 100;
}

.legendLinAxis path,
.legendLinAxis line {
  fill: none;
  stroke: none;
  shape-rendering: crispEdges;
}

.legendLinG .tick line {
  stroke: black;
  stroke-width: 1px;
}

.chartTitle {
  font-weight: 500;
  margin: 0;
  background-color: DeepPink;
  padding: 5px;
}

Immunization coverage

HIT

        <input type="checkbox" id='legendRectSwitchButton' autocomplete='off'>

A: i just remove display:flex and just add overflow:auto to #legendRectRow id

#legendRectContainer {
 border: 1px solid black;
}

 /* The switch - the box around the slider */
.switch {
 position: relative;
 display: inline-block;
 width: 26px;
 height: 15px;
 background-color: lime;
 margin-top: 3.5px;
}

/* Hide default HTML checkbox */
.switch input {
 display: none;
}

/* The slider */
.slider {
 position: absolute;
 cursor: pointer;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background-color: #ccc;
 -webkit-transition: .4s;
 transition: .4s;
}

.slider:before {
 position: absolute;
 content: "";
 height: 11px;
 width: 11px;
 left: 2px;
 bottom: 2px;
 background-color: white;
 -webkit-transition: .4s;
 transition: .4s;
}

input:checked + .slider {
 background-color: #2196F3;
}

input:focus + .slider {
 box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
 -webkit-transform: translateX(11px);
 -ms-transform: translateX(11px);
 transform: translateX(11px);
}

/* Rounded sliders */
.slider.round {
 border-radius: 15px;
}

.slider.round:before {
 border-radius: 50%;
}

#legendRectRow {
 background-color: yellow;
 overflow:auto;
 align-items: center;
}
#titleLegendRectRow {
 float: left;
}
#switchTitleLegendRectRow {
 background-color: orange;
 float: right;
}
#switchLegendRectRow {
 text-align: right;
 float: right;
}
#switchAndHit {
 border: 1px solid green;
}

#svgLegendRectRect text {
 font-size: 7pt;
 font-weight: 100;
}

.legendLinAxis path, .legendLinAxis line {
 fill: none;
 stroke: none;
 shape-rendering: crispEdges;
}

.legendLinG .tick line {
 stroke: black;
 stroke-width: 1px;
}

.chartTitle {
 font-weight: 500;
 margin: 0;
 background-color: DeepPink;
 padding: 5px;
}

Immunization coverage

HIT

        <input type="checkbox" id='legendRectSwitchButton' autocomplete='off'>

 tell me if any other question


text:
Q: How do I set a common header component for all my pages in IONIC 4? I want to set a common component as the header in all my ionic pages (Ionic4). What is the proper way to do it?

A: create a custom component.
Run: ionic g component header
command generate a component with this content
header.component.html
header.component.scss
header.component.ts

Inside header.component.html put your header content, for example:
<ion-toolbar>
  <ion-buttons slot="start">
    <ion-back-button></ion-back-button>
  </ion-buttons>
  <ion-title class="ion-text-center">title</ion-title>
</ion-toolbar>

Inside every html page of your app insert:
<ion-header>
  <app-header></app-header>
</ion-header>

<ion-content>

</ion-content>

Remeber to add Component's Module inside app.module.ts or page.module.ts if using lazy loading

A: Improving parrycima answer:
<ion-toolbar>
  <ion-buttons slot="start">
   <ion-back-button></ion-back-button>
  </ion-buttons>
  <ion-title class="ion-text-center">{{title}}</ion-title>
</ion-toolbar>

So you can change title on every page you import header.
In header.component.ts:
@Input() public title: string = "";

So title is an input you can pass when you use app-header inside your html page:
<app-header title="CurrenPageTitle"></app-header>

The best aprouch that works for me is to create the file components.module.ts in src/app with this code:
@NgModule({
    declarations: [HeaderComponent],
    imports: [IonicModule],
    exports: [HeaderComponent]
})

Then in app.module.ts:
entryComponents: [HeaderComponent],
imports: [
    ....,
    ComponentsModule,
    ...
]

On every html page you want to add this custom header you need to add ComponentsModule to imports of yourhtmlpage.modules.ts:
imports: [
        ....,
        ComponentsModule,
        ...
    ]

A: On your app.component.html you can add header component like this:
<app-header></app-header>
<main>
<router-outlet></router-outlet>
</main>


text:
Q: Javascript trigger button by pressing Enter without attaching it to the FormID What I have
I have a simple view in my .cshtml file which uses the form
                      //actionName  //controller //method         //htmlAttributes
@using (Html.BeginForm("TableName", "Data",      FormMethod.Post, new { id = "frmName" }))
{
    //combobox with id
    //button with id
}

I was able to implement triggering the button with Enter key by using answers from this thread as a basis.
$('#frmName').on('keypress', function (e) {
  sender = event || window.event;
  var hasfocus = $('#btnGo').is(':focus') || false;
  if (sender.keyCode == 13 && !hasfocus) {
     e.preventDefault();
     $('#btnGo').trigger('click');
  }
});

In above scenario, everything works as intended.
What I need
I recently found that this particular view will not be using the form. As a result, I wanted to adapt my javascript code to separate it from the frmName. However, it proved to be trickier than I anticipated.
What I tried
I tried replacing the formID with the button ID
$('#btnGo').on('keypress', function (e) {
  sender = event || window.event;
  var hasfocus = $('#btnGo').is(':focus') || false;
  if (sender.keyCode == 13 && !hasfocus) {
     e.preventDefault();
     $('#btnGo').trigger('click');
  }
});

I tried implementing something similar to accepted answer of the thread mentioned above.
document.getElementById("cbID")
.addEventListener("keyup", function (event) {
   event.preventDefault();
   if (event.keyCode == 13 || $('#btnGo').is(':focus')) {
      document.getElementById("btnGo").click();
   }
});

In both cases, when I select a value from the combobox and press enter key, an unexpected error pops up

Can you please point me in the right direction how I can attach Enter to button while separating it from my FormID? (Preferably, without altering my initial javascript code too much, but I'm flexible to suggestions)
Edit
After testing in different browsers(IE, Chrome, FF) for debugging purposes, I got the following results:

*

*Initial scenario works as intended in all 3 browsers

*My attempts inside Chrome leads to an error inside the browser instead of intended error checker

*My attempts inside FF leads so asking for my credentials, which I am hesitant to give

Honestly, I am more interested now in why pressing Enter leads me to some kind of file saving and options provided in my picture. The question itself is still relevant though.