text:
Q: Out of Memory issue while using Picasso and Recycler View I get this error:
java.lang.OutOfMemoryError: Failed to allocate a 15052812 byte allocation with 12653776 free bytes and 12MB until OOM

This is my Adapter:
public class ExploreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Obj> exploreList;
    private Context context;
    private Typeface typeFace, italicTypeface, boldTypeface;
    private DatabaseHelper db;

    private Obj featureProject;
    private boolean exploreReturned50;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView projectTitle;
        public ImageView projectPicture;

        public MyViewHolder(View view) {
            super(view);
            projectTitle = (TextView) view.findViewById(R.id.exploreProjectTitle);
             projectPicture = (ImageView) view.findViewById(R.id.exploreProjectPicture);

        }

    }

    private static OnGrabMoreListener mOnGrabMoreListener;

    public interface OnGrabMoreListener {
        void onGrabMore(int position);
    }

    public void setOnGrabMoreListener(OnGrabMoreListener onGrabMoreListener) {
        mOnGrabMoreListener = onGrabMoreListener;
    }

    public class MyFeatureViewHolder extends RecyclerView.ViewHolder {
        public TextView featureProjectTitle;
        public ImageView featureProjectImage;

        public MyFeatureViewHolder(View view) {
            super(view);

            featureProjectImage = (ImageView) view.findViewById(R.id.featureProjectImage);
            featureProjectTitle = (TextView) view.findViewById(R.id.featureProjectTitle);
           }

    }

    public ExploreAdapter(Context mContext, Obj featureProj, List<Obj> explores, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
        context = mContext;
        exploreList = explores;
        typeFace = myTypeface;
        italicTypeface = myTypefaceItalic;
        boldTypeface = myTypefaceBold;
        //to set up grabmore
        if(exploreList.size() == 50 || exploreList.size() == 51) {
            exploreReturned50 = true;
        }
        db = new DatabaseHelper(mContext);
        featureProject = featureProj;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType){
            case 0:
                return new MyFeatureViewHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.feature_item, parent, false));  }
         return new MyViewHolder(LayoutInflater.from(parent.getContext())
                 .inflate(R.layout.explore_item, parent, false));

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        int pos = getItemViewType(position);

        if(pos == 0) {

            MyFeatureViewHolder featureViewHolder = (MyFeatureViewHolder) holder;

           featureViewHolder.featureProjectTitle.setTypeface(boldTypeface);

            featureViewHolder.featureProjectTitle.setText(featureProject.getProjectTitle());

             String createImagePath = Constants.PROJECT_IMAGE + featureProject.getDefaultPicId();
            Picasso.with(context).load(createImagePath).placeholder(R.drawable.default_user).into(featureViewHolder.featureProjectImage);

        } else {

            MyViewHolder myViewHolder = (MyViewHolder) holder;
            Obj proj = exploreList.get(position);

            myViewHolder.projectTitle.setTypeface(boldTypeface);

            myViewHolder.projectTitle.setText(proj.getProjectTitle());

            String createImagePath = Constants.PROJECT_IMAGE + proj.getDefaultPicId();
            Picasso.with(context).load(createImagePath).placeholder(R.drawable.default_user).into(myViewHolder.projectPicture);

        }

            mOnGrabMoreListener.onGrabMore(position);
        if (position > (exploreList.size() - 20) && exploreReturned50) {
            grabMoreFromExplorer();
        }

    }

    private void grabMoreFromExplorer() {

        Log.d(Constants.DEBUG, "GRAB MORE");

        Call<List<ObjResp>> call = ApiManager.getAsyncApi().exploreProjects(exploreList.size());
            call.enqueue(new Callback<List<ObjResp>>() {
                @Override
                public void onResponse(Call<List<ObjResp>> call, Response<List<ObjResp>> response) {
                    storeInDbNewExplore(response);
                }

                @Override
                public void onFailure(Call<List<ObjResp>> call, Throwable t) {

                    Log.d(Constants.DEBUG, "There has been an error retrieving explores project " + t);
                }
            });

    }

    private void storeInDbNewExplore(Response<List<ObjResp>> response) {
        Log.d(Constants.DEBUG, "STORING explores ");
        List<ObjResp> projectsApi = response.body();

        for(ObjResp proj: projectsApi) {
            String projectId, projectTitle, defaultPicId, isType, isChanged;

            projectId = proj.get_id();
            projectTitle = proj.getTitle();
            defaultPicId = proj.getDefaultPicId();

            isType = 1;
            isChanged = 0;
            Obj newDbExploreProj = new Obj(projectId, projectTitle,  defaultPicId, isChanged, isType);

            db.createProject(newDbExploreProj);
        }
        //TODO sort explores by dateAdded
        List<Obj> newExploreList = db.getProjects(1, 0);
        exploreList.addAll(newExploreList);
    }

    //Plus one for feature project
    @Override
    public int getItemCount() {

      //  Log.d(Constants.DEBUG, "THE EXPLORE LIST SIZE IS "  + exploreList.size() );
        return exploreList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

}

