text:
Q: socket in linux I have an error during compiling:
raja@raja-desktop:~/socket$ g++ Socket.cpp
Socket.cpp: In member function 'int Socket::recv(std::string&) const':
Socket.cpp:135: error: 'cout' is not a member of 'std'

Source of Socket.cpp:
// Implementation of the Socket class.

#include "Socket.h"
#include "string.h"
#include <string.h>
#include <errno.h>
#include <fcntl.h>

Socket::Socket() :
  m_sock ( -1 )
{

  memset ( &m_addr,
    0,
    sizeof ( m_addr ) );

}

Socket::~Socket()
{
  if ( is_valid() )
    ::close ( m_sock );
}

bool Socket::create()
{
  m_sock = socket ( AF_INET,
      SOCK_STREAM,
      0 );

  if ( ! is_valid() )
    return false;

  // TIME_WAIT - argh
  int on = 1;
  if ( setsockopt ( m_sock, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 )
    return false;

  return true;

}

bool Socket::bind ( const int port )
{

  if ( ! is_valid() )
    {
      return false;
    }

  m_addr.sin_family = AF_INET;
  m_addr.sin_addr.s_addr = INADDR_ANY;
  m_addr.sin_port = htons ( port );

  int bind_return = ::bind ( m_sock,
        ( struct sockaddr * ) &m_addr,
        sizeof ( m_addr ) );

  if ( bind_return == -1 )
    {
      return false;
    }

  return true;
}

bool Socket::listen() const
{
  if ( ! is_valid() )
    {
      return false;
    }

  int listen_return = ::listen ( m_sock, MAXCONNECTIONS );

  if ( listen_return == -1 )
    {
      return false;
    }

  return true;
}

bool Socket::accept ( Socket& new_socket ) const
{
  int addr_length = sizeof ( m_addr );
  new_socket.m_sock = ::accept ( m_sock, ( sockaddr * ) &m_addr, ( socklen_t * ) &addr_length );

  if ( new_socket.m_sock <= 0 )
    return false;
  else
    return true;
}

bool Socket::send ( const std::string s ) const
{
  int status = ::send ( m_sock, s.c_str(), s.size(), MSG_NOSIGNAL );
  if ( status == -1 )
    {
      return false;
    }
  else
    {
      return true;
    }
}

int Socket::recv ( std::string& s ) const
{
  char buf [ MAXRECV + 1 ];

  s = "";

  memset ( buf, 0, MAXRECV + 1 );

  int status = ::recv ( m_sock, buf, MAXRECV, 0 );

  if ( status == -1 )
    {
      std::cout << "status == -1   errno == " << errno << "  in Socket::recv\n";
      return 0;
    }
  else if ( status == 0 )
    {
      return 0;
    }
  else
    {
      s = buf;
      return status;
    }
}

bool Socket::connect ( const std::string host, const int port )
{
  if ( ! is_valid() ) return false;

  m_addr.sin_family = AF_INET;
  m_addr.sin_port = htons ( port );

  int status = inet_pton ( AF_INET, host.c_str(), &m_addr.sin_addr );

  if ( errno == EAFNOSUPPORT ) return false;

  status = ::connect ( m_sock, ( sockaddr * ) &m_addr, sizeof ( m_addr ) );

  if ( status == 0 )
    return true;
  else
    return false;
}

void Socket::set_non_blocking ( const bool b )
{

  int opts;

  opts = fcntl ( m_sock,
   F_GETFL );

  if ( opts < 0 )
    {
      return;
    }

  if ( b )
    opts = ( opts | O_NONBLOCK );
  else
    opts = ( opts & ~O_NONBLOCK );

  fcntl ( m_sock,
   F_SETFL,opts );

}

And Socket.h:
// Definition of the Socket class

#ifndef Socket_class

#define Socket_class

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <unistd.h>

#include <string>

#include <arpa/inet.h>

const int MAXHOSTNAME = 200;

const int MAXCONNECTIONS = 5;

const int MAXRECV = 500;

class Socket

{

 public:

  Socket();

  virtual ~Socket();

  // Server initialization

  bool create();

  bool bind ( const int port );

  bool listen() const;

  bool accept ( Socket& ) const;

  // Client initialization

  bool connect ( const std::string host, const int port );

  // Data Transimission

  bool send ( const std::string ) const;

  int recv ( std::string& ) const;

  void set_non_blocking ( const bool );

  bool is_valid() const { return m_sock != -1; }

 private:

  int m_sock;

  sockaddr_in m_addr;

};

#endif

A: To add to John's answer, also fix the top to this:
// string.h is deprecated
#include <string>
// or
#include <cstring>

A: Add this at the top of the file:
#include <iostream>


text:
Q: How can I tab inside a text box? I'm using OS X and when I am typing in a text box and press the tab key, it will jump to the next HTML element on the page. I've tried using the modifier keys to prevent this from happening but that doesn't seem to work.
Is there a way I can get my keyboard to type "tabs" in a text box without having to copy and paste them from another editing tool?

A: If you use Firefox, check this extension: https://addons.mozilla.org/en-US/firefox/addon/tabinta/

A: It's usually Ctrl-Opt-Tab if Tab is used to move keyboard focus to a different element, but seems to require a well-behaved OS X application. It works in Safari, iTunes, Things, Automator, etc.

redpajama_set_name: RedPajamaStackExchange


text: Q: could not find bibliography file: citations.bib in r shiny I'm having trouble with rmarkdown::render() recognizing a .bib file. I've tried putting it in the www file and also the directory from which the app is run with no success. I've had success locally by adding /users/blah/blah/citations.bib but when deploying this workaround it doesn't work (as it shouldn't). I've also looked into this Bibliography not working when rendering a R Markdown document within an R Shiny App, which works great for static htmls produced prior to deploying; however, my case involves the user creating a unique report while deployed and nullifies this option (I think...). Any suggestions would be much appreciated. Thanks.


text:
Q: spark standalone cluster - privilege issue in creating output file I'm working with spark standalone cluster (Linux platform and python application), using nfs to share files across master and worker machines. I'm trying with a master and one worker machine and able to submit application, it runs in worker machine but it fails to create output file (using spark saveAsTextFile), throws mkdir failed error. In both master and worker machine the nfs directory have the permission to create and delete files and I'm able to create it manually but when spark tries to create files inside that directory it creates the temporary folders ( _temporary and 0 folders) but fails to create part files.
I have tried using "chmod -R 777", but still it fails. Is there any way to make it work!
Thanks in advance

A: It seems to be a privilege issue.
When you Create a directory in NFS you have to provide directory privilege using
chown username:groupname path-of-the-NFS-directory
Then you must run spark application using privileged user or group.
If you still facing that issue
you could try these
chgrp group name path-of-the-NFS-directory
And then try,
chmod 777 path-of-the-NFS-directory
This will work.


text:
Q: How to add new link on checkout page in Magento 2.2.4? I have created 1 custom tab on the checkout page and it's working fine I follow below link to add the tab on cart page.
Magento 2 - Add step on checkout
I want to add a link name as "Create an account".On click of that link, I want to redirect the page on create account page.

A: Useful link how to add the link in a tag
Best Way Of Getting Base URL Inside KnockoutJS .html File
checkout-login-step.js file
define(
    [
        'ko',
        'uiComponent',
        'underscore',
        'Magento_Checkout/js/model/step-navigator',
        'Magento_Customer/js/model/customer',
        'mage/url'
    ],
    function (
        ko,
        Component,
        _,
        stepNavigator,
        customer,
        url
    ) {
        'use strict';
        /**
         * check-login - is the name of the component's .html template
         */
        return Component.extend({
            defaults: {
                template: 'Lalitmohan_Checkoutstep/check-login'
            },

            //add here your logic to display step,
            isVisible: ko.observable(true),
            isLogedIn: customer.isLoggedIn(),
            //step code will be used as step content id in the component template
            stepCode: 'isLogedCheck',
            //step title value
            stepTitle: 'custom step 2',

            /**
             *
             * @returns {*}
             */
            initialize: function () {
                this._super();
                // register your step
                stepNavigator.registerStep(
                    this.stepCode,
                    //step alias
                    null,
                    this.stepTitle,
                    //observable property with logic when display step or hide step
                    this.isVisible,

                    _.bind(this.navigate, this),

                    /**
                     * sort order value
                     * 'sort order value' < 10: step displays before shipping step;
                     * 10 < 'sort order value' < 20 : step displays between shipping and payment step
                     * 'sort order value' > 20 : step displays after payment step
                     */
                    21
                );

                return this;
            },

            /**
             * The navigate() method is responsible for navigation between checkout step
             * during checkout. You can add custom logic, for example some conditions
             * for switching to your custom step
             */
            navigate: function () {

            },
            getBaseUrl: function() {
                return url.build('customer/account/create');
            },
            /**
             * @returns void
             */
            navigateToNextStep: function () {
                stepNavigator.next();
            }
        });
    }
);

check-login.html file

You Are Already not Logged-in

       Create an Account
       <form data-bind="submit: navigateToNextStep" novalidate="novalidate">

                   <button data-role="opc-continue" type="submit" class="button action continue primary">

                   </button>

       </form>

A: In your xml you can add a new item under the step like so:
 <item name="create-account-link" xsi:type="array">
    <item name="component" xsi:type="string">VENDOR_MODULE/js/view/create-account-link
     </item>
 </item>

Then create a js file for it.
web/js/view/create-account-link.js
define([
    'uiComponent'
], function (Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'VENDOR_MODULE/create-account-link'
        },

    });
});

Then create the html for it:
web/template/create-account-link.html


text:
Q: High surrogate char always goes first (at lower index) within String? 1) Is high and low surrogate char order within String is fixed? Can I rely on it? Experimentally on Windows highSurrogate goes first into String (at lower index in terms of String.charAt(int index)). Is this always so on any Platform (Linux, etc)?  Is this documented anywere?
    int[] codePoint = { 0x1F71D };
    String s = new String(codePoint, 0, 1);
    System.out.println(s.length()); // 2
    System.out.println(s); //

    System.out.println((int) Character.highSurrogate(codePoint[0]));
    System.out.println((int) Character.lowSurrogate(codePoint[0]));

    System.out.println((int) s.charAt(0)); // highSurrogate
    System.out.println((int) s.charAt(1)); // lowSurrogate

2) Besides, I am a bit confused: is there any corellation between high/low surrogate codeunit order and endianness? I guess there is no corellation whatsoever, these two notions are orthogonal?

A: UTF-8 mandates that the surrogate indicator precede the second char, so that's how Java does it. Endianness is a byte order, not a char order. The JVM spec mandates endianness for the class-file format. Endianness at runtime is specified by the underlying physical platform. Some search engine time will grant you the details.
http://www.unicode.org/
https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html


text:
Q: Finding the work using integrals A tank full of water has the shape obtained by revolving the curve $y = arcsin(x)$ around the y axis
from $x = 0$ to $x = 1$. Find the work required to pump the water out of the tank. (The density of water
is $1000$ kg /
m$^3$ ).
I know I have to use integration to solve the problem, but I don't know anything other than that.

