text:
Q: Why does adding \usepackage{breqn}, even if not used, cause LaTeX compile errors in some places? I have many LaTeX files that includes a common .tex file which has the preamble code.
In this include file I added, at the end, this
\usepackage{breqn}

and then run make to build the whole tree. I see now new errors showing in files which compiled ok before.
One example was this question
Another example is below. The LaTeX code is auto-generated by SWP.
\documentclass[]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
%\usepackage{breqn}  %uncomment this to see the error
\begin{document}
\[
\left(  X\circledast Y\right)  \circledast W={\displaystyle\sum\limits_{l=-\infty}^{\infty}}\left(  \overset{\left(  X\circledast Y\right)  \left(  l\right)}{\overbrace{{\displaystyle\sum\limits_{k=-\infty}^{\infty}}X\left(  k\right)  Y\left(  l-k\right)  }}\right)  W\left(  n-l\right)
\]
\end{document}

uncommenting \usepackage{breqn} in the above, gives the error
>pdflatex foo.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (TeX Live 2012/Debian)
 restricted \write18 enabled.

(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd)
! Limit controls must follow a math operator.
<argument> {\displaystyle \sum \limits
                                       _{k=-\infty }^{\infty }}X\left ( k\ri...
l.8 ...}X\left(  k\right)  Y\left(  l-k\right)  }}
                                                  \right)  W\left(  n-l\right)
?

I'd like to just understand what is going to help in managing this. I see the error message above, but if the LaTeX code was invalid, then how could it have compiled OK before adding breqn?  Why is adding breqn causes some compile errors in some places that did not exist before?
Using TexLive 2012 debian original package. No changes/addition to it made on my Linux box.

A: To put stuff above an \overbrace simply use the construction \overbrace{-bottom-}^{-top-}, which works fine with breqn.
Your construction \overset{-top-}{\overbrace{-bottom-}} is an abuse of \overset, which as far as I can tell is meant for stacking single symbols or relations.  Here you pile a whole formula atop another.  One way around the error which egreg details is to save the primitive \let\orig@limits\limits and redefine \def\limits{\ifx\@sym\binrel@sym\else \orig@limits \fi}, so as to only call the primitive when in a normal mode.  Alas! there is still a second error Limit controls must follow a math operator.  And nothing can save us so easily, because this time \sum is really not typeset as an operator.  Why?  Well, breqn tries to find out what symbols you are trying to pile with \overset.  It turns out that the last atom in the math list for the bottom is an ordinary symbol, so breqn considers the whole bottom stuff as a single ordinary symbol: everything in there is treated like ordinary symbols (\mathord).  In particular the \sum becomes \mathord{\sum}, and that does not accept \limits controls.
Document that works:
\documentclass[]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{breqn}
\begin{document}
\[
\left(  X\circledast Y\right)  \circledast W
={\displaystyle
\sum\limits_{l=-\infty}^{\infty}} \left(
\overbrace{
  {\displaystyle\sum\limits_{k=-\infty}^{\infty}}X
  \left(  k\right)  Y\left(  l-k\right)
}^{
  \left(  X\circledast Y\right)
  \left(  l\right)}
\right)
W\left(  n-l\right)
\]
\end{document}

There are problems with breqn but this ain't one.

A: The breqn package changes the definition of \sum (and of almost all other commands for math mode). The definition it uses is (using the output of \show)
> \sum=\protected\long macro:
->\@sym \sum \math_sym_COs:Nn \mg@cop {50}.

The macro \@sym is the same as \@gobble, at least between \[ and \], so the first two tokens disappear. Now TeX finds \math_sym_COs:Nn
> \math_sym_COs:Nn=\long macro:
->\math_bsym_COs:Nn .

Uhm. Let's see \math_bsym_COs:Nn
> \math_bsym_COs:Nn=\long macro:
#1#2->\math_char:NNn 1#1{#2}\sumlimits .

So the tokens \mg@cop and {50} are the second and third arguments to \math_char:NNn
> \math_char:NNn=\protected\long macro:
#1#2#3->\tex_mathchar:D \__int_eval:w "#1#2#3\__int_eval_end: .

This simply produces
\mathchar"1350

because \mg@cop expands to 3 (the number of the math extension font family). So the symbol is produced, but there's \sumlimits after it
> \sumlimits=\displaylimits.