This is my Recycler View Call in my activity:
exploreAdapter = new ExploreAdapter(this, featureProject, exploreProjectsList, TypeFaceProvider.getTypeFace(this, 0),
                TypeFaceProvider.getTypeFace(this, 1), TypeFaceProvider.getTypeFace(this, 2));
        GridLayoutManager mLayoutManager = new GridLayoutManager(this, 2);

        //used for setting spotlight item first
        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if(exploreAdapter.getItemViewType(position) == 0) {
                    return 2;
                } else {
                    return 1;
                }

            }
        });
        exploreRecyclerview.setLayoutManager(mLayoutManager);
        exploreRecyclerview.setItemAnimator(new DefaultItemAnimator());

        exploreRecyclerview.setAdapter(exploreAdapter);
        exploreRecyclerview.addOnItemTouchListener(new RecyclerClicks.RecyclerTouchListener(this, exploreRecyclerview, new RecyclerClicks.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                DatabaseProject proj = exploreProjectsList.get(position);
                Toast.makeText(getApplicationContext(), proj.getProjectTitle() + " is selected!", Toast.LENGTH_SHORT).show();
                takeToProjectProfile(exploreProjectsList.get(position));
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        exploreAdapter.notifyDataSetChanged();

A: CRASH:
As your stacktrace says:

"java.lang.OutOfMemoryError: Failed to allocate a 15052812 byte
  allocation with 12653776 free bytes and 12MB until OOM"

you try to display a huge bitmap on your view. Your phone doesn't like it.
Two solutions:

*

*reduce the dimensions of your image, use a smaller image... and
retry!

*or set android:largeHeap="true" in your Manifest, in your application
tags. It will increase your heap size and avoid the OutOfMemory
error, but your application will probably lag.

A: Just a quick update in case someone has a similar problem: replacing Picasso with COIL has solved like magic my OOM issue in a low-capacity smartphone. The memory usage dropped almost 50% in my case. Here's the link FYI: https://github.com/coil-kt/coil
It's worth mentioning that I'm using Kotlin.
Happy coding! ;)


text:
Q: Borel sets used in Model Theory In Lemma 4.4.13 (page 161) of D.Marker- Model Theory book it is proved that  $D(F,T)$ (the set of all possible F-diagrams of models of T) is a  Borel set.
Can someone explain to me the proof given a little bit more detailed?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle a random popup while executing Selenium Script? I'm executing a Selenium script, and randomly a popup appears which is about a survey one. I'm not sure when this would appear and the scripts are failing because of this. So please help me if anyone experienced the similar behavior and how did they resolve it. Thanks for your help.

A: Typically these are there to make it harder to navigate through the website through automation. That said, it may or may not be possible to cirumnavigate it. It is hard to answer without the webpage. I would suggest looking for what is causing this popup to be triggered and try to deactivate it by sending Javascript through Selenium


text:
Q: 3D Gaussian Process with different kernels per dimension I am trying to implement a 3D Gaussian Process in Python.  The output of the function depends on two axes, call them x and y, that have different mean functions and different kernel functions.  In practice, I would just take:
K(x, x') * K(y, y')
But I do not know how or if I can implement that in sklearn.  I have tried reviewing the docs but I haven't seen how this could be handled; all combinations of kernel functions I have seen are of the form k1(x, x')*k2(x,x').
Is this solveable in sklearn?  Or GPy?  Or Pymc3? Or....
Thank you in advance.

A: If the two outputs, x, y, are truly independent, which the factorization
K(x_i, x_j) * K(y_i, y_j)

implies, then one could fit two separate models, i.e., one for each of them.


text:
Q: Get total disk usage for user in GitLab (via API) I'm trying to find a way to get the total disk usage for all of a user's projects via GitLab API. Note that this would only be for projects the user has created - not projects they are members of, etc.
I can do this by going through all of a user's projects and summing the repository size, but that can be slow, especially if the user has more than 100 projects and you have to paginate. Curious if there's some method I'm missing.
Thanks!

A: Only a graphQL query would be faster than the regular GitLab API.
GitHub has one.
GitLab announced its intention to support one.
The 10.0+ version should now support GraphQL as a POC.
But it won't be available before 11.x in 2018 Q2.


text:
Q: Como criar um emulador sem utilizar a ide? Eu preciso emular o android na minha máquina, mas não queria utilizar uma máquina virtual porque utilizaria muitos recursos, queria usar o sdk tools do android studio, mas também não queria instalar o android studio para isso.
Então eu baixei o sdk tools no site do android studio e tentei rodar, nas versões antigas tinha uma gui e era bem simples para criar e rodar, mas na versão atual não tem, é tudo via comando, tentei ate executar alguns mas nenhum foi bem sucedido.
Executei isso:
C:\Users\Futurotec\Downloads\sdk-tools-windows-3859397\tools>android
**************************************************************************
The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools\bin\sdkmanager.bat
and tools\bin\avdmanager.bat
**************************************************************************

Invalid or unsupported command ""

Supported commands are:
android list target
android list avd
android list device
android create avd
android move avd
android delete avd
android list sdk
android update sdk

Então tentei rodar o comando android create avd:
C:\Users\Futurotec\Downloads\sdk-tools-windows-3859397\tools>android create avd
**************************************************************************
The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools\bin\sdkmanager.bat
and tools\bin\avdmanager.bat
**************************************************************************

Invoking "C:\Users\Futurotec\Downloads\sdk-tools-windows-3859397\tools\bin\avdmanager" create avd

Error: The parameters --package, --name must be defined for action 'create avd'

Usage:
      avdmanager [global options] create avd [action options]
      Global options:
  -s --silent     : Silent mode, shows errors only.
  -v --verbose    : Verbose mode, shows errors, warnings and all messages.
     --clear-cache: Clear the SDK Manager repository manifest cache.
  -h --help       : Help on a specific command.

Action "create avd":
  Creates a new Android Virtual Device.
Options:
  -a --snapshot: Place a snapshots file in the AVD, to enable persistence.
  -c --sdcard  : Path to a shared SD card image, or size of a new sdcard for
                 the new AVD.
  -g --tag     : The sys-img tag to use for the AVD. The default is to
                 auto-select if the platform has only one tag for its system
                 images.
  -p --path    : Directory where the new AVD will be created.
  -k --package : Package path of the system image for this AVD (e.g.
                 'system-images;android-19;google_apis;x86'). [required]
  -n --name    : Name of the new AVD. [required]
  -f --force   : Forces creation (overwrites an existing AVD)
  -b --abi     : The ABI to use for the AVD. The default is to auto-select the
                 ABI if the platform has only one ABI for its system images.
  -d --device  : The optional device definition to use. Can be a device index
                 or id.

Tentei varias parâmetros, mas nenhum criava o emulador.
Tentei utilizar também o comando avdmanager direto, mas apresentou as mesmas mensagens.
Em todas as minhas pesquisas só encontrava soluções que era necessário abrir o android studio ou que os comandos eram das versões antiga.

A: TL;DR
Um exemplo de comando válido para criar um avd:
avdmanager create avd -n "Meu-Emulador" -k "system-images;android-26;google_apis_playstore;x86"

avdmanager
O programa utilizado para criar AVDs é o avdmanager. Ele está localizado em sdk/tools/bin/avdmanager. O android também funcionaria, mas ele acaba utilizando o avdmanager por baixo.
Para a criação de um AVD dois parâmetros são obrigatórios:

*

*-n ou --name para nomear o AVD

*-k ou --package para indicar qual imagem de sistema será utilizada

Imagens de sistema
Para a criação de AVDs é obrigatório indicar uma imagem de sistema. Para listar as imagens instaladas, utilize o mesmo comando sem o parâmetro -k:
avdmanager create avd -n "Meu-Emulador"
Se nenhuma imagem for listada, significa que nenhuma foi instalada. A instalação de novas imagens pode ser feita através da utilização do sdkmanager.
Para listar os pacotes disponíveis:
sdkmanager --list --verbose

Nota: o --verbose foi utilizado para não truncar os nomes dos pacotes.
Para instalar uma imagem:
sdkmanager "system-images;android-26;google_apis;x86"

Executando o avd no emulador
Para iniciar o emulador, utilize o programa emulator, localizado em sdk/tools/emulator, informando o nome do AVD a ser executado:
emulator -avd "Meu-Emulador"


text:
Q: The mystery of the disappearing sampi I define a command \msampi - to display the archaic Greek letter sampi - by including the line
\DeclareMathSymbol{\msampi}{\mathord}{extraitalic}{166}

in the preamble. (Yes, I am specifying polutonikogreek in babel.) This works fine in the office, but I've just realized that, when I compile the file at home, the letter sampi is omitted every time from the resulting pdf. (No error message - there is simply nothing in place of the sampi.) What may be the issue? How to fix it?
\documentclass{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[greek,english]{babel}
\languageattribute{greek}{polutoniko}
\selectlanguage{english}
\usepackage[utf8]{inputenc}
\DeclareSymbolFont{extraitalic}      {U}{zavm}{m}{it}
\DeclareMathSymbol{\mSampi}{\mathord}{extraitalic}{165}
\DeclareMathSymbol{\msampi}{\mathord}{extraitalic}{166}
\begin{document}
Hi, $\msampi$! And hi to you, $\gamma$!
\end{document}

A: If you do not have uzavm.fd from the arev font package setup installed (typically via tlmgr or miktex update) then (a) latex substitutes the default family and then (b) warns (in the log, not to the terminal) that that font has no character in that position:
LaTeX Font Info:    Try loading font information for U+zavm on input line 11.
LaTeX Font Info:    No file Uzavm.fd. on input line 11.

LaTeX Font Warning: Font shape `U/zavm/m/it' undefined
(Font)              using `U/cmr/m/n' instead on input line 11.

Missing character: There is no ¦ in font cmr10!

If the fd file (and associated fonts) are there then the log will show:
LaTeX Font Info:    Try loading font information for U+zavm on input line 11.

(/usr/local/texlive/2016/texmf-dist/tex/latex/arev/uzavm.fd
File: uzavm.fd 2006/05/30 Fontinst v1.929 font definitions for U/zavm.

the files could be installed in texlive using
tlmgr install arev

if they are not already installed.

A: Here is an example:
\documentclass{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[greek,english]{babel}
\languageattribute{greek}{polutoniko}
\selectlanguage{english}
\usepackage[utf8]{inputenc}
\DeclareSymbolFont{extraitalic}      {U}{zavm}{m}{it}
\DeclareMathSymbol{\mSampi}{\mathord}{extraitalic}{165}
\DeclareMathSymbol{\msampi}{\mathord}{extraitalic}{166}
\begin{document}
Hi, $\msampi$! And hi to you, $\gamma$!
\end{document}


text:
Q: Getting input date from the user in python using datetime.datetime I am trying to get input date from the user and store it in the form of
dt_start = dt.datetime(2006, 1, 1)

I am currently doing this:
i = str(raw_input('date'))
dt_start = dt.datetime(i)

But it throws an error:
Traceback (most recent call last):
File "C:/.../sim.py", line 18, in <module>
    dt_start = dt.datetime(i)
TypeError: an integer is required

Thanks for the help guys!

A: If you are using the %Y, %m, %d format, you can try with datetime.strptime:
from datetime import datetime

i = str(raw_input('date'))
try:
    dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
    print "Incorrect format"

A: datetime() only takes int as parameter.
Try this:
from datetime import datetime

date_entry = input('Enter a date (i.e. 2017,7,1)')
year, month, day = map(int, date_entry.split(','))
date = datetime(year, month, day)


text:
Q: No server response for AJAX request when accessing site via Google Translate I've hit a snag with my site when it is run through Google Translate: my server does not respond at all to my browser for an AJAX request, not a single header.
The request URL looks like:
https://translate.google.com/translate?depth=1&hl=en&rurl=translate.google.com&sl=en&tl=sq&u=https://www.example.com/
Google Translate sends an origin request header with the value https://translate.googleusercontent.com.
I've made numerous attempts, here are essentially the header responses I've attempted to setup via PHP:

*

*header('Access-Control-Allow-Origin: https://translate.googleusercontent.com');

*header('Access-Control-Allow-Origin: *');

*header('Access-Control-Allow-Headers: X-Requested-With');

*header('Access-Control-Allow-Origin: translate.googleusercontent.com');

*header('Access-Control-Allow-Origin: googleusercontent.com');

*header('Access-Control-Allow-Origin: google.com');
Obviously the * value is least secure but nothing working calls for more drastic experimentation. I also (without success) added this to the AJAX request:
//This is now removed due to research revealing this is why Chrome was making the request as
//an HTTP OPTIONS method.
if (window.location.host!=domain) {xhr.setRequestHeader('Access-Control-Allow-Origin','*');}

I've set PHP to email me a dump of $_SERVER via Google Translate requests:
Array
(
 [GATEWAY_INTERFACE] => CGI/1.1
 [HTTPS] => on
 [HTTP_ACCEPT] => *
 [HTTP_ACCEPT_CHARSET] => utf-8,*
 [HTTP_ACCEPT_ENCODING] => gzip,deflate,br
 [HTTP_CONNECTION] => Keep-alive
 [HTTP_HOST] => www.example.com
 [HTTP_USER_AGENT] => ***
 [HTTP_VIA] => 1.0 translate.google.com TWSFE/0.9
 [HTTP_X_FORWARDED_FOR] => [my IP], [my IP...again]
 [PATH] => /bin:***
 [PHPRC] => ***
 [QUERY_STRING] => query=index.php
 [REDIRECT_STATUS] => 200
 [REMOTE_ADDR] => 66.102.8.203 [Google Proxy]
 [REMOTE_PORT] => ***
 [REQUEST_METHOD] => GET
 [REQUEST_URI] => /
 [SCRIPT_FILENAME] => index.php
 [SCRIPT_NAME] => /index.php
 [SERVER_ADDR] => ***
 [SERVER_ADMIN] => ***
 [SERVER_NAME] => www.example.com
 [SERVER_PORT] => 443
 [SERVER_PROTOCOL] => HTTP/1.1
 [SERVER_SIGNATURE] =>
 [SERVER_SOFTWARE] => Apache
 [SSL_TLS_SNI] => www.example.com
 [UNIQUE_ID] => ***
 [PHP_SELF] => /index.php
 [REQUEST_TIME_FLOAT] => ***
 [REQUEST_TIME] => ***
)

Firefox makes the request correctly using the HTTP POST method. For some reason Chrome makes the AJAX request using the HTTP OPTION method...wait what? That isn't how my site is coded.
I suspect that the server may be responding to Google's initial request server instead of my browser though I'm not sure. The $_SERVER does include a $_SERVER['HTTP_X_FORWARDED_FOR'] with my IP address listed twice though I'm not sure how all that works out. I'm guessing this is a bit more complicated than a normal CORS request. How can I get my server to respond to my browser?


text:
Q: Load balancing options with rabbit mq What are the options available with rabbitMQ for load balancing.
I have already gone throght the article http://insidethecpu.com/2014/11/17/load-balancing-a-rabbitmq-cluster/ . Is there any alternative way that can be done? We have only single queue which is mirrored b/w two nodes and we need to load balance b/w them

A: AMQP guarantees message ordering. That's why a queue has a single master and many slaves, and all messages need to go through the master instance.
If you don't need this ordering, your best solution is to not cluster RabbitMQ nodes. Just run them independently and load-balance your clients in a round-robin manner.


text:
Q: Vba from excel to access I am quite new to coding and I was given this project that is beyond my scope, but I do not have the option to turn it down. I am desperate and would appreciate any help I can get. I did some preliminary searching but either haven't found anything similar or I just don't comprehend the code. Thank you in advance!
So I have a set of data on a spreadsheet with 26 columns. Each one has a category but I am only interested in 5 being: the 23 column(Name, 2 column(Years), 3 column( date), column 8( value) and column 11 (value). I just need to have a button where it would write that information into the Access database, so that everyday I would be able to record that information. The code would also be able to loop and make sure that there will be no duplicates of information. Please assist with the coding!

A: Just create a query with those 4 fields and export the query.  :)
As for the dupes, just turn on the Macro recorder and click the Data tab then click 'Remove Duplicates'.  That will give you the VBA code that you need.  Or, if you want to handle the dupes, you can do that in Access before you do the export.  In Access click Create > Query Wizard > Find Duplicates Query Wizard.  Find the duplicates and eliminate them.

A: You can accomplish this with MS Access without the VBA.
In Access you'll need to Link an Access table to your Excel datasource. Next you'll need to create an Append Query to append the records in the Linked Excel table to the target Access table.  You should set the criteria of the append query to select the records of the Linked Excel table that are not in the target table.
If you can't manage to setup the criteria then append all the records and Delete the Duplicate records.


text:
Q: Segmentation fault error - C programming I am receiving a Segmentation Fault error when I run this program. To summarize, the program reads in multiple data files (129 of them). Each file contains information about a specific name. The information includes how many people were named a specific name in a specific year and the gender. For now, I am trying to store each name in a linked list. Whenever I read in more than about 4 data files, I get the Segmentation Fault error. I have written this program in Java, which was much simpler. If anybody could simply point me in the right direction, as I am almost certain this has to do with memory allocation, but I cannot seem to solve this myself. Thank you.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
using namespace std;

//typedef struct Node NodeStruct;
struct Node {
  char *namePtr;
  Node *nextPtr;
};

int main() {
  // Declare variables
  Node *headPtr = NULL;
  Node *tempPtr;
  Node *currentPtr;

  // Variables for reading in a file
  FILE *filePtr;
  char fileName[20];
  int i;
  int nameLength;
  char inputLine[81];

  cout << "Reading from data files, please be patient...\n";

  // Loop through files
  for (i = 1880; i <= 2009; i++) {
    sprintf(fileName, "data/yob%d.txt", i);
    filePtr = fopen(fileName, "r");    // Open the file
    // Check to ensure file was opened
    if(filePtr == NULL) {
      cout << "Error opening input file...check location of data files\n";
      exit(-1);   // Exit program
    } // End if statement

    while (fscanf(filePtr, "%s", inputLine) != EOF) {

      // Create a node
      tempPtr = (Node *) malloc(sizeof(Node));
      tempPtr->nextPtr = NULL;

      // Set the head pointer of first node
      if (headPtr == NULL) {
    headPtr = tempPtr;
    currentPtr = tempPtr;
      } // End if statement

      // Link the list
      currentPtr->nextPtr = tempPtr;
      currentPtr = currentPtr->nextPtr;

      // Create pointer variables
      char *startPtr = inputLine;
      char *endPtr = NULL;

      endPtr = strchr(inputLine, ',');   // Point to end of name
      int length = endPtr - inputLine;      // Calculate length
      // Create space for the name
      tempPtr->namePtr = (char *) malloc(sizeof(length + 1));
      strncpy(tempPtr->namePtr, startPtr, length); // Store pointer to name
      //      cout << tempPtr->namePtr << endl;

    }
  } // End of for (i = 1880...
  cout << "Done reading from data files...\n";
} // End of main function

A: Surely
tempPtr->namePtr = (char *) malloc(sizeof(length + 1));

should be
tempPtr->namePtr = (char *) malloc(length + 1);

since you copy that many characters to the string.  sizeof (length + 1) would evaluate to four on a 32-bit machine (eight on 64-bit).  Not enough memory was being allocated, so the strncpy which followed this was overwriting memory not belonging to you.

A: Rather than find your bug, let's try to teach you some practical lessons. Here are my C++ rules for C programmers:
1) Don't use pointers to track your data. The standard containers work just fine for that.
2) Don't use pointers to manage your strings. The standard string type works just fine for that.
3) Don't use pointers for anything else, until you need to learn how polymorphism works.
4) Don't use malloc at all. Ever.
5) Don't use new, hardly at all.
The neat thing about not using pointers (or arrays), is that you will never make pointer bugs. No more buffer overflows, no more segmentation faults. Joy!
Here is my translation of your program into idiomatic C++. Because I let std::list do all of the list management, all of the silly headPtr, nextPtr, etc, goes away. Because I let std::string do all of the string management, I don't need to malloc(strlen()) (or fix my bug and malloc(strlen()+1). Because I use the RAII idiom, I don't have to worry about closing my files.
It all just works.
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <cstdlib>
#include <sstream>