A: Show that the work involved in pumping a cross-sectional element of the water is
$$\pi \rho g x^2(y) (1-y) dy$$
where $x(y) = \sin{y}$.  $\rho$ is the density and $g$ is acceleration due to gravity.  $1-y$ is the distance needed to raise the element to pump it out of the tank.  The the total work involved is
$$\pi \rho g  \int_0^1 dy \, (1-y) \sin^2{y} $$
This integral may be done using integration by parts.  The result is that the work is
$$\frac{\pi}{4} \rho g \cos^2{(1)}$$


text:
Q: Precedence constrainted biknapsack I don't have a stong background in combinatorial optimization nor programming and I have to write some code to solve the bi knapsack (2 capacities ) with constraints of precedence.. I've been working on it for 3 months now and I can't debug it and find out why it doesn't return the right answers yet ... I used a CONCERT configuration on C++
So here's how my program works :
First I solve the linear relaxation using CPLEX, the output returns the value of the objective function + the index of the fractional variable + a variable that indicates if the relaxation is feasible + a variable that indicates if all variables are integer .
Second I implemented a branch and bound function that does a BFS tree search
so first it verifies if the relaxation is feasible and then if it is and there are fractional variables it branches on them ..
each node has 2 caracteristics : its bound which means the value of the relaxation in this node + a list of values indicating if the decision was taken on a variable or not ( it is equal to 0 if we decide not to pick the element , 1 if we decide to pick it, and 2 if we have not yet taken any decision ...)
So here's my code , problem is it branches ONLY on the first node
#include <queue>
#include<cmath>
#include<ilcplex/ilocplex.h>
#include <iostream>
#include<typeinfo>
using namespace std;

IloEnv env;
IloCplex cplex;
IloModel model;

struct node
{
    double bound;
    int val[100];
    int profit;

};

/***************************BORNE***************************/

double *bound(node u,int T,int W,int n,int Pre[],int CapaciteTemps[],int CapaciteSac[],int CoutObj[]){

    int indicefrac=0;
    double *resultat=new double[4];

    try{
        env = IloEnv();
        model=IloModel(env);

        //définition des variables de décision
        IloNumVarArray x(env,n);
        for (IloInt i=0; i<n;i++){
            x[i]=IloNumVar(env);
        }

        //contrainte 1: Capacité temps
        IloExpr Contr1(env);
        for (IloInt i=0; i<n;i++){

            Contr1 += CapaciteTemps[i]*x[i];

        }

        model.add(Contr1<=T);

        //contrainte 2: Capacité volume
        IloExpr Contr2(env);
        for (IloInt i=0; i<n;i++){

            Contr2 += CapaciteSac[i]*x[i];
        }
        model.add(Contr2<=W);

        //contrainte 3: Relaxation des variables entre 0 et 1 les variables peuvent prendre des valeurs continues mais que sur l'intervalle 0,1

        for (IloInt i=0; i<n;i++){
            model.add(0<=x[i]<=1);
        }

        //contrainte 4: Contrainte de précédence si l'on veut prendre un élément il faut avoir nécéssairement avoir pris tout ses prédécesseurs

/*
        for(IloInt i=0;i<n;i++)
        {
            for(IloInt j=0;j<n;j++){

                if(Pre[i]<=Pre[j])

                {
                    model.add(x[i]>=x[j]);
                }

            }
        }

*/

        //élément pris ou non on force sa valeur a être égale à 0 ou à 1

        for (IloInt i=0;i<n;i++){
            if(u.val[i]==0){
                model.add(x[i]<=0);}
            else if(u.val[i]==1){
                model.add(x[i]>=1);
            }

        }

        //fonction objectif
        IloExpr obj(env);
        for (IloInt i=0;i<n;i++){
            obj += CoutObj[i]*x[i];
        }
        model.add(IloMaximize(env,obj));

        cplex=IloCplex(model);

        cplex.solve();

        //affichage de la valeur des variables

        for(IloInt i=0; i<n; i++){
            cout<<"x["<<i<<"]= "<<cplex.getValue(x[i])<<endl;
        }

        if ( ! (cplex.getStatus() == IloAlgorithm::Infeasible ) ) {
            bool isfractionnelb=false;
            double isfractionneli;

            for(IloInt i=1;i<n;i++){

                if(cplex.getValue(x[i]) != (int)cplex.getValue(x[i]))
                    isfractionnelb=true;
            }

            if(isfractionnelb==true){
                for(IloInt i=1;i<n;i++){

                    if(abs(cplex.getValue(x[i])-0.5)<abs(cplex.getValue(x[indicefrac])-0.5) ){
                        indicefrac=i;
                    }
                }
            }

            if(isfractionnelb==true)
            {isfractionneli=1;}
            else{isfractionneli=0;}

            resultat[0]=cplex.getObjValue(); // borne , valeur de la relaxation
            resultat[1]=(double)indicefrac;  //indice fractionnaire
            resultat[2]=isfractionneli; // indique si une valeur fractionnaire existe après la relaxation
            resultat[3]=1;  // indique si la relaxation linéaire est réalisable

        }
        if (  (cplex.getStatus() == IloAlgorithm::Infeasible ) ){cout<<"infeasable";}

    }catch(IloException& e){

        e.print(cout);

    }

    return resultat;

}

int knapsack(int n, int p[],int t[],int T,int w[], int W, int Pre[])
{
    queue<node> Q;
    node v,ug,ud;
    vector<int> pV;
    vector<int> wV;
    vector<int> tV;
    vector<int> tPre;
    Q.empty();

    double *borneg;
    double *borned;

    for (int i = 0; i < n; i++)
    {
        pV.push_back(p[i]);
        wV.push_back(w[i]);
        tV.push_back(t[i]);
        tPre.push_back(Pre[i]);
    }

v.profit=0;

    for(int i=0;i<n;i++)
    {v.val[i]=2;}

    int maxProfit = 0;

    double *borne=bound(v,T, W, n,Pre, t, w, p) ;
    v.bound=borne[0];
    cout<<"borne "<<borne[0]<<endl;

    if(borne[2]==1){
        cout<<"indice fractionnaire : "<<borne[1]<<endl;}
    Q.push(v); // adds at top of list

    if( borne[3]==1 ){
        if(borne[2]==0){
            cout<<"la solution optimale est : "<<endl;
            maxProfit=borne[0];
            v = Q.front(); // reference a l'élement suivant dans la liste
            Q.pop(); // supprime l'élément suivant de la liste
        }

        else{
            // v = Q.front(); // reference a l'élement suivant dans la liste
            // Q.pop(); // supprime l'élément suivant de la liste
            //Q.push(v); // adds at top of list

            while (!Q.empty())
            {

                v = Q.front(); // reference a l'élement suivant dans la liste
                Q.pop(); // supprime l'élément suivant de la liste

                cout << "Noeud courant:";
                for(int i = 0 ; i < n ; ++i)
                    cout << " " << v.val[i];
                cout << endl;
                cout << "Objet fractionnaire: " << borne[1] << endl;

                int indice=(int)(borne[1]);

                node ug;
                node ud;
                int k[n];

for(int i=0;i<n;i++)
{
if (ud.val[i]==0)
k[i]=0;
else if (ud.val[i]==1)
k[i]=1;
else
k[i]=0;
}

for(int i=0;i<n;i++)
{ud.profit+=p[i]*k[i];}
for(int i=0;i<n;i++)
{
    int k[n];
if (ug.val[i]==0)
k[i]=0;
else if (ug.val[i]==1)
k[i]=1;
else
k[i]=0;

}

for(int i=0;i<n;i++)
{ug.profit+=p[i]*k[i];}

                for(int i=0;i<n;i++)
                {ug.val[i]=v.val[i];
                ug.val[indice]=1;
                }

                for(int i=0;i<n;i++)
                {ud.val[i]=v.val[i];}
                ud.val[indice]=0;

                borneg=bound(ug,T, W, n,Pre, t, w, p) ;
                borned=bound(ud,T, W, n,Pre, t, w, p) ;

cout<<"borne fils gauche"<<borneg[0]<<endl;
cout<<"borne fils droite"<<borned[0]<<endl;

                if(borned[3]==1)
                {if (borned[2]==0){
if(ud.profit>maxProfit)
{maxProfit=ud.profit;}
                    if (borned[0]>maxProfit)
                    {

                     borne[1]=borned[1];
            //  for(int i=0;i<n;i++)
                        //      {v.val[i]=fil[1].val[i];}
                         //     v.bound=fil[1].bound;
Q.push(ud);
                    }

                }

                }

            //  else {ud = Q.front(); // reference a l'élement suivant dans la liste
            //  Q.pop();
            //  cout<<"aaaaa";}

                if(borneg[3]==1)
                {if (borneg[2]==0){
                    if(ug.profit>maxProfit)
                    {maxProfit=ug.profit;}

                    if (borneg[0]>maxProfit)
                    {Q.push(ug);
                    borne[1]=borneg[1];

            //      for(int i=0;i<n;i++)
            //      {v.val[i]=fil[0].val[i];}
             //     v.bound=fil[0].bound;
               //   borne[1]=borneg[1];
                    }
                }

                }

                //else {
                //ug = Q.front(); // reference a l'élement suivant dans la liste
                //Q.pop();
                //}

cout<<"debug1"<<endl;

            }
            cplex.exportModel("/net/cremi/sbounejmate/prog1.lp");

        }}
    else{cout <<"problème irréalisable"<<endl;
    maxProfit =0;

    }

    return maxProfit;
}

int main()
{

    vector<int> pV;
    vector<int> wV;
    vector<int> tV;
    vector<int> tPre;
    int n = 6;
    int W = 6;
    int T= 3;
    int p[6]= {15,5,15,15,3,5};
    int w[6]= {1,5,5,10,2,3};
    int t[6]={2,1,3,2,2,3};
    int Pre[6]={1,1,5,1,18,1};
    for (int i = 0; i < n; i++){
        pV.push_back(p[i]);
        wV.push_back(w[i]);
        tV.push_back(t[i]);
    }

    //double *b=bound(u,T, W, n, t, w, p) ;
    int k=knapsack(n,p,t,T,w,W,Pre);
    cout<<"knapsack"<<k<<endl;

    //cout<<"La valeur de la relaxation de l'objectif est : "<<b[0]<<endl;
    //cout<<"L'indice fractionnaire le plus proche de 0.5 est : "<<b[1]<<endl;

    return 0;

}

I'd be very grateful if you help me find out where my logic went wrong

A: I'm not going to solve your problem, but if you're working three months on this, then you need some strategies.
I'm missing any kind of debugging information. It's easy. You add some variables
static bool debug_thisthing = true;
static bool debug_thatthing = true;
... and so on

and then for example afer the code following "définition des variables de décision" you add
if (debug_thisthing) {
    ... print out stuff to make sure that you can check
    ... that these values are correct.
}

And you do that with after every step, making sure that at every step you have the results that you expect, and once you've checked one bit you can set the debugging code for that part to false.
One day of focused work and you'll be in a much better position.
Next you construct some examples where you can find the solution by hand, and see how they work out.