Wait! This means that \sum\limits should be legal!
Indeed it is. But in some situations \@sym is not equivalent to \@gobble (and this is the reason why it's there). When the second argument to \overset is being processed, \@sym becomes equivalent to \binrel@sym
\def\binrel@sym#1#2#3#4{%
  \xdef\binrel@@##1{%
    \ifx\math_sym_Ord:Nn #2 \math_csym_Ord:Nn
    \else\ifx\math_sym_Var:Nn#2 \math_csym_Var:Nn
    \else\ifx\math_sym_COs:Nn#2 \math_csym_COs:Nn
    \else\ifx\math_sym_COi:Nn#2 \math_csym_COi:Nn
    \else\ifx\math_sym_Bin:Nn#2 \math_csym_Bin:Nn
    \else\ifx\math_sym_Rel:Nn#2 \math_csym_Rel:Nn
    \else\ifx\math_sym_Pun:Nn#2 \math_csym_Pun:Nn
    \else\exp_not:N\@symErr \fi\fi\fi\fi\fi\fi\fi
  ?{\exp_not:N\OrdSymbol{##1}}}%
}

This is the cause of the error: \limits comes after nothing, because one of the workings of \overset is to examine its second argument in order to apply the correct spacing around the whole construction. Here breqn (more precisely flexisym.sty) tries to be clever and does a different test than amsmath. The failure is here: when \@sym is redefined, it absorbs four arguments using only the second one (\sum itself). And \limits remains alone in the input stream.
A minimal example showing the failure is
\documentclass{article}
\usepackage{amsmath}
\usepackage{breqn}  %uncomment this to see the error
\begin{document}
\[
\overset{X}{\sum\limits_0}
\]
\end{document}

The (wrong) assumption made by flexisym is that the second argument of \overset contains a single token.


text:
Q: TortoiseSVN Update Command Line Arguments I've run into an interesting annoyance that I'm trying to remove.
I'm creating a batch file to automatically update TortoiseSVN repos to the correct revisions for my technicians.
However, when executing svn update on the command line, SVN assumes that the current user login is the username for SVN.
That's not correct on our tech's machines. We have a local user of "Tech" that can be accessed by everyone and this user login runs the batch file. When we do an svn update from the batch file, it'll ask for a password with the username of "Tech" which isn't on SVN. Then it'll ask for a username and password input because it couldn't login with the previous credentials.
I'm trying to skip that unnecessary step, but I don't know other command line arguments (like --force --no-auth-cache) that will help.
Is there a way to force TortoiseSVN to ask for the username instead of assuming it is the login name?
Update: found the options for the command line on TortoiseSVN, but don't know which to use correctly - http://svnbook.red-bean.com/en/1.7/svn.ref.svn.html

A:
SVN assumes that the current user login is the username for SVN.

No, and never was so
From svn help update
>Global options:
>  --username ARG           : specify a username ARG
>  --password ARG           : specify a password ARG

But The Right Way (tm) will be

*

*Remove stored wrong credentials from %AppData%\Subversion\auth (most probably \svn.simple) (URLs are plain-text parameters inside files)

*Login once to needed repository (with any command, which require authentication) with --username, --password, using correct credentials

*Remove auth. data from update command (cached data will be used)

redpajama_set_name: RedPajamaStackExchange


text:
Q: taking input using scanf when i run this program this takes input for a two times even if scanf is used only once,WHY?????
  #include<stdio.h>
  #include<conio.h>
int main(){
   int a,b,i=1,product;
   printf("Enter the value of a\n");
   scanf("%d\n",&a);
   printf("Enter the value of b\n");
   scanf("%d\n",&b);
   while(i<b){
      product = i*3;
      if(product > a){
         printf("%d*3 = %d\n",i,product);
         }
         i = i + 1;
      }
  }


text:
Q: Why does JavaConversions._ do not take place for Buffer when java List is expected? I am using Scala in Android, and I want to convert scala.collection.mutable.ArrayBuffer to Java.util.List. But it do not work out, can some help me out?
code:
package com.ssj.DoubanPipi.activity.fragment

import android.app.Fragment
import android.view.{View, LayoutInflater, ViewGroup}
import android.os.Bundle
import com.ssj.DoubanPipi.R
import android.widget.{ListView, SimpleAdapter}
import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConversions._

/**
 * Created by shenshijun on 14-5-31.
 */
class MainFragment extends Fragment {
  override def onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle) = {
    val rootView = inflater.inflate(R.layout.main_fragment, container, false)
    val listView = (rootView findViewById R.id.fragment_list).asInstanceOf[ListView]
    val adapter = new SimpleAdapter(getActivity, MainFragment.menu_list,
      R.layout.main_fragment_list, Array("text", "image"), Array(R.id.action, R.id.action_image))
    listView setAdapter adapter
    rootView
  }

  def onSign(view: View) {
  }
}

object MainFragment {
  val menu_list_text = Array(R.string.login, R.string.exit)
  val menu_list_image = Array(R.drawable.douban, R.drawable.exit)
  val menu_list = new ArrayBuffer[Map[String, Any]]()
  val len = menu_list_image.length
  for (index <- 0 until len) {
    val map = Map("text" -> menu_list_text(index), "image" -> menu_list_image(index))
    menu_list += map
  }
}

and the error message is the following:
type mismatch;
 found   : scala.collection.mutable.ArrayBuffer[scala.collection.immutable.Map[String,Any]]
 required: java.util.List[_ <: java.util.Map[String, _]]
    val adapter = new SimpleAdapter(getActivity, MainFragment.menu_list,
                                                              ^

A: Calling .toList() on menu_list should do the job.
    MainFragment.menu_list.toList

edit:
In case you need to convert scala Map to java.util.Map also, this snippet should work:
menu_list.map(_.asInstanceOf[java.util.Map[String, Any]])
val javaMenuList: java.util.List[java.util.Map[String, Any]] = menu_list.map { map =>
  val javaMap: java.util.Map[String, Any] = map
  javaMap
}


text:
Q: How can I scale subreport in Jasper? I have a subreport inside a report. My subreport is with dimensions 577x370, but I need to scale it up to 820x525 inside my main report.
Is it possible?

A: AFIK: No it's not possible
You can not scale from main report nor can you send dimension to subreport, since you can't not set dimension of a jrxml report dynamically.
The only thing that is possible is to allow subreport to stretch dynamically in height.
Solution

*

*Design another scaled report and call correct one from main.

*Substitute your sub report with html (naturally not always feasible and with image result instead of searchable text elements in report), the hc:html allows dynamic scaling, since it creates an image of the html


text:
Q: Тип указателя на член класса Какой тип имеет указатель на член класса? Другими словами, что нужно подставить здесь, чтобы работало? Очевидное int* не работает.
struct X {
    int x = 0;
};

template<class T, T value>
auto foo() { return *value; }

int main() {
    std::cout << foo</* какой тип? */, &X::x>();
}

A: Указатель на поле класса должен иметь тип int X::*, а чтобы приведенный код работал надо еще создать экземпляр класса X:
#include <iostream>

struct X
{
    int x = 0;
};

template<auto x_pointer, typename x_Class>
auto foo(x_Class & obj)
{
    return obj.*x_pointer;
}
// или так
template<int X::* x_pointer>
auto foo(X & obj)
{
    return obj.*x_pointer;
}

int main()
{
    X x{};
    std::cout << foo<&X::x>(x);
}

online compiler


text:
Q: Parameterizing deviation from average I am seeking help in parameterizing a concept.
For instance:
"Interest in literature" may be higher for poorer book owners than book owners with higher income, given that book ownership is only 10% in low income population in comparison to 90% in high income population.
I would like to parameterize as ordinal variable "Interest in literature", using two variables, book ownership (binary) and income (continuous).
Any suggestions or reference for doing this would be greatly appreciated. Thank you.


text:
Q: Object parameters are always null after Web API call I am trying to call an ASP.NET Web API method from an AngularJS script. The HTTP request is of POST type, and I am trying to send some data over to the Web API method.
Here is my AngularJS code. d is a simple JSON object.
$http({
    url: '/api/StudentsBasicInfo/InsertOrUpdateStudentBasicInfo',
    method: "POST",
    data: JSON.stringify(d),
    contentType: "application/json;charset=utf-8",
    dataType: 'json'
}).success(function (data, status) {
    if (data == "\"success\"") {
});

Here is my Web API:
[ActionName("InsertOrUpdateStudentBasicInfo")]
public string InsertOrUpdateStudentBasicInfo([ModelBinder] StudentDynamicFormVM student)
{
    try
    {
        StudentsBasicInfoBL studentsBasicInfoBL = new StudentsBasicInfoBL();
        long returnedId = studentsBasicInfoBL.InsertStudentsBasicInfoAndEnrolledProgram(student);
        if(returnedId > 0)
        {
            return "success";
        }
        else
        {
            return "error";
        }
    }
    catch(Exception ex)
    {
        return "error";
    }
}

Below is the strongly typed C# object that I am trying to bind the HTTP request data to:
public class StudentDynamicFormVM
{
    public long SerialId { get; set; }
    public long StudentSerialId { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public int ProgramTypeId { get; set; }
    public string AdmittedSemester { get; set; }
    public string AdmittedDate { get; set; }
    public int DepartmentId { get; set; }
    public int ProgramId { get; set; }
    public string MaritalStatus { get; set; }
    public string Nationality { get; set; }
    public string BloodGroup { get; set; }
    public string Country { get; set; }
    public string Religion { get; set; }
    public int Mobile { get; set; }
    public string Email { get; set; }
    public string NationalId { get; set; }
    public string PresentAddress { get; set; }
    public string PermanentAddress { get; set; }
    public string IdentificationMark { get; set; }
    public string ColourOfHair { get; set; }
    public string DateofBirth { get; set; }
}

However, when I try to execute this code, my Web API is called correctly (verified by debugging), but all the properties of the model class are found to be null, as shown in the screenshot.

Following the suggestion in this post (Web API complex parameter properties are all null), I also changed my Web API code to this:
[HttpPost]
[ActionName("InsertOrUpdateStudentBasicInfo")]
public string InsertOrUpdateStudentBasicInfo(object model)
{
    try
    {
        var jsonString = model.ToString();
        StudentsInfoHybrid student = JsonConvert.DeserializeObject<StudentsInfoHybrid>(jsonString);
        StudentsBasicInfoBL studentsBasicInfoBL = new StudentsBasicInfoBL();
    }
    catch(Exception ex)
    {
        return "error";
    }
}

But then I saw that the JSON object was being correctly received by the Web API, but after attempting to serialize, the object parameters were coming null, that is, the same result as before (there was no exception thrown, however).
I have even tried to omit the JSON.stringify method calls from my AngularJS code, and tried to remove the contentType headers in POST request. But the results remained exactly the same.
Tech stack:

*

*ASP.NET 4.5

*Web API

*Angular JS 1.2.19

*Visual Studio 2015

Finally, I am attaching a screenshot of Google Chrome's network log:

A: Change the name of your property in WebAPI to the name of the property that you are sending. It looks like you are sending an object called Academic_DetailsStatic.
Alternatively, change the name of the object you are posting to match the model binding property name in WebAPI


text:
Q: Simply connected linear algebraic group Following is what I understand regarding the simply connected linear algebraic groups afer reading some definition in Hochschild's 'Basic Theory of Algebraic Groups' :
(I don't know about fundamental group)
Let $G$ be a linear algebraic group over a field $F$ of characterstic zero. Then $G$ is said to be simply connected if any surjective homomorphism of algebraic groups
$$\phi : H \to G$$
where Ker $\phi$ is finite turns out to be an isomorphism.
Now, $G$ being defined over $F$ means the defining equations have coefficients in $F$. However, $G$ has points coming from $F^n$ as well as $K^n$ where $K$ is some extension of $F$. Let us denote the $F$-points in $G$ by $G_F$.
Following are my questions:

*

*What can be say about the simple-connectness of $G_F$? Is this simply connected as well ? I would appreciate if you could refer to some results leading to the conclusion.

*What about the Lie algebra of $G_F$? Is $Lie(G) \cong Lie(G_F)$?
I do not know much algebraic geometry and these type of results are coming in a paper which I am reading. Please help me out. I would appreciate if the explanation is simple and detailed.
Thanks !


text:
Q: Why TRUE == "TRUE" is TRUE in R?
*

*Why TRUE == "TRUE" is TRUE in R?

*Is there any equivalent for === in R?

Update:
These are all returning FALSE:
TRUE == "True"
TRUE == "true"
TRUE == "T"

The only TRUE value is TRUE == "TRUE".
In case of checking with identical() everything works fine.
Second Update:
By === operator I meant the process of checking the Value and the Data Type of a variable. In this case I assumed that the == operator will only compare the Values of variables, not their Data Type as well.

A: According to the help file ?`==` :

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.

So TRUE is coerced to "TRUE" (i. e. as.character(TRUE)), hence the equality.
The equivalent of an operator === in some other language (i. e. are the two objects equal and of the same type) would be function identical:
identical(TRUE, "TRUE")
[1] FALSE

A: In addition to
TRUE == "TRUE"
these are also true:

*

*TRUE==1

*TRUE==1.0

*TRUE==1.0000000000000001

*TRUE==0.99999999999999999
etc, in general also all values close enough to 1.0 to be IEEE754-rounded to it.

But what is more interesing is what if() checks: it checks non-false; in fact this plots!:
if(4.0) plot(1)

I think the only values that dont trigger if() are 0, F, FALSE and "FALSE" they seem defined as exactly 0.

A: TRUE and FALSE are reserved words in R. I don't think eznme was correct (before his edit)  when he said any non-zero value was TRUE, since TRUE == "A" evaluates to FALSE. (That would have been correct in explaining why TRUE == 1 evaluates to TRUE, but it would not explain the result for TRUE == 7
The explanation given by plannapus was taken out of the context of describing the behavior of as.logical. It is closer to the "truth", because it is the implicit coercion of TRUE to character by the == operator that creates this result. Although T and F are initially given the values of TRUE and FALSE, they can be reassigned to other values or types.
> TRUE == as.logical( c("TRUE", "T", "true", "True") )
[1] TRUE TRUE TRUE TRUE

>  TRUE == 7
[1] FALSE
> TRUE == as.logical(7)
[1] TRUE
>  TRUE == as.logical("A")
[1] NA

(I earlier incorrectly wrote that the coercion induced by TRUE == "TRUE" was to logical; it's actually via as.character(TRUE) returning "TRUE".)


text:
Q: using flask-admin and sqlalchemy; now i am trying to make a form to add/delete/edit my table I create a custom view that organizes all of my products and services in an accordion-like fashion so that the data is user friendly.  Below is my custom view:
class productView(BaseView):
    form_columns = ['name','price']
    @expose('/')
    def index(self):
        myServ = Product.query.all()
        myProd =  Productcategories.query.all()
        return self.render('admin/products.html', myProd = myProd, myServ = myServ)

admin.add_view(productView(name='Products and Services', endpoint='products'))

I then proceeded to make my HTML view and that has worked like gangbusters.  Where I'm at now is that I've created some buttons that user my jquery to load a modal.  That works great as well.  However, I'm somewhat stuck in the next step.
Once I hit the "submit" button, how do I tell it to add/delete/edit the particular item?

//button scripts
$(document).ready(function() {
  $(".add-category-item").click(function() {
    $('.bg-modal').fadeIn('slow');
  });

  $(".close").click(function() {
    $('.bg-modal').fadeOut('slow');
  });
});

$(document).ready(function() {
  $(".subtract-category-item").click(function() {
    $('.bg-modal').fadeIn('slow');
  });

  $(".close").click(function() {
    $('.bg-modal').fadeOut('slow');
  });
});

$(document).ready(function() {
  $(".edit-category-item").click(function() {
    var parent = $(this).attr("data-parent");
    $('#papa').val(parent);
    console.log("the parent caregory is:" + parent);
    $('.bg-modal').fadeIn('slow');
  });

  $(".close").click(function() {
    $('.bg-modal').fadeOut('slow');
  });
});

 {{prod.category_name}}

+

    <form action="">
      <input type="text" placeholder="Name of category">
      <input type="text" id="papa">
      Submit
    </form>

A: If you are not using flask-admin generic delete and edit views you could expose a route that will do the delete/edit for you and add this route as your form action
for example
class productView(BaseView):
    form_columns = ['name','price']
    @expose('/')
    def index(self):
        myServ = Product.query.all()
        myProd =  Productcategories.query.all()
        return self.render('admin/products.html', myProd = myProd, myServ = myServ)

    @expose('/custom_delete')
    def custom_delete(self):
        # write custom code to delete from the database
        return self.render('admin/products.html', myProd = myProd, myServ = myServ)

Then in your HTML

+

    <form action="{{url_for('.custom_delete')}}">
      <input type="text" placeholder="Name of category">
      <input type="text" id="papa">
      Submit
    </form>

Your form will get submitted to the endpoint where you can take care of the delete action in your backend


text:
Q: Windows Server 2012 R2, Kerberos: Should the SPN "host/localhost" exist? I noticed that the eventlog "Microsoft-Windows-Security-Kerberos" is filled with the same entry around every minute (sometimes three times per minute, sometimes only after two or three minutes):

*

*Event ID: 100

*Description (roughly translated from German): The Service Principal Name "host/localhost@MYDOMAIN.LOCAL" is not registered, causing an error with Kerberos authentication: 0x7. Use the command line tool "setspn.exe" to register the SPN

This happens on our primary domain controller (also hosting Exchange 2013), but not on our secondary.
I have searched a lot, but couldn't find anything applicable except for https://comp.protocols.kerberos.narkive.com/WfAhMzuZ/host-localhost-principal:

There are significant security issues to having a host/localhost on all your machines. If one of your machines is compromised it can be used to attack the other machines.

I have no idea which service might be causing those entries. I could register the SPN, but don't know if this is a good idea or could be causing other problems. Also, I didn't notice any problems so far that might be caused by those entries.

*

*How can I find out which service is causing this?

*Should I create the SPN?


text:
Q: Send json by ajax - Object - object I have problem with send json by AJAX.
var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Willow", "surname": "Smith", "age": "15"}];

$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: "json",
    data: data,
    success: function(response)
    {
        alert(response);
    }
});

ajax.php
<?php
     echo json_encode($_POST);
?>

And ajax alert response is[object Object]
How to get array in php side?

A: You have to convert data to string by JSON.stringify method and place it into an object. Somehow like this:
$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: "json",
    data: {"data": JSON.stringify(data)},
    success: function(response)
    {
        alert(response);
    }
});

Then on server-side you can access passed data by $_POST['data']:
echo json_decode($_POST['data']);


text:
Q: What's this syntax mean in objc? I am creating a module swift i wish i could convert the code swift. Can you tell me what is the method declaration type is used and what it is used?
-(void)sync:(void (^)(UIBackgroundFetchResult result))handler {

// Make sure not to launch to syncing process at the same time
if(syncing) {
    if(handler) {
        handler(UIBackgroundFetchResultNoData);
    }
    return;
}

syncing = YES;

[[VDARSDKController sharedInstance].afterLoadingQueue addOperationWithBlock:^(void) {
    dispatch_async(dispatch_get_main_queue(), ^(void) {

        NSArray *tags = nil;

        // If you need to synchronize with tags, you can add some tags this way:
        tags = @[ [VDARTagPrior tagWithName:@"BusDev"] ];

        //Synchronize the local DB. The old models which are not anymore needed will be automatically deleted.
        [[VDARRemoteController sharedInstance] syncRemoteModelsAsynchronouslyWithPriors:tags withCompletionBlock:^(id result, NSError *err) {
            syncing = NO;
            NSLog(@"PixLive System got the following models: %@",result);

            if(err)
                NSLog(@"The system got an error: %@",err);

            if(handler) {
                handler(err ? UIBackgroundFetchResultFailed : UIBackgroundFetchResultNewData);
            }
        }];

    });

}];
}

A: A literal Swift translation of this method is:
func sync(handler: ((result: UIBackgroundFetchResult) -> ())?) {

    guard let handler = handler else {
        return
    }

    if syncing {
        handler(result: .NoData)
        return
    }

    syncing = true

    VDARSDKController.sharedInstance().afterLoadingQueue.addOperationWithBlock {
        NSOperationQueue.mainQueue().addOperationWithBlock {
            let tags = [VDARTagPrior.tagWithName("BusDev")]
            VDARRemoteController.sharedInstance.syncRemoteModelsAsynchronouslyWithPriors(tags) { [unowned self] result, error in
                syncing = false
                NSLog(@"PixLive System got the following models: \(result)");

                if let error = error {
                    NSLog(@"The system got an error: \(err)");
                    handler(result: .Failed)
                } else {
                    handler(result: .NewData)
                }
            }
        }
    }
}


text:
Q: Error in Installation of Openstack Kilo on CentOS7 I was installing OpenStack Kilo on CentOS. I gave the command to run the main installation script with the following command >
#packstack --allinone --os-heat-install=y

I get the following error
Pre installing Puppet and discovering hosts' details[ ERROR ]

ERROR : Failed to run remote script, stdout: Loaded plugins: fastestmirror, langpacks
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=stock error was
14: curl#6 - "Could not resolve host: mirrorlist.centos.org; Name or service not known"

stderr: Warning: Permanently added '172.16.34.145' (ECDSA) to the list of known hosts.
+ trap t ERR
+ yum install -y puppet hiera openssh-clients tar nc rubygem-json

One of the configured repositories failed (Unknown),
and yum doesn't have enough cached data to continue. At this point the only
safe thing yum can do is fail. There are a few ways to work "fix" this:

 1. Contact the upstream for the repository and get them to fix the problem.

 2. Reconfigure the baseurl/etc. for the repository, to point to a working
    upstream. This is most often useful if you are using a newer
    distribution release than is supported by the repository (and the
    packages for the previous distribution release still work).

 3. Disable the repository, so yum won't use it by default. Yum will then
    just ignore the repository until you permanently enable it again or use
    --enablerepo for temporary usage:

        yum-config-manager --disable <repoid>

 4. Configure the failing repository to be skipped, if it is unavailable.
    Note that yum will try to contact the repo. when it runs most commands,
    so will have to try and fail each time (and thus. yum will be be much
    slower). If it is a very temporary problem though, this is often a nice
    compromise:

        yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot find a valid baseurl for repo: base/7/x86_64
++ t
++ exit 1

Thank you in advance.

A: First go to  /etc/resolv.conf and comment out "search cloudlab.net".It should work because it worked for me regarding this issue.


text:
Q: getting format of JFormatTextField I've several text fields with certain formats: percent format, date format, etc:
     DateFormat dfm= new SimpleDateFormat("yyyy-MM-dd");
     textField = new JFormattedTextField(dfm);

Later I want to check what format is being used in a textField. I have checked if there is a method textField.getFormat() or similar. Didn't see anything relevant. Is there a way to know this?

A: As you can see in the source code, your Format is converted to a JFormattedTextField.AbstractFormatterFactory
public JFormattedTextField(java.text.Format format) {
  this();
  setFormatterFactory(getDefaultFormatterFactory(format));
}

There is a getter available on JFormattedTextField to retrieve this JFormattedTextField.AbstractFormatterFactory afterwards. This JFormattedTextField.AbstractFormatterFactory gives you access to a JFormattedTextField.AbstractFormatter.
However, you can no longer access your actual Format instance. Depending on why you need it, the JFormattedTextField.AbstractFormatter might be sufficient


text:
Q: What is this function doing in Lua? function splitSat(str, pat, max, regex)
    pat = pat or "\n" --Patron de búsqueda
    max = max or #str

    local t = {}
    local c = 1

    if #str == 0 then
            return {""}
    end

    if #pat == 0 then
            return nil
    end

    if max == 0 then
            return str
    end

    repeat
            local s, e = str:find(pat, c, not regex)     -- Dentro del string str, busca el patron pat desde la posicion c
                                                         -- guarda en s el numero de inicio y en e el numero de fin
            max = max - 1
            if s and max < 0 then
                    if #(str:sub(c)) > 0 then           -- Si la longitud de la porcion de string desde c hasta el final es mayor que 0
                            t[#t+1] = str:sub(c)
                    else                                                                                values
                            t[#t+1] = ""    --create a table with empty
                    end
            else
                    if #(str:sub(c, s and s - 1)) > 0 then          -- Si la longitud de la porcion de string str entre c y s
                            t[#t+1] = str:sub(c, s and s - 1)
                    else
                            t[#t+1] = ""            --create a table with empty values
                    end
            end
            c = e and e + 1 or #str + 1
    until not s or max < 0

    return t
    end

I'd like to know what this function is doing. I know that it makes a kind of table taking a string and a pattern. Especially I want to know what *t[#t+1] = str:sub(c, s and s - 1)* is doing.

A: From what I get, it splits a long string into substrings that match a certain pattern and ignores everything in between the pattern maches. For example, it might match the string 11aa22 to the pattern \d\d, resulting in the table ["11", "22"].
t[#t+1] = <something> inserts a value at the end of table t, it's the same as table.insert(t, <something>)
#t returns the length of an array (that is, a table with consecutive numeric indices), for example, #[1, 2, 3] == 3
str:sub(c, s and s - 1) takes advantage of many of luas features. s and s - 1 evaluates to s-1 if s is not nil, and nil otherwise. Just s-1 would throw an error if s was nil

*

*10 and 10 - 1 == 9

*10 - 1 == 9

*nil and nil - 1 == nil

*nil - 1 -> throws an error

str:sub(a, b) just returns a substring starting at a and ending at b (a and b being numeric indices)
("abcde"):sub(2,4) == "bcd"


text:
Q: dynamically resize iframe height based on dynamic content First, I'll give you the structure of my page:

If only I knew ahead the size of div1, there's no problem here. However, I am dynamically adding contents into div1 using jquery ajax and so I could not pre-set the 's height.
I've tried the solutions I found in other threads by adding some script in the onload of the  but it's useless since the contents are dynamically changing without reloading the page.
Any help?

A: In your child page, after the dynamically generated code has finished loading, insert this code:
// Rsize containing iframe to proper height
parent.parent.resizeIframe($('html').height());

Then, in the parent page, include this function:
function resizeIframe(newHgt)
{
    $('#iframeid').height((parseInt(newHgt)+75)+'px');
}

This will get you where you need to be, but the issue I'm trying to resolve is how to determine the size of the iframe contents after the dynamically generated code has finished loading ... "all from the parent page".
Anyway, hope this helps you.
...

A: I am not sure why you want to use an iframe here. But maybe you cantry using
http://sonspring.com/journal/jquery-iframe-sizing


text:
Q: Examples of certain proofs by induction What are the best examples of proof by mathematical induction on $n$ of statements of the form $\left( \forall n \in \{1,\ldots, N\}\,\,\Big(\cdots\cdots\cdots\Big) \right),$ where there's some good reason why there are only finitely many cases?

A: There's the following unusual proof of (more or less) Fermat's little theorem: for all $x \in \mathbb F_p$, $x^p - x = 0$.
For $x=0$, we have $0^p - 0 = 0$. Assume that for some $x$, $x^p-x = 0$, and consider $(x+1)^p - (x+1)$. Because we're working in characteristic $p$, $(x+1)^p = x^p + 1$; therefore $$(x+1)^p - (x+1) = x^p + 1 - x - 1 = x^p - x = 0.$$ By induction, this claim holds for all $p$ values of $x$.


text:
Q: ATL CCommand Close on destruction I'm using ATL to communicate with a SQL database through OLEDB.
My question is whether or not I have to explicitly call CCommand::Close if I've previously called Open or whether the CCommand destructor will clean up.
I have a feeling that I must call Close but it would be nice if I didn't have to!
Thanks.

A: See my comment to Daniel's answer. Destructor cleans it up and you don't have to worry. MSDN code snippet would have destructor called after CoUninitialize and this is the only reason they do explicit ReleaseCommand in order to release interfaces prior to shutting down COM.
They could have it done like this instead:
CoInitialize(...);
{
  CCustomer rs;
  // ...
  // rs.ReleaseCommand() <<-- Not needed
  // rs.Close() <<-- Not needed
}
// NOTE: ~CCustomer already worked, it is safe to shut COM down
CoUninitialize();

Why? ATL's atldbcli.h:
~CAccessorRowset()
{
    Close();
}

// ...

~CCommandBase()
{
    ReleaseCommand();
}

// ...

class CCommand :
    public CAccessorRowset<TAccessor, TRowset>,
    public CCommandBase,
    public TMultiple

So CCommand's destructor does it all.

A: You need to call both Close and ReleaseCommand as described in the MSDN.


text:
Q: FBSDKMessageDialog sharing link take very long time to load when in Messenger I tried to let users able to share my URL via Messenger with Facebook iOS SDK 4.6 . The problem is when the Messenger opened. The "send field" is empty and take sometimes to for the sharing link to appear.  This is annoying . Are there anyway to solve this ?
Here is my code
 FBSDKMessageDialog *messageDialog = [[FBSDKMessageDialog alloc] init];

    if([messageDialog canShow]) {

        FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
        content.contentURL = shareURL;
        content.contentTitle = shareTitle;
        content.imageURL = imageURL;

        content.contentDescription = @"#xxxxx";

        messageDialog.shareContent = content;
        messageDialog.delegate = self;

        [messageDialog show];

    }


text:
Q: Signing the packets with the application name When a linux application opens a socket to transfer packets I would like to intercept the socket call and insert the application name into these packets. I'm fairly acquainted with core networking principles; I just have no clue where to start if I want to write a software that can perform such task. Could anyone give me some pointers?
Updated question
The original problem is that: I want to distinguish each packet based on the the application that generated them, so I can classify them and feed them to my machine learning algorithm.


text:
Q: When use AWS Lambda to process mails from mailgun, can't get mails in JSON format What I am tried to do is to have a lambda function proccess emails forwarded by mailgun.
So far, I have setup mailgun's route so it will forward emails to a AWS api gateway, then the api gateway triggers a lambda function.
The problem comes when I try to process the mail, instead of getting a pretty Json that I am expecting inside the lambda's event.body, I m getting raw post form data like

--cff4e6b3-a3a4-4131-bb8d-90a73f1b4c36\r\nContent-Disposition: form-data; name=\"Content-Type\"\r\n\r\nmultipart/mixed; boundary=\"001a1140216cee404d05440c49e7\"\r\n--cff4e6b3-a3a4-4131-bb8d-90a73f1b4c36\r\nContent-Disposition: form-data; name=\"Date\"\r\n\r\nTue, 20 Dec 2016 13:40:53 +1300\r\n--cff4e6b3-a3a4-4131-bb8d-90a73f1b4c36\r\nContent ......

My question is, what should I do to get the JSON version of the forwarded emails in lambda?

A: Not sure if you ever came to a solution, but I have this working with the following settings.

*

*Setup your API Gateway method to use "Use Lambda Proxy integration"

*In your lambda (I use node.js) use busboy to work through the multi-part submission from mailgun. (use this post for help with busboy Busboy help)

*Make sure that any code you are going to execute after all busboy is complete is executed in the 'finish' portion of the busboy code.

A: This suggests that your mailgun route is misconfigured and ends with a MIME request:

When you specify a URL of your application as a route destination through a forward() action, Mailgun will perform an HTTP POST request into it using one of two following formats:
Fully parsed: Mailgun will parse the message, transcode it into UTF-8 encoding, process attachments, and attempt to separate quoted parts from the actual message. This is the preferred option.
Raw MIME: message is posted as-is. In this case you are responsible for parsing MIME. To receive raw MIME messages, the destination URL must end with mime

From Receiving Messages via HTTP through a forward() action


text:
Q: Why is '2' less than 'a'? I have two compare to chars:
'2' < 'a'. I typed this into my console and it returned true.
Why is that?

A: Because the character 2 comes before the character a in the ASCII table.
Indeed, 2's decimal code is 50, whereas a's decimal code is 97, so the latter occurs 97 - 50 = 47 characters after the former, as demonstrated by this:
iterate succ '2' !! 47

which gives back 'a'. iterate has signature (a -> a) -> a -> [a], and guess what it does, iterate f x is the infinite list [x, f x, f (f x), f (f (f x)), …], from which we take the 47th element via !! 47.

A: Both values, 2 and a are of type Char.
-- GHCi

:t '2'    -- Char
:t 'a'    -- Char

In Haskell, a Char is a 32 bit integer. So, the question is, can we use the operator < to compare these integers? Yes!
:i Char   -- instance Ord Char -- Defined in `GHC.Classes'

So, Haskell says that Char can be ordered, because it is in class Ord, and we can use operators like < to compare them.
If I go on Hoogle, the Haskell version of Google, I can see the definition of the Ord class, by simply typing Ord into the search box.
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min             :: a -> a -> a

compare x y = if x == y then EQ
              -- NB: must be '<=' not '<' to validate the
              -- above claim about the minimal things that
              -- can be defined for an instance of Ord:
              else if x <= y then LT
              else GT

x <  y = case compare x y of { LT -> True;  _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x >  y = case compare x y of { GT -> True;  _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }

Char is a type which is not quite UTF-32 compliant. In UTF-32, the ASCII codes are stored in the bottom 7 bits, 00 through 7F hex. In ASCII, a is 97 dec, 61 hex, and 2 is 50 dec, 32 hex and hence when we compare the 32 bit values, 2 is indeed less than a. The declared function (<) returns True.


text:
Q: Visual Studio no reconoce el lenguaje que utilizo en los archivos Soy nuevo programando, y uso el VS Code para programar en python (mi primer lenguaje) y cada vez que creaba un archivo nuevo para empezar una lección nuevo o miniproyecto siempre reconocía que estaba creando un archivo .py
Ahora ya no lo hace y tampoco con el nuevo lenguaje que estoy aprendiendo (C++) y ya instalé los paquetes y todo está en orden para mí. ¿Alguna solución?
He intentado desinstalarlo y vovlerlo a instalar, busqué tutoriales sin éxito :(


text:
Q: Iterator writing to File.txt Java Here  is my issue: I need to write the Interator to the file "random.txt" I am able to see all the data. The data is Store where suppose to, I can see it with the System.out.print but my file is in blank. I am able to create the file but not to writer to it.
I am reading a file from my comp. store in the Treemap and trying to write to the text file. ( I am able to doit with Array with not problem) But this Map with Iterator is bouncing my head.
If some one can help me a litter I will appreciated.
I need to use the TreeMap and the Iterator.
public static void main(String[] args) throws FileNotFoundException, IOException {
    Map<String, String> Store = new TreeMap<>();

    Scanner text=new Scanner(System.in);

    System.out.println("enter file:  ");

    //C:\Users\Alex\Desktop\Fruits\fruits.txt

    String rap=text.next();

    File into = new File(rap);

    try (Scanner in = new Scanner(into)) {

        while (in.hasNext()){
            String name=in.next();
            String fruta = in.next();
            Integer num= Integer.parseInt(in.next());
            System.out.println(fruta+"\t"+name+"\t"+num);

            if (Store.containsKey(fruta)){
                Store.put(name,Store.get(name)+fruta );
            }
            else{
                Store.put(name,fruta);
            }
        }

        in.close();

    }

    System.out.println();

    // insert data to store MAP
    Set top=Store.entrySet();
    Iterator it = top.iterator();

    // debugging

    System.out.println(top);

    // Creating file???????
    FileWriter fstream = new FileWriter("random.txt");

    //identify File to be write??????
    BufferedWriter out = new BufferedWriter(fstream);

    //iterator Loop
    while(it.hasNext()) {

        Map.Entry m = (Map.Entry)it.next();
        String key = (String)m.getKey();
        String value = (String)m.getValue();

        //writing to file?????
        out.write("\t "+key+"\t "+value);

        // debugging
        System.out.println(key +"\t"+ value);
    }

    System.out.println("File created successfully.");
}

A: After your while loop (the one writing to file) is finished, do:
out.flush();
out.close();

Short explanation: BufferedWriter buffers in memory what you write. It doesn't immediately write to file when you call the write method. Once the while loop is finished and the data to write to file is prepared in buffer memory, you should call flush to do the actual writing to hard disk. And finally you should always close the BufferedWriter that will no longer be used, to avoid memory leaks.


text:
Q: How to insert new record ( model ) in TreePanel? I use TreeStore & TreePanel. I need to insert new node in my Tree , how to this?
I have TreeStore component who following config:
var monPrestore = Ext.create('Ext.data.TreeStore', {
    folderSort : true,
    model : 'Task',
    proxy : {
        model : 'Task',
        appendId: true,
        type : 'ajax',
        url : '/intranet-timesheet2-tasks-extjs/getJSON.tcl',
        reader : {
            type : 'json'
        },
        writer : {
            type : 'json'
        },
    }

I have defined Task Model (it is what I want to insert) with blank value:
Ext.define('Task', {
    extend : 'Ext.data.Model',
    fields : [
        {
            name : 'task',
            type: 'string'
        },
        {
            name : 'material',
            type: 'string'
        },
        {
            name : 'cc',
            type: 'string'
        },
        {
            name : 'start_date',
            type: 'string'
        },
        {
            name : 'short_desc',
            type: 'string'
        },
        {
            name : 'id',
            type: 'string'
        }
    ]
});

I want to insert new record when event itemdlclick is fired:
I have tested that but it doesn't work:
itemdblclick: function(view, model, htmlitem, index, e) {
    var task = {
        task: 't0',
        material: 'm0',
        cc: 'c0',
        start_date: '12',
        short_desc: 'sht',
        id: '120',
        leaf: true
    };

    monPretree.insert(4,task);
}

Thanks a lot :) !

A: I think you asked the similar question here!
There is no insert method for tree panel. You will have to get hold of the tree's root node to modify the tree. In your case, you might have to do the following:
var rootNode = monPretree.getRootNode();
rootNode.insertChild(4,task);

For other tree manipulation methods, refer the API documentation of NodeInterface.


text:
Q: git: get effective GIT_DIR, if current dir is a working tree subdir and $GIT_DIR is unset From a script, how to determine the current GIT_DIR?
If not overriden, it's just the top level dir or the top level dir of a bare repo.
I want something like:
[/git/repo1/subdir]$ git show-git-dir
/git/repo1/.git

A: This can be done with rev-parse:
git rev-parse --git-dir

A: Here is a pure bash version, and will find the directory when you are in the root.
(Ikke's solution is better by the way).
a=$PWD

while [ "$a" != "" ] && [ "$a" != '/' ];
do
    a=`dirname $a`;
    if [ -d $a/.git ];
    then
        echo "$a";
        break;
    fi
done

On windows you will probably have to add another [ "$a" != '\' ] to test for that case, and I dont have access at the moment to check if the bash shell that comes with Msysgit supports "dirname".
But works in Terminator on Ubuntu.


text:
Q: Effective Force in a spinning bucket If we consider a bucket of water spinning about it's symmetric axis with angular velocity $\boldsymbol{\omega}$, and define a rotating polar coordinate system with origin at the bottom and center of the bucket, we should see that there are two contributing components to the effective force. A gravitational force in the $\hat{\textbf{z}}$ direction and a centrifugal force in the $\hat{\textbf{r}}$ direction.
$$\boldsymbol{F}_\text{eff} = mg\hat{\boldsymbol{z}} + m\omega^2r\hat{\boldsymbol{r}}$$
However, when I compute the centrifugal force for an arbitrary vector $\boldsymbol{r} = \langle r, \theta, z \rangle$, I find it has a $\hat{\boldsymbol{z}}$ component (using $\boldsymbol{\omega} =\langle 0, \omega, 0 \rangle$) :
$$\boldsymbol{F}_\text{cf} = -m\boldsymbol{\omega} \times (\boldsymbol{\omega}\times\boldsymbol{r}) = \langle m\omega^2r, 0, m\omega^2z\rangle $$
So what's gone wrong here? There should not be a $\hat{\boldsymbol{z}}$ component of centrifugal force in this case as I understand it.

A: $\mathbf{\omega}=\langle 0,0,\omega \rangle$ is oriented along the $z$ axis, not the $\theta$ axis.


text:
Q: Confusion regarding proof of L'Hopital rule. I was reading Spivak's Calculus. I have a query with regards to the proof for L'Hopital's rule for the 0/0 indeterminate form.
Theorem Statement :-
"Suppose that
$
\lim_{x\to a} f(x) = 0 $ and
$\lim_{x\to a} g(x) = 0
$
and suppose that $ \lim_{x\to a} \frac {f'(x)}{g'(x)} $ exists .
Then $ \lim_{x\to a} \frac {f(x)}{g(x)} $ exists and
$$
\lim_{x\to a} \frac {f(x)}{g(x)} = \lim_{x\to a} \frac {f'(x)}{g'(x)}
$$
"
I have a confusion with regards to the last part of the proof.
Using the Cauchy Mean Value Theorem it is shown that there exists a number $\alpha_x$ in $(a,x)$ such that $$
\ \frac {f(x)}{g(x)} = \ \frac {f'(\alpha_x)}{g'(\alpha_x)}
$$
Now $\alpha_x$ approaches $a$ as $x$ approaches $a$ because $\alpha_x$ is in $(a,x)$ , it follows that
$$
\lim_{x\to a} \frac {f(x)}{g(x)} = \lim_{x\to a} \frac {f'(\alpha_x)}{g'(\alpha_x)} = \lim_{\alpha_x\to a} \frac {f'(\alpha_x)}{g'(\alpha_x)} = \lim_{y\to a} \frac {f'(y)}{g'(y)}
$$
My query is regarding the last two of the above equations. I understand that as $x$ approaches $a$ so does $\alpha_x$ , but then how are we treating $\alpha_x$ as a 'dummy variable' and replacing it with $y$. Is not $\alpha_x$ a dependent variable on x.
(I am also having some trouble in seeing how the step
$$\lim_{x\to a} \frac {f'(\alpha_x)}{g'(\alpha_x)} = \lim_{\alpha_x\to a} \frac {f'(\alpha_x)}{g'(\alpha_x)}$$ is justified )
Thanks in advance. I am new to these forums and looking forward to the discussion.

A: The last two identities follow from the following fact:

Assume that the function $h$ has limit $\ell$ at $a$ and that the function $\alpha$ has limit $a$ at $x_0$, that is,
  $$
\lim_{t\to a}h(t)=\ell,\qquad\qquad\lim_{x\to x_0}\alpha(x)=a.
$$
  Then, the function $h\circ\alpha$ has limit $\ell$ at $x_0$, that is,
  $$
\lim_{x\to x_0}h(\alpha(x))=\ell.
$$

A simple proof is by the usual epsilon-delta approach.

A: These equalities hold because you assumed that the limit $\displaystyle\lim_{x\rightarrow a} \dfrac{f'(x)}{g'(x)}$ exists.  That means it doesn't really matter how you approach $a$ (i.e. either take $x\rightarrow a$ or $\alpha_x\rightarrow a$), you have to arrive at the same value for the limit.  This also explains why your last equality is okay, since you have some variable approaching $a$, it doesn't matter how you get there; essentially if the limit exists, then the variable respect to which you are taking the limit is automatically a dummy variable.
If you want to be more precise, you can use the $\varepsilon$-$\delta$ definition of the limit.  Say $L$ is your limit, which we assume exists.  Then for all $\varepsilon>0$ there exists some $\delta>0$ such that if $|a-x|<\delta$ then $\left|L-\dfrac{f'(x)}{g'(x)}\right|<\varepsilon$. But $|a-\alpha_x|<|a-x|<\delta$, so we know that for each $\varepsilon$, we can use the same $\delta$ to see that if $|x-a|<\delta$, then $\left|L-\dfrac{f'(\alpha_x)}{g'(\alpha_x)}\right|<\varepsilon$.  This immediately implies $\displaystyle \lim_{x\rightarrow a}\dfrac{f'(\alpha_x)}{g'(\alpha_x)} = L$.

A: I see your point and it may be viewed as sloppy formulation.
We start on the left with an arbitrary sequence $x\to a$ and want to show that we obtain the same value for all such arbitrary sequences. Then we replace this arbitrary sequence with a specific sequence $\alpha_x\to a$ (depending on the given arbitray sequence). Since the premise is that the right hand side limit exists, i.e. that we obtain the same value for all sequences $y\to a$, we know that our specific sequence yields that very value.


text:
Q: Woocommerce get billing state manually Im modifying the receipts for the email admin notifications with woocommerce filter "woocommerce_email_recipient_new_order" Im conditioning them to the state wich the order is billed. For this there is the method get_billing_state(), this works perfect sending the notifications but in the admin i got the error:

Uncaught Error: Call to a member function get_billing_state() on null.

Im assuming that I can call the billing state maually to put it in some way.
function tm_destinatario_condicionado_wc( $recipient, $order ) {

    $estados = array(
        'aguascalientes'        => 'AG',
        'baja-california'       => 'BC',
        // etc etc ...
    );

    // Get billing state 2 digits
    // This is what is causing the error
    $estado_siglas = $order->get_billing_state();

    // Get the keys of $estados by the value (wich is the 2 digit billing
    // state) to get state name
    $estado_slug = array_search( $estado_siglas, $estados );

    // Gets the id of a taxonomy related to the state based on the name
    // obtained from $estados theres a custon field containing the recipients
    $estado_id = get_term_by( 'slug', $estado_slug, 'estados' )->term_id;

    // get the custom field with the recipients
    $emails  = get_field( 'sucursal_email', 'estados_' . $estado_id );

    // Add the custom field content to the recipient
    $recipient .= ', ' . $emails;

    return $recipient;
}

add_filter( 'woocommerce_email_recipient_new_order', 'tm_destinatario_condicionado_wc', 10, 2 );

I apreciate any ideas.

A: To avoid that error, you have to add something in your function like:
add_filter( 'woocommerce_email_recipient_new_order', 'tm_destinatario_condicionado_wc', 10, 2 );
function tm_destinatario_condicionado_wc( $recipient, $order ) {

    // To avoid an error in backend
    if( ! is_a($order, 'WC_Order') ) return $recipient;

    $estados = array(
        'aguascalientes'        => 'AG',
        'baja-california'       => 'BC',
        // etc etc ...
    );

    // Get billing state 2 digits
    // This is what is causing the error
    $estado_siglas = $order->get_billing_state();

    // Get the keys of $estados by the value (wich is the 2 digit billing
    // state) to get state name
    $estado_slug = array_search( $estado_siglas, $estados );

    // Gets the id of a taxonomy related to the state based on the name
    // obtained from $estados theres a custon field containing the recipients
    $estado_id = get_term_by( 'slug', $estado_slug, 'estados' )->term_id;

    // get the custom field with the recipients
    $emails  = get_field( 'sucursal_email', 'estados_' . $estado_id );

    // Add the custom field content to the recipient
    $recipient .= ', ' . $emails;

    return $recipient;
}

This should solve your issue definitively…


text:
Q: canvas.drawCircle sometimes working, sometimes not I bought the book Programming Android, and it's a little confusing and disappointing on how they have different code in their Github (https://github.com/bmeike/ProgrammingAndroid2Examples/tree/master/AndroidUIDemo) and their book. I'm stuck in an example that teaches how to draw a circle in a random point, with the color that is assigned to the button, like, when I click the RED button, it should draw a red circle in a view.
I did some extra code and somehow I managed to get it working. Here is my onDraw method:
@Override
protected void onDraw(Canvas canvas)
{
paint.setStyle(Style.STROKE);
paint.setColor(hasFocus() ? Color.BLUE : Color.GRAY);
canvas.drawRect(0, 0, getWidth() - 1, getHeight() - 1, paint);

    if (this.points == null) return;

    paint.setStyle(Style.FILL);

    for (Point p : points.getAllPoints())
    {
        paint.setColor(p.getColor());
        canvas.drawCircle(p.getX(), p.getY(),
                  p.getDiameter(), paint);
    }
}

Sometimes it works, sometimes not, BUT when it works, it draws a thin, large oval shape.
p.getDiameter() is ALWAYS 6. Even if I put it to a fixed 6, the effect is the same.
Also, there is some strange thing happening: If I replace p.getY() and p.getX() by  50, it will never draw anything on the screen. 50 should not be out of the screen bounds.
In the image below you can see what it's being rendered and some code I use to create the views.

Here is some extra relevant code.
Setting the pointView size (the place where I draw points):
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    super.onWindowFocusChanged(hasFocus);

    pointView.setLayoutParams(new android.widget.LinearLayout.LayoutParams(root.getWidth(), root.getHeight()/2));
}

Add an OnCLickListener to the button, so when I click it, it should draw a circle.
button1.setOnClickListener(new OnClickListener() //I'll not put the Red button here, for the sake of brevity.
    {
        @Override
        public void onClick(View arg0)
        {
            makeDot(pointModel, pointView, Color.GREEN);
        }
    });

And the makeDot method:
private final Random rnd = new Random();
void makeDot(Points points, PointView pointView, int color)
{
    points.addPoint(
            rnd.nextFloat()*pointView.getWidth(),
            rnd.nextFloat()*pointView.getHeight(),
            color, POINT_DIAMETER /*always 6*/);

}

(I think POINT_DIAMETER should be POINT_RADIUS but it's OK for now.)
So, how can I get it to draw a round circle in a random position in the screen?

A: Here are a few ideas:
In addPoint, try generating the coordinates like this:
points.addPoint(
            rnd.nextInt() % pointView.getWidth(),
            rnd.nextInt() % pointView.getHeight(),
            color, POINT_DIAMETER /*always 6*/);

In your onClick method, try adding a call to invalidate:
button1.setOnClickListener(new OnClickListener() //I'll not put the Red button here, for the sake of brevity.
    {
        @Override
        public void onClick(View arg0)
        {
            makeDot(pointModel, pointView, Color.GREEN);
            pointView.invalidate();
        }
    });

When you set the Style.FILL, set the color as well:
paint.setStyle(Style.FILL);
paint.setColor(hasFocus() ? Color.BLUE : Color.GRAY);

Also, remove this line of code:
pointView.setScaleX(20);

That's all I could think of for now.
Hope this helps :)


text:
Q: Error in Angular ng serve static ɵfac: i0.ɵɵFactoryDef I had to install a project in another pc, I use Angular v 9.1.0 but after I run npm install I have this error:

ERROR in node_modules/angular-shepherd/lib/shepherd.service.d.ts:64:18 - error TS2314: Generic type 'ɵɵFactoryDef' requires 2 type argument(s).
64     static ɵfac: i0.ɵɵFactoryDef;

I have the same version of the package in both pc angular-shepherd": "^0.5.0
I already tried to remove and reinstall node_modules and also the package angular-shepherd but I still have the error.
In the old pc, all works well.
If it helps this is the package:
"dependencies": {
    "@angular/animations": "^9.1.0",
    "@angular/cdk": "^9.1.0",
    "@angular/common": "^9.1.0",
    "@angular/compiler": "^9.1.0",
    "@angular/core": "^9.1.0",
    "@angular/forms": "^9.1.0",
    "@angular/material": "^9.1.0",
    "@angular/material-moment-adapter": "^9.1.0",
    "@angular/platform-browser": "^9.1.0",
    "@angular/platform-browser-dynamic": "^9.1.0",
    "@angular/platform-server": "^9.1.0",
    "@angular/router": "^9.1.0",
    "@angular/service-worker": "^9.1.0",
    "@auth0/angular-jwt": "^3.0.1",
    "@fullcalendar/angular": "^4.4.5-beta",
    "@ngx-translate/core": "12.1.2",
    "@ngx-translate/http-loader": "4.0.0",
    "angular-shepherd": "^0.5.0",
    "animate.css": "3.7.2",
    "bootstrap": "4.4.1",
    "chart.js": "^2.9.3",
    "core-js": "^3.6.4",
    "font-awesome": "^4.7.0",
    "google-libphonenumber": "^3.2.7",
    "i18n-iso-countries": "^5.1.0",
    "intl-tel-input": "^16.0.11",
    "jquery": "^3.4.1",
    "jsbarcode": "^3.11.0",
    "latinize": "^0.4.0",
    "material-community-components": "^6.0.0",
    "moment": "^2.24.0",
    "moment-timezone": "0.5.28",
    "net": "^1.0.2",
    "ng2-ckeditor": "^1.2.7",
    "ng2-password-strength-bar": "^1.2.3",
    "ng2-tel-input": "2.3.0",
    "ngx-barcode6": "^1.0.10",
    "ngx-cookie-service": "^3.0.3",
    "ngx-daterangepicker-material": "^2.2.0",
    "ngx-device-detector": "latest",
    "ngx-highlightjs": "^4.0.2",
    "ngx-image-zoom": "^0.6.0",
    "ngx-infinite-scroll": "^8.0.1",
    "ngx-loading": "^8.0.0",
    "node-sass": "^4.13.1",
    "placeholder-loading": "^0.2.5",
    "popper.js": "^1.16.1",
    "primeicons": "^2.0.0",
    "primeng": "^9.0.0",
    "print-js": "^1.0.63",
    "rxjs": "^6.5.4",
    "stompjs": "^2.3.3",
    "stream": "0.0.2",
    "timers": "^0.1.1",
    "tslib": "^1.10.0",
    "url-search-params-polyfill": "^8.0.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.901.0",
    "@angular/cli": "^9.1.0",
    "@angular/compiler-cli": "^9.1.0",
    "@types/bootstrap": "4.3.2",
    "@types/chartist": "0.9.48",
    "@types/jasmine": "3.5.10",
    "@types/jquery": "3.3.34",
    "@types/node": "^13.9.5",
    "@types/xml2js": "^0.4.5",
    "codelyzer": "^5.2.1",
    "concurrently": "^5.1.0",
    "cypress": "^4.1.0",
    "cypress-plugin-tab": "^1.0.5",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~5.0.1",
    "karma": "~4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "lite-server": "^2.5.4",
    "protractor": "^5.4.3",
    "ts-node": "~8.8.1",
    "tslint": "6.1.0",
    "typescript": "3.8.3"
  }

A: I was having this error today as well. My issue was the version of "@angular/compiler-cli" in my main project was 9.1, but in the library I was importing (it was a local node module), it was using 9.0. I updated the library to use 9.1 and that fixed it for me.
In your case, looks like this is running an older version of the compiler, so you might have to change the version in your project so that they match. Hope this helps!

A: It is due to the upgrade to angular 9.1.
When updating to 9.1, ngcc doesn't seem to handle the conversion well.
Remove the lib and reinstall it, it should fix the issue


text:
Q: Why does building my native react android app after implementing facebook sdk gives me these errors? I did the tutorial on facebook for using the facebook sdk for my react native android app exactly as its documented but I get the following errors when I try to run $react-native run-android:

A: Please follow this tutorial
https://tylermcginnis.com/installing-the-facebook-sdk-into-a-react-native-android-and-ios-app/
There are some missing pieces with the fbsdk official.
The above link will definitely solve your problem.
I have successfully implemented it.


text:
Q: Input error when trying to set an integer in mysql Database. (IllegalArgumentException: null PK instance) I am trying to input some data into a mysql database. However, when I try to run the program I get this error:java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find opertaion, I suspect this is due to event.setPriority(prist); however I am not experienced enough to tell why and how I can fix it.
 try{ Calendar duedate = Calendar.getInstance();
 Listevent event = new Listevent();
 TimeTableAddEvent tb = new TimeTableAddEvent();

 int prist = Integer.parseInt(PriTxt.getText());

 event.setName(EventTxt.getText());
 event.setDescription(DescTxt.getText());
 event.setPriority(prist);
 event.setDateofdue(DateTxt.getDate());

 EntityManagerFactory emf = Persistence.createEntityManagerFactory("TimeEven DataBasePU");
 ListeventJpaController lejc = new ListeventJpaController((emf));
 lejc.create(event);
 }catch(Exception e){

     JOptionPane.showMessageDialog(null,e);
 }


text:
Q: Trigonometry book which develops geometric intuition. I'm looking for a trigonometry text that helps develop a lot of geometric intuition and goes deep into the subject. Also some geometry problems which actually require thinking about would be in order.
Regards.

A: I would recommend Hall, Knight - Elementary Trigonometry. It's not as elementary as the title suggests and is quite rigorous for a text at that level. It would fit your requirements as it uses a lot of geometric proofs where possible, and this will motivate the geometric intuition you seek.
I'll give you an example of this: in order to show that 1 radian is a constant measure for all circles, the text first insists on establishing that the ratio of the circumference of a circle to its radius (the ratio given by $\frac{C}{r}$) is always constant. It does this by using a proof where a regular polygon of $n$-sides is inscribed into two circles of differing sizes, the proof then goes on to decompose these polygons into $n$-isosceles triangles, and through various similarity arguments shows that the ratio of the circle's circumferences to their respective radii are equivalent. It then extends this argument, to show that for sufficiently large $n$ that the ratio of the perimeter of the $n$-sided polygon (the sum of all its edges) to the radii of the circle is constant, it defines that constant to be $2\pi$.
Only after doing this does it then go on to show why the angle measure 1 radian is constant for all circles. It does this by using another similarity argument, in which it compares an arc equivalent in length to the radius to an arc made by 2 right angles (i.e. $\pi$ radians or $180^\circ $). The main thrust of the argument is that the ratio of an arc equivalent to the length of the radius (i.e. the arc that subtends an angle that measures 1 radian) to a semi-circle arc is a constant, and thus the angle measure of 1 radian holds for all circles.
If this all sounds long winded to you it's not, I'm not the greatest at exposition but the author of book is and it's a quite joy to read. The exercises are also very challenging and some questions quite unconventional. It has a whole chapter dedicated to geometric proofs of certain trigonometric identities. If you're looking for geometric proof (which will motivate geometric intuition) in the context of trigonometry, this is your book. I don't know if it'll give you a deep intuition of geometry you'll probably need to consult a geometry textbook for that, but you'll gain a solid understanding of trigonometry from it. The only downside is the last time I checked the book is quite expensive second hand, but you can find it here electronically. I highly recommend it.

A: Notes from Trigonometry by Steven Butler is a good intuitive book to understand trigonometry deep from it's roots.This book is especially for novices who can't even understand how Pythagorean theorem was found.
In the Preface it says that:

My major motivation for creating these notes was to talk about topics not
  usually covered in trigonometry, but should be.

You could also check my answer here.


text:
Q: Monotone Class Theorem and another similar theorem. I found different statements of the Monotone Class Theorem.
On probability Essentials (Jean Jacod and Philip Protter) the Monotone Class Theorem (Theorem 6.2, page 36) is stated as follows:

Let $\mathcal{C}$ be a class of subsets of $\Omega$ under finite intersections and containing $\Omega$. Let $\mathcal{B}$ be the smallest class containing $\mathcal{C}$ which is closed under increasing limits and by difference. Then $\mathcal{B} = \sigma ( \mathcal{C})$.

While on Wikipedia (https://en.wikipedia.org/wiki/Monotone_class_theorem) the theorem is:

Let $G$ be an algebra of sets and define $M(G)$ to be the smallest monotone class containing $G$. Then $M(G)$ is precisely the $\sigma$-algebra generated by $G$, i.e. $\sigma(G) = M(G)$.
Where a monotone class in a set $R$ is a collection $M$ of subsets of $R$ which contains $R$ and is closed under countable monotone unions and intersections.

It looks like the second theorem should be a special case of the first. Does the first prove the second? Is it possible to prove the first from the second? Is there a decent literature on those two theorems?

A: Both results are actually equivalent. You can prove one from the other.
Regarding the first result:

Let $\mathcal{C}$ be a class of subsets of $\Omega$ closed under finite intersections and containing $\Omega$. Let $\mathcal{B}$ be the smallest class containing $\mathcal{C}$ which is closed under increasing limits and by difference. Then $\mathcal{B} = \sigma ( \mathcal{C})$.

Some books call it "Monotone Class Theorem", although this is not the most usual naming.
A class having $\Omega$, closed under increasing limits and by difference is called a "Dynkin $\lambda$ system". A non-empty class closed under finite intersections is called a "Dynkin $\pi$ system".
The result above can be divided in two results
1.a. A $\lambda$ system which is also a $\pi$ system is a $\sigma$-algebra.
1.b. Given a $\pi$ system, the smallest $\lambda$ system containing it is also a $\pi$ system.
Some books call result 1.a (or result 1.b) "Dynkin $\pi$-$\lambda$ Theorem.
Some quick references is
https://en.wikipedia.org/wiki/Dynkin_system
The second result

Let $G$ be an algebra of sets and define $M(G)$ to be the smallest monotone class containing $G$. Then $M(G)$ is precisely the $\sigma$-algebra generated by $G$, i.e. $\sigma(G) = M(G)$.
Where a monotone class in a set $R$ is a collection $M$ of subsets of $R$ which contains $R$ and is closed under countable monotone unions and intersections.

is usually called "Monotone Class Lemma" (or theorem)  you can find it in books like Folland's Real Analysis or Halmos' Measure Theory. In fact, Halmos presents a version of this result for $\sigma$-rings.

Let $G$ be ring of sets and define $M(G)$ to be the smallest monotone class containing $G$. Then $M(G)$ is precisely the $\sigma$-ring generated by $G$.

Let us prove that the results are equivalent

Result 1: Let $\mathcal{C}$ be a class of subsets of $\Omega$ closed under finite intersections and containing $\Omega$. Let $L(\mathcal{C})$ be the smallest class containing $\mathcal{C}$ which is closed under increasing limits and by difference. Then $L(\mathcal{C}) = \sigma ( \mathcal{C})$.

Result 2: Let $G$ be an algebra of sets and define $M(G)$ to be the smallest monotone class containing $G$. Then $M(G)$ is precisely the $\sigma$-algebra generated by $G$, i.e. $\sigma(G) = M(G)$.
Where a monotone class in a set $R$ is a collection $M$ of subsets of $R$ which contains $R$ and is closed under countable monotone unions and intersections.

Proof:
(2 $\Rightarrow$ 1). Note that any class containing $\mathcal{C}$ which is closed under increasing limits and by difference is close by complement because $\Omega \in \mathcal{C}$, and so it is also closed by decreasing limits. So it is closed under countable monotone unions and intersections. It means: any class containing $\mathcal{C}$ which is closed under increasing limits and by difference is a monotone class.
Note also that any class containing $\mathcal{C}$ which is closed under increasing limits and by difference contains $A(\mathcal{C})$  the algebra generated by $\mathcal{C}$.
Then using Result 2 we have
$$ \sigma(\mathcal{C}) = \sigma(A(\mathcal{C})) = M(A(\mathcal{C})) \subseteq L(A(\mathcal{C}))=L(\mathcal{C}) $$
Since $\sigma(\mathcal{C})$ is a class containing $\mathcal{C}$ which is closed under increasing limits and by difference, we have $L(\mathcal{C}) \subseteq \sigma(\mathcal{C})$, so $L(\mathcal{C}) = \sigma(\mathcal{C})$.
(1 $\Rightarrow$ 2). First let us prove that $M(G)$ is a class containing $G$ which is closed under increasing limits and by difference. Since $M(G)$ is monotone, we have that $M(G)$ is closed under increasing limits.
Now, for each $E\in M(G)$, define
$$M_E=\{ F \in M(G) : E\setminus F , F \setminus E \in M(G) \}$$
Since $M(G)$ is a monotone class, $M_E$ is a monotone class. Moreover, if $E\in G$ then for all $F \in G$, $F\in M_E$, because $G$ is an algebra. So, if $E\in G$, $G \subset M_E$. So, if $E\in G$,   $M(G) \subset M_E$. It means that for all $E\in G$, and all $F \in M(G)$, $F \in M_E$. So, for all $E\in G$, and all $F \in M(G)$, $E \in M_F$. So, for all $F \in M(G)$, $G \subset M_F$, but since
$M_F$ is a monotone class, we have, for all $F \in M(G)$, $M(G)\subset M_F$. But that means that $M(G)$ is closed by differences.
So we proved that  $M(G)$ is a class containing $G$ which is closed under increasing limits and by difference.
So by Result 1, $$\sigma(G)=L(G) \subseteq M(G)$$
Since $\sigma(G)$  is a monotone class, we have
$$ M(G) \subseteq \sigma(G)$$
So we have $$\sigma(G)= M(G)$$


text:
Q: How to prompt the user for a filename of the first and second files I have tried to use the following script, however, this only prompts one input.
from pathlib import Path
out_path = input('Filename A')
path = Path(out_path)

from pathlib import Path
out_path = input('Filename B')
path = Path(out_path)


text:
Q: Why can a struct encapsulating a class be a compile-time constant? Default parameters must be a compile-time constant so they can be either built-in types or struct. More precisely, they cannot be a class instance.
public class Complex { }

public struct Point
{
    public Complex complex;
    public Point(int any)
    {
        complex = new Complex();
    }
}

static class Program
{
    static void Method1(Point p = new Point()) { }

    //static void Method2(Complex c = new Complex()) { } //cannot be compiled

    static void Main()
    {
        Method1();

        // Method2(); cannot be compiled
    }
}

What I don't understand is why can a struct encapsulating a class be a compile-time constant recall that a class instance is not a compile-time constant?

A: It is not a compile time constant.  Your Point call is allowed as optional arguemnts can be:

*

*a constant expression;

*an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

*an expression of the form default(ValType), where ValType is a value type.

In this case, you're using the 2nd allowed option for optional arguments - an expression of the form new ValType(), as a struct is a value type.
The fact that your value type encapsulates a class doesn't matter - you get the default value for the value type (which will have complex set to null).


text:
Q: Can multiply RabbitMQ producers produce messages concurrently in same 'priority queue'? I need to build scalable application that have several Java applications (Spring RabbitMQ producers) that consume messages from other applications by HTTP protocol, calculating priority of message, and send them in to 'priority queue' that matches the params.
So far under load of hundreds of messages per second, one application works just fine, but there is need to scale up applications.
The problem is that I don't really understand how does RabbitMQ producers work with 'priority queues'. I've been searching information in RabbitMQ documentation and I found docs that says that every producer needs to get acks to make sure that messages have proceed successfully.
So the questions are

*

*Docs says that priority of messages calculated under hood AMQP protocol, so do RabbitMQ will send acks to producer after the position for messages will be selected or before

*How does messages will be treated if assume that we have 2 producers that produce 2 different messages with same priority to the same 'priority queue'

I will be appreciated for any hint that will help me with that!


text:
Q: Android - using activity getters from custom RecyclerView adapter I've got the following classes:
MatchActivity.java:
public void setDart1(int playerIndex, int points) {
        getDart1().set(playerIndex, points);
    }

    public ArrayList<Integer> getDart1() {
        return dart1;
    }

    public void setDart2(int playerIndex, int points) {
        getDart2().set(playerIndex, points);
    }

    public ArrayList<Integer> getDart2() {
        return dart2;
    }

    public void setDart3(int playerIndex, int points) {
        getDart3().set(playerIndex, points);
    }

    public ArrayList<Integer> getDart3() {
        return dart3;
    }

MatchActivityPlayerAdapter.java:
package de.tkirchmann.myaveragev3;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import java.io.Serializable;
import java.util.List;

public class MatchActivityPlayerAdapter extends RecyclerView.Adapter<MatchActivityPlayerAdapter.MatchActivityPlayerRowViewHolder> {

    private final List<Player> playerList;
    private final Match match;
    private Context context;

    MatchActivityPlayerAdapter(List<Player> playerList, Match match) {
        this.playerList = playerList;
        this.match = match;
    }

    @NonNull
    @Override
    public MatchActivityPlayerAdapter.MatchActivityPlayerRowViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.match_activity_row_layout, parent, false);
        return new MatchActivityPlayerRowViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MatchActivityPlayerAdapter.MatchActivityPlayerRowViewHolder holder, int position) {
        final Player player = playerList.get(position);
        MatchActivity matchActivity = new MatchActivity();

        holder.nameTextView.setText(player.getPlayerName());
        holder.pointsTextView.setText(matchActivity.getRemainingPoints().get(position));
        holder.dart1.setText(matchActivity.getDart1().get(position));
        holder.dart2.setText(matchActivity.getDart2().get(position));
        holder.dart3.setText(matchActivity.getDart3().get(position));
        holder.dartsCombined.setText(matchActivity.getDartsCombined().get(position));
        /*holder.averageTextView.setText(matchActivity.getAverage().get(position));*/
    }

    @Override
    public int getItemCount() {
        return playerList.size();
    }

    class MatchActivityPlayerRowViewHolder extends RecyclerView.ViewHolder {
        public TextView nameTextView, pointsTextView, averageTextView, dart1, dart2, dart3, dartsCombined;

        public MatchActivityPlayerRowViewHolder(View playerRowView) {
            super(playerRowView);
            final ConstraintLayout playerRowRootLayout = playerRowView.findViewById(R.id.match_player_row_root_layout);
            nameTextView = playerRowView.findViewById(R.id.name);
            pointsTextView = playerRowView.findViewById(R.id.points);
            averageTextView = playerRowView.findViewById(R.id.average);
            dart1 = playerRowView.findViewById(R.id.dart1);
            dart2 = playerRowView.findViewById(R.id.dart2);
            dart3 = playerRowView.findViewById(R.id.dart3);
            dartsCombined = playerRowView.findViewById(R.id.last_darts_combined);
        }
    }
}

In the onBindViewHolder() method in the custom adapter I want to set the texts of my views by getting the values from the lists via getters from my activity. But I am getting a IndexOutOfBoundsException, so I propably don't have a correct reference/context when calling the getters.
How can I get the correct context/reference to my activity?

A: You can try this:
((YourActivityName) itemView.getContext()).getDart1();

and then so on for other getters. You can use any public method using this.


text:
Q: ruby / watir webdriver - url encoding for spaces, etc I'm trying to follow with Watir links with spaces and "http://"-s in them. Doing it manually I'm able to copy-paste something like that:
http://somewebsite.com/car%20navigation%20systems/products~NS-1~linkin_id-8016137~cid-3220953854?ef_id=test:@a-b

into the browser address bar, and open the proper page. When I assign this string to a variable url_string in ruby code and do "puts url_string" I see that string in exactly this way (with %20-s in it).
When I use it with watir webdriver's "b.goto url_string" it shows "car navigation systems" instead of "car%20navigation%20systems" in the browser, and obviously it doesn't work.
When I "require open-uri" and instead of doing "b.goto url_string" use "b.goto URI::encode(url_string)" I see in the browser that %20 was replaced with %2520 ("car%2520navigation%2520systems") – and again it's not working.
What should I do with the strings like that (which works OK with manual copy-pasting into a browser) to properly use them with b.goto?
http://somewebsite.com/car%20navigation%20systems/products~NS-1~linkin_id-8016137~cid-3220953854?ef_id=test:@a-b

http://somewebsite.com/somepage.cmp?bm=513&BEFID=1398&aon=%5E1&MerchantID=26574&crawler_id=1903439&dealId=U4KvhohLLfNITUSw9xH1PA%3D%3D&url=http%3A%2F%2Flink.mercent.com%2Fredirect.ashx%3Fmr%3AmerchantID%3DREI%26mr%3AtrackingCode%3D4B0E6F02-7411-E111-804A-A8C6AF702B72%26mr%3AtargetUrl%3Dhttp%3A%2F%2Fwww.rei.com%2FOM%2Fsku%2F8108320014%253fcm_mmc%253dcse_shopping-_-datafeed-_-product-_-na%26sdc_id%3D%7Bsdc_id%7D&linkin_id=8011139&Issdt=&searchID=On29U8JKSm&DealName=Garmin+Edge+800+Wireless+Bike+Computer+Color+BLACK&dlprc=449.95&AR=23&NG=29&NDP=40&PN=1&ST=7&FPT=DNSR&NDS=&NMS=&MRS=&PD=104443840&brnId=2455&IsFtr=0&IsSmart=0&op=&CM=&RR=23&IsLps=0&code=&acode=602&category=&HasLink=&ND=&MN=&GR=&lnkId=&SKU=8108320014&IsGtb=0&SPT=CROSSGV&MNID=22406&EF=TEST300%3A3&sig=e917ca16cfc85bedd51b2445ee2aa566f1ccc319&CT=14

UPDATE: so far b.goto url_string.gsub("%20", "+") worked for most of the URLs.

A: This turned out to be working:
url_string = "http://somewebsite.com/car%20navigation%20systems/products~NS-1~linkin_id-8016137~cid-3220953854?ef_id=test:@a-b"
b.goto url_string.gsub("%20", "+")


text:
Q: Passing a struct by reference errors( incomplete struct and redeclaration) I'm trying to pass a struct by reference but no matter what I do I'm running into errors. I think I have the prototyping and declaration and the pointers all screwed up.
This is for an Arduino project of mine. The code works fine on the Arduino compiler but doesn't compile on Pelles C compiler.
#include <stdio.h>
#include <string.h>
#include <stdint.h>

void Fault_Bits_To_Flags(uint8_t Master_Fault_Byte, struct Fault_Flag_Struct *Fault_Flag);

struct Fault_Flag_Struct {
    char Fault_Name[30];
    uint8_t Fault_State;
};
struct Fault_Flag_Struct Fault_Flag [7];

int main(void) {
    uint8_t Master_Fault_Byte = 181;

    strcpy(Fault_Flag[0].Fault_Name, "fault 0");
    Fault_Flag[0].Fault_State = 1;

    strcpy(Fault_Flag[1]....
    strcpy(Fault_Flag[2]....
    strcpy(Fault_Flag[3]....
    strcpy(Fault_Flag[4]....

    Fault_Bits_To_Flags( Master_Fault_Byte, *Fault_Flag);
    return 0;
}

//Puts 8 bits from single byte into 8 separate bytes (flags)//
void Fault_Bits_To_Flags(uint8_t Master_Fault_Byte, struct Fault_Flag_Struct *Fault_Flag) {
    for ( int i = 0; i < 8; i++ )
        {
            Fault_Flag[i].Fault_State = (Master_Fault_Byte >> i) & 1;
    }
}

error #2140: Type error in argument 2 to 'Fault_Bits_To_Flags';
  expected '(incomplete) struct Fault_Flag_Struct *' but found 'struct
  Fault_Flag_Struct'.
error #2120: Redeclaration of 'Fault_Bits_To_Flags', previously
  declared at Reference.c(4); expected 'void function(unsigned char,
  (incomplete) struct Fault_Flag_Struct *)' but found 'void
  function(unsigned char, struct Fault_Flag_Struct )'.
   Error code: 1 *

A: The scope of a parameter declaration in the list of parameters of a function prototype terminates at the end of the function declarator. Opposite to C++ there is no such a notion as the elaborated type specifier in C.
From the C Standard (6.2.1 Scopes of identifiers)

*... If the declarator or type specifier that declares the identifier appears
  within the list of parameter declarations in a
  function prototype (not part of a function definition), the identifier
  has function prototype scope, which terminates at the end of the
  function declarator

So the type specifier struct Fault_Flag_Struct used in the function prototype
void Fault_Bits_To_Flags(uint8_t Master_Fault_Byte, struct
Fault_Flag_Struct *Fault_Flag);

denotes a different entity compared with the declaration that follows the function prototype
struct Fault_Flag_Struct {
char Fault_Name[30];
uint8_t Fault_State;
};

So you have to exchange the placements of the declarations.
Also this call
Fault_Bits_To_Flags( Master_Fault_Byte, *Fault_Flag);

is invalid because the type of the expression *Fault_Flag is struct Fault_Flag_Struct  while the function expects the type struct Fault_Flag_Struct *. That is instead of a pointer to an object of the type struct Fault_Flag_Struct  you are passing the object itself.

A: Scope and Structure Types
There are two problems in the code shown.
The first is because C has some odd rules about structure definitions. One rule, in C 2018 6.7.2.3 4, is that structure declarations with the same tag (the name after struct) declare the same type (a structure type with that name) only if they have the same scope:

All declarations of structure, union, or enumerated types that have the same scope and use the same tag declare the same type.…

When you declare a structure inside a function declaration, like this:
void foo(struct X *p);

Then the scope of X is function prototype scope. Per 6.2.1 4, this scope ends at the end of the function declaration. Then, when you later define the structure, as with:
struct X { int q; }

it is in a different scope, and, per the rule above, the struct X in the function declaration is not the same type as the struct X in the later definition. One way to fix this is to move the structure definition prior to the function declaration. It also suffices merely to declare the structure tag prior to the function declaration, as with:
struct X;
void foo(struct X *p);

To fully understand what is happening here, we should consider two other issues. One issue is that we could have struct X in two different translation units (different source files compiled separately), and calling a function defined with a struct X * parameter in one unit from another unit that defines struct X is allowed. This is because that, although the two struct X types in the two translations units are different, they are compatible. 6.2.7 1 says:

… Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if…

Oddly, this rule only applies to structures declared in separate translation units. If we defined void foo(struct X *p { … } prior to defining struct X in one translation unit, they are different and incompatible types, but, if we define them in separate units, they are compatible types!
The second issue is how can this code work when the structure declarations have separate scopes:
struct X;
void foo(struct X *p);

The first struct X has file scope (per 6.2.1 4), and the second struct X has function prototype scope. The rule in 6.7.2.3 4 only applies if the declarations have the same scope, so it does not say these declare the same struct X. Instead, there is another rule, in 6.7.2.3 9:

If a type specifier of the form struct-or-union identifier or enum identifier occurs other than as part of one of the above forms, and a declaration of the identifier as a tag is visible, then it specifies the same type as that other declaration, and does not redeclare the tag.

(The "above forms" are definitions or stand-alone declarations.) This causes the struct X in the function declaration after a prior file-scope struct X to specify the same type.
Error in Argument
The second error is in the second argument passed to the function in this statement:
Fault_Bits_To_Flags( Master_Fault_Byte, *Fault_Flag);

Fault_Flag is an array, so *Fault_Flag is the first element of the array. This is a structure, not a pointer. To pass a pointer to the first element of the array, use:
Fault_Bits_To_Flags( Master_Fault_Byte, Fault_Flag);


text:
Q: Android FFMPEG: Could not execute the ffmpeg from Java code I am working on an Android app where I want to create a video from a
list of static images. After doing some search on internet, it made me
realized that using "FFMPEG" is the way to go in getting this thing
done. So I got hold of this site:
https://github.com/guardianproject/android-ffmpeg-java from where I
downloaded the C library and the Java wrapper. I was able to compile the
C library - of course not the way the instruction was laid out - but
still I was able to get "ffmpeg" executable under
/external/android-ffmpeg/ffmpeg directory. I copied that executable in
my current directory and then copied it to a directory under Android
where my app can access it. Then I called the provided Java wrapper but
I am seeing some errors in the log file like follows:
08-13 11:55:37.848: D/FFMPEG(29598): /data/data/com.sample/app_bin/ffmpeg -y -loop 1 -i /storage/emulated/0/usersnapshot/ffmpeg/image%03d.jpg -r 25 -t 2 -qscale 5 /storage/emulated/0/video/snapshot-video.mp4
08-13 11:55:37.898: I/ShellCallback : shellOut()(29598): /data/data/com.sample/app_bin/ffmpeg[1]: syntax error: '(' unexpected
08-13 11:55:37.938: I/ShellCallback : processComplete()(29598): 1

And following is the code snippet (where targetDirectoryForFFMPEG = directory where the images are stored):
FfmpegController ffmpegController = new FfmpegController(this, targetDirectoryForFFMPEG);
String out = videoOutPutFile.getPath();
        MediaDesc mediaIn = new MediaDesc();
        mediaIn.path = targetDirectoryForFFMPEG+"/image%03d.jpg";
        mediaIn.videoFps =  "25";
        ffmpegController.convertImageToMP4(mediaIn, 2, out,new ShellCallback() {

            @Override
            public void shellOut(String shellLine) {
                Log.i("ShellCallback : shellOut()", shellLine);
            }

            @Override
            public void processComplete(int exitValue) {
                Log.i("ShellCallback : processComplete()", exitValue+"");
            }
        });

Has anybody implemented this before? If yes, can you point me to what am I doing incorrect? I will provide more information if needed.

A: Do you have root on the device?
Mount '/data' and then enter your same 'ffmpeg' command in the shell and see whether the error is the same.
Try using the shell to test out different command expressions.
Try 'ffmpeg' alone and with just one input file. See whether those commands produce expected output.
My wild guess would be that there is an issue with calling 'ffmpeg.main()'  that relates to the details of your build.

A: Your ffmpeg might not be compiled properly for the arm.  I was getting the same error when not using a correctly compiled ffmpeg.


text:
Q: ESLlint Resolve error: TypeError: Cannot read property 'baseUrl' of undefined from using "config" npm depencency I recently started receiving the below error in Intellij
ESLint:
Resolve error: TypeError: Cannot read property 'baseUrl' of undefined
    at Object.<anonymous> (C:\Users\Levi\workspace\webpack.config.js:35:45)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.exports.resolve (C:\Users\Levi\workspace\node_modules\eslint-import-resolver-webpack\index.js:69:27)
    at v2 (C:\Users\Levi\workspace\application\node_modules\eslint-module-utils\resolve.js:117:23)
(import/no-unresolved)

This is the portion of the webpack.config.js mentioned in the error
const config = require('config');
const webpackConfig = removeEmpty({
 output: {
        publicPath: ifNotProd(`${config.app.baseUrl}/`),  <-----line 35 from the error

At first, I thought, it was caused by the latest update to Intellij IDEA 2020.2.  To verify that I downgraded the version of Intellij.  The error did resolve itself for a short time, but then returned even after being on the previous version of Intellij.  Like something was cached but once a specific sort of rebuild of my Intellij environment occurred the error resurfaced.
My main concern is that whatever sort of magic Intellij does to resolve dependencies is erroring in most, but not all of my files.
Sometimes it looks like this:

Other times it looks like this:

If I disable all of ESLint the errors go away, as you would expect.  I tried to ignore just the webpack.config.js file but that did not appear to resolve the issue.
I've considered semantic versions of dependencies changing as I use ^version syntax.
My questions are:

*

*What is ESLint doing that it's running into issues, is it "building" something that allows it to do loose type checking that is now failing?

*Has anyone else run across this sort of issue with the config npm module?

If you need more information let me know and I will try to provide it.

A: As a first step to debugging this I would replace removeEmpty with Object.freeze to see if you can find what is deleting baseUrl.
If you catch it needing to change something else first, just move Object.freeze to after that and catch the next mutation until you find the one your interested in.


text:
Q: Powershell DSC what is the execution context for current configuration? I'm trying to deploy a powershell profile through DSC.
The configuration should copy a .ps1 file from a network share to a local path.
Running the script fails with the following error SourcePath must be accessible for current configuration. yet this path is accessible from the console, so what user/context is used during dsc configuration ?
Here is the script

Edit after @ravikanth's reply

$ConfigurationData = @{
AllNodes = @(
    @{
        NodeName="*"
        PSDscAllowPlainTextPassword=$true
     }
    )
}
Configuration MyProfile
{
  param ([string[]]$MachineName,
        [PSCredential]$Credential)

  Node $MachineName
  {
    Log startconfig
    {
        # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log
        Message = "starting the file resource with ID MyProfile with $($myinvocation.mycommand) user : $env:username"
    }
    File profile
    {
      Credential=$credential
      Ensure = 'Present'
      SourcePath = "\\web-mridf\powershell\profil_1.ps1"
      DestinationPath = "c:\temp\test.txt"
      Type = "File" # Default is "File".
      DependsOn = "[Log]startconfig"
    }

     Log AfterDirectoryCopy
     {
        # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log
        Message = "Finished running the file resource with ID MyProfile"
        DependsOn = "[File]profile" # This means run "MyProfile" first.
     }
  }
}

MyProfile -MachineName web-mridf -OutputPath c:\temp\dsc
Start-DscConfiguration -Path c:\temp\dsc -credential (get-credential("DOMAIN\user")) -force -verbose -Wait

And the error received ( invalid argument)
PS C:\temp> .\dsc.ps1

    Répertoire : C:\temp\dsc

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        04/06/2014     10:54       2834 web-mridf.mof
COMMENTAIRES : Effectuez l'opération « Invoquer une méthode CIM » avec les
paramètres suivants : « 'methodName' = SendConfigurationApply,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration ».

COMMENTAIRES : [WEB-MRIDF] :                            [[File]profile]
SourcePath must be accessible for current configuration.
COMMENTAIRES : [WEB-MRIDF] :                            [[File]profile] The
related file/directory is: \\web-mridf\powershell\profil_1.ps1.
SourcePath must be accessible for current configuration. The related
file/directory is: \\web-mridf\powershell\profil_smac.ps1. . L'ID de ressource
associé est [File]profile.
    + CategoryInfo          : InvalidArgument : (:) [], CimException
    + FullyQualifiedErrorId : MI RESULT 4
    + PSComputerName        : web-mridf

COMMENTAIRES : [WEB-MRIDF] : Gestionnaire de configuration local :  [ Fin
Définir  ]
La fonction SendConfigurationApply n'a pas réussi.
    + CategoryInfo          : InvalidArgument : (root/Microsoft/...gurationMan
   ager:String) [], CimException
    + FullyQualifiedErrorId : MI RESULT 4
    + PSComputerName        : web-mridf

COMMENTAIRES : L'opération « Invoquer une méthode CIM » est terminée.
COMMENTAIRES : Le temps nécessaire à l'exécution du travail de configuration
est de 0.881 secondes

A: DSC Local configuration manager runs as SYSTEM. So, it will not have access to the share. You need to pass the credentials to access the share. For the credentials, you need to either use certificates to encrypt the password or use plain-text password.
For the plain text password, check the article I posted at PowerShell Magazine.
http://www.powershellmagazine.com/2013/09/26/using-the-credential-attribute-of-dsc-file-resource/
If you want to use certificates for the password encryption, check the PS Team blog post at http://blogs.msdn.com/b/powershell/archive/2014/01/31/want-to-secure-credentials-in-windows-powershell-desired-state-configuration.aspx
Update based on the comments below:
The $AllNodes.Nodename is the key when using Configuration Data. Do not replace that with a static nodename.
$ConfigurationData = @{
    AllNodes = @(
        @{
            NodeName="*"
            PSDscAllowPlainTextPassword=$true
         }
        @{
            NodeName="ServerName"
         }
    )
}

Configuration MyProfile
{
    param (
        [PSCredential]$Credential
    )

    Node $AllNodes.NodeName
    {
        Log startconfig
        {
            # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log
            Message = "starting the file resource with ID MyProfile with $($myinvocation.mycommand) user : $env:username"
        }
        File profile
        {
            Credential=$credential
            Ensure = 'Present'
            SourcePath = "e:\powershell\profil_smac.ps1"
            DestinationPath = "c:\temp\test2.txt2"
            Type = "File" # Default is "File".
            DependsOn = "[Log]startconfig"
        }

        Log AfterDirectoryCopy
        {
            # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log
            Message = "Finished running the file resource with ID MyProfile"
            DependsOn = "[File]profile" # This means run "MyProfile" first.
        }
    }
}

MyProfile -configurationdata $configurationdata -machinename "web-mridf.groupe.sa.colas.com" -credential (get-credential("groupe\sys-mac-smacsr")) -OutputPath c:\temp\dsc
Start-DscConfiguration -Path c:\temp\dsc -force -verbose -Wait