using std::string;
using std::cout;
using std::list;
using std::ifstream;
using std::stringstream;

int main() {
  // Declare variables
  list<string> list;

  cout << "Reading from data files, please be patient...\n";

  // Loop through files
  for (int i = 1880; i <= 2009; i++) {
    stringstream fileName;
    fileName << "data/yob" << i << ".txt";
    ifstream filePtr(fileName.str().c_str());

    if(!filePtr.is_open()) {
      cout << "Error opening input file: " << fileName.str() << " ...check location of data files\n";
      exit(-1);   // Exit program
    }

    string inputLine;
    while (filePtr >> inputLine) {
      list.push_back(inputLine);
    }
  } // End of for (i = 1880...
  cout << "Done reading from data files...\n";
} // End of main function

A: I know this one is already answered, but you should also be in the habit of closing your files.  For you with something like fclose(filePtr).  By the way if you learn how to use std::ifstream then you don't have to close, it auto closes when the std::ifstream goes out of scope.


text:
Q: Backpropagation derivation- chain rule expansion I'm trying to write out the calculations for backpropagation but I'm having trouble getting the final answer- I believe I should be getting something similar to $-(y - \sigma(w \cdot x + b))\sigma'(w \cdot x + b)$. I have checked questions related to backpropagation on the site, but my question specifically deals with expansion of the terms via the chain rule.
I have some cost function $C$, and I'm using mean squared error for it, therefore: $C = \frac{1}{2n}\sum_{i=0}^n(y_i-\hat{y_i})^2$
I'm using sigmoid activation for my neurons, therefore values for layer activation are given by: $a = \sigma(w \cdot x + b)$, where $w$ and $x$ are matrices that can be multiplied together.
To make the network "learn", the total cost/error of the network needs to be minimized, so weights $w$ and biases $b$ need to be updated for each neuron in the network using gradient descent. However, gradient descent requires the derivative of the cost function to be calculated. This means the function has to be derived with respect to the weights and biases. I've done the following steps so far for weights:
$C = \frac{1}{2n}\sum_{i=0}^n(y_i-\hat{y_i})^2$
$\frac{\partial C}{\partial w} = \frac{1}{2n}\sum_{i=0}^n\frac{\partial}{\partial w}(y_i-\hat{y_i})^2$
$= \frac{1}{n}\sum_{i=0}^n(y_i-\hat{y_i})\frac{\partial}{\partial w}(y_i-\hat{y_i})$
$= \frac{1}{n}\sum_{i=0}^n(y_i-\hat{y_i})(\frac{\partial}{\partial w}y_i-\frac{\partial}{\partial w}\hat{y_i})$
$= \frac{1}{n}\sum_{i=0}^n(y_i-\hat{y_i})(-\frac{\partial}{\partial w}\hat{y_i})$
$= -\frac{1}{n}\sum_{i=0}^n(y_i-\hat{y_i})(\frac{\partial}{\partial w}\hat{y_i})$
This is where I get stuck. I understand that $\frac{\partial}{\partial w}\hat{y_i}$ can be expanded to $\frac{\partial C}{\partial a}\frac{\partial a}{\partial net}\frac{\partial net}{\partial w}$, and that $\frac{\partial a}{\partial net}$ will expand to $\sigma(w \cdot x + b)(1 - \sigma'(w \cdot x + b)) \frac{\partial a}{\partial net} (w \cdot x  + b)$, but how do I complete the final derivations/substitutions and obtain $-(y - \sigma(w \cdot x + b))\sigma'(w \cdot x + b)$? Would this answer also apply to the derivative with respect to the bias?


text:
Q: Seaborn (violinplot) too many y-axis values I have a couple of subplots and the data are probabilities, so should (and do) range between 0 and 1. When I plot them with a violinplot the y-axis of ax[0] extends above 1 (see pic). I know this is just because of the distribution kernel that the violinplot makes, but still it looks bad and I want the y-axes of these 2 plots to be the same. I have tried set_ylim on the left plot, but then I can't get the values (or look) to be the same as the plot on the right. Any ideas?

A: When creating your subplots, set the sharey parameter to True so that both plots share the same limits for the vertical axis.

[EDIT]
Since you have already tried setting sharey to True, I suggest getting the lower and upper limits ymin and ymax from the left hand side figure and passing them as arguments in set_ylim() for the right hand side figure.
1) Create your subplots:
fig, ax1 = plt.subplots(1,2, figsize = (5, 5), dpi=100)
2) Create left hand side figure here: ax[0].plot(...)
3) Get the axes limits using the get_ylim() method as detailed here: ymin, ymax = ax[0].get_ylim()
4) Create right hand side figure: ax[1].plot(...)
5) Set the axes limits of this new figure: ax[1].set_ylim(bottom=ymin, top=ymax)

A: I don't have subplots, but I do have probabilities, and this visual extension beyond 1.0 was frustrating to me.
If you add 'cut=0' to the sns.violinplot() call, it will truncate the kernel at the range of your data exactly.
I found the answer here:
How to better fit seaborn violinplots?


text:
Q: Modify JSON object taking value from table I am populating the html table using a JSON object using the following code -
html -
<input type="button" value="Generate Table" id="btn" />

JS -
$('#btn').click(function () {

    var obj = [{ id: 1, name: "bunny", city: "nyc",userinput:"",iscancelled:"" }, { id: 2, name: "sunny", city: "LA",userinput:"",iscancelled:"" }, { id: 3, name: "chubby", city: "PA",userinput:"",iscancelled:"" }
    , { id: 4, name: "punny", city: "DC",userinput:"",iscancelled:"" }, { id: 5, name: "money", city: "Pen",userinput:"",iscancelled:"" }];

    alert(JSON.stringify(obj));
    var table = document.createElement("table");
    table.border = "1";
    var columnCount = obj[0].length;

    var row = table.insertRow(-1);
    for (var i = 0; i < columnCount; i++) {
        var headerCell = document.createElement("th");
        headerCell.innerHTML = obj[0][i];
        row.appendChild(headerCell);
    }

    $.each(obj, function (i, obj) {
        row = '
<input type="checkbox" value=' + obj.id + '>	' + obj.id + '	' + obj.name + '	'
            + obj.city + '	<input type="text" id="address" >
';

        table.append(row);
    });

    var dvTable = document.getElementById("dvTable");
    dvTable.innerHTML = "";
    dvTable.appendChild(table);

});