text:
Q: How to select html element located in an iframe on the page I am writing webextension to ease account managers login into accounts, when I try to automate login of the user into angularjs app when I try to get login input with js it is not found. The element is represented in browser's inspector panel but is absent in page source.
UPD: I found the reason of the issue - this element is located in the iframe on the page and my current issue is how to access iframe's document.
I found that in devtools console there is command 'cd' what does exactly what I need:
var ifr = document.getElementById('aid-auth-widget-iFrame');
var ifrContent = ifr.contentWindow;
cd(ifrContent);
document.getElementById('sign-in').value = 'login';

But but 'cd' can not be executed from within the script on the page.
Next I did try to access frame's document as:
var ifr = document.getElementById('aid-auth-widget-iFrame');
ifr.contentWindow.document;
SecurityError: Permission denied to access property "document" on cross-origin object

Is it possible to execute a js in the iframe existing on the page or select and manipulate an element within this iframe?
Deprecated question content:
I found that angular.element probably may help but it does not find an element also. Probably it's because I tried 'document' what is the same 'document' what I access with vanilla js and where desired element is absent.
Do I need to pass something else to angular.element argument? Tried few selectors like angular.element('div#pageWrapper') as kind of root but getting error(error says that such selector is unsupported)
angular.element('div#pageWrapper')
Error: [jqLite:nosel] http://errors.angularjs.org/1.5.8/jqLite/nosel

A: I don't think angular.element you are using will work for your requirement. Try using angular.element(document).find(#account_name_text_field).
Please refer more info in https://docs.angularjs.org/api/ng/function/angular.element

A: The find() method is only limited to lookups by tag name. So you cannot access the element using the method you have shown.
You can instead access the element using the syntax below
angular.element($document[0].querySelector('#account_name_text_field'));

// or

angular.element(document.querySelector('#account_name_text_field'));

where $document is a jqLite wrapper for the browser's window.document object.


text:
Q: Why don't clojure operators match normal logic operations? Would someone please explain clojure's unusual operators?
Why does or return first true or last false? Why does and return first false or last true?
Why don't they return true or false?

A: Convenience. Clojure embraces falsey (nil and false are both falsey) and truthy (everything else).
(or a b c)

Is more convenient than
(cond (not (nil? a)) a (not (nil? b)) b (not (nil? c)))

Treating nil as false makes expressions terser, and returning values tend to make functions and conditionals more composable. For example
(if a b c)

In an imperative language would return no result. In Clojure it returns a value so you can compose the expression with other expressions.
(or (if a b c) (if d e f))

Similarly or and and are more composable with language abstractions when they return a value instead of a boolean.
(if a (or b c) d)

It really boils down to if you want true/false or truthy/falsey. Truthy/falsey allows for more concise expressions and is the Clojure choice.

A: This is called short-circuit evaluation. Short-circuit operators evaluate minimal set of arguments that is necessary to get result. For example or evaluates to true when at least one argument evaluates to true, so or can stop ("short-circuit") evaluating arguments after the first true and return it.
It's common for many programming languages (e.g. C++, Java). Clojure additionally takes advantage of its feature that all values can be coerced to boolean so or and and can return the last evaluated argument rather than corresponding boolean value.

A: To illustrate what the question is about:
user=> (or [1] nil)
[1]
user=> (or nil [1])
[1]
user=> (and [1] nil)
nil
user=> (and nil [1])
nil

Here [1] is truthy and nil is falsey. Truthy/false is something that can be considered as true/false. Obviously the value true is truthy and the value false is falsey.
Why doesn't and & or return a boolean?
Well, it actually does:
user=> (or false true)
true
user=> (or true false)
true
user=> (or false false)
false
user=> (or true true)
true
user=> (and false true)
false
user=> (and true false)
false
user=> (and false false)
false
user=> (and true true)
true

So it's not that and & or is disobeying laws of logic. Their functionality is extended to provide support for other types. And other usages stem from this.
Short-cirtuiting
I forgot to mention this, until I saw Alex Filatov's answer. If the first expression to and/or evaluates to truthy/falsey, then the second argument is not evaluated at all:
user=> (or true (do (prn :huh) false))
true
user=> (and false (do (prn :huh) true))
false

Hence the similarity to if & cond.
Note that and & or takes any number of arguments and the same rule applies to third, fourth and further arguments. Basically they evaluate their arguments from left to right, failing as early as possible.


text:
Q: find image links in html using php Why does this code not find picture links in text?
$text = 'text text  text text';
preg_match_all('#^http:\/\/(.*)\.(gif|png|jpg)$#i', $text, $all_img);

A: There are any number of ways to parse the DOM with PHP. Here is an example that does exactly what you want (gets every img src from the html string)
http://simplehtmldom.sourceforge.net/#fragment-11
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
    echo $element->src . '
';

Regular expressions are poorly suited for parsing HTML.

A: Remove the ^ and $ and if you want to capture the url for later use surround in ()
preg_match_all('#(http:\/\/(.*)\.(gif|png|jpg))#i', $text, $all_img);


text:
Q: Best way to validate infopath form - specific scenario I have this infopath form with 8 fields named:
Field1
Field2
Field3
Field4
etc.

How should I go to validate the form in a way that I cannot have duplicate values on those fields.
I cannot use code-behind because I dont have access to the central admin, plus a code-behind sandbox solution is too buggy for my like, keep getting random errors when publishing, using it. So I am looking for a no-code solution. I am using Sharepoint Server 2010.
Thanks

A: If you're wanting to just compare values to make sure there are no duplicates among them, you could create a validation rule on each of the fields that compares the values of each of the affected fields every time the value changes, and throws a validation error if duplicates are found.

A: So I end up doing a full compare of all the possible combinations:
8 choose 2 = 28.

Thats a lot of rules. There is another limitation, one item cannot have more than 6 rules (or at least i thought so), looks like this limitation is only on the designer to overcome this limitation do the folloing:
In the Rule condition select expression and you can insert as many comparisiona as you want like:
. = ../my:Field2 or . = ../my:Field3 or . = ../my:Field4 ...etc