For simplicity, I have taken a small JSON object but usually I have a very heavy object. I want to take the value user enters in each textbox and save it in 'userinput' field of each element of JSON object. Moreover, I also want to save if 'checkbox' is checked or not and save a 'Y' or 'N' in the 'iscancelled' field of the JSON object.
I have written the following code for this but this doesn`t seem to work. What can be the problem ?
var revArray="";
$("[type='input']").each(function () {
        revArray = $(this).val;
    });

$.each(obj, function (i, obj) {

        for (var i = 0; i < revArray.length; i++) {
            obj.userInput= revArray[i];
        }
if ($("[type='checkbox']:checked"))
            obj.isCancelled = 'Y';
        else
            obj.isCancelled = 'N';
alert(JSON.stringify(obj));

A: So I eventually got it done using jquery in the following manner accessing each row of the table and then finding textbox on that row -
$('table tr:gt(0)').each(function (i, row) {
            var $row = $(row);
            var val1 = $row.find('input[type="text"]').val();
        });

For those who are facing problems like this can use it, works perfectly fine!


text:
Q: Publish button doesn't do anything (django forms) I am following an online django course and one of the exercises includes creating a blog. One of the elements of the blog includes a "Publish" button but when I click it nothing happens.
This is the code:
HTML:
Publish

views.py:
@login_required
def post_publish(request,pk):
    post = get_object_or_404(Post,pk=pk)
    post.publish()
    return redirect('post_detail',pk=pk)

urls.py:
url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),

A: Check if you have added the below detail in your settings file. If yes, then skip this part.
settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],  # Add this to your settings file
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

myproject/
 |-- myproject/
 |    |-- myapp/
 |    |-- myproject/
 |    |-- templates/     <-- here!
 |    |    |-- myapp/
 |    |    |    |-- index.html
 |    |    |-- base.html
 |    |    +-- home.html
 |    +-- manage.py
 +-- venv/

views.py:
@login_required
def post_publish(request,pk):
    post = get_object_or_404(Post,pk=pk)
    return render(request, template_name.html,{'post': post})

Try using return render this will work for sure.
In your view you have not show anywhere. what is your template_name.

A: From Django Docs:
Additional form template furniture
Don't forget that a form's output does not include the surrounding  tags, or the form's submit control. You will have to provide these yourself.
https://docs.djangoproject.com/en/2.0/topics/forms/
You are missing the input with type submit:
<input type="submit" value="Submit">

After handling the submitted data in your views.py you can redirect to the desired url there is no need to use an  tag.


text:
Q: Remote location loses connectivity I have a remote location that has constant internet access using DSL. The remote location only has three Linksys cameras that have internet access from a router. There is no computer on the network. The router is configured to use the DYN.org service to keep the IP address updated if the internet provider assigns a new ip address. The problem I am having is the router after a period of time stops responding to incoming ping requests and the cameras are shown offline. However, if I keep one of the cameras constantly streaming data then the connection to all the cameras works just fine all the time. How can I keep the router from appearing to be sleeping and not responding to incoming requests? The router is the Linksys WRT300N.

A: I would look for a keep alive setting in your router at the remote location.  You're probably running DSL over a PPPoE connection and it's timing out not seeing any traffic over the link.  By setting a keep alive period for less than the timeout period (i.e. 4 minutes if the timeout period is 5 minutes) will tell the router to send packets down the link to keep it open.  If that doesn't work you could probably script a job to periodically hit one of the cameras at your remote location to keep the link up.


text:
Q: Game Center show "No score" I recently tried to add Game Center to my Sprite Kit Game, but it's not working properly.
So I am sending scores to the GC leaderboards, I receive no errors and the scores apprently send but I still see no scores listed in the leaderboards! The leaderboard itself is listed in Game Center there are just no scores.
GameViewController
import GameKit

class GameViewController: UIViewController, GKGameCenterControllerDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        let skView = self.view as! SKView
        let scene = GameScene(size: skView.bounds.size)
        scene.scaleMode = .AspectFit

        skView.presentScene(scene)
        authenticateLocalPlayer()

    }

    //Initiate GameCenter
    func authenticateLocalPlayer(){

        var localPlayer = GKLocalPlayer.localPlayer()

        localPlayer.authenticateHandler = {(viewController, error) -> Void in

            if (viewController != nil) {
                self.presentViewController(viewController, animated: true, completion: nil)
            }

            else {
                println((GKLocalPlayer.localPlayer().authenticated))
            }
        }

    }

    func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
    {
        gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
    }

}

GameState
import Foundation
import GameKit

class GameState {

    var score: Int
    var highScore: Int

    class var sharedInstance :GameState {
        struct Singleton {
            static let instance = GameState()
        }

        return Singleton.instance
    }

    init() {
        // Init
        score = 0
        highScore = 0

        // Load game state
        let defaults = NSUserDefaults.standardUserDefaults()

        highScore = defaults.integerForKey("highScore")
    }

    func saveState() {
        // Update highScore if the current score is greater
        highScore = max(score, highScore)

        // Store in user defaults
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setInteger(highScore, forKey: "highScore")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

    func saveHighScore(high:Int64) {
        NSUserDefaults.standardUserDefaults()
        //check if user is signed in
        if GKLocalPlayer.localPlayer().authenticated {

            var scoreReporter = GKScore(leaderboardIdentifier: "LeaderboardID")

            scoreReporter.value = Int64(highScore) //score variable here (same as above)

            var scoreArray: [GKScore] = [scoreReporter]

            GKScore.reportScores(scoreArray, withCompletionHandler: {(error : NSError!) -> Void in
                if error != nil {
                    println(error.description)
                }
            })

        }
    }
}

EndGameScene
class EndGameScene: SKScene, GKGameCenterControllerDelegate {

    func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
    {
        gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)

    }
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch = touches as! Set<UITouch>
    var location = touch.first!.locationInNode(self)
    var node = self.nodeAtPoint(location)

    if (node.name == "gameCenter") {
        var vc = self.view?.window?.rootViewController
        var gc = GKGameCenterViewController()
        gc.gameCenterDelegate = self
        vc?.presentViewController(gc, animated: true, completion: nil)

    }

How can I fix? Thanks and sorry for my English


text:
Q: Send Childs in Woocommerce REST API categories endpoint How can I add extra data to the product categories endpoint?
I can update products endpoint by applying the filter woocommerce_rest_prepare_product_object
Can't seem to find the function to apply a filter for the categories endpoint.
This is how I am modifying the products endpoint:
add_filter('woocommerce_rest_prepare_product_object', 'custom_change_product_response', 20, 3);
add_filter('woocommerce_rest_prepare_product_variation_object', 'custom_change_product_response', 20, 3);

function custom_change_product_response($response, $object, $request) {
    $response->data['custom_field'] = "Custom Data";
    return $response;
}

I want to send all the children to the /products/categories endpoint.

A: I just found it after a lot of searching.
I had to modify the filter method :
return apply_filters( "woocommerce_rest_prepare_{$this->taxonomy}", $response, $item, $request );

Here the taxonomy for categories is: product_cat
So to add data you have to use the filter:
add_filter('woocommerce_rest_prepare_product_cat', 'custom_change_category_response', 20, 3);

And for sending child categories we will use:
$catTerms = get_terms('product_cat', array(
    'hide_empty' => 0,
    'orderby' => 'ASC',
    'child_of'=> $id
    ));

So the whole code is like this:
function custom_change_category_response($response, $object, $request) {

    $id = $response->data['id'];
    // Get subcategories of the current category
    $catTerms = get_terms('product_cat', array(
    'hide_empty' => 0,
    'orderby' => 'ASC',
    'child_of'=> $id
    ));

    $response->data['children_count'] = count($catTerms);
    $response->data['childs_array'] = $catTerms;
    return $response;
}

add_filter('woocommerce_rest_prepare_product_cat', 'custom_change_category_response', 20, 3);


text:
Q: Average of dataframes values in a list by name I have a question related to R and nested lists.
Let's assume I have a nested list with this structure:
library(tidyr)
library(purrr)

simul<-list(
  "Q"=tibble(
    months = seq(1,12,by=1),
    run1 = runif(12),
    run2 = runif(12),
    run3= runif(12)),
  "ET1"=tibble(
    months = seq(1,12,by=1),
    run1 = runif(12),
    run2 = runif(12),
    run3= runif(12)),
  "ET2"=tibble(
    months = seq(1,12,by=1),
    run1 = runif(12),
    run2 = runif(12),
    run3= runif(12)),
  "ET3"=tibble(
    months = seq(1,12,by=1),
    run1 = runif(12),
    run2 = runif(12),
    run3= runif(12))
  )

I am trying to obtain some averages by variables ("ET") and by run, thus maintaining the lower-level list structure. The variables are grouped by their starting characters, and vary by the number at the end.
So far I solved my problem in this way, however, I was wondering if you could please suggest to me a better way, which I can apply easily to a larger list, with more "variables" and "runs".
nested_avg <-list("Q"=simul["Q"],
                  "ET"=tibble(months = simul$ET1$months,
                              run1=rowMeans(do.call(cbind, simul[c("ET1","ET2","ET3")]%>% map(2))),
                              run2=rowMeans(do.call(cbind, simul[c("ET1","ET2","ET3")]%>% map(3))),
                              run3=rowMeans(do.call(cbind, simul[c("ET1","ET2","ET3")]%>% map(4)))
                  ))

Thank you so much for your answer.

A: Some enframe then deframe with grouping does the trick:
simul %>%
  setNames(str_remove_all(names(.), "\\d")) %>%
  enframe() %>%
  group_by(name) %>%
  summarise(value = list(as_tibble(Reduce("+", value) / n()))) %>%
  deframe()

Note that the as_tibble is necessary because Reduce automatically converts to matrix.

A: Looping and Mapping (not purrr::map, base::Map in this instance):
vars <- startsWith(names(simul), "ET")
out <- list(
    "Q" = simul["Q"],
    "ET" = as_tibble(do.call(Map, c(\(...) rowMeans(cbind(...)), simul[vars])))
)

identical(out, nested_avg)
#[1] TRUE

And an alternative method flattening everything to an array:
out <- list(
  "Q" = simul["Q"],
  "ET" = as_tibble(apply(sapply(simul[vars], as.matrix, simplify="array"), 1:2, mean))
)

identical(out, nested_avg)
#[1] TRUE


text:
Q: JDBC: safe row update when multiple requests I have a Java RESTful API that uses JDBC with ComboPooledDataSource for connection pooling (http://www.mchange.com/projects/c3p0/), and a PreparedStatement that updates a row by incrementing a field:
public void update(int messageId) {

    String UPDATE_STM = "UPDATE table SET count_field = count_field +1 WHERE id=?";
    conn = ConnectionManager.getConnection();
    PreparedStatement stm = conn.prepareStatement(UPDATE_STM );
    stm.setInt(1, messageId);
    stm.executeUpdate();
}

(I've omitted try/catch, and ConnectionManager.getConnection() gives me one of the available connections from the pool).
If my RESTful service receives two or more requests for update() method at the same time, am I granted that the count is updated correctly?
If not, how I should modify the code to avoid a wrong count update?

A: Use InnoDB
As far as I can see, your Java code is thread-safe, it doesn't access or change any fields. All you have to worry about is the UPDATE action on the database side. I assume you are using MySQL, since you have tagged the question with mysql tag. MySql DBMS offers the ACID model, you need to set the database engine to InnoDB for that to work. For more details see this link.


text:
Q: How to reorder entries in a Perl Tk listbox using drag and drop? I have a scrollable listbox and I'd like to allow drag and drop to rearrange the order of entries. i.e. select a listbox entry and drag it to a different position in the same listbox.
Any working examples please?


text:
Q: Installing the contextBroker I got some problems installing the contextBroker on my own server.
I got a CentOS installation. Im trying to install the contextBroker with yum.
I have setup the repo as discribed in (https://stackoverflow.com/a/24510985/4953537)
Output when trying to install:
yum install contextBroker
Loaded plugins: fastestmirror
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: ftp.plusline.de
 * epel: mirror.proserve.nl
 * extras: mirror.softaculous.com
 * updates: mirror.netcologne.de
No package contextBroker available.
Error: Nothing to do

Output of yum repolist
yum repolist
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.plusline.de
 * epel: mirror.proserve.nl
 * extras: mirror.softaculous.com
 * updates: mirror.netcologne.de
repo id                      repo name                                                 status
base                         CentOS-6 - Base                                           4926
epel                         Extra Packages for Enterprise Linux 6 - i386              9467
extras                       CentOS-6 - Extras                                           34
mongodb                      MongoDB Repository                                         269
testbed-fi-ware              Fiware Repository                                          108
updates                      CentOS-6 - Updates                                         864
repolist: 15668

What am i missing here?
Update:
cat /etc/yum.repos.d/testbed-fi-ware.repo
[testbed-fi-ware]
name=Fiware Repository
baseurl=http://repositories.testbed.fi-ware.org/repo/rpm/x86_64/
gpgcheck=0
enabled=1

"rpm -qa | grep contextBroker" doesnt give any output
Update:
I tryed to install the package manually and i installed all the dependancies listed on https://forge.fiware.org/plugins/mediawiki/wiki/fiware/index.php/Publish/Subscribe_Broker_-_Orion_Context_Broker_-_Installation_and_Administration_Guide#Installing
The contextBroker package (mandatory) depends on the following packages: boost-filesystem, boost-thread, libmicrohttpd (new requirement in 0.8.0), logrotate (new requirement in 0.13.0), libcurl (new requirement in 0.14.1) and boost-regex (new requirement in 0.22.0).

Still, when installing the RPM package( sudo rpm -i http://repositories.testbed.fiware.org/repo/rpm/x86_64/contextBroker-0.22.0-1.x86_64.rpm) i get:
 Failed dependencies:
        ld-linux-x86-64.so.2()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        ld-linux-x86-64.so.2(GLIBC_2.3)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libboost_filesystem-mt.so.5()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libboost_regex-mt.so.5()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libboost_system-mt.so.5()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libboost_thread-mt.so.5()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libc.so.6()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libc.so.6(GLIBC_2.2.5)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libc.so.6(GLIBC_2.3.2)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libc.so.6(GLIBC_2.3.4)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libcurl.so.4()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libgcc_s.so.1()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libgcc_s.so.1(GCC_3.0)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libm.so.6()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libm.so.6(GLIBC_2.2.5)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libmicrohttpd.so.10()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libpthread.so.0()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libpthread.so.0(GLIBC_2.2.5)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        librt.so.1()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        librt.so.1(GLIBC_2.2.5)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libstdc++.so.6()(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libstdc++.so.6(CXXABI_1.3)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libstdc++.so.6(GLIBCXX_3.4)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libstdc++.so.6(GLIBCXX_3.4.10)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libstdc++.so.6(GLIBCXX_3.4.11)(64bit) is needed by contextBroker-0.22.0-1.x86_64
        libstdc++.so.6(GLIBCXX_3.4.9)(64bit) is needed by contextBroker-0.22.0-1.x86_64

Why do i get this?

A: Sometimes yum doesn't detect new packages in the repositories. In that case, I have found that the following command use to help:
yum clean all

next, try again
yum install contextBroker

A: Another way is installing directly from the repository with rpm command, e.g.:
sudo rpm -i http://repositories.testbed.fiware.org/repo/rpm/x86_64/contextBroker-0.22.0-1.x86_64.rpm

However, in this case, if some package dependency fails, you would need to deal with it manually.
EDIT: in the case of dependencies problems, you can use the following in order to know which package provides each dependency:
yum whatprovides libboost_filesystem-mt.*
yum whatprovides libstdc++.so.6

However, not sure if this would work in you case, given that the fail in yum install contextBroker at the very beginning makes me think if yum is not working fine in your environment...


text:
Q: SCrypt - Hashing and comparing password on browser Is there any JS library that support hashing and comparing SCrypt-based passwords like node-scrypt?

A: i know about this one this is easy to use and documentation is very easy check it
https://www.npmjs.com/package/password-hash


text:
Q: ASP.NET MVC 5 best approach for outputting and downloading file progress I must to create a function which allow an user click a button in browser and request to server to get information from database. The information will be output to a .csv file, after that client able to download it.
I intend to use one of two method of System.Web.Mvc.Controller
protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)
or
protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
But the output file size can be up to 4 gigabytes, so I worry the buffering size of a file in Stream or byte[] will cause server memory leaks.
I split my progress into 2 steps
Step 1: output csv file with memory leaks consideration
public CsvOutputHelper(List<string> csvHeader)
{
    this._csvHeader = csvHeader;
}

public void OutputFile(List<List<string>> data, string filePath)
{
    // Create the new file and write the header text
    File.WriteAllText(filePath, this._csvHeader.ConvertToCsvRecord());

    // 'StringBuilder' for output file
    var sb = new StringBuilder();
    sb.AppendLine();

    // Line counter
    var lineCounterValue = 1;

    for (var i = 0; i < data.Count; i++)
    {
        // Create line content of csv file and append it to buffer string
        sb.AppendLine(data[i].ConvertToCsvRecord());

        // Increase value of line counter
        lineCounterValue++;

        // If buffer string is reach to 100 lines or the loop go to the end of data list,
        // output text to file and reset value of buffer string and value of line counter
        if (lineCounterValue == MaxCountOfOutputLine || i == data.Count - 1)
        {
            // Output buffer string
            File.AppendAllText(filePath, sb.ToString());

            sb = new StringBuilder();       // Re-create a new instance of 'StringBuilder'
            lineCounterValue = 1;           // Reset line counter value to 1
        }
    }
}

Step 2: return output filePath in server (relative path) to browser and browser request to path to download file.
Is my solution is a good way to implement in that case? Is using Stream or bytes will to be caused server memory leaks or not? Please explain for me.


text:
Q: .forEach() on Arrays vs NodeList (JavaScript) What I want to know
I've heard that sometimes NodeLists need to be changed to Arrays to use forEach() method.
What kind of situation do I have to do it in?

What I tried
I wrote this:

const items = document.querySelectorAll('.js-li');
const arrItems = Array.from(items);

items.forEach((v, i, a) => console.log(`${v} / ${i} / ${a}`));
arrItems.forEach((v, i, a) => console.log(`${v} / ${i} / ${a}`));

zero

one

two

three

four

But I couldn't understand the difference between with/without Array.from().

A: Look

NodeLists and Arrays are two different things because NodeLists are
  actually not a JavaScript API, but a browser API.

Things like querySelectorAll() and getElementsByTagName() aren't JavaScript methods, they're browser APIs that let you access DOM elements. You can then manipulate them with JavaScript.
NodeLists differ from Arrays in another meaningful way, too.
They are often live lists, meaning that if elements are removed or added to the DOM, the list updates automatically. querySelector() and querySelectorAll() return a static list (one that doesn't update), but properties like .childNodes are live lists that will change as you manipulate the DOM (which can be a good or bad thing, depending on how you're using it).
This is all made more confusing because arrays can contain nodes. And, there's another, older type of list called an HTMLCollection that predates NodeLists, but is functionally similar (another article for another day).

The key way to think about NodeLists vs. Arrays: NodeLists are a
  language-agnostic way to access DOM elements, and Arrays are a
  JavaScript object you can use to contain collections of stuff.

They each have their own methods and properties, and you can convert a NodeList into an Array if you need to (but not the other way around).


text:
Q: How to read a file from a different directory then print it to the screen in c I am supposed to write a program called www.c. That will read data, describing most popular websites, from a file called web-data, and emit various bits of information about what it found in the file. The info we are supposed to be using is in a file which is in a completley different directory than mine.
How do I open up this file so that I am able to read it?
so far I have:
#include <stdio.h>

int main () {
 char* file = "filename";
 int c;
 FILE *www;
 www = fopen("file", "rb");
 if (www) {
    while ((c = getc(www)) != EOF)
    putchar(c);
    fclose(www);
 }
 return 0;
 }

but it wont print anything to the screen so I don't think it is actually accessing the file.
Also what command would I use to look through the file and find the best ranked and the lowest alexa?
Thank you so very much for your help.

A: Just take the double quotes off 'file' in your fopen call:
Like this:
 www = fopen(file, "rb");

Otherwise you're trying to open a file called "file", rather than a file whose name is referenced by the variable file.


text:
Q: Implementing a function in R to find the coefficients of a linear regression model from the ground up # but cannot handle categorical variables
my_lm <- function(explanatory_matrix, response_vec) {
  exp_mat <- as.matrix(explanatory_matrix)
  intercept <- rep(1, nrow(exp_mat))
  exp_mat <- cbind(exp_mat, intercept)
  solve(t(exp_mat) %*% exp_mat) %*% (t(exp_mat) %*% response_vec)
}

The above code will not work when there are categorical variables in the explanatory_matrix.
How can I implement that?

A: Here is an example for a data set with one categorical variable:
set.seed(123)

x <- 1:10
a <- 2
b <- 3

y <- a*x + b + rnorm(10)
# categorical variable
x2 <- sample(c("A", "B"), 10, replace = T)
# one-hot encoding
x2 <- as.integer(d$x2 == "A")

xm <- matrix(c(x, x2, rep(1, length(x))), ncol = 3, nrow = 10)
ym <- matrix(y, ncol = 1, nrow = 10)

beta_hat <- MASS::ginv(t(xm) %*% xm) %*% t(xm) %*% ym
beta_hat

This gives (note the order of coefficients - it matches the order of the predictor columns):
      [,1]
[1,]  1.9916754
[2,] -0.7594809
[3,]  3.2723071

which is identical to the output of lm:
d <- data.frame(x = x,
                x2 = x2,
                y = y)
lm(y ~ ., data = d)

Output
# Call:
#   lm(formula = y ~ ., data = d)
#
# Coefficients:
#   (Intercept)            x           x2
# 3.2723       1.9917      -0.7595

A: For categorical handling you should use one-hot encoding.
Do something like
  formula <- dep_var ~ indep_var
  exp_mat <- model.matrix(formula, explanatory_matrix)
  solve(t(exp_mat) %*% exp_mat) %*% (t(exp_mat) %*% response_vec)


text:
Q: change the frequecy of a users voice, android What I am trying to do, is create an app that takes a recording of a persons voice, for example you could say " hello my name is James", the app would first record this, then change its frequency and give you an output.
The output would obviously sound stupid and maybe funny, but that is what I'm trying to do.
I have got the code to record and play anything that a user says, but how do I manipulate it, how do I change the pitch of the voice.

A: I googled for the same requirement and got something like,soundpool can be used to achieve this. I tried to create it out of the stuff i got,but no success yet. but you can go through the links.These might help you.
http://www.droidnova.com/creating-sound-effects-in-android-part-1,570.html
http://www.anddev.org/using_soundpool_instead_of_mediaplayer-t3115.html
http://blog.nelsondev.net/?p=207


text:
Q: got Highcharts error #13 when running unit test The highcharts render fine in browser without error, but when running test on the component, I got test failing:
● renders correctly
Highcharts error #13: www.highcharts.com/errors/13

  22 |
  23 |     highChartsRender(options) {
> 24 |         Highcharts.chart(this.props.id,{
     |                    ^
  25 |             chart: {
  26 |               type: "line",
  27 |               renderTo: "lineChart",

and in my HCLineChart.test.js file, I have this:
it('renders correctly', () => {
  const tree = TestRenderer
    .create(<HCLineChart title={title} options={options} id={"LineChart1"} />)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

and then in my HCLineChart.js file, I have this:
import React from "react";
import Highcharts from "highcharts";
import HC_exporting from "highcharts/modules/exporting";
import HC_exporting_data from "highcharts/modules/export-data";
import PropTypes from "prop-types";

class HCLineChart extends React.Component {
    constructor(props){
        super(props);
        HC_exporting(Highcharts);
        HC_exporting_data(Highcharts);
    }

    componentDidMount() {
        this.highChartsRender(this.props.options);
    }

    shouldComponentUpdate(nextProps) {
        this.highChartsRender(nextProps.options);
        return false;
    }

    highChartsRender(options) {
        Highcharts.chart(this.props.id,{
            chart: {
            type: "line",
            renderTo: "lineChart",
            height: 500,
            },
            title: {
                text: this.props.title,
            },
            xAxis: {
                categories: options.xAxisCategories,
            },
            yAxis: {
                title: {
                    text: this.props.title,
                },
            },
            plotOptions: {
                series: {
                    marker: {
                        enabled: false,
                    },
                },
            },
            credits:{
                enabled: false,
            },
            exporting: {
                buttons: {
                    contextButton: {
                        enabled: true,
                        menuItems: [
                            "printChart",
                            "downloadCSV",
                            "downloadXLS",
                        ],
                    },
                },
            },
            series: options.data,
        });

        Highcharts.setOptions({
            lang: {
                thousandsSep: ",",
            },
        });
    }

    render() {
        return <div className="line-chart" id={this.props.id} />;
    }
}

export default HCLineChart;

So why I got the error only in testing? I saw the div already there before calling the Highchart.chart ?
Thank you.
Lei


text:
Q: Find where a row of data in one column doesn't exist in another column so I'm trying to figure out a way to compare each and every row of a column against all the rows in another column and filter out those that doesn't exist in the column that it is comparing to. I understand how to compare the two columns on a row-by-row basic like this:
select table1.column1
from table1 inner join
     table2 on table1.id = table2.id
where column1 <> column2

But I want to compare the rows from table1 in column1 against ALL the rows of column2 in table2 and find rows in column1 that doesn't exist in column2 at all. So it would be something like columns with these values:
Column1        Column2
1              2
2              1
4              3
5              5
7              6

And after the SQL it would become something like this:
Column1
4
7

A: Try with NOT IN:
select table1.column1
from table1
where table1.column1 not in (select table2.column2 from table2)

A: select column1 from table1 as t1 where not exists
(select column2 from table2 as t2 where t1.id=t2.id)

A: If you compare column between 2 tables
SELECT table1.column1 FROM table1
WHERE table1.column1 NOT IN
(SELECT table2.column2 as column1 FROM table2)

If you compare column1 with column2 against same table
SELECT table1.column1 FROM table1
WHERE table1.column1 NOT IN
(SELECT table1.column2 as column1 FROM table1)

A: select t1.id
from ... t1
left join ... t2 on t1.id = t2.id
where t2.id is null


text:
Q: Why I've got org.postgresql.util.PSQLException: ERROR: Invalid endian flag value encountered? I recently worl with hibernate-spatial 5 and I bumped with problem. When I'm trying to add my Geometry data to Postgres. I've got the next error on the commit transaction stage:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: Invalid endian flag value encountered.

My Entity looks like this, I've configured it like in previous posts with the same problem:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "geotable")
@Indexed(index = "geoindex")
public class GeoPointModel implements Serializable {

    @Id
    @GeneratedValue
    @DocumentId
    @Column(name = "point_id")
    private Long id;
    @Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
    @FieldBridge(impl = GeoBridge.class)
    @Column(name = "location", columnDefinition = "geometry(Point,4326)")
    private Geometry location;
}

My dependencies:
dependencies {
    implementation 'org.hibernate:hibernate-core:5.4.5.Final'
    implementation 'org.hibernate:hibernate-spatial:5.4.5.Final'
    implementation 'org.springframework:spring-orm:5.1.5.RELEASE'

    compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.1.8.RELEASE'
    compile group: 'org.hibernate', name: 'hibernate-search-orm', version: '5.11.3.Final'
    compile group: 'org.apache.lucene', name: 'lucene-spatial', version: '5.5.5'
    compile group: 'com.spatial4j', name: 'spatial4j', version: '0.4.1'
    compile group: 'com.vividsolutions', name: 'jts', version: '1.13'
    compile group: 'net.postgis', name: 'postgis-jdbc', version: '2.3.0'
}

Dialect:
dialect=org.hibernate.spatial.dialect.postgis.PostgisPG9Dialect

What did I lose? How it can be fixed?

A: Probably https://hibernate.atlassian.net/browse/HHH-11086 ? A workaround seems to be using Point instead of Geometry: https://forum.hibernate.org/viewtopic.php?p=2490324&sid=36d7ee961e6ff5e45e71a8aa613cb469#p2490324
On a not-so-related note, if you're still trying to use Hibernate Search (you tagged it in this question, after all), have a look at @Spatial: https://docs.jboss.org/hibernate/search/5.11/reference/en-US/html_single/#spatial-indexing . In your case you would only have to make your GeoPointModel class implement org.hibernate.search.spatial.Coordinates and to add a @Spatial(name = "location") annotation on GeoPointModel.


text:
Q: Wordpress Require Login I have some restricted content on a WordPress site. What I want is pretty simple (I think). If a user is not logged in, redirect to the /login page with an error like "You must be logged in to view this content". The problem is that I don't know what GET (or POST) request variables are to accomplish this. Is there an error_message variable  or even a login_required variable or anything I can set to make this happen? I have Googled this, but can't seem to find much.
if( !is_user_logged_in() ){
    wp_redirect('/login?error_message=ERRORMESSAGEHERE&redirect_to=http%3A%2F%2Fexample.dev%2Fwp-admin%2F&reauth=1');
}

NOTE: I would much prefer to avoid using any plugins to accomplish this. Although recommending plugins is... ok, it's not the solution I'm looking for.

A: Well I think there is no default GET/POST parameter for this in Wordpress itself but what you are looking for seems to be part of the theme anyway.
Go to path/to/wordpress/wp-content/themes/yourtheme/header.php
And add something linke this at the end:
if($_GET['error_message']){
  echo '
 Error:  '.htmlentities($_GET['error_message']).'
';
}

You can easily use CSS to style your "error-box". Note that the "htmlentites" is necessary to prevent XSS attacks on your site.

A: After some more digging, I found this over on wordpress.stackexchange.com. Below is an example of what I may ended up using:
page-templates/custom-template.php:
if( !is_user_logged_in() ){
    wp_redirect('/login?err=err1&redirect_to=http%3A%2F%2Fexample.dev%2Fwp-admin%2F&reauth=1');
}

functions.php:
add_action('login_head','custom_errors');
function custom_errors() {
    global $error;
    if( !empty($_GET['err']) ){
        $err = $_GET['err'];
        switch ($err) {
            case 'err1': $error = 'Error 1'; break;
            case 'err2': $error = 'Error 2'; break;
        }
    }
}


text:
Q: Jest - Mocking JQuery plugin's functions I have to test (using Jest) some JQuery plugins.
I'm having problems with this one, because I want to check if some function is called and it keeps telling me that it hasn't.
I simplified the plugin's structure and its something like this:
;(function($) {
  $.List= function() {

    plugin = this;
    plugin.functionA = function() {
       plugin.functionB();
    }

    plugin.functionB = function() {
       console.log("I'm Here")
    }

  }
}

When I try to test functionA through Jest, i do this:
it("should check if functionB is called when functionA is called", () => {

   const list = Manager.addList(); //we have a manager class thats responsible for adding the plugin to the page

   list.functionB = jest.fn();
   list.functionA();

   expect(list.functionB).toHaveBeenCalled();
});

The words 'I'm Here' are printed in the console but Jest keeps telling me that functionB has not been called. Any idea why?


text:
Q: how to define routingdatasource for two mysql and oracle? I want to define a routingdatasource for two different databases: mysql and oracle
I've defined the following config.xml

<bean id="dataSourceTarget" class="com.test.common.RoutingDataSource">
    <property name="targetDataSources">
        <map key-type="com.test.common.DataSourceType">
            <entry key="MY_SQL" value-ref="mySqlDataSource"/>
            <entry key="ORACLE" value-ref="oracleDataSource"/>
        </map>
    </property>
    <property name="defaultTargetDataSource" ref="mySqlDataSource"/>
</bean>

<bean id="mySqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close">
    <property name="driverClass" value="${jdbc.driver.classname}" />
    <property name="jdbcUrl" value="${mysql.url}" />
    <property name="user" value="${mysql.username}" />
    <property name="password" value="${mysql.password}" />
</bean>

<bean id="oracleDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close">
    <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
    <property name="jdbcUrl" value="${oracle.url}" />
    <property name="user" value="${oracle.user}" />
    <property name="password" value="${oracle.passw}" />
</bean>

and now I can define session factory and transaction manager

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.use_sql_comments">true</prop>
        </props>
    </property>
</bean>

But this is doesn't work. I'm getting the
Caused by: java.lang.UnsupportedOperationException: The user must supply a JDBC connection

And in addition I must define the dialect for session.
But how can I define it depending on the datasourse it is working on?


text:
Q: Multiple headers, How to get different margin_top value for different pages In my application, i need create a document pdf in wkhtmltopdf.
There are more than one pages in my document pdf. I generate dynamicly a file html static for header_html specified to the first page and another header_html specified for the rest of page.
My question is the two headers are not the same height:

How can i get margin_top value dynamicly for each page ?
Thank you for your answers.

A: If you want make your first page is different from the others pages. you can use cover page like:
wkhtmltopdf -H cover cover.html ...

doc


text:
Q: Finding trend of a time series data (Line or 1d data) using python I have a 1d time-series data or line. I want to know what is the trend of its slices. Picture:

some slices are equal, some are uptrend and some slices are downtrend. In the picture the green marker shows uptrend and red are showing downtrend.
I want to have a list or array that show each index is in which slice.
For example, I want something like this:
[equal, equal, ..., up, up, ..., down, down]
each item is just a tag that shows the direction of its slice. For example, if the second item in the list is 'up', this means that the instance is placed in the slice which is uptrend.
I have tried many ways best of them was scipy's argrelextrema.
I have used arglextrema for finding local maxima and minima then comparing them by order of appearance in the index.
from scipy.signal import argrelextrema
d = data['tenkan_sen'].fillna(1)
h1 = d.append(pd.Series([5, 4, 3, 2, 1]), ignore_index=True)
g = argrelextrema(h1.values, np.greater)[0]
l = argrelextrema(h1.values, np.less)[0]
e = argrelextrema(h1.values, np.equal)[0]

extermas = dict()
extermas[0] = 'start'
for item in g:
    extermas[item] = 'greater'
for item in l:
    extermas[item] = 'less'
extermas = dict(sorted(extermas.items()))
idx_extermas = list(extermas.keys())

status = []

for item in range(len(idx_extermas)-1):
    if extermas[idx_extermas[item+1]] == 'less':
        stat = 'down'
    if extermas[idx_extermas[item+1]] == 'greater':
        stat = 'up'
    for _ in range(idx_extermas[item], idx_extermas[item+1]):
        #print(_)
        status.append(stat)

#print(len(status))
for item in e:
    #print(item)
    status[item] = 'equal'

This method cannot find the direction of the ending slice of the line. to solve this problem, I have added five points manually at the end of the line, but it did not work.
I have searched a lot I could not find a suitable solution.

A: Firstly, if you want to smooth out your data, run
data=np.convolve(data,[1/4,2/4,1/4],"valid")

This will remove noise, but also blur your data and shrink it slightly as it does so.
Then run
data=np.convolve(data,[1,-1],"valid")
gap=0.1
direction=(data>gap).astype(int)-(data<-gap).astype(int)

This gives you an array that is 1 when the data was sloping upwards by at least gap, and -1 when sloping downwards. (In general being exactly constant is rare in most data sets, you only want to pick up the steep slopes.)
Adjust gap until you are only picking out the steepness you want.


text:
Q: Kindle Fire opening front camera by default while it should open the back camera I have this camera application which is working fine on almost all other devices except the Kindle Fire HDX 8.9
The problem is that when I open the camera inside the surface view I explicitly tell it to open the Back facing camera:
this.camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);

But for some reason, on the Kindle Fire HDX, a user has reported that it is opening the front camera by default. Any ideas as to how to fix it?


text:
Q: Excel won't show list of autosaved documents even though I've set autosave to every minute I've just lost quite a lot of work.
I hit save every few minutes myself just to be extra careful but even when I reopened the document, it opened to a far earlier version that excludes much work I've done.
I went to the autosave folder, unless I'm going to the incorrect folder, there's only one unrelated autosaved Excel spreadsheet.
If I've set it to save every 1 min, should there not be a vast collection of files stored?
I'm working on a Mac / Mavericks OS
Also, I can see the Sandwich Baron (Version 1) when I try save a blank document to the autosave folder but when I go there, there's no Sandwich Baron (Version 1)
Any answer will be MUCH appreciated!!!


text:
Q: Do I have to re-compile everytime I add a new device for ad-hoc installation? I have created an ad-hoc provision profile for my iPhone application. Everytime I add a new device, do I need to re-compile my application so that it can be distributed? This is VERY tedious.

A: Yes. When you compile your application it is code signed with the *.mobileprovision you have selected for the current build configuration. Each time you add a new device, it changes the *.mobileprovision file to allow for that unique UDID, so you need to both recompile AND reinstall your *.mobileprovision (by dragging into iTunes again) in order for the new devices to run the Ad Hoc distro.


text:
Q: sklearn.ensemble.RandomForestClassifier with non-consistent output I have a trained sklearn randomforest multi-label classifier, in the training set, one class is always present, which means you expect the classifier to always return 1 for this class. This happens, however the classifier returns [1] instead of [0, 1]. See output bellow:
[array([[0.05, 0.95]]), array([[0.97, 0.03]]),
array([[0.95, 0.05]]), array([[1., 0.]]), array([[1., 0.]]),
array([[1., 0.]]), array([[0.65, 0.35]]), array([[1.]])]

Why is this the case, and how do I prevent this from happening? In the example, it is the result of only a single input however in my case I have a full data frame as input which I transform into class predictions. This is not possible if one of the arrays has only a single dimension: [1] instead of two dimensions [0,1] like the predictions for the other classes.
Can this be changed with a setting in sklearn?
Extra clarification why I have a training set with only positive class samples: This is part of a recommender system and sometimes a product is bought every time by every type of customer.

A: I solved it using a simple list comprehension check that adds a second column to the inconsistent output array. The code to do this is bellow where rfc_output is the random forest output where there are inconsistent columns present.
rfc_output = [np.c_[x, np.zeros(window_size)] if len(x[1])<2 else x for x in rfc_output ]


text:
Q: How to pass a VF controller list to a VF/javascript table Please I need to put a list var "who I received from controller" in the JavaScript table and brows it.
This my code :
Public class Controller_OlympusLR_addMultipleVouchers
{
    public ValidateField_OlympusLR var {get;set;}

    public Controller_OlympusLR_addMultipleVouchers(ApexPages.StandardSetController stdcontroller)
    {
        var = new List<Olympus_Server__c>();
        var = [select Olympus_Project__r.Name ,MAC_Address__c from Olympus_Server__c where Olympus_Project__c != null ];
    }
}

A: Because of the inconsistent handling of trailing commas in arrays in JavaScript, it is probably simplest to generate the JavaScript array text in Apex and just output it in the Visualforce. So the aim is to generate a string of this form:
["abc","def","ghi"]

To do that you can first build the array in Apex and then use a JSON.serialize call (which will correctly escape the array values):
Public class Controller_OlympusLR_addMultipleVouchers
    public String array {get; set;}
    public Controller_OlympusLR_addMultipleVouchers(ApexPages.StandardSetController sc)
    {
        String[] items = new String[] {};
        for (Olympus_Server__c os : [
                select Olympus_Project__r.Name, MAC_Address__c
                from Olympus_Server__c
                where Olympus_Project__c != null
                order by MAC_Address__c
                ]) {
            // ... or whichever field you require here
            items.add(os.MAC_Address__c);
        }
        array = JSON.serialize(items);
    }
}

Then in the Visualforce you can just assign the value to a JavaScript variable:
 var array = ["abc","def","ghi"];

like this:
<script>
var array = {!array};
// For debugging to check that the array values are there
for (var i = 0; i < array.length; i++) {
    console.log(array[i]);
}
// Your logic
...
</script>

Use your browser's "View Source" feature to check the text that ends up in the page and also check the JavaScript console to make sure there are no errors there.

A: <script>
    var s = [];
    <apex:repeat value="{!var}" var="thing">
      s.push('{!JSENCODE(thing)}');
    </apex:repeat>
  </script>

Hope this helps!


text:
Q: What's the purpose of *(id*)obj? typedef struct _wax_instance_userdata {
    id instance;
    BOOL isClass;
    Class isSuper;
    BOOL actAsSuper;
} wax_instance_userdata;

https://github.com/probablycorey/wax/blob/master/lib/wax_helpers.m#L497
void* afunc(){ // the function is too long
    void *value = nil;
    // ...
    wax_instance_userdata *instanceUserdata = (wax_instance_userdata *)luaL_checkudata(L, stackIndex, WAX_INSTANCE_METATABLE_NAME);

    instance = instanceUserdata->instance;

    *(id *)value = instance;
    return value;
}

https://github.com/probablycorey/wax/blob/master/lib/wax.m#L243
id* ret = afunc(); //same without this * .
id lastValue = *(id*)ret;
//now I can use lastValue;

Why need do this ?
I can't understand the *(id*)
also the id* ret = afunc() ,when delete this star , it also works well.

A: afunc is referencing the function (void *)wax_copyToObjc(...). The intent of this function is to translate a Lua object into a C or Objective-C value. Because it could be a primitive type or an objective-c instance it doesn't know what it is going to return. So always returns a pointer to void (meaning a pointer to something unknown). In the case of an id, it will return a pointer to an id.
It might be easier to explain what is happening with an int, it will alloc space for the int and copy the its value:
value = calloc(sizeof(int), 1)
*(int *)value = lua_tointeger(L, stackIndex)

(int *)value is translates to "value is a pointer to an int"
adding the *  in front of it like *(int *)value translates to "copy the int to the alloc'd memory that value points to."
In your example:
id *ret = afunc(); // returns a pointer to an id
id lastValue = *(id*)ret; // dereferences the pointer to id so it is just an id

A: This looks weird. Since the issues came from what looks like C Code, I suggest to not use id. Although it's supposed to be the same as void*, devs tend to use the first in ObjC code, and the latter in C code. You'd gain in clarity.
Now, I don't see why void* value = instance; and void* ret = afunc(); should not do as expected.


text:
Q: How to output value displayed on external webpage with JS I'm trying to get the value displayed on this webpage (Loadshedding value)
After I get the value I want to use a if/else statement to check the value, and then display the result in html.
The first Line is the only place I'm going wrong, I think:
load.js
var status = "http://loadshedding.eskom.co.za/LoadShedding/GetStatus";
var value = "Error1";

function checkStatus(){
    if(status == 1){
        value = "No Loadshedding at the moment";
        }
        else if(status == 2){
            value = "Stage 1 Loadshedding";
        }
        else if(status == 3){
        value = "Stage 2 Loadshedding";
        }
        else if(status == 4){
            value = "Stage 3 Loadshedding";
        }
        else{
            value = "Error";
        }
    return value;
    }

Then I'm outputting the result in html with the following.
index.html

I just can't figure out how to get the value off  that page and check(if/else) and display it.
Many thanks!

A: You're literally comparing that link to the numbers. Just because you have a link as a string doesn't mean it's going to make a network call for you. Since you tagged this as jquery, I'll use that.
$.ajax({
    url: "http://loadshedding.eskom.co.za/LoadShedding/GetStatus",
    method: "GET"})
.done(function(status) {
    var value = "Error1";
    if(status == 1){
        value = "No Loadshedding at the moment";
    }
    else if(status == 2){
        value = "Stage 1 Loadshedding";
    }
    else if(status == 3){
        value = "Stage 2 Loadshedding";
    }
    else if(status == 4){
        value = "Stage 3 Loadshedding";
    }
    else{
        value = "Error";
    }

    document.write(value);
});

EDIT FOR OP
Here's the entire page for you so you understand it better.

Stop trying to use return. Don't use return. No return. Stop.

A: Use Jquery to get value. Replace first 2 lines of code with below code snippet to show the value
var value = "Error1";
   $.get( "http://loadshedding.eskom.co.za/LoadShedding/GetStatus", function( data ) {
            value = data;
});


text:
Q: Using just the textview from SlackTextViewController I am writing a job management app that allows users to post responses to a job and I'd like to use a textview similar to the iMessage style. Essentially a textbox at the bottom of the view that when focused moves up to sit on top of the keybaord and moves the view content up aswell, but also grows as the text is being typed in.
I have come across SlackTextViewController which exactly suits my needs, however there is one issue. I already have the job view setup (Storyboard and Objective c) and all I'd like to do is use the textview portion of SlackTextViewController to write responses in, however SlackTextViewController ships with it's own tableview built in etc so whenever I use the textview, the table lays over the top of everything else on the view.
Is there anyway to 'break off' just the textview portion and use that in a pre-existing UIViewController? Or does anybody know of any alternatives that would achieve what I'm after?


text:
Q: How do I access/read from/write to Documents folder in Internal Storage on Android devices? How do I access public Documents folder on an Android phone's internal storage? I need to read and write publicly-accessible files into the Documents folder.

A: Well I have solved this myself :)
It's pretty much the same as you would do it for a normal Windows Desktop application:
Create and read file from Documents folder (on an Android device):
string content = "Jason rules";
string filename = "file.txt";

var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(documents))
{
    Console.WriteLine("Directory does not exist.");
}
else
{
    Console.WriteLine("Directory exists.");

    File.WriteAllText(documents + @"/" + filename, content);

    if (!File.Exists(documents + @"/" + filename))
    {
        Console.WriteLine("Document not found.");
    }
    else
    {
        string newContent = File.ReadAllText(documents + @"/" + filename);

        TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
        if (viewer != null)
        {
            viewer.Text = newContent;
        }
    }
}

Complete Sample:
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ToolbarSample
{
    [Activity(Label = "ToolbarSample", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.button);

            if (button != null)
            {
                button.Click += delegate
                {
                        button.Enabled = false;

                        string content = "Jason rules";
                        string filename = "file.txt";

                        var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                        if (!Directory.Exists(documents))
                        {
                            Console.WriteLine("Directory does not exist.");
                        }
                        else
                        {
                            Console.WriteLine("Directory exists.");

                            File.WriteAllText(documents + @"/" + filename, content);

                            if (!File.Exists(documents + @"/" + filename))
                            {
                                Console.WriteLine("Document not found.");
                            }
                            else
                            {
                                string newContent = File.ReadAllText(documents + @"/" + filename);

                                TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
                                if (viewer != null)
                                {
                                    viewer.Text = newContent;
                                }
                            }
                        }
                };
            }
        }
    }
}

A: don't forget to add permission to androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

sample of writing
        // write on SD card file data in the text box
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

sample of reading
         try {
            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow + "\n";
            }
            txtData.setText(aBuffer);
            myReader.close();
            Toast.makeText(getBaseContext(),
                    "Done reading SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

A: if you are running on sdk higher than 23, android version higher than 6, you should implement access request to user. please find more information here on this link

A: With permissions to read external storage, this code should work for you.
var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);

var filename = System.IO.Path.Combine(path.ToString(), strFile);

System.IO.FileStream fs = new FileStream(filename, FileMode.Open);

byData = new byte[fs.Length];

fs.Read(byData, 0, (int)fs.Length);
fs.Close();


text:
Q: An integer I pass as an argument becomes a method I am trying to write a function. Here is the code.
def get_sum(a,b)
  if a == b do
    return a
    end
  else
    total = 0
    for num in a...b
      total += num
    end
    return total
  end
end

I get this error:
undefined method `b' for main:Object (NoMethodError)

Can anyone tell me why I get this?

A: No do for ifs
if a == b
  return a
end

Note that you can do the same thing so
def get_sum(a, b)
  return a if a == b
  (a...b).inject(:+)
end

A: It is because you have a block do ... end after b. Neither the keyword if nor the syntax sugar form ... == ... accepts a block. The only possibility left to interpret your code syntactically is to interpret b as a method that takes this do ... end block, and that is how it is parsed.


text:
Q: Both Image.export_to_png and Image.export_as_image not working I have the following code:
from kivy.app import App
from kivy.uix.image import Image

class MyApp(App):

    def build(self):
        my_image = Image(source='test.png')
        with my_image.canvas:
            Triangle(point=(0, 0, 30, 30, 60, 0))
        my_image.export_to_png('test2.png')
        my_image.export_as_image().save('test3.png')
        return my_image

myapp = MyApp().run()

The expected outcome of its execution should be two copies of the 'test.png' named 'test2.png' and 'test3.png with the added triangle on them. However, two files with triangles only, without original texture are created. What is the mistake and how do I export widgets to png?
EDIT: I've done my research and found out that it is caused by the fact that these functions (I'm only sure about
image.export_to_png but image.export_as_image provides the same result) export not the widget itself but rather canvas of the widget. That leads me to two question:
1)How do I export changed picture but not the changes themselves?
2)How do I just export the original image if no changes occurred?