text:
Q: How to get a list of files (*. jpg) from all folders? How do I get a list of files (*.jpg) from all folders, using Script-FU in GIMP?
(let* ((filelist (cadr (file-glob pattern 1)))

This only gets files from the current folder.

A: It will be a bit complicated, but it can be done. The list of files which file-glob returns for the current directory includes subdirectories. So you can use that list to recursively build more glob strings, which can be passed to file-glob, and so on.
(define separator "\\") ; I am using Windows
(define (all-files dir)
  (let* ((patt  (string-append dir separator "*"))
         (files (cadr (file-glob patt 1))))
    (append files (search-dirs files))))
(define (search-dirs dirs)
  (if (null? dirs)
      (list)
      (append (all-files (head dirs)) (search-dirs (tail dirs)))))

This works, but it is slow. Perhaps you can find a way to make it faster?
By the way, this returns all files, not just JPGs. To make it return only JPGs, modify the line which says "(append files (search-dirs files))". Rather than appending "files", filter out the JPGs and append those only.


text:
Q: Export excel file without grouping options in angular slickgrid I have enabled the excel export feature with grouping options in angular slickgrid. without the grouping data, the exported file shows the data in table style. While grouping the data in slickgrid, the exported file formed with grouping style. So i cant able to view the data in table style. emphasized textI want to export the data in table style. Kindly assist me to achieve this.
Here attached the sample screenshot
Exporting file with grouping

Expected file look

Sample Code
 gridOptions: GridOption = {
    enableAutoSizeColumns: false,
    autoFitColumnsOnFirstLoad: false,
    autoCommitEdit: true,
    enablePagination: true,
    pagination: {  // Pagination UI - Item per page select options for default pagintation
        pageSizes: [10, 15, 20, 25, 50, 75, 100],
        pageSize: 25
    },
    autoEdit: false,
    rowHeight: 40,
    headerRowHeight: 40,
    enableCellNavigation: true,
    editable: true,
    enableAutoResize: true,
    enableSorting: true,
    enableFiltering: true,
    enableExcelExport: true,
    enableExport: true,
    i18n: this.translateService,
    gridMenu: {
        hideExportExcelCommand: true,
        hideExportCsvCommand: true,
        customItems: [{
            command: "cspfm-excel-export",
            titleKey: "EXPORT_TO_EXCEL",
            iconCssClass: "fa fa-file-excel-o",
            action: (event, callbackArgs) => {
                this.excelExport(event, callbackArgs)
            }
        }, {
            command: "cspfm-csv-export",
            titleKey: "EXPORT_TO_CSV",
            iconCssClass: "fa fa-download",
            action: (event, callbackArgs) => {
                this.excelExport(event, callbackArgs)
            }
        },
        { divider: true, command: '', positionOrder: 90 },
        {
            command: "cspfm-appm-guide-fetch-mode-fully",
            titleKey: "Full fetch",
            iconCssClass: "icon-mat-explore",
            action: (event, callbackArgs) => {
                this.dataFetchMode = 'Full';
                this.fetchModeChanged()
            },
            positionOrder: 91
        }, {
            command: "cspfm-appm-guide-fetch-mode-batch",
            titleKey: "Batchwise fetch",
            iconCssClass: "icon-mat-autorenew",
            action: (event, callbackArgs) => {
                this.dataFetchMode = 'Batch';
                this.fetchModeChanged()
            },
            positionOrder: 92
        }, {
            command: "cspfm-appm-guide-fetch-mode-action",
            titleKey: "On click batchwise",
            iconCssClass: "icon-mat-touch_app",
            action: (event, callbackArgs) => {
                this.dataFetchMode = 'OnClickBatch';
                this.fetchModeChanged()
            },
            positionOrder: 93
        }, {
            command: "cspfm-toggle-pagination",
            titleKey: "Toggle pagination",
            iconCssClass: "fa fa-bookmark",
            action: (event, callbackArgs) => {
                this.togglePagination(event, callbackArgs)
            },
            positionOrder: 94
        },
        {
            command: "cspfm-groupby",
            titleKey: "Group-by",
            iconCssClass: "icon-mat-account_tree",
            action: (event, callbackArgs) => {
                this.openDraggableGroupingRow()
            },
            positionOrder: 95
        }, {
            command: "cspfm-clear-groupby",
            titleKey: "Clear Grouping",
            iconCssClass: "fa fa-times",
            action: (event, callbackArgs) => {
                this.clearGrouping()
            },
            positionOrder: 96
        }
        ]
    },
    enableAutoTooltip: true,
    autoTooltipOptions: {
        enableForCells: true,
        enableForHeaderCells: true,
        maxToolTipLength: 1000
    },
    headerMenu: {
        hideColumnHideCommand: true
    },
    autoResize: {
        containerId: this.gridContainerId,
        calculateAvailableSizeBy: 'container'
    },
    exportOptions: {
        exportWithFormatter: true
    },
    excelExportOptions: {
        exportWithFormatter: true,
    },
    enableTranslate: true,
    presets: {
        sorters: [{ columnId: this.tableColumnInfo['insitute']['institutename_7']['prop'], direction: 'ASC' }],
    },
    enableAsyncPostRender: true, // for the Angular PostRenderer, don't forget to enable it
    asyncPostRenderDelay: 0,    // also make sure to remove any delay to render it
    params: {
        angularUtilService: this.angularUtilService // provide the service to all at once (Editor, Filter, AsyncPostRender)
    },
    enableDraggableGrouping: true,
    createPreHeaderPanel: true,
    showPreHeaderPanel: false,
    preHeaderPanelHeight: 40,
    draggableGrouping: {
        dropPlaceHolderText: 'Drop a column header here to group by the column',
        deleteIconCssClass: 'fa fa-times',
        onGroupChanged: (e, args) => this.onGroupChanged(e, args),
        onExtensionRegistered: (extension) => {
            this.draggableGroupingPlugin = extension
        }
    },
};

 **excelExport(event, callbackArgs)** {

    if (this.draggableGroupingPlugin && this.draggableGroupingPlugin.setDroppedGroups) {
        this.draggableGroupingPlugin.clearDroppedGroups();

        this.gridOptions['autoFitColumnsOnFirstLoad'] = true
        this.gridObj.setOptions(this.gridOptions);
    }
    var fileType = FileType.xlsx;
    var displayFileType;
    if (callbackArgs['command'] == 'cspfm-excel-export') {
        fileType = FileType.xlsx;
        displayFileType='Excel ';
    } else if (callbackArgs['command'] == 'cspfm-csv-export') {
        fileType = FileType.csv;
        displayFileType='CSV ';
    }
    const cspfmGridCustomData = callbackArgs['grid']['cspfm_grid_custom_data']
    if (cspfmGridCustomData) {
        const pageTitle = cspfmGridCustomData['page_title_key']
        const objectName = cspfmGridCustomData['object_display_name']

        this.presentToast("Export to " + displayFileType + "initiated");

        return this.translateService.get(pageTitle).subscribe(res => {
            var filename = res;
            if (objectName) {
                filename = res + " - " + objectName;
            }
            var options = {
                filename: filename,
                format: fileType
            }
            if (callbackArgs['command'] == 'cspfm-excel-export') {
                return cspfmGridCustomData['angular_grid_excel_export_service_instance'].exportToExcel(options).catch(error => {
                    this.showAlert(error.message);
                    return error;
                });
            } else {
                options['delimiter'] = (fileType === FileType.csv) ? DelimiterType.comma : DelimiterType.tab;
                return cspfmGridCustomData['angular_grid_export_service_instance'].exportToFile(options).catch(error => {
                    this.showAlert(error.message);
                    return error;
                });
            }
        })
    }
}


text:
Q: How to make the flex item text wrapped under the adjutants item How to get the text wrapped under the points?
https://codepen.io/neginbasiri/pen/ZEGReRZ

  <svg class="icon--icon--base--17 pointLine__RooIcon-wgyo1p-0 iBQvHK">IMAGE</svg>

16,000

Points when you join or switch
3

In the example switch should show under 16,000.

A:

.bUhvVh {
    display: flex;
    margin-bottom: 20px;
    width: 300px;

}

.iBQvHK {
    color: #e40000;
    font-size: 24px;
    margin-right: 10px;
    border: 1px solid red;
    width: 20px;
}

.icon--icon--base--17 {
    height: 1em;
    min-width: 1em;
    vertical-align: middle;
    fill: currentColor;
}

.cPwDGx {
    font-family: Ciutadella Regular;
    font-size: 18px;
    color: #555;
    letter-spacing: normal;
    line-height: 1.5;
}

.enMiay {
    float: left;
    font-family: Ciutadella Medium;
    margin-right: 4px;
    position: relative;
    color: #323232;
}

.dufgDt {
    margin: 0;
    font-family: 'Ciutadella Regular',sans-serif;
    font-size: 18px;
    color: #555;
    letter-spacing: normal;
    line-height: 1.5;
}

  <svg class="icon--icon--base--17 pointLine__RooIcon-wgyo1p-0 iBQvHK">IMAGE</svg>

16,000

 Points when you join or switch 3

*

*Remove display: flex; flex: 1 from .cPwDGx.

*Remove display: inline-block from .enMiay and add float: left for this element.

*Update width to min-width for icon--icon--base--17. It will not shrink if text is larger.

Refer : https://codepen.io/bala_tamizh/pen/WNvyEPg


text:
Q: Gimp batch create from differing elements I am trying to create images made up from different elements, some of which are static, some of which are variable.
The endresult should be a set of flyers, made of of a background image, a logo (both static) as well as a QR code and a description of the QR code (text) - both variable.
I do have the background image, logo and QR codes (several dozens) as separate files and am looking for a away to batch create these flyers automatically whereby each QR code is combined wit the background image and the logo (and ideally text as well).
I am well versed with BIMP, however this doesn't allow the option to have certain elements be variables.

A: Forget Gimp and use ImageMagick's compose utility.
See here.


text:
Q: laravel eloquent query group by last id Hi I'm trying to get the last register in DB for each equipment
I got like
id   | id_equip
-----+----------
   1 |    3
   2 |    3
   3 |    3
   4 |    2
   5 |    2

I want to query like the last id of each equip like:
  id   | id_equip
  -----+----------
  3    |    3
  5    |    2

I tried this:
$calibracao = $this->calibracao->orderBy('id', 'DESC')->groupBy('id_equip')->get();

thanks for the help!

A: A simple way, without join, using max:
$query = DB::table('equip')
    ->select(DB::raw('*, max(id) as id'))
    ->groupBy('id_equip')
    ->orderBy('id', 'asc')
    ->get();

(Assuming, of course, that you can count on your id to be in date order.)

You can also do this with Eloquent, using a self-referencing one-to-one relationship. The query takes longer, but it's much more Laravel-like:
Define the relationship in your model:
class myModel extends Eloquent {
    public function latestEquipment()
    {
        return $this->hasOne('myModel', 'id_equip', 'id_equip')->latest();
    }
}

(Note that in this case, we're using latest() so that we don't rely on the order of ids to determine the most recent entry, but rather on the created_at date of each record. This is more accurate.)
To retrieve all the records, with their latest equipment entry:
$latest = myModel::with('latestEquipment')->groupBy('id_equip')->get();
// loop over the results
foreach ($latest as $l) {
    if ($l->equipment) {
        echo('ID: ' . $l->id . 'ID_EQUIP: ' . $l->id->id_equip . '<br>');
    }
}

A: I'm not sure if there's an easier way and this is kind of convoluted because of the join, but it should give the result you want:
DB::table('equip as e')
    ->select('e.*')
    ->join(DB::raw("(SELECT id_equip, MAX(id) id FROM equip GROUP BY id_equip) as _e"), function ($join) {
        $join->on('e.id', '=', '_e.id')->on('e.id_equip', '=', '_e.id_equip');
    })
    ->orderBy('id', 'asc')
    ->get();

A: public function latest($equipamentos)
    {
        foreach ($equipamentos as $equip)
        {
            $latest[$equip->cod] = DB::table('tb_calibracao')
                                ->where('cod_equipamento', $equip->cod)
                                ->where('parecer', '1')
                                ->orderBy('cod', 'Desc')
                                ->first();
        }

        return $latest;
    }

That worked, thx for the help!


text:
Q: Determine context of framework currently running in I have a .net standard library that will be called from either a .net framework 4.x program or a .net core program.  When the code is executing a method in the .net standard library I would like to check to see the context of the framework it was called from.  More specific : if called from within 4.x I want to ensure that the 4.x set the value of a static variable in the standard library, whereas when called from core I want to ensure it wasn't set.

A: You could possibly handle that with an #if preprocessor directive.  There is the list of target framework's names in the article, so you could do something akin to
#if NET48 || NET472 || ...
    staticVariable = "SomeStaticValue";
#endif

As a small suggestion, though, if it's possible for you to set that variable in the program that's using it, that'd likely be easier.  It could then be passed into the library and used if needed.


text:
Q: How to update state inside componentDidMount? I'm using fetch API and I want update the const called state inside the componentDidMount() (with onChange) which are being using in a template string. How do I update this value with onChange?
import React, {Component} from 'react'

class Data extends Component {
    constructor() {
        super();
        this.state = {
            items: {},
            value: '',
            isLoaded: false
        }
    }

    handleChange(e) {
        this.setState({value: e.target.value});
    }

    componentDidMount() {

        const state = this.state.value

        fetch(`http://api.timezonedb.com/v2.1/get-time-zone?key=J9X3EOT2EM8U&format=json&by=zone&zone=${state}`)
        .then(res => res.json())
        .then(json => {
            this.setState({
                isLoaded: true,
                items: json,
            })
        });
    }

    render(){
        const {isLoaded} = this.state;

        if(!isLoaded) {
            return
Loading...

        }

        return(

                <select onChange={this.handleChange}>
                    <option value="America/Chicago">Chicago</option>
                    <option value="America/Sao_Paulo">São Paulo</option>
                </select>

        )
    }
}

So, how can I update the value of the const state with onChange?

A: componentDidMount() is called when the React component has mounted, and it happens only once.
If I understand correctly, you want to call fetch on each change of the value stored under value state property, so the componentDidMount method is not a perfect place to put that kind of logic. You can create a separate method called fetchData and pass the value to it as an argument. Then you can call that method on componentDidMount as well as on each value property change (in our case - onChange event).

import React, { Component } from "react";

class Data extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: {},
      value: "America/Chicago",
      isLoaded: false
    };

    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    const { value } = this.state;

    this.fetchData(value);
  }

  handleChange(event) {
    const value = event.target.value;

    this.setState({
      value
    });

    this.fetchData(value);
  }

  render() {
    const { isLoaded, value, items } = this.state;

    if (!isLoaded) {
      return
Loading...
;
    }

    return (

        <select onChange={this.handleChange} value={value}>
          <option value="America/Chicago">Chicago</option>
          <option value="America/Sao_Paulo">São Paulo</option>
        </select>
        {JSON.stringify(items)}

    );
  }

  fetchData(value) {
    fetch(
      `https://api.timezonedb.com/v2.1/get-time-zone?key=J9X3EOT2EM8U&format=json&by=zone&zone=${value}`
    )
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json
        });
      });
  }
}

Working demo: https://codesandbox.io/embed/728jnjprmq

A: Tomasz's code has 2 mistakes: (1) it fetches resources w/o checking if the component has been unmounted; (2) it starts the request w/o updating the UI first.
I would do the following instead:
import React, {Component} from 'react'

class Data extends Component {
    constructor() {
        super();
        this.state = {
            items: {},
            value: '',
            isLoaded: false
        }

        this._isMounted = false;

        // don't forget to bind your methods
        this.handleChange = this.handleChange.bind(this);
    }