A: Looks like you just need to wait for the next frame, probably for OpenGL initialisation reasons:
from kivy.app import App
from kivy.uix.image import Image
from kivy.graphics import Triangle
from kivy.clock import Clock

class MyApp(App):

    def build(self):
        self.my_image = Image(source='test.png')
        with self.my_image.canvas:
            Triangle(point=(0, 0, 30, 30, 60, 0))

        Clock.schedule_once(self.export, 1)
        return self.my_image

    def export(self, dt):
        self.my_image.export_to_png('test2.png')
        self.my_image.export_as_image().save('test3.png')

myapp = MyApp().run()

EDIT: I've done my research and found out that it is caused by the fact that these functions (I'm only sure about image.export_to_png but image.export_as_image provides the same result) export not the widget itself but rather canvas of the widget.

There isn't anything to the widget's appearance except what it draws on its canvas.
I don't understand your final questions.


text:
Q: How to apply a list of ApplyChangesOperation on a Roslyn Workspace I have a set of ApplyChangesOperation, which I want to apply to a Workspace in a loop.
All the operations operate on a single file.
Something like:
//Filter out a set of ApplyChangesOperation as applychangesoperations
//These changes all apply to one file with name filename
foreach (var op in applychangesoperations)
{
    op.Apply(workspace, CancellationToken.None);
}