    componentDidMount() {
        this._isMounted = true;
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    handleChange(e) {
        const value = e.target.value;
        this.setState({ value }, () => {
            if (!this._isMounted) return;
            const url = `http://api.timezonedb.com/v2.1/get-time-zone?key=J9X3EOT2EM8U&format=json&by=zone&zone=${value}`
            fetch(url).then((res) => {
                if (!this._isMounted) return;
                const data = res.json();
                this.setState({ isLoaded: true, items: data });
            })
        });
    }

    render(){
        const { isLoaded } = this.state;

        if(!isLoaded) {
            return
Loading...

        }

        return(

                <select onChange={this.handleChange}>
                    <option value="America/Chicago">Chicago</option>
                    <option value="America/Sao_Paulo">São Paulo</option>
                </select>

        )
    }
}

A: Assuming you want to refresh the value of this.state.items when the user changes the value of the select, you can do this in the onChange. However, your code is in a few (incorrect) pieces. Let's start from the top.
First of all, you're setting the value property of state to '', so your componentDidMount function is going to see that value. I assume that's no good, so let's strip that out of componentDidMount entirely. We can move this code to the handleChange function instead, but it'll still need to be changed:
handleChange(e) {
    this.setState({value: e.target.value});

    fetch(`http://api.timezonedb.com/v2.1/get-time-zone?key=J9X3EOT2EM8U&format=json&by=zone&zone=${e.target.value}`)
    .then(res => res.json())
    .then(json => {
        this.setState({
            isLoaded: true,
            items: json,
        })
    });
}

Notice my change - we can't access the value from the state, because setState is asynchronous, and so the value hasn't been updated by this point. We know the value comes from the select though.
The other thing you could do to improve this functionality is to turn the select into a controlled component. To do this, you just have to set the value of the field to be controlled by the state of this component. Since you're using an onChange listener for this, it makes the field a controlled component (if you weren't using an onChange, it would be a read-only field.
The loading variable in state appears to be being used incorrectly, I'm guessing you just need to check if there's data in 'items'. I'll remove this for now, but you could come back to this.
render(){
    const {isLoaded} = this.state;

    if(!isLoaded) {
        return
Loading...

    }

    return(

            <select onChange={this.handleChange}>
                <option value="America/Chicago">Chicago</option>
                <option value="America/Sao_Paulo">São Paulo</option>
            </select>

    )
}


text:
Q: Find order of elliptic curve Given a prime $p$ such that $3$ does not divide $p-1$, what is the order of the elliptic curve over $\mathbb{F}_p$ given by $E\left(\mathbb{F}_p\right)=\left\{ (x,y)  \in {\mathbb{F}_p}^2 \;|\; y^2=x^3+7 \right\}$
I thought if I could find the order of a point then I could find multiples of that which lie in the interval given by Hasse's theorem, but it seems like I dont have enough information for this approach. Any hint as to what else I should look at would be appreciated!

A: The key result: If $p \not \equiv 1 \mod{3}$ then every element of $\mathbb{F}_p$ has exactly one cube root.  Prove this, then the problem should be easy.


text:
Q: INTERNAL_SERVICE_ERROR PayPal REST API https://api.paypal.com/v1/payments/payment Using "LIVE" credentials, I'm getting an INTERNAL_SERVICE_ERROR accepting a credit card payment, using this resource: https://api.paypal.com/v1/payments/payment.  Same error happens on the web and via cURL. NOTE: This does not happen in SANDBOX only LIVE.  See steps to recreate below.  For this post, I had to add a space in "http s" as I cannot submit more than 2 links.

*

*Get an OAuth token (substitute username/password in LIVE_USER_ID:LIVE_PASSWORD
curl http s://api.paypal.com/v1/oauth2/token -H "Accept: application/json" -H  "Accept-Language: en_US" -u "LIVE_USER_ID:LIVE_PASSWORD" -d "grant_type=client_credentials"

*No problem getting a token using LIVE credentials.  Add the token to the following request to the resource:
curl -v http s://api.paypal.com/v1/payments/payment \

-H "Content-Type:application/json" \
-H "Authorization:Bearer YK.GUHkGhBAQgGgGkilvHoL7DdE9SVq.IDl-mRwAZeM" \
-d '{
  "intent": "sale",
  "payer": {
    "payment_method": "credit_card",
    "funding_instruments": [
      {
        "credit_card": {
          "number": "5500005555555559",
          "type": "mastercard",
          "expire_month": 12,
          "expire_year": 2018,
          "cvv2": 111,
          "first_name": "Joe",
          "last_name": "Shopper"
        }
      }
    ]
  },
  "transactions": [
    {
      "amount": {
        "total": "0.01",
        "currency": "USD"
      },
      "description": "This is the payment transaction description."
    }
  ]
}'
"name":"INTERNAL_SERVICE_ERROR","message":"An internal service error has occurred","information_link":"http_s://developer.paypal.com/webapps/developer/docs/api/#INTERNAL_SERVICE_ERROR","debug_id":"525bfb7a6382a"}johnruffin:~ johnruffin$
Thoughts???

A: Thanks for bringing this issue to our attention.  I've opened an internal bug with the payments rest api development team.  From the debug id provided I see that the credit card is being refused.  In the future the error message from this scenario will fall under this error condition: https://developer.paypal.com/webapps/developer/docs/api/#CREDIT_CARD_REFUSED
Please try a another/valid credit card to verify.

A: Looks like the URL is not well formed. It's https and not http s as provided above.
Tried the calls now, it works fine. Please check and confirm.


text:
Q: SKAction playSoundFileNamed stops background music I want my SpriteKit game not to interrupt background music that user listens (Music.app or radio app).
Everything goes fine until execution reaches this line:
sSharedShootSoundAction = [SKAction playSoundFileNamed:@"plane_shoot.aiff"
                                     waitForCompletion:NO];

After this line background music stops. How to avoid this?

A: I have also encountered this problem myself. FYI my solutions are in swift so just translate this to Objective C if you are still using that.
For me my solution included two parts. First, I had to initialize my SoundAction SKAction within my didMoveToView function in my scene file. So your scene file should look something like this:
import SpriteKit
import GameKit
import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {

    var sSharedShootSoundAction: SKAction = SKAction()

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        sSharedShootSoundAction = SKAction.playSoundFileNamed("plane_shoot.aiff", waitForCompletion: false)
    }

}

Then in your AppDelegate file you need to place the following line of code in your application didFinishLaunchingWithOptions function. (DO NOT FORGET TO IMPORT AVFOUNDATION IN YOUR APPDELEGATE). So your app delegate method should like something like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // INSERT THIS LINE BELOW.
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)

    return true
}

Hope this solves it for you as it did for me! Let me know if it doesn't.

A: Update for Swift 5, Xcode 11:
Put this into AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    // Below line will set all app sounds as ambient
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)

    return true
}


text:
Q: The right way to use a PHP backend serving oauth tokens to a Javascript frontend sending credentials? I know Javascript but I don't know PHP. Through some tutorials, I build a basic PHP server hosted on an AWS EC2 Linux environment. I've built a simple PHP script that sends a post request to an external API to get a token with correct credentials. My Javascript does a typical fetch post to the PHP server with correct credentials. The response I get is a response object with a body that has a readableStream object with key/value locked: false. I've never seen this before.
Here is my PHP code with credentials disguised:
<?php

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

    $email = $_POST['email'];
    $password = $_POST['password'];
    $post_array = array(
        'partnerName' => '<partner name hardcoded>',
        'partnerPassword' => '<password hardcoded>',
        'partnerUserID' => $email, // param passed from frontend
        'partnerUserSecret' => $password // same here
    );
    postAuth($post_array);

function postAuth($post_array){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_array);
    curl_setopt($curl, CURLOPT_URL, '<address to external site to get auth token>');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    $result = curl_exec($curl);
    if(!$result){die("Connection Failure");}
    curl_close($curl);
    echo $result;
}

And here is my Javascript:
const authApi = async () => {
  const data = {
    email: "<email required to get auth token>",
    password: "<password required to get auth token>",
  };
    const response = await fetch("<php server address>", {
        method: "post",
        data: data,
    })
    console.log(response)
};

authApi()


text:
Q: Facebook - OAuth Token - redirect_uri isn't an absolute URL ... but it is!
I am calling the facebook API with the following link in order to receive my access token:
https://www.facebook.com/dialog/oauth?client_id=myclientid&redirect_uri=http%3A%2F%2Fmydomain.org%3A8080%2FServer%2FFacebookAuthenticationVerificationServlet&scope=manage_notifications,offline_access,read_mailbox,read_stream,publish_stream
What am I doing wrong?
Facebook answers with the following error:
message: redirect_uri isn't an absolute URI. Check RFC 3986.
type: OAuthException
code: 191

It shouldn't have anything to do with it, but I am using java's URLEncode.encode() to encode the URL into UTF-8. I compared the result with that one from JavaScript's encodeURIComponent() and didn't find any difference.
EDIT: Do I have to set the domain into my configuration? I can't locate it on "App Domains" (because facebook doesn't allow me to add domains there with port configuration) but I set the domain as "URL of my website".
EDIT2: The unencoded redirect uri: http://mydomain.org:8080/Server/FacebookAuthenticationVerificationServlet
EDIT3: This has nothing to do with the :8080. I tested it with a php-script (URL was  like bla.domain.org/myphp.php) and sent the code by the php script to the tomcat server, but the error persisted.

A: Okay, it turned out I misunderstood the OAuth protocol. I was fetching the authorizationCode that THEN leeds me to the accessToken.
But I wasn't able to fix that error in specific. I just redeveloped the procedure and implemented auth-code and access-token separation and it works fine now.
Maybe unauthorizating the app and reauthorizating it @ facebook did fix it?

A: Error code 191 for Facebook is

API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.

Make sure mydomain.org is in the App Domains field, and that the Website with Facebook login field is correct.

A: You shouldn't encode redirect_uri. http%3A%2F%2Fmydomain.org is not understood as http://mydomain.org


text:
Q: Removing bitwise flags How would i remove flags from my enum
I can add them easy with m_Buttons | (button);
enum WindowButton
{
    None = 0,

    Minimize = (1 << 0),
    Maximize = (1 << 1),
    Close = (1 << 2),
};
inline WindowButton operator|(WindowButton a, WindowButton b)
{
    return static_cast<WindowButton>(static_cast<int>(a) | static_cast<int>(b));
}
inline WindowButton& operator |= (WindowButton& lhs, WindowButton rhs)
{
    return lhs = static_cast<WindowButton>(static_cast<WindowButton>(lhs) | static_cast<WindowButton>(rhs));
}

This is the function where im trying to add / remove
void Window::SetButton(WindowButton button, bool show)
{
    if (show)
        m_Buttons |= (button);
    else
        m_Buttons | ~(button); // This is not working to remove flags
}

A:
m_Buttons | ~(button); // This is not working to remove flags

Of course not. It sets where it should clear, and then throws away the result. Should be
m_Buttons &= ~button;

NB parentheses are redundant here.


text:
Q: How do I create an index using the FairCom c-treeACE CTDB API? Here is my code based on the CTDB tutorial.
#include <stdio.h>
#include <tchar.h>
#include "ctdbsdk.h" /* c-tree headers */

#define END_OF_FILE INOT_ERR  /* INOT_ERR is ctree's 101 error. See cterrc.h */

CTHANDLE hSession;
CTHANDLE hDatabase;
CTHANDLE hTable;
CTHANDLE hRecord;

VOID Handle_Error(CTSTRING errmsg)
{
    printf("\nERROR: [%d] - %s \n", ctdbGetError(hSession), errmsg);
    printf("*** Execution aborted *** \n");
    printf("Press <ENTER> key to exit...");

    ctdbLogout(hSession);

    ctdbFreeRecord(hRecord);
    ctdbFreeTable(hTable);
    ctdbFreeSession(hSession);
    getchar();
    exit(1);
}

// Open the table, if it exists. Otherwise create and open the table
VOID Define(VOID)
{
    CTHANDLE hField1, hField2, hField3, hField4;
    CTHANDLE hField5, hField6, hField7;

    printf("DEFINE\n");

    /* allocate a table handle */
    if ((hTable = ctdbAllocTable(hDatabase)) == NULL)
        Handle_Error("Define(); ctdbAllocTable()");

    /* open table */
    printf("\tOpen table...\n");
    if (ctdbOpenTable(hTable, "custmast", CTOPEN_NORMAL)) {
        /* define table fields */
        printf("\tAdd fields...\n");
        hField1 = ctdbAddField(hTable, "cm_custnumb", CT_INT8U, 0);
        hField2 = ctdbAddField(hTable, "cm_custzipc", CT_FSTRING, 9);
        hField3 = ctdbAddField(hTable, "cm_custstat", CT_FSTRING, 2);
        hField4 = ctdbAddField(hTable, "cm_custratg", CT_FSTRING, 1);
        hField5 = ctdbAddField(hTable, "cm_custname", CT_STRING, 47);
        hField6 = ctdbAddField(hTable, "cm_custaddr", CT_STRING, 47);
        hField7 = ctdbAddField(hTable, "cm_custcity", CT_STRING, 47);

        if (!hField1 || !hField2 || !hField3 || !hField4 ||
            !hField5 || !hField6 || !hField7)
            Handle_Error("Define(); ctdbAddField()");

        /* create table */
        printf("\tCreate table...\n");
        if (ctdbCreateTable(hTable, "custmast", CTCREATE_NORMAL))
            Handle_Error("Define(); ctdbCreateTable()");

        if (ctdbOpenTable(hTable, "custmast", CTOPEN_NORMAL))
            Handle_Error("Define(); ctdbOpenTable()");
    }
}