//Assuming all these operations apply to one file
var myNewDoc = workspace.GetDocument(fileName);
var myNewDocText = await newDoc.GetTextAsync();

When I do this, I only get the last change which was applied to the workspace is in myNewDocText.
Is there a way I can apply the whole list of changes I have in
applychangesoperations to the workspace and extract the text of the updated file?


text:
Q: Compilation error in Eclipse in Kotlin + Java project, but project builds with Maven This happens in a Java and maven project in Eclipse with a kotlin nature.
In this part of the code:
    val faces = figure.getFaces()
    for (polygon in faces) {
        //...

I get the error below in eclipse, where faces, in the second line above, is underlined in red:
Cannot access class 'Polygon'. Check your module classpath for missing or conflicting dependencies

The project is a mix of Java and Kotlin. The figure object is an instance of a Java class, while the faces are a set of type Polygon which is in a different project that is pure Kotlin (ie Polygon is a Kotlin type, in a separate Kotlin project).
This Kotlin project where Polygon is, is indeed in the classpath as a Maven dependency, and in fact used by the Java class of which figure is an instance.
I think the problem is in Eclipse, because I can build the project with maven successfully. It looks like either a bug in eclipse or a configuration issue.
I know it's strange to have a mix of Java and Kotlin. I simply started this project in Java and then decided to convert it to Kotlin gradually. So far I haven't had many issues but I'm aware that Kotlin tools and support in eclipse are not mature yet.

A: Not much of a proper solution: I converted my Figure class to Kotlin and the problem went away, but I can do that because I have full control on my project.
Possibly newer versions of the eclipse plugin won't generate this error or, as suggested in the comments, switching to IntelliJ IDEA is another option.