NINT main(NINT argc, pTEXT argv[])
{
    CTDBRET  retval;

    printf("INIT\n");

    if ((hSession = ctdbAllocSession(CTSESSION_CTDB)) == NULL) /* allocate session handle */
        Handle_Error("Initialize(): ctdbAllocSession()");

    printf("\tLogon to server...\n");
    if (ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN")) /* connect to server */
        Handle_Error("Initialize(): ctdbLogon()");

    hDatabase = ctdbAllocDatabase(hSession);
    if (ctdbConnect(hDatabase, "FTS") == CTDBRET_OK) {
        printf("Connected to DB\n");
    } else {
        printf("Creating DB\n");
        if (ctdbCreateDatabase(hSession, "FTS", "")) {
            Handle_Error(hSession, "ctdbCreateDatabase()");
        }
        ctdbConnect(hDatabase, "FTS");
    }

    Define();

    printf("\tClose table...\n");
    if (ctdbCloseTable(hTable))
        Handle_Error("Done(): ctdbCloseTable()");

    printf("\tLogout...\n");
    if (ctdbLogout(hSession))
        Handle_Error("Done(): ctdbLogout()");

    ctdbFreeRecord(hRecord);
    ctdbFreeTable(hTable);
    ctdbFreeDatabase(hDatabase);
    ctdbFreeSession(hSession);

    printf("\nPress <ENTER> key to exit . . .\n");
    getchar();

    return(0);
}

A: Simply add this before you call ctdbCreateTable:
    CTHANDLE hIndex;
    if ((hIndex = ctdbAddIndex(hTable, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO)) == NULL)
        Handle_Error("Define(); ctdbAddIndex()");

    CTHANDLE hSeg;
    if ((hSeg = ctdbAddSegment(hIndex, hField1, CTSEG_SCHSEG)) == NULL)
        Handle_Error("Define(); ctdbAddSegment()");


text:
Q: 0xc000021a Windows Error I installed Windows 8.1 from Windows 7 a few weeks ago, and have since had to reinstall THREE times because of this same error.
Basically, after a few days of normal use, I start getting "Shockwave Flash Player has stopped working" in google chrome, firefox, windows apps, etc.
So, I go ahead and try to restart windows. Shuts down just fine. But, it wont start. I now get the automatic repair, which doesn't work. Error code i'm given from the BSOD: 0xc000021a. Safe Mode does not work.
Some programs i've had installed: Chrome, Photoshop, Firefox, Trello (Windows App), Java, SublimeText 2, FileZilla, Skype, and a few others that don't come to mind.
Any help would be greatly appreciated. In the mean time, I'm using Ubuntu.

A: There is more information on this topic located here, on the Microsoft support site. After reading that, you may decide what you think is best. If you are installing from a disc, you may have a defect in the disc, which could cause a problem with the installation.


text:
Q: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output, while installing: drun-airsim-client by pip I'm having a problem to install the drun-airsim-client package (https://pypi.org/project/drun-airsim-client/). I am using a virtual environment and my python version is 3.8.10, my OS is Ubuntu 20.04. This is the log for the error.
ERROR: Command errored out with exit status 1:
     command: '/home/USER/DRONE/venv/bin/python3' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-e0459yt7/airsim/setup.py'"'"'; __file__='"'"'/tmp/pip-install-e0459yt7/airsim/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-e0459yt7/airsim/pip-egg-info
         cwd: /tmp/pip-install-e0459yt7/airsim/
    Complete output (11 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-e0459yt7/airsim/setup.py", line 2, in <module>
        from airsim import __version__
      File "/tmp/pip-install-e0459yt7/airsim/airsim/__init__.py", line 1, in <module>
        from .client import *
      File "/tmp/pip-install-e0459yt7/airsim/airsim/client.py", line 3, in <module>
        from .utils import *
      File "/tmp/pip-install-e0459yt7/airsim/airsim/utils.py", line 1, in <module>
        import numpy as np #pip install numpy
    ModuleNotFoundError: No module named 'numpy'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Can you please suggest me a solution, I have never faced this problem before with other packages & I have look for a solution but I still have the same error.
Thanks in advance.

A: It's a bug in airsim package: its setup.py imports airsim module and the module imports everything else. That is, setup.py imports all the dependencies before they are installed.
Please report the bug.

A: If you run !pip install msgpack-rpc-python before it should work


text:
Q: Difference between the static initializer block and regular static initialization As the title says, what exactly is the difference between
public static String myString = "Hello World!";

and
public static String myString;

static {
    myString = "Hello World";
}

is there any important difference other than the structure ?

A: The static {...} block gives you the opportunity to do more than you would be able to do in the field declaration.
For example, you can fill in some details of a map:
private static final Map<String, String> data = new HashMap<String, String>();

static {
    data.put("A", "Hello");
    data.put("B", "There");
    data.put("C", "You");
}

Sometimes you may also need to get data (from a file, database, etc) before you can instantiate:
public class Foo {
    private static final Person person;

    static {
        InputStream personData = Foo.class.getResourceAsStream("something.txt");
        person = new Person(personData);
    }
    ...
}

A:
Difference between static initializer block and regular static initialization.

In case of variable initialization both are same.
But If we want to connect with database only once or any operation you want to load once. Then write the code in static block because its execute only once when first class load no matter how many objects of that type you create.
EDIT :
You can also construct a similar block:
{
    // Do Something...
}

Example:
public class Demo {

    static{
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        Demo demo2 = new Demo();
    }
}

Output:
Static
Non-static block
Non-static block

A: Well, in your first example the variable is declared and initialized on the same line. In your second the variable is first declared, then initialized. In the second case you could have any number of other static variable and block initializations occur before getting to the initialization block in question. Consider this case:
public static String myString = "Hello World!";
public static String yourString = myString;
static {
    System.out.println(myString);
    System.out.println(yourString);
}

vs:
public static String myString ;
public static String yourString = myString;

static {
    myString = "Hello World";
}

static {
    System.out.println(myString);
    System.out.println(yourString);
}

Output from the first example:

Hello World
Hello World

Output from the second example:

Hello World
null

A: with static blocks you can change the order of the initialisation different to the order of declaration.

A: To continue with what Scott Stanchfield wrote, you can use the Collections.unmodifiableXXX() methods for safety, though libraries like Google Guava may make that less necessary.  Consider:
public static final Map<String, String> CAPITALS;
static {
    Map<String, String> map = new HashMap<>(); //Java 7.
    map.put("NY", "Albany");
    map.put("MD", "Annapolis");
    map.put("VA", "Richmond");
    map.put("CT", "Hartford");
    // 46 more states
    CAPITALS = Collections.unmodifiableMap(map);
}

Of course, having a 52-line static block may be disorienting, and so you might instead take the static block and turn it into a static method.
public static final Map<String, String> CAPITALS = capitals();
private static Map<String, String> capitals() {
    Map<String, String> map = new HashMap<>(); //Java 7.
    map.put("NY", "Albany");
    map.put("MD", "Annapolis");
    map.put("VA", "Richmond");
    map.put("CT", "Hartford");
    // 46 more states
    return Collections.unmodifiableMap(map);
}

The difference is a matter of style. You might instead just work with a database table.

A: For your example, there is no difference.  But as you can see,
public static String myString = "Hello World!";

can only accept an expression to initialize the variable.  However, in a static initializer (JLS 8.7), any number of statements may be executed.  E.g. it's possible to do this:
static
{
    myString = "Hello";
    myString += " ";
    myString += "World";
}

For your example, there's obviously no need to do that, but it's possible for the initialization of a variable to take more than an expression, perhaps many statements, so Java made static initializers.

A: A static variable stores a value that is shared between all instances (or the non-instance) of the Class it is defined in.
A static block is a section of code that gets executed when Class is first loaded.
"regarding scope, static block is accssible only in the same class"," whereas static variable can be accessed from any class"

A: Generally a static variable's value is shared between all instances (or the non-instance) of the Class it is defined in where a static block is a section of code that gets executed when Class is first loaded. Functionally There is no difference.

A: It is really really surprising that the MOST IMPORTANT feature is NOT explicitly answered here.
Yes, you can have multiple lines. But what's the point in this? You could also use just one call to a factory method in the in-line static initialization assignment. (static public final MyType mySPVar = factoryCreateObject();)
So let's focus on static public final variables:
But WHAT IF that method (or any of your multiple lines) throws Exceptions or even Throwables?

*

*Checked Exceptions (not derived from RuntimeException)

*or Unchecked Exceptions that can be

*

*

*derived from RuntimeException

*

*

*or derived from other Throwables, like Error
The most important aspect of initializer blocks (static and non-static) is the ability to do localized individual Exception Handling that still grant the exclusive/privileged access that other methods cannot provide.
With exclusive/privileged access I address the issues of

*

*being the first code to run inside this Class (after the static variable initializers) , so we have a truly pure state

*being the only place in code blocks where you can assign final variables (unless you use Reflection, of course)

*not having to take care of localized synchronization, because

*

*

*the static  initializer method for each specific class never runs in parallel to itself

*

*

*under normal Java conditions (no Reflection or Bytecode Weaving/Injection magic; things that the JVM would allow, as opposed to plain-old-Java), each static initializer is guaranteed to only be run once.

And to oppose some of the other answers here: concerning clean code, static and publicly accessible fields should be final - if not even immutable. This is where the initializer blocks work best.
Now let's take a look at the other cases:
For any other scenario like

*

*(being able to) change the variable later on (not final)

*or letting it only be accessed only through a method (variable not public, together with a Getter method)

different solutions are much better:

*

*For changing a variable later on a Setter Method should be used to control the state of the variable/class/object

*for only accessing the variable via a method one could also use lazy initialization, something along the line if(myObj == null) {myObj = new Something();} return myObj; (consider synchronization here!)

Addendum:
All this talk here considers (static) class variables, but most points written here also strongly relate to (non-static) object member variables.


text:
Q: Does Keras ModelCheckpoint save the best model across multiple fitting sessions? If I have a Keras model fitted with the ModelCheckpoint callback and fit it in several 'fitting sessions' (i.e. I call model.fit() multiple times), will the callback save the best model in the most recent fitting session or the best model out of all fitting sessions?
Thanks.

A: Good question. I did an experiment with an existing model and data set. I created a  checkpoint callback as shown and used it in model.fit
file_path1=r'c:\temp\file1'
mchk=tf.keras.callbacks.ModelCheckpoint( filepath=file_path1,  monitor="val_loss", verbose=1,
    save_best_only=True, save_weights_only=True, mode="auto", save_freq="epoch" )

history = model.fit(X_train, Y_train, validation_data=val_data,
                     batch_size= 128, epochs= 5,  verbose= 1, callbacks=[mchk])

I saved the weights only and saved only the weights for the epoch with the lowest validation loss. I set verbose=1 in the callback so  I could see the values of the validation loss on each epoch. Next I ran essentially the same code again but I changed
the name of the filepath to file2. Code for that is below
file_path2=r'c:\temp\file2'
mchk=tf.keras.callbacks.ModelCheckpoint( filepath=file_path2,  monitor="val_loss", verbose=1,
    save_best_only=True, save_weights_only=True, mode="auto", save_freq="epoch" )

history = model.fit(X_train, Y_train, validation_data=val_data,
                     batch_size= 128, epochs= 5,  verbose= 1, callbacks=[mchk])

Now model.fit preserves its state at the end of a session so if you run it a second time
it starts from where it left off. However it does not preserve the state of the callback.
So on the second run the callback initializes the validation loss as np.inf so it will
save the weights at the end of the first epoch for sure. If you don't change the name of the file it will over write the file you saved due to the first run. If in the second run the value of the validation loss for which the weights were saved is LOWER than the validation loss of the first run then you wind up with the best saved weights overall. However if in the second run the validation loss is higher than in the first run you end up not saving the OVERALL best weights. So that's how it works for the case where the the callback has save_weights_only=True. I thought it might behave differently if you save the entire model because it may in that case preserve the state of the callback. So I reran the experiment with save_weights_only=False. The results indicate saving the entire model does not save the state of the callback. Now I am using Tensorflow 2.0. The results  may be different for different versions. I would run this experiment on your version and see if it behaves similarly.

A: It will save the best model in the most recent fitting session

A: It would save the model for the last fit() as you are essentially overwriting the same file.
If you wanted to find the best model over N iterations you should save them with a prefix N in the file name. This way it will save the best model for a particular fit() and you can easily compare them later. You could just manually add in the N i.e., 1,2,3,N for each fit().
// Example
ModelCheckpoint(
        '/home/jupyter/checkpoint/best_model_{N}.h5',
        monitor="val_loss",
        save_best_only=True,
        save_weights_only=False,
        mode="min")

A: Yes, a checkpoint will only be saved if the performance is better than over all calls to fit. In other words, if none of your epochs in the latest call to fit had better performance than an epoch in a previous call to fit, that previous checkpoint won't be overwritten.
There is one proviso: you must remember to create the callback outside of the call to fit. That is, do this:
checkpoint_callback = keras.callbacks.ModelCheckpoint(
    "checkpoint.h5", save_best_only=True)

model.fit(..., callbacks=checkpoint_callback)
...
model.fit(..., callbacks=checkpoint_callback)

not this:
model.fit(..., callbacks=keras.callbacks.ModelCheckpoint(
                   "checkpoint.h5", save_best_only=True))
...
model.fit(..., callbacks=keras.callbacks.ModelCheckpoint(
                   "checkpoint.h5", save_best_only=True))

The checkpoint callback object has a best attribute which stores the best monitored value so far (and is initially set to the worst possible value, e.g. infinity if lower is good). This is not reset when the object is passed to fit. However, if you instantiate a new callback object within the call to fit, as in the latter code, naturally best will be initialised to the worst possible value, not the best monitored value stored by other callback objects in previous calls to fit.


text:
Q: Does this look right for SQL? Prompt:
The library provides books to borrowers. Each book is described by title, edition, and year of publication, and is uniquely identified using the ISBN. Each borrower is described by his or her name and address and is uniquely identified using a borrower number. The library provides one or more copies of each book and each copy is uniquely identified using a copy number, status indicating if the book is available for loan, and the allowable loan period for a given copy. A borrower may loan one or many books, and the date each book is loaned out and is returned is recorded. Loan number uniquely identifies each book loan.
DROP DATABASE IF EXISTS library;
CREATE DATABASE library;`

USE library;

`DROP TABLE IF EXISTS book CASCADE;
CREATE TABLE book (
    title   varchar(30) not null,
    edition varchar(10),
    year    char(4),
    ISBN    char(13),
    primary key (ISBN),
);

DROP TABLE IF EXISTS loan CASCADE;
CREATE TABLE loan (
    return date varchar(10) not null,
    leave date varchar(10),
    primary key (copy_num),
);

DROP TABLE IF EXISTS borrower CASCADE;
CREATE TABLE borrower (
    Name_first  varchar(25) not null,
    Name_last   varchar(25) not null,
    Address varchar(20),
    borrow_num  char(14),
    primary key (borrow_num),
);

DROP TABLE IF EXISTS copy CASCADE;
CREATE TABLE copy (
    status  varchar(25) not null,
    loan period varchar(2),
    copy_num    char(13),
    primary key (copy_num),
);

A: I think that it is valid SQL but you don't need to DROP those tables separately as you are deleting a whole database so the tables in it will also get deleted.

A: While not necessarily how I'd do it, the requirement is, nevertheless, very clear:
ISBN_detail(ISBN*,title, edition,year)

(We don't really need to store this, if we have access to an externally maintained catalogue)
borrower (borrower_number*,name,address)

(I would use a surrogate id here, in case we ever decide to change the borrower numbering system. I would also want to record more information about the status of the borrower, e.g. date joined)
book (copy_number*, isbn*, status, loan_period)

(Again, I would have surrogate id - I think copy number is a weak concept. Loan_period is the duration (in days) that a book can be borrowed, and note that in real life, some borrowers are sometimes allowed to borrow books longer than others, but that's for another day)
loans(loan_number*,borrower_number,copy_number,ISBN,loaned_date [not null],returned_date [null])

THIS IS WHY I WOULD HAVE A book_id!!!
This table could have been...
loans(borrower_id*,book_id*,loan_date*,returned_date)

... but the specification doesn't allow for this.
Note that borrowers can normally borrow only a finite amount of books at any one time, but again, that's not part of this assignment .
* = (component of) PRIMARY KEY


text:
Q: Azure Function fires twice with SFTP when files uploaded I have a BlobTrigger Azure Function which works with SFTP Connection via Webhook Event in Container.
So my problem is when I upload files with SFTP Connection it fires my Azure Function twice. (via SFTP Clients(WinSCP, FileZilla etc.) or even with Windows Powershell directly it fires 2 times with two different IDs. )
But when I upload(without SFTP) directly to Storage Account\Container it fires only once as it must be.
How function monitor looks like when I upload my file via SFTP

Logs

My Azure Function

Tried to handle this with changing extension values in host.json such as maxConcurrent maxProcessor (1 most of the time..) none of it worked unfortunately. I've checked but there is only one slot, Sessions is not allowed etc.
My webhook event in Storage Account\Container

A: I found the issue and hopefully it can help someone else in the future;
When we upload a blob directly from the Azure portal, it would only create a single "PutBlob" event, when you use sftp protocol (no matter what software it is), it would create 2 events (sftpcreate and sftpcommit) right after the sftpconnect event. Azure Blob Storage as Event Grid source - Azure Event Grid | Microsoft Learn.
Based on the official documentation, SFTP uploads will generate 2 events. One SftpCreate for an initial empty blob created when opening the file and one SftpCommit when the file contents are written. If you want to ensure that the Microsoft.Storage.BlobCreated event is triggered only when a Block Blob is completely committed, filter the event for the SftpCommit REST API call.
It meets my expectations


text:
Q: Is it possible to make a function parameter optional by condition? type TestType<A> = [A] extends [never] ? void : A

class Singleton<T, A> {
    private ClassRef: (new (...args: A[]) => T)
    private args: TestType<A>
    private _instance?: T

    constructor(ClassRef: (new (...args: A[]) => T), args: TestType<A>) {
        this.ClassRef = ClassRef
        this.args = args
    }

    public get instance() {
        if (!this._instance) {
            this._instance = new this.ClassRef(this.args as A)
        }

        return this._instance
    }
}

class Empty {}

const test = new Singleton(Empty)

If I specify
type TestType<A> = void

then the compiler does not swear.
But if I do it conditionally
I get an error "Expected 2 arguments, but got 1."

A: I would suggest to replace the argument with a variadic tuple type. If A is never, we evaluate TestType to be an empty tuple. If not, TestType resolves to a tuple with a single element containing A.
type TestType<A> = [A] extends [never] ? [] : [args: A]

/* ... */

constructor(ClassRef: (new (...args: A[]) => T), ...args: TestType<A>) {
    this.ClassRef = ClassRef
    this.args = args
}

Here are some tests:
class Empty {}
class NotEmpty {
  constructor(arg: string) {}
}

const test1 = new Singleton(Empty)
const test2 = new Singleton(NotEmpty)
//                          ^^^^^^^^ Error: Arguments for the rest
//                                   parameter 'args' were not provided
const test3 = new Singleton(NotEmpty, "abc")

Playground


text:
Q: Convert date time into universal timestamp in PHP for calendars I am building a PHP service that will allow people to click on an Add to calendar button on their mobile devices.
How do I convert 2009-09-12 15:00 into the example timestamp I have been given 20091109T101015Z using PHP?
I have played around with strtotime gmdate but I think I am just missing the correct format parameter.
Thanks

A: Try this:
$date = '2009-09-12 15:00';
$formatted_date = gmdate('Ydm\THis\Z', strtotime($date));

A: Did you try to use formating?
$date = new DateTime("2009-09-12 15:00");
$formated = $date->format("Ydm\THis\Z");

For reading: http://php.net/manual/ru/function.date.php

A: Here you go:
 $the_date = strtotime("2010-01-19 00:00:00");
 echo(date_default_timezone_set("UTC") . "
");
 echo(date("YmdTG:iz", $the_date) . "
");


text:
Q: Grouping items into groups with max size If I have up to $n$ non distinct items to distribute among $b$ distinct buckets that can hold up to $c$ items each, how can I find how many different states there can be? The ordering of items doesn't matter, and obviously $cb >= n$.
For example, if $n=4$, $b=3$ and $c=2$ then the answer would be $23$, with the possible states being (calculated using brute force):

 A | B | C
---+---+---
 0 | 0 | 0
 0 | 0 | 1
 0 | 0 | 2
 0 | 1 | 0
 0 | 1 | 1
 0 | 1 | 2
 0 | 2 | 0
 0 | 2 | 1
 0 | 2 | 2
 1 | 0 | 0
 1 | 0 | 1
 1 | 0 | 2
 1 | 1 | 0
 1 | 1 | 1
 1 | 1 | 2
 1 | 2 | 0
 1 | 2 | 1
 2 | 0 | 0
 2 | 0 | 1
 2 | 0 | 2
 2 | 1 | 0
 2 | 1 | 1
 2 | 2 | 0

A: This is a problem well-suited to generating functions.
In each bucket we have the choice to put any number from $0$ to $c$ items. Each of these represents one state. We denote this by:
$$1+x+\ldots+x^c = \frac{x^{c+1}-1}{x-1}$$
using the power of $x$ to keep track of the number of items placed.
Because the buckets are distinct, we may multiply to check our possible states:
$$\left(\frac{x^{c+1}-1}{x-1}\right) \cdots \left(\frac{x^{c+1}-1}{x-1}\right) = \left(\frac{x^{c+1}-1}{x-1}\right)^b$$
It is now clear that the solution to this problem will be the coefficient of $x^n$ in this expression. In short, we seek: $$[x^n]\left(\frac{x^{c+1}-1}{x-1}\right)^b$$
The $[x^n]$ operator is manifestly linear, so that applying the binomial theorem to the numerator, we obtain:
$$[x^n]\left(\frac{x^{c+1}-1}{x-1}\right)^b = \sum_{i=0}^b\binom bi (-1)^{b-i}\ [x^n]\left(\frac{x^{i(c+1)}}{(x-1)^b}\right)$$
Now to compute $[x^n]\left(\frac{x^k}{(x-1)^b}\right)$:
\begin{align}
[x^n]\left(\frac{x^k}{(x-1)^b}\right) &= [x^{n-k}]\left(\frac1{(x-1)^b}\right)\\
&= \frac1{(n-k)!}\left(\prod_{j=0}^{n-k-1}-b-j\right)\cdot(-1)^{-(b+n-k)}\\
&= (-1)^{-b}\frac{(n+b-k-1)!}{(b-1)!(n-k)!} = (-1)^{-b}\binom{n+b-k-1}{b-1}
\end{align}
where in passing to the second line, we used the identity $[x^n](f) = \frac1n[x^{n-1}](f')$ repeatedly, and $[x^0](f) = f(0)$ once. (NB. Note that in passing, we have derived the solution to the stars and bars problem, since that corresponds to finding $[x^n]((1-x)^{-b})$.)
This means that for our original problem, we end up with:
\begin{align}
[x^n]\left(\frac{x^{c+1}-1}{x-1}\right)^b &= \sum_{i=0}^b\binom bi (-1)^{b-i}\ (-1)^{-b}\binom{n+b-i(c+1)-1}{b-1}\\
&= \sum_{i=0}^b (-1)^i \binom bi\binom{n+b-i(c+1)-1}{b-1}
\end{align}
It is clear that we may restrict $i$ to be smaller than $\dfrac{n+b-1}{c+1}$ due to the second binomial coefficient, but other than that I see no easy way to achieve further simplification of this sum.


text:
Q: How to write `$("user")` in kotlin with flink from flink 1.14, it suggest using $() for retrieving elements like below:
Table table = tableEnv.fromDataStream(ds, $("user"), $("product"), $("amount"));

so is there a way to convert it to kotlin, for it causing compiler error in kotlin:
var table = tableEnv.fromDataStream(ds, $("user"), $("product"), $("amount"));

A: I am not familiar with Apache Flink, but you're not allowed to use the dollar sign on it's own.
For function names with special characters, e.g. whitespace, you have to put the function name into backticks (`), e.g.:
fun `white space`() = Unit
fun `$`() = Unit

fun main() {
    `white space`()
    `$`()
}

Thus, your code example above works on my machine with the following adjustments.
import org.apache.flink.table.api.Expressions.*

...

val table = tableEnv.fromDataStream(ds, `$`("user"), `$`("product"), `$`("amount"))

A: This problem will be fixed in one of the next Flink releases:
https://issues.apache.org/jira/browse/FLINK-26278


text:
Q: SQL Exam Normalisation issue Current studying towards a software engineering degree. One of the main topics I study under this umbrella is databases. I just sat my mock exam for this module and I came up across this question about normalising a database to 3NF.
The reason I ask this question is the marking for the mock exam states that the final total number of tables after normalisation is 5. However I got 4 and i'm curious where I went wrong
Image of the un-normalised data to be normalised
The final tables i got are listed as below
Batch_id, Agent_id, Agent_name
batch_id, holiday_code
holiday_code, airport_id, price, quantity
airport_id, airport

A: When I write it down, I come up with the following tables:
Agent: agent_id, name
Holiday: holiday_code, price, airport_id
Airport: airport_id, airport_name
Batch: batch_id, agent_id
BatchLine: batch_id, holiday_code, quantity

Your answer:

Batch_id, Agent_id, Agent_name

Agent_id, agent_name, otherwise you would repeat agent_name in your first table – Joakim Danielson

holiday_code, airport_id, price, quantity

Won't match up for code B563 (different quantities)


text:
Q: Project-Swift.h file after Swift 3.0 migration is compiling the same functions hundreds of times and taking 7 minutes to compile After migrating to Swift 3.0 our first time build time now takes 7 minutes when it used to take 1:20. Does anyone know how can I speed this up?
I work on a large project with lots of Objective C files, approximately 640 Swift files, 20 Cocoapod dependencies, a Today View extension and UITests. After the first time build, an incremental build only takes about 10 seconds.
I have run the excellent Build Time Analyzer here:
https://github.com/RobertGummesson/BuildTimeAnalyzer-for-Xcode
 and attached a screenshot below.

It seems that several of the functions in about 20 of the classes are compiled 631 times. This seems like the problem but I don't know how to fix it. No other function or class takes very long to compile on its own.
Almost all of the 7 minute build time is spent on compiling swift files up until this output:

After this line all of the rest of the swift files are compiled and run in about 10 seconds.
It's worth noting that the generated project-swift.h file is 4500 lines long and the bridging-header has 150 lines of imports.

A: This may not be a complete solution, but here is at least what is happening. So, you might have 631 files pointing to ViewControllerRecycler.swift.
lets say that ClassA calls something from ViewControllerRecycler.swift, ClassC calls something from ViewControllerRecycler.swift and so on.
If you follow this and add the debugging flag -driver-show incremental to "other swift flags", you will see something like:
Queuing ViewControllerRecycler.swift
Queuing ClassA.swift
Queuing ViewControllerRecycler.swift because of dependencies discovered later

and then
Queuing ViewControllerRecycler.swift because of dependencies discovered later
Queuing ViewControllerRecycler.swift because of dependencies discovered later
Queuing ViewControllerRecycler.swift because of dependencies discovered later

something like that. When ClassA is changed, for example, even if it is nothing about ViewControllerRecycler.swift, it will be queued for compilation again "due to dependencies". This causes your files to be compiled so many times.
You may want to look at the following sites to try to optimise your code to be more faster:

*

*https://spin.atomicobject.com/2016/04/26/swift-long-compile-time/

*XCode 8 very slow swift compiling

*Xcode 8 does full project rebuild

*http://bits.citrusbyte.com/improving-swift-compile-time/

*https://medium.com/@RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31#.8pvjh9p27
Maybe these will help you to compile a bit, if not extremely, faster

A: Got the fix! Turned out to be just a settings change as detailed in this SO post here:
https://stackoverflow.com/a/40370475/1455770

This change got my compile down from 7 minutes to a far more manageable 2 minutes. Build Time Analyzer shows each file compiling only once now. I'm not 100% sure why this fixed the problem but I noticed that while generating the module-swift.h file the compiler now seems to generate it all in one go instead of file by file. This turns out to be a lot faster.


text:
Q: Threads or background processes in Google App Engine (GAE) I'm running a post, and need the request to be replied fast. So I wanted to put a worker running some operations in background and reply the request imidiatly.
The worker is always finite in operations and executes in [0;1] second
How can I do this? Is there any module that suports this in the google app engine api?
Edit:
In python

A: Yes.  You want to use the Task Queue API.  It does exactly what you need.

A: There is now threading support for python 2.7.
https://developers.google.com/appengine/docs/python/backends/overview#background_threads
If you want a long-running worker thread, it will have to live in a backend, but if you want a thread for the lifetime of the request to asynchronize your operations and boost speed, you can now use real threads (just beware that frontend threads are killed when the http request is over).


text:
Q: Scala : Template testing with Play framework I am transitioning from Java to Scala. I am looking for a way to do test similar as :
//As a template is a just a method, you can execute it from a test and check the result:

@Test
public void renderTemplate() {
  Content html = views.html.index.render("Welcome to Play!");
  assertEquals("text/html", html.contentType());
  assertTrue(contentAsString(html).contains("Welcome to Play!"));
}

I found it here: https://www.playframework.com/documentation/2.8.x/JavaTest
Any attempts to find this in documentation to follow to write similar test in scala have failed. Can anyone help?

A: These kind of tests called Functional Tests in PlayFramework
Yes, there are well documented samples for writing functional tests as well as testing templates. The following code sample is alternative version in Scala
"render index template" in {
  val html = views.html.index("Hello")

  contentType(html) must equalTo("text/html")
  contentAsString(html) must contain("Welcome to Play!")
}

Example2. Testing the router:
"respond to the index Action" in {
  val Some(result) = routeAndCall(FakeRequest(GET, "/Bob"))

  status(result) must equalTo(OK)
  contentType(result) must beSome("text/html")
  charset(result) must beSome("utf-8")
  contentAsString(result) must contain("Hello Bob")
}


text:
Q: What is wrong with this PGFPlots Boxplot? The following MWE:
\documentclass{standalone}

\usepackage{tikz}
\usepackage{pgfplots}

\usetikzlibrary{pgfplots.statistics}

\pgfplotsset{compat=1.9}

\begin{document}

    \begin{tikzpicture}
      \begin{axis}
        \addplot+[boxplot] table[row sep=\\,y index=0] {
          data\\
          1\\ 2\\ 1\\ 5\\ 4\\ 10\\ 9\\
        };
        \addplot+[boxplot] table[row sep=\\,y index=0] {
          data\\
          1\\ 2\\ 1\\ 5\\ 4\\ 10\\
        };

     \end{axis}
   \end{tikzpicture}

\end{document}

results in th folllowing error whn compiled with pdflatex:
! Package PGF Math Error: Sorry, an internal routine of the floating point unit
 got an ill-formatted floating point number `'. The unreadable part was near ''
..

See the PGF Math package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.25         };

Where am I wrong and why the second example causes this error ?

A: Please upgrade to pgfplots 1.12 . It improves the boxplot quality significantly, especially if you write \pgfplotsset{compat=1.12} (in which case it will use standardized value estimators). Aside from the general improvements, it also comes with a bugfix for this issue.