text:
Q: jquery multilevel select list i have problem with my multilevel dependent select lists, i have six select lists dependent on each other and i have write a code to create dynamic lists using jquery. selects named as district, tehsil, project, center, school and user. it is working fine when i choose all options in a sequence, district-> tehsil-> project -> center -> school -> user, and when i change sequence at any level like district -> tehsil -> district( here district is parent of tehsil) after clicking on parent child tehsil not refreshed, and this problem exist in all hierarchy.... this jquery code calls 6 controller and models. those are not include here due to length of question. what should i do ?
this is my jquery code
$('#districts_id,#tehsils_id,#projects_id,#centers_id,#schools_id').on('change', function() {

                    //alert($("#districts_id option:selected").attr("title"));
                    //var parameters = {};
                    var parameters;
                    var url;

                    if($('#schools_id').val())
                    {
                        $("#users_id").removeAttr('disabled');
                        //parameters = JSON.stringify({schools_centers_id:$('#centers_id').val()});
                        parameters = {"users_schools_id": $('#schools_id').val(), users_gender: $('#gender').val()};
                        url = "<?php echo base_url();?>/BtaAdministratorUnionMembers/get_teachers_users_by_school_id";
                    }
                    else if($('#centers_id').val())
                    {
                        $("#schools_id").removeAttr('disabled');
                        //parameters = JSON.stringify({schools_centers_id:$('#centers_id').val()});
                        parameters = {"schools_centers_id": $('#centers_id').val()};
                        url = "<?php echo base_url();?>/BtaAdministratorUsers/get_schools_by_center_id";
                    }
                    else if($('#projects_id').val())
                    {
                        $("#centers_id").removeAttr('disabled');
                        //parameters = JSON.stringify({centers_probject_id:$('#projects_id').val()});
                        parameters = {"centers_probject_id": $('#projects_id').val()};
                        url = "<?php echo base_url();?>/BtaAdministratorUsers/get_centers_by_project_id";
                    }
                    else if($("#tehsils_id option:selected").attr("title") == 'tehsils_id')//($('#tehsils_id').val())
                    {
                        $("#projects_id").removeAttr('disabled');
                        //parameters = JSON.stringify({projects_tehsil_id:$('#tehsils_id').val()});
                        parameters = {"projects_tehsil_id": $('#tehsils_id').val()};
                        url = "<?php echo base_url();?>/BtaAdministratorUsers/get_projects_by_tehsil_id";
                        //alert(parameters + ' '+ url);
                    }
                    else if($("#districts_id option:selected").attr("title") == 'districts_id')//($('#districts_id').val())
                    {
                        $("#tehsils_id").removeAttr('disabled');
                        //$("#tehsils_id").empty();
                        //parameters = JSON.stringify({tehsils_districts_id:$('#districts_id').val()});
                        parameters = {"tehsils_districts_id": $('#districts_id').val()};
                        url = "<?php echo base_url();?>/BtaAdministratorUsers/get_tehsils_by_districts_id";
                        //alert(parameters + ' '+ url);
                    }

                    $.ajax({
                    type: "GET",
                    url: url,
                    data:parameters,
                    //contentType: "application/json;charset=utf-8",
                    dataType: 'json',
                    success: function(data){
                    //alert(data);
                    //alert(JSON.stringify(data));
                        if($('#schools_id').val())
                        {
                            //alert(JSON.stringify(data));
                            $('#users_id').empty();
                            $('#users_id').append("<option value=''>Select Teacher....</option>");
                            $.each(data,function(key,value){
                                $('#users_id').append('<option value="'+value.users_id+'">'+value.users_firstname_users_lastname+'</option>');
                                });
                        }
                        else if($('#centers_id').val())
                        {
                            //alert(JSON.stringify(data));
                            $('#schools_id').empty();
                            $('#schools_id').append("<option value=''>Select School....</option>");
                            $.each(data,function(key,value){
                                $('#schools_id').append('<option value="'+value.schools_id+'">'+value.schools_name+'</option>');
                                });
                        }
                        else if($('#projects_id').val())
                        {
                            //alert(JSON.stringify(data));
                            $('#centers_id').empty();
                            $('#centers_id').append("<option value=''>Select Center....</option>");
                            $.each(data,function(key,value){
                                $('#centers_id').append('<option value="'+value.centers_id+'">'+value.centers_schoolName+'</option>');
                                });
                        }
                        else if($("#tehsils_id option:selected").attr("title") == 'tehsils_id')//($('#tehsils_id').val())
                        {
                            //alert(JSON.stringify(data));
                            $('#projects_id').empty();
                            $('#projects_id').append("<option value=''>Select Project....</option>");
                            $.each(data,function(key,value){
                                $('#projects_id').append('<option value="'+value.projects_id+'">'+value.projects_name+'</option>');
                                });
                        }
                        else if($("#districts_id option:selected").attr("title") == 'districts_id')//($('#districts_id').val())
                        {
                            //clearDropDown($('select'), 5);
                            $('#tehsils_id').empty();
                            $('#tehsils_id').append("<option value='' title=tehsils_id>Select Tehsils....</option>");
                            $.each(data,function(key,value){
                                $('#tehsils_id').append('<option value="'+value.tehsils_id+'" title=tehsils_id>'+value.tehsils_name+'</option>');
                                });
                        }
                    },
                error: function(data){
                    alert(JSON.stringify(data));
                    //console.log(data);
    }
                    });

        });

A: In each level you have to remove all next options when a top level option is changed and the set the next level again e.g in school level:
$('#schools_id').nextAll("select").each(function(){
   $(this).find('option').remove();
})
// Then set again the next level

I used nextAll assuming that selects are siblings. elsewhere you have to use propper selector

A: With all of your if else statements organized from the most specific to least specific, fiddling with a parent input triggers the event handler but is caught by the else statement for its child.
Use separate event handlers for all six inputs based on the one you are interacting with rather than checking for values alone, and your logic will work morelike you planned.
You'll even be able to more easily handle the case where the user is jumping back a few levels and you should reset/disable a few selects.


text:
Q: How does electrical current have energy? (when electrons move very slowly through circuit ) I'm interested to know how electric current carries energy. I understand that the huge amount of electrons pass at one point through conductor, but they move slowly. So I do not understand how much energy they have.

A:
How does electrical current have energy?

Voltage and current together can transfer energy (do work) because volts x amps = power and the time integral of power is energy.
For a rotating mechanical system, power = speed (radians per second) x torque so power is the product of torque and speed but either isn't power or energy on its own.

redpajama_set_name: RedPajamaStackExchange


text:
Q: will child have its own field variable or share its parent variable through inheritance? I want to consult an issue about Java field variable inheritance. Here is the code segment:
//parent
public class Parent {
    protected int a = 0;
}

//son
public class Son extends Parent{
    public void demo(){
        a = 1;
        System.out.println(super.a);
    }
    public static void main(String[] args){
        Son son = new Son();
        son.demo();
    }
}

output:
1

expect:
0

In my code the child will inherit field variable a, and we called it sonA and the field variable a of parent called parentA.
My question is whether sonA and parentA  the same one (e.g there address is 0x1234)? or they represent two different variable (e.g. one address 0x1234 another 0x5678)?

A: It's the same one, because Son doesn't have an a of its own. If you introduce one, you'll hide Parent's a and then you'll see the behaviour you're expecting:
//parent
public class Parent {
    protected int a = 0;
}

//son
public class Son extends Parent{
    int a = 0; // this hides the Parent field

    public void demo(){
        a = 1; // this accesses the Son field
        System.out.println(super.a); // this accesses the Parent field explicitly
    }
    public static void main(String[] args){
        Son son = new Son();
        son.demo();
    }
}

However, this would generally not be a recommended practice, as it could lead to a lot of confusion.

A: They share the same address, however you did overwrite the default value 0 with 1 so it's correct behaviour. Let's check that:
Son son = new Son();
Parent parent = new Parent();
Field fieldAParent = parent.getClass().getDeclaredField("a");
Field fieldA = son.getClass().getDeclaredField("a");

You'll get an exception on the last line, because class son doesn't contain field a


text:
Q: Explicit type conversion in Scala 3 macros I defined the following trait in Scala 3:
trait A[T <: Tuple]

Using Scala 3 macros, I then create objects of this trait performing further checks on the actual types of the tuple T; in particular, I want to check that all the types (T_1, …, T_n) of the tuple T are subtypes of another given type, B:
trait B
private def allSubtypesOfB[T <: Tuple: Type](using quotes: Quotes): Boolean = {
    import quotes.reflect.*
    case '[Nothing] => false // I don't want nothing to be in T
    case '[head *: tail] if TypeRepr.of[head] <:< TypeRepr.of[B] => allSubtypesOfB[tail]
    case '[EmptyTuple] => true
    case _ => false
}

inline def createA[T <: Tuple] = ${ createAImpl[T] }
private def createAImpl[T <: Tuple: Type](using quotes: Quotes): Expr[A[T]] = {
    import quotes.reflect.*
    if !allSubtypesOfB[T] then report.error("All types in T must be subtypes of B")
    // ... create instance of A
}

The problem is that later I need to call, for each type in the tuple type T, a method that has the following signature:
def doSomethingWithBSubtype[T <: B] = ??? // Do something with type T

So, the code would look something like this:
private def createAImpl[T <: Tuple: Type](using quotes: Quotes): Expr[A[T]] = {
    import quotes.reflect.*
    if !allSubtypesOfB[T] then report.error("All types in T must be subtypes of B")
    Type.of[T] match {
        case '[head *: tail] => doSomethingWithBSubtype[head]
        case '[EmptyTuple] => ???
    }
    // ... create instance of A
}

This code won't compile as the compiler says that head must be a subtype of B to be used in the method doSomethingWithBSubtype. However, with the if preceding the match case, I already ensured that all types inside T are subtypes of B. Is there a way to force the compiler to recognise head as a subtype of B?

A: There are compile time and runtime of macros. There are compile time and runtime of main code (using the macros). The runtime of macros is the compile time of main code.
Inside createAImpl the line if !allSubtypesOfB[T]... ensures that all types of T are subtypes of B at the runtime of createAImpl. But when you call doSomethingWithBSubtype[head] you need to know that head is a subtype of B at the compile time of createAImpl so you don't have information from the runtime of createAImpl yet (if !allSubtypesOfB[T]...).
You could do
case '[head *: tail] => doSomethingWithBSubtype[head & B]

Also maybe something like the following is possible
Type.of[T] match {
  case '[head *: tail] =>
    '{foo[head]} match {
      case '{
        type h <: B
        foo[`h`]
      } => doSomethingWithBSubtype[h]
    }
  case '[EmptyTuple] => ???
}

// outside def createAImpl, otherwise "access to method foo from wrong staging level"
def foo[A] = ???

https://docs.scala-lang.org/scala3/guides/macros/quotes.html#type-variables-in-quoted-patterns

In some cases we need to define a pattern variable that is referenced several times or has some type bounds. To achieve this, it is possible to create pattern variables at the start of the pattern using type t with a type pattern variable.

fuseMap macro in scala 3
What Scala 3 syntax can match on a Type and its Type parameters in the context of a macro?
Get information of type in Scala3 macro
Turning inlined varargs into a generic tuple


text:
Q: usage of virtual keyword with a class declaration I was asked in an interview that what is the usage of virtual keyword with a class declaration in C++ and I answered that virtual keyword cannot be used with a class declaration in C++. The interviewer said that it is possible and asked me to test it later.
Now that I have checked it myself I have come to know that this is possible and this is not a compiler error. In fact, when I do something like this with a Visual C++ compiler:
virtual class Test
{
   int i;
};

I get a compiler warning "warning C4091: 'virtual ' : ignored on left of 'Test' when no variable is declared". I haven't been able to find out yet that what this warning means and further what is the usage of virtual keyword. If there is no helpful usage, then why is this allowed in the first place and why is this not a compiler error.

A: virtual can be used when deriving from another class:
class Foo : public virtual Bar
{
}

This is used to avoid having multiple versions of the same base class when using multiple inheritance. Wikipedia has a good article on the subject.

A: That's a bug in VC++. Comeau and gcc both reject the code.

A: You simply can't use virtual for a class. It only works for member functions

A: You're looking at the wrong sort of usage - I'm pretty sure that the interviewer was referring to virtual base class declarations, like so:

  class A : virtual public B, public C {
    ...
  };

This is a common idiom and used to get around the "multiple base class" scenario in diamond-shaped inheritance trees. The typical problem with them is that you inherit from both class B and class C and they share the common ancestor A. If you go 'up' the inheritance tree you'll hit the ambiguity as to which instance of 'A' you're supposed to use. If B & C have A as a virtual base class instead, they will refer to the same instance of A, which solves this problem.
You can find a more exhaustive description with class diagrams here.

A: Maybe he was referring to virtual inheritance / virtual base classes?  E.g.
class A : virtual public B
{ ... }

That would technically be part of the class definition.

A: Could he have been talking about using a virtual base class in the class declaration?
Like this:
class CashierQueue : virtual public Queue {};

This is used in multiple inheritance when you want to avoid a derived class having multiple copies of the member data when it inherits from two or more classes that share the same base class.
class Queue {};
class CashierQueue : virtual public Queue {};
class LunchQueue : virtual public Queue {};
class LunchCashierQueue : public LunchQueue, public CashierQueue {};

See http://msdn.microsoft.com/en-us/library/wcz57btd(VS.80).aspx


text:
Q: AWS SAM Function AutoPublishAlias "Invalid function version" I am using AWS SAM to deploy a Lambda function. I'am using the AutoPublishAlias property to automatically publish a new version when I deploy the function but I'm getting the following error: Invalid function version 9. Function version 9 is already included in routing configuration. (Service: AWSLambdaInternal; Status Code: 400; Error Code: InvalidParameterValueException; Request ID: 56b59a6b-6c57-434e-a505-ce7aa27c99b6). Every time I delete and create the stack the function gets created successfully, but when I try to update the stack I get the error. I'm also wondering why is the version number not starting from 1 after deleting the Lambda?
The Lambda definition:
ApiLambda:
Type: AWS::Serverless::Function
Properties:
  FunctionName: !Sub '${TagApplication}-${TagEnvironment}-api-lambda'
  CodeUri: ../build
  Handler: lambda.handler
  MemorySize: 256
  Role: !GetAtt LambdaExecutionRole.Arn
  Runtime: nodejs10.x
  Timeout: 30
  AutoPublishAlias: 'live'
  ProvisionedConcurrencyConfig:
    ProvisionedConcurrentExecutions: '1'

Screenshot of AWS Lambda console Alias menu:

A: Looks like you need to configure the DeploymentPreference property as well - see this link - https://github.com/awslabs/serverless-application-model/issues/1296 and https://github.com/jcts3/sam-pc-experiment/blob/master/template.yaml#L22


text:
Q: Showing a span attribute value when hovering I have an HTML like this:

Uneven development is, precisely that: capitalist
factors (firms, industries, countries) have a common trait, but

they show uneven unfolding and cannot be individually
predicted. Since the factors are mutually and interdependently
related, the general trend that we define as the law of uneven
development can be inferred from their relationship, which
has a specific connotation, i.e., the difference in the paces of
the factors that make up the relationship itself. Since the general
trend is determined by capitalism's nature, it cannot change without changing the nature of
capitalism itself.

How can I show the value of ref attribute of span tag when hovering on its text.

A: you can use title attribute or you can make your own custom tooltip like this, in this case, be aware of positioning your tooltip to prevent overflows, in HTML you can add your custom attributes as well starting with data- for example data-customAttribute
the attribute selector in CSS looks like this [data-customAttribute] {.....} for more specificity you can add the element span[data-customAttribute] {.....}

/** Tootip **/
  span[ref]:hover:after {
    opacity: 1;
    transition: all 0.1s ease .5s;
    visibility: visible;
    animation: grow 3s forwards;
}

span[ref]:after {
    content: attr(ref);
    background-color: #00adb5;
    color: #fff;
    position: absolute;
    padding: 1px 5px 2px 5px;
    top: 100%;
    left: 0px;
    white-space: nowrap;
    opacity: 0;
    box-shadow: 3px 3px 5px #00ADB5;
    border: 1px solid rgb(197, 195, 195);
    border-radius: 0 5px 0 5px;
    visibility: hidden;
    z-index: 20;
}

span[ref] {
    position: relative;
}

/* you can ignore the animation it is not mandatory */
@keyframes grow {
    0% {
        transform: scale(0);
    }

    30%, 65% {
        transform: scale(1);
    }

    70%, 100% {
        transform: scale(0);
    }
}

Uneven development is, precisely that: capitalist
factors (firms, industries, countries) have a common trait, but

they show uneven unfolding and cannot be individually
predicted. Since the factors are mutually and interdependently
related, the general trend that we define as the law of uneven
development can be inferred from their relationship, which
has a specific connotation, i.e., the difference in the paces of
the factors that make up the relationship itself. Since the general
trend is determined by capitalism's nature, it cannot change without changing the nature of
capitalism itself.


text:
Q: Issue In pulling the data from AccessDB I am trying to pull the data from access db and populate, with the following code
    String[] tableColumnsName = {"col 1","col 2","col 3"};
    DefaultTableModel aModel = (DefaultTableModel) jTable2.getModel();
    aModel.setColumnIdentifiers(tableColumnsName);
    try {
        // the query
        rs = db.query("SELECT * FROM Students ");
    } catch (SQLException ex) {
        Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Loop through the ResultSet and transfer in the Model
    java.sql.ResultSetMetaData rsmd = null;
    try {
        rsmd = rs.getMetaData();
    } catch (SQLException ex) {
        Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    //int colNo = rsmd.getColumnCount();
    try {
        while(rs.next()){
        Object[] objects = new Object[10];
        // tanks to umit ozkan for the bug fix!
        for(int i=0;i<10;i++){
        objects[i]=rs.getObject(i+1);
        }
        aModel.addRow(objects);
        }
    } catch (SQLException ex) {
        Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    jTable2.setModel(aModel);
}//GEN-LAST:event_jButton2ActionPerformed

I am able to pull the data from one. How can I pull it from another table?

A: You're making a lot of assumptions about your data, and leaving your resources open after you've finished with them.
First, you should use ResultSetMetaData to build the TableModel column information, then you should use it to build the row data from the ResultSet, for example...
DefaultTableModel aModel = new DefaultTableModel();
try (ResultSet rs = db.query("SELECT * FROM Students ")) {
    ResultSetMetaData rsmd = rs.getMetaData();
    for (int col = 0; col < rsmd.getColumnCount(); col++) {
        aModel.addColumn(rsmd.getColumnName(col + 1));
    }

    while (rs.next()) {
        Object[] value = new Object[rsmd.getColumnCount()];
        for (int col = 0; col < rsmd.getColumnCount(); col++) {
            value[col] = rs.getObject(col + 1);
        }
        aModel.addRow(value);
    }
} catch (SQLException ex) {
    Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex);
}
jTable2.setModel(model);

Now, I'd build a utility method which could take your query (or table name) and return a TableModel


text:
Q: How to check if a COM property or method exists without generating an exception? I'm working on some legacy code that creates a list of strings containing property and/or method names and then attempts to apply those properties or methods to a COM object. The property or method for the COM object is not guaranteed to exist and it could be either a property or a method I don't know which.
At the moment if a property or method doesn't exist it's caught as a COM exception. This results in poor performance. I am trying to find a way to check if a property or method exists in a COM object without generating an exception so that I can check for its existence before attempting to apply it.
Using GetType returns type System.com_object. Using GetProperty on System.com_object doesn't work as this is the exact runtime type not the type it's derived from. Instead I have to InvokeMember which creates an exception if the member doesn't exist. Does anyone have a better way of doing this?
I'm working in .NET 3.5 at the moment. Migration to .NET 4 is not an option at present but I'd still be interested in solutions in .NET 4 if the new language features provide a better way of solving the problem.
public static bool CheckIfComPropertyOrMethodExists<T1>(T1 objectToCheck, string propertyOrMethodName)
{
    if (CheckIfComPropertyExists(objectToCheck, propertyOrMethodName) == false & CheckIfComMethodExists(objectToCheck, propertyOrMethodName) == false) {
        return false;
    }
    {
        return true;
    }
}

public static bool CheckIfComPropertyExists<T1>(T1 objectToCheck, string propertyName)
{
    return objectToCheck.GetType().InvokeMember(propertyName, BindingFlags.GetProperty, null, objectToCheck, null) != null;
}

public static bool CheckIfComMethodExists<T1>(T1 objectToCheck, string methodName)
{
    return objectToCheck.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance) != null;
}

Helpful articles so far
How to check whether an object has certain method/property?
Calling a member of IDispatch COM interface from C#
http://msdn.microsoft.com/en-us/library/aa909091.aspx
Implementing IDispatch in c#
http://msdn.microsoft.com/en-us/magazine/dd347981.aspx
http://blogs.msdn.com/b/lucian/archive/2008/10/06/reflection-on-com-objects.aspx

A: Most probably the COM class implements also the IDispatch interface. You could then use its GetIDsOfNames to check whether a member exists in the class.
Here someone calls it from C#:
Calling a member of IDispatch COM interface from C#


text:
Q: new duplicate copy of MRTG install is making ugly rescaled graphs I'm duplicating an existing working MRTG setup. I set up the source machine a few years ago. Source and target are both CentOS 6.10, running MRTG 2.16.2.
Copying the commands run on the source machine which are stored in their files:
/usr/bin/cfgmaker --no-down --subdirs=HOSTNAME -o dell-x1018p.cfg -ifref=name -ifdesc=alias --global "WorkDir: /var/www/mrtg/" --global "RunAsDaemon: no" --global "Options[_]: pngdate" --global "EnableIPv6: no" public@dell-x1018p

/usr/bin/indexmaker --output /var/www/mrtg/dell-x1018p.html --title Dell-X1018p --columns 1 --width 800 --height 160 --show day /etc/mrtg/dell-x1018p.cfg

This generates very pretty 800 pixel wide graphs.
Properly scaled graph
When I use the same syntax on the target machine:
/usr/bin/cfgmaker --no-down --subdirs=HOSTNAME -o dell-x1018.cfg -ifref=name -ifdesc=alias --global "WorkDir: /var/www/mrtg/" --global "RunAsDaemon: no" --global "Options[_]: pngdate" --global "EnableIPv6: no" public@dell-x1018

/usr/bin/indexmaker --output /var/www/mrtg/dell-x1018.html --title "Dell X1018 (downstairs switch)" --columns 1 --width 800 --height 160 --show day /etc/mrtg/dell-x1018.cfg

This generates really ugly 500 pixel wide graphs that are scaled up to 800x160
rescaled graph
I must have done something else when I set up the source machine years ago, but looking at the files I see no difference. What am I missing?

A: It looks like you're running MRTG in Native mode (IE no RRDTool).
You should add global settings like:
XSize[_]: 800
Ysize[_]: 100

to the start of your master CFG file (before the 'Include' lines).  This will set the default graph size to 800x100 rather than the smaller default (note that this is the size of the graph, not the image, which includes a legend space as well).
You should consider installing RRDTool with LogFormat: RRD and using a graph-on-demand frontend instead like Routers2 as this gives more features and a smaller load on your system.


text:
Q: Converting expressions from Prefix to Postfix ( Facing Problems with Precedence) I have been attempting to write a code that converts Prefix expressions to Postfix expressions.
So far here's what I have made (note that I am new and hence may not be efficient!)
/***************************************************
 NOTE: This code fails to realise the precedence
    of parentheses and $ (exponential) expressions
****************************************************/

import java.util.Scanner;

class Stack{
    //Private Declarations
    private int top;
    private String a[] = new String [100];
    //Public Declarations
    public Stack(){
        top = -1;
        a[0] = "\0";
    }
    public void push(String x){
        if (top != 99){
            a[++top] = x;
        }
        else{
            System.out.println("Stack overflow");
        }
    };
    public String pop(){
        if (top == -1){
            System.out.println("\nStack empty!");
            return "\n";
        }
        else{
            return a[top--];
        }
    };
    public int ret_top(){
        return top;
    };
}

public class Prefix2Postfix {
    public static void main(String[] args) {
        //Declaration
        Scanner in = new Scanner (System.in);
        Stack op = new Stack ();
        Stack sym = new Stack ();
        char ch;
        int i;
        String exp, str, str1, str2, str3;

        //Taking input from the user
        System.out.println("Enter the prefix expression : ");
        exp = in.next();

        for (i=0; i<exp.length(); i++){
            ch = exp.charAt(i);
            if((ch == '+')
             ||(ch == '-')
             ||(ch == '*')
             ||(ch == '/')
             ||(ch == '$')){
                str = Character.toString(ch);
                op.push(str);
            }
            else{
                str = Character.toString(ch);
                sym.push(str);
            if (sym.ret_top() == 1){
                str1 = sym.pop();
                str2 = sym.pop();
                str3 = op.pop();
                str1 = str2.concat(str1);
                str1 = str1.concat(str3);
                sym.push(str1);
            }
            }
        }

        //Output
        str = sym.pop();
        System.out.println("After conversion to postfix" + ": " + str);
        in.close();
    }
}

As I have already commented in the code, my code fails to realize the precedence in the case of prefix expressions.
For example:
Infix   : a + (b*c)
Prefix  : +a*bc
Postfix : abc*+ //Expected output
Output I get : ab*c+

Is something wrong in the logic I am using or is there something I need to add?
Can you please suggest some method by means of which my code can work properly?
If anybody can help I will be grateful.
NB: Our professor has advised us to write our own stack class and code. Please also note that this is kind of a homework assignment.
Thanks in advance.

Edit:
In order to make sure that my STACK works fine I wrote the following piece of code and it works perfectly alright.
import java.util.Scanner;

class STACK {
    //Private Declarations
    private int top;
    private int elem[] = new int [100];
    //Public Declarations
    public STACK (){
        top = -1;
        elem[0] = 0;
    }
    public void push(int x){
        if (top != 99){
            elem[++top] = x;
        }
        else{
            System.out.println("Stack overflow");
        }
    };
    public int pop(){
        if (top == -1){
            System.out.println("Stack empty!");
            return 0;
        }
        else{
            return elem[top--];
        }
    };
}

public class StackPushPop {
    public static void main(String[] args) {
        STACK s = new STACK();
        Scanner in = new Scanner (System.in);
        int choice, x;
        do{
            System.out.println("Menu Options :");
            System.out.println("1 -> Push an element");
            System.out.println("2 -> Pop an element");
            System.out.println("3 -> Empty complete stack");
            System.out.println("Any other input for exit");
            System.out.println("Your choice : ");
            choice = in.nextInt();
            switch(choice){
                case 1:
                    System.out.println("\nEnter element : ");
                    x = in.nextInt();
                    s.push(x);
                    break;
                case 2:
                    System.out.print("\nPopping element : ");
                    x = s.pop();
                    if (x != 0){
                        System.out.println(x);
                    }
                    break;
                case 3:
                    System.out.println("\nEmptying stack!");
                    x = 1;
                    while (x!= 0){
                        x = s.pop();
                        if(x != 0){
                            System.out.print(x + "  ");
                        }
                    }
                    break;
                default:
                    choice = 0;
            }

        }while (choice != 0);
    }
}

EDIT
I finally managed to create a program that works perfectly fine.
import java.util.Scanner;

class STACK{
    private int top, MAX;
    private String a[] = new String [1000];
    public STACK(){
        top = -1;
        MAX = 1000;
        a[0] = "";
    }
    public void push(String x){
        if (top <= MAX-1){
            a[++top] = x;
        }
        else{
            System.out.println("Stack overflow");
        }
    };
    public String pop(){
        if (top == -1){
            System.out.println("\nStack empty!");
            return "\n";
        }
        else{
            return a[top--];
        }
    };
    public int getTop(){
        return top;
    };
}

public class Prefix2Postfix_STACK{
    static boolean isOperator (char ch){
        switch (ch){
            case '+':
            case '-':
            case '*':
            case '/':
            case '$':
                        return true;
            default :
                        return false;
        }
    }
    public static void main(String[] args) {
        //declarations
        Scanner in = new Scanner (System.in);
        String exp;
        int i;
        STACK s = new STACK ();
        String exp_str[] = new String[100];
        String postfix_exp = "\n";

        //input
        System.out.println("Enter prefix expression (No spaces or brackets) : ");
        exp = in.next();

        //create a string array of all characters but in reverse
        for(i=0; i<=exp.length()-1; i++){
            exp_str[exp.length()-1-i]=Character.toString(exp.charAt(i));
        }

        //computing postfix:
        i=0;
        do{
            if (!isOperator(exp_str[i].charAt(0)))
                s.push(exp_str[i]);
            else{
                String str1 = s.pop();
                String str2 = s.pop();
                str1 = str1 + str2 + exp_str[i];
                postfix_exp = str1;
                s.push(str1);
            }
            i++;
        }while(s.getTop()>=0 && i!=exp.length());

        //Output
        System.out.println("After converting to postfix : " + postfix_exp);
        in.close();
    }
}

A: The code you have written only does the job of shifting the operators from left to right.
A nudge in the right direction :

Insert a condition to check for operators between symbols in the
  prefix string and solve them first!

This might solve your problem.


text:
Q: Почему не работает sort() не могу понять, почему не работает sort((a, b) => b - a), но когда делаю просто sort() - работает?

function isIsogram(str){
  return str.split('').sort((a,b) => a - b);

}

console.log(isIsogram("Dermatoglyphics"));

A: Потому что здесь
a - b

строки преобразуются в числа.
"D" -> NaN
"e" -> NaN
"r" -> NaN

Ваш компаратор всегда возвращает NaN.
Ваши односимвольные строки можно сравнить
(a, b) => a < b ? -1 : a > b ? 1 : 0

или так
(a, b) => a.codePointAt(0) - b.codePointAt(0)

А если нужно сравнивать не по кодам символов, а по языковым правилам, то можно так
(a, b) => a.localeCompare(b)


text:
Q: Providing descriptive help context for Enums in C# Visual Studio? Is it possible to have help context displayed for each individual enum on code drop down display? (i.e. control space ?)
e.g.
public enum Moods
{
    Depressed = 1,  ///On Rainy Days use this
    BlownAway = 2, ///On Stormy nights use this
    Ferengi = 3  //Use this for Profit and glory
}

and later on in code have the specific enum and it's comment displayed in the code completion drop down when we type : Moods.

A: For intellisense descriptions, use the <summary> tag, as in:
/// <summary>
/// Various moods
/// </summary>
public enum Moods
{
    /// <summary>
    /// On Rainy Days use this
    /// </summary>
    Depressed = 1,
    /// <summary>
    /// On Stormy nights use this
    /// </summary>
    BlownAway = 2,
    /// <summary>
    /// Use this for Profit and glory
    /// </summary>
    Ferengi = 3
}


text:
Q: ASP.Net Model to Javascript - Passing Data from server to client Hey guys quick question what is the best approach on converting Model to Javascript.
I tried using this
@{
    var arr = new string[3];
    arr[0] = "1";
    arr[1] = "2";
    arr[2] = "3";
    var jason = JsonConvert.SerializeObject(Model);

}
<script type="text/javascript">
    var string = '@jason';
    var variable2 = jQuery.parseJSON(string);
    alert(variable2.Id);
</script>

as you can guess it did not work, I look through the sample of jQuery which should work but I am not sure if it is compatible with JsonConvert of .net
Its my first time on programming in the client side so this is quite a simple question but I tried looking the answer from the net. Mostly I see are uber complicated answers and at least 3 and higher old so I am guessing there should be an easier way to do this now?

A: I feel like this needs an answer because it's the number 2 result from google and has been viewed over 200 times, and as stated by the OP every other answer is generally long and/or convoluted. But the simplest answer is:
Javascript added to your aspx page:
<script type="text/javascript">
   var myObject = <%=JsonConvert.SerializeObject(MyNetObject)%>;
</script>

The key bit being that your output of HTML looks as follows:
<script type="test/javascript">
   var myObject = {"Prop1":"value1","Prop2":"Value2"};
</script>

Javascript natively handle JSON so you don't need to reparse anything on the client side. If the object is properly serialized it will be recognized without further conversion (this includes lists and object properties).
In the example provided in the OP the resultant Javascript object would be a simple array. So access to the elements on the client side would be:
alert(variable2[0]), alert(variable2[1]), alert(variable2[2])....

In order to provide the Javascript property calling functionality that OP is trying to do on the client side would require the following on the server side:
var json = JsonConvert.Serialize(new { ID1 = 1, ID2 = 2, ID3 = 3 });

In which an object with Named properties is serialized into the page.


text:
Q: Pyautogui.click(x, y) error So I am learning to use python 3 and now the "pyautogui" module. When I try to use "pyautogui.click(x, y)". I get this error "[WinError 5] Access is denied". It still clicks the coordinates, but why I get this error. I have tried to run this from normal and administer CMD. I am using windows 10. If you can help me please help!
Thanks for advice!

A: I had the same problem using Windows 8.1. I solved making a bat file calling the python script and running the bat file as administrator.
To run the bat file as administrator I made a right click on bat file and run as administrator.

A: I found out another way. You can use two "try/except":
try:
    pyautogui.click(x, y)
except:
    try:
        pyautogui.click(x, y)
    except:
        pass

I don't know why and how, but it works.

A:
The root cause is when you have a mouse options app installed (at least in my case).
I know it from this story: I had a python script that used click (twice). It worked well, but in the meantime, I installed a mouse settings app on my comp. After that I run my script, but got this access denied error. (However, the first click worked, only the second one gave that error). Then I uninstalled this mouse software (almost unusable anyway), and voila, the clicking was again all right.
Hope this helps you as well.


text:
Q: Continuous choropleth map in Leaflet I want to create a continuous choropleth map in Leaflet.js. Specifically, I have a bunch of geographical points that I have data for (a value ranging from 0.0 to 1.0) and I want to create a map where each point on the map has a value interpolated from the nearest points for which data exist.
Is there a simple way to do this in Leaflet.js? I guess I could create a whole bunch of polygons to approximate a continuous map, but that would get heavy quick. Are there any plugins that do this, or is the best solution to write my own code with something like D3?

A: While polygons may not be an ideal solution, they are easy to create with Turf.tin, so it's probably worth checking out. Say you have a GeoJSON object with a bunch of points, and they have a property called size that you would like to average over a TIN and display with with a color ramp. The following code will do that:
var maxAvg = 0
var tin = turf.tin(dots, 'size')
for (var i = 0; i < tin.features.length; i++) {
  var properties  = tin.features[i].properties;
  properties.average = (properties.a+properties.b+properties.c)/3;
  if (properties.average > maxAvg) maxAvg = properties.average;
}

colorRamp = chroma.scale('YlGnBu');
L.geoJson(tin, {style: tinStyle}).addTo(map);

function tinStyle(feature) {
    return {
        fillColor: colorRamp(feature.properties.average/maxAvg),
        weight: 0,
      fillOpacity: 0.7
    };
}

I'm using chroma.js to create the color ramp, but you could also create your own function (as in the Leaflet choropleth example). Here is a fiddle using this technique on some synthetic GeoJSON data:
http://fiddle.jshell.net/nathansnider/rku0pvLL/
This is using 1000 points, and it seems speedy enough. If you increase the dotcount to 10000, it gets noticeably slower, but not entirely unusable. Whether or not it works in your case will probably depend on how many points you have (and of course whether a TIN gives a smooth enough interpolation for your purposes).

A: If I understand your issue correctly Turf.js isolines is what you're looking for.


text:
Q: How to determine which area is clicked in a complex image map? We are given a rather complex image map, like the one linked below. Except that the layout, shapes of each booth are more irregular, and we have lots of image maps to process.

The requirement is that the software is able to detect which booth (the boxes) is being clicked on. Once having identified the booth, we have to fetch its ID and do some processing. So we need a way to map the physical data on the map to its logical counterpart.
Usually, there are two ways I would approach the problem.

*

*Pragmatically determine where the hotspot are - however in this case, there is no consistency in the layout of booths - some are a small rectangle, some are a squares

*Manually figure out the coordinates of each booth and program it into a giant lookup. This is very time consuming, considering the number of booths (the image below is not from the project - it's just a demo). There's an estimate of at least 5000 booths spread across different maps.
Besides the two usual methods of creating hotspots for an image map, what other ways could I use to determine which booth is being clicked?
Platform used is LimeJS, but this problem should be generic enough...

A: You could separate the map into booths using flood-fills, a new color for each region. You want to flood a known "corridor" spot first to eliminate that. 0,0 should work for that on most maps, I'd imagine.
This would create the hotspots you need. To cope with the print inside the boxes messing with the fill, you can just use the far corners of each region to create a rectangle. This assumes the booths are actually rectangular on the map, of course. For L-shaped booths, a little extra work might be necessary.
To get the ID from each booth, you can feed each region(from above) into an OCR, but you'll have to be able to distinguish between the ID numbers and the dimensions, etc.


text:
Q: BASH scipt. how to code if (array=nothing) then echo "no element in array" in bash script in bash script, I define a array:
array=$(awk '{print $4}' /var/log/httpd/sample | uniq -c | cut -d[ -f1)

Now, I want to translate this content to code in bash script:
"if there is NOT any element in array, it means array=nothing, then echo "nothing in array".
help me to do that??? Thanks a lot
*besides, I want to delete access_log's content periodically every 5min (/var/log/httpd/access_log). Please tell me how to do that??*

A: Saying:
array=$(awk '{print $4}' /var/log/httpd/sample | uniq -c | cut -d[ -f1)

does not define an array.  This simply puts the result of the command into the variable array.
If you wanted to define an array, you'd say:
array=( $(awk '{print $4}' /var/log/httpd/sample | uniq -c | cut -d[ -f1) )

You can get the count of the elements in the array by saying echo "${#foo[@]}".
For checking whether the array contains an element or not, you can say:
(( "${#array[@]}" )) || echo "Nothing in array"


text:
Q: How to make a navbar transparent? This is the HTML code for navigation bar using Bootstrap framework.
I want to make it little transparent.
How to do this with CSS? I tried but nothing happend.

        <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
            Toggle navigation

        </button>

HOME

ABOUT US

HEALTH MANAGEMENT

PRE-POST PRAGNANCY

WEIGHT LOSS

CONTACT US

A: Add this to your CSS
.navbar-header {
    background:transparent;
}

A: Just use rgba color.
E.g.:
background-color: rgba(0, 0, 0, 0.5)

A: You didn't post the css. Though, if you want to change the background color of the nav you need to use RGBA color. So, you can make your nav bar little transparent with white background this way -
.navbar-default{
    background-color: rgba(255, 255, 255, 0.7);
}

A: Give your nav an ID so it's easy to select with CSS.
Then just use
#yourNavsID { opacity:0.7; }

Obviously you can change the 0.7 to whatever number suits your needs.
Example fiddle: http://jsfiddle.net/fr2wayy7/


text:
Q: jQuery newsTicker pause on mousehover I had already made a newsTicker in jQuery but need to pause on hover. What I have done so far follows:
a .php file newsticker.php

                    Title Lorem Ipsum 1
                    some text that will be shown here.need to pause the
                                news on mouse hover and showing the news in different                   box

                    Title Lorem Ipsum 2
                    some text that will be shown here.need to pause the
                                news on mouse hover and showing the news in different box

jQuery file common.js
$(document).ready(function() {
    var ticker = function() {
        setTimeout(function(){
            $('#ticker li:first').animate({
                marginTop: '-120px'},
                800,
                function() {
                    $(this).detach().appendTo('ul#ticker').removeAttr('style');
                });
            ticker();
        }, 4000);
    };
    ticker();
});

How can I pause the news and show in different div box like found in here when mouse hovers?
run jsfiddle link here

A: First thing, there is a small bug inside. Then we use small trick.
var ticker = function()
{
    setTimeout(function(){
        $('#ticker li:first:not(.stop)').animate( {marginTop: '-120px'}, 800, function()
        {
           var me = $(this);

           me
            .clone(true)
            .appendTo('ul#ticker')
            .removeAttr('style')

           me.remove();
        });
        ticker();
    }, 4000);
};

ticker();

// simply toggle class on hover
// animation will not run with `li` having this class

$('#ticker li').hover(function() {
    $(this).addClass('stop')
}, function() {
    $(this).removeClass('stop')
});


text:
Q: Changing the value of a React component prop from within the component I am trying to make a modal component which has a button within it that is supposed to close it:
import React, { useState } from "react";
import "./Modal.css";

interface modalProps {
    children?: React.ReactNode;
    width: string;
    height: string;
    screenFlood?: boolean; //Makes the rest of the screen go dark
    openModal: boolean;
}

const Modal = (props: modalProps) => {

    return props.openModal ? (
        <>
            {props.screenFlood &&

}

Modal title

{props.children}

                <button
                    onClick={() => {
                        props.openModal = false;
                    }}
                >
                    Button
                </button>

        </>
    ) : (
        <></>
    );
};

export default Modal;

The modal is opened from an external button here:
const [openModal, setOpenModal] = useState(false);

<Modal
    width="800px"
    height="400px"
    screenFlood={true}
    openModal={openModal}
>

Modal here

</Modal>

How can I make the button inside the modal close the modal (I understand that props are readonly)

A: Add another prop called onClose, and pass it a function to change the value of openModal.
Your modal button becomes:
<button
    onClick={onClose}
>
    Close Modal
</button>

And your parent container becomes:
const [openModal, setOpenModal] = useState(false);
const handleClose = () => setOpenModal(false);

<Modal
    width="800px"
    height="400px"
    screenFlood={true}
    openModal={openModal}
    onClose={handleClose}
>

Modal here

</Modal>

A: I once did a modal similar using functional components. Basically you can pass both the variable and the set function (setOpenModal) function to the modal as props and then use that setOpenmodal inside your modal component to change the state and close itself from within.
Something like this...
// Parent Component
const [openModal, setOpenModal] = useState(false);

<Modal
    width="800px"
    height="400px"
    screenFlood={true}
    openModal={openModal}
    setOpenModal={setOpenModal}
>

Modal here

</Modal>

// Modal Component
const Modal = (props: modalProps) => {
    const { openModal, setOpenModal } = props
    return props.openModal ? (
        <>
            {props.screenFlood &&

}

Modal title

{props.children}

                <button
                    onClick={() => {
                       setOpenModal(false);
                    }}
                >
                    Button
                </button>

        </>
    ) : (
        <></>
    );
};

export default Modal;

A: Created new prop called closeModal with the type of the setter from use state:
interface modalProps {
    children?: React.ReactNode;
    width: string;
    height: string;
    screenFlood?: boolean; //Makes the rest of the screen go dark
    closeModal: React.Dispatch<React.SetStateAction<boolean>>;
}

In the parent container:
const [openModal, setOpenModal] = useState(false);

<button onClick={() => setOpenModal(true)}>
    Click me
</button>

{openModal && (
    <Modal
        width="800px"
        height="400px"
        screenFlood={true}
        closeModal={setOpenModal}
    >

Modal

    </Modal>
)}

By moving the logic to open the modal outside into the parent, I could have the Modal and Parent share the state from the setter.


text:
Q: Enable Python code only for unittests? Let's say I have the following function:
def f():
    if TESTING:
        # Run expensive sanity check code
    ...

What is the correct way to run the TESTING code block only if we are running a unittest?
[edit: Is there some "global" variable I can access to find out if unittests are on?]

A: Generally, I'd suggest not doing this.  Your production-code really shouldn't realize that the unit-tests exist.  One reason for this, is that you could have code in your if TESTING block that makes the tests pass (accidentally), and since production runs of your code won't run these bits, could leave you exposed to failure in production even when your tests pass.
However, if you insist of doing this, there are two potential ways (that I can think of) this can be done.
First of, you could use a module level TESTING var that you set in your test case to True.  For example:
Production Code:
TESTING = False    # This is false until overridden in tests

def foo():
    if TESTING:
        print "expensive stuff..."

Unit-Test Code:
import production

def test_foo():
    production.TESTING = True
    production.foo()    # Prints "expensive stuff..."

The second way is to use python's builtin assert keyword.  When python is run with -O, the interpreter will strip (or ignore) all assert statements in your code, allowing you to sprinkle these expensive gems throughout and know they will not be run if it is executed in optimized mode.  Just be sure to run your tests without the -O flag.
Example (Production Code):
def expensive_checks():
    print "expensive stuff..."
    return True

def foo():
    print "normal, speedy stuff."
    assert expensive_checks()

foo()

Output (run with python mycode.py)
normal, speedy stuff.
expensive stuff...

Output (run with python -O mycode.py)
normal, speedy stuff.

One word of caution about the assert statements... if the assert statement does not evaluate to a true value, an AssertionError will be raised.


text:
Q: saveAction stores empty object Whenever I fill a form and click "Save", magento doesn't get the form data. It just saves an empty object in the database. I can't figure out why.
Here's my form and file structure:
Form
File Structure
Controller:
<?php
class Vkusen_Kartof_Adminhtml_KartofController extends Mage_Adminhtml_Controller_Action
{
....
 public function saveAction()
{
    $data = $this->getRequest()->getPost();
    var_dump($data);
    >>>> Dumps : array(1) { ["form_key"]=> string(16) "N1sBdZb21Nb7dYHT" }

   /* >>>>  Sends me to the save page which is blank, saving an empty row in DB:

    if ( $data = $this->getRequest()->getPost() ) {
        $this->_getSession()->setFormData($data);
        $model = Mage::getModel('vkusen_kartof/kartof');
        $id = $this->getRequest()->getParam('id');

        try {
            if ($id) {
                $model->load($id);
            }
            $model->addData($data);
            $model->save();

            $this->_getSession()->addSuccess(
                $this->__('Kartof was successfully saved')
            );
            $this->_getSession()->setFormData(false);

            if ( $this->getRequest()->getParam('back') ) {
                $params = array('id' => $model->getId());
                $this->_redirect('*/*/index');
            }
        } catch (Exception $e) {
            $this->_getSession()->addError($e->getMessage());
            if ($model && $model->getId()) {
                $this->_redirect('*/*/edit', array(
                    'id' => $model->getId())
                );
            } else {
                $this->_redirect('*/*/new');
            }
        }
        return;
    }
    $this->_getSession()->addError($this->__('No data found to save'));
    $this->_redirect('*/*');

*/
      }
    }
kartof.xml (the layout):
<?xml version="1.0" encoding="UTF-8" ?>
<layout>
<adminhtml_kartof_index>
    <reference name="content">
        <block type="vkusen_kartof/adminhtml_kartof" name="vkusen.kartof.block"  />
    </reference>
</adminhtml_kartof_index>

<adminhtml_kartof_edit>
    <reference name="content">
        <block type="vkusen_kartof/adminhtml_kartof_edit" name="vkusen.kartof.form"  />
    </reference>
    <reference name="left">
        <block type="vkusen_kartof/adminhtml_kartof_edit_tabs" name="kartof_info_tabs" />
    </reference>
</adminhtml_kartof_edit>
</layout>

Edit.php:
class Vkusen_Kartof_Block_Adminhtml_Kartof_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
protected function _construct()
{
    parent::_construct();
                                            // vkusen_kartof/adminhtml_kartof_edit_form
    $this->_objectId = 'id';
    $this->_blockGroup = 'vkusen_kartof';
    $this->_controller = 'adminhtml_kartof';
    $this->_mode = 'edit';
}

protected function _prepareLayout()
{
    parent::_prepareLayout();

    $this->_updateButton('save', 'label',
        $this->__('Save Kartof'));

    $this->_updateButton('delete', 'label',
        $this->__('OBLITERATE Kartof'));

    $this->_addButton('save and continue', array(
        'label' => $this->__('Save And Continue Edit'),
        'onclick' => 'saveAndContinueEdit()',
        'class' => 'save',
    ), -100);

    $this->_formScripts[] = "
        function saveAndContinueEdit() {
              editForm_submit($('edit_form').action+'back/edit'
        }
    ";
    return $this;
}

public function getHeaderText()
{
    $model = Mage::registry('current_kartof');
    if ($model && $model->getId()) {
        return $this->__('Edit Kartof (%s)',
            $this->__($model->getTitle())
        );
    } else {
        return $this->__('New kartof');
    }
}
}

Tabs.php:
class Vkusen_Kartof_Block_Adminhtml_Kartof_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
    parent::__construct();
    $this->setId('kartof_info_tabs');
    $this->setDestElementId('edit_form');
    $this->setTitle($this->__('Kartof Information'));
}

protected function _beforeToHtml()
{
    $this->parent = parent::_prepareLayout();
    $this->addTab('general', array(
        'label'     => $this->__('Change details'),
           'content'   => $this->getLayout()->createBlock('vkusen_kartof/adminhtml_kartof_edit_tab_general')->toHtml(),
        'active'    => true,
    ));

    $this->parent = parent::_prepareLayout();
    $this->addTab('gggg', array(
        'label'     => $this->__('Change something'),
        'active'    => false,
    ));

    return parent::_beforeToHtml();
}
}

Form.php
class Vkusen_Kartof_Block_Adminhtml_Kartof_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
    if (Mage::registry('current_kartof'))
    {
        $data = Mage::registry('current_kartof')->getData();
    } else {
        $data = array();
    }

    $form = new Varien_Data_Form(array(
            'id' => 'edit_form',
            'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
            'method' => 'post',
            'enctype' => 'multipart/form-data'
        )
    );

    $form->setUseContainer(true);
    $this->setForm($form);
    $form->setValues($data);

    return parent::_prepareForm();
}
}

General.php:
class Vkusen_Kartof_Block_Adminhtml_Kartof_Edit_Tab_General extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
   if (Mage::registry('current_kartof'))
    {
        $data = Mage::registry('current_kartof')->getData();
    } else {
        $data = array();
    }

    $form = new Varien_Data_Form();
    $this->setForm($form);
    $fieldset = $form->addFieldset('general_form', array(
        'legend' => $this->__('General Setup')
    ));

    $fieldset->addField('title', 'text', array(
        'label' => $this->__('Title'),
        'class' => 'required entry',
        'required' => true,
        'name' => 'the_title',
    ));

    $fieldset->addField('description', 'text', array(
        'label' => $this->__('Description'),
        'class' => 'required entry',
        'required' => true,
        'name' => 'the_description',
    ));

    // Pass info from the entity:
         $form->setValues($data);

    return parent::_prepareForm();
}
}

And the config.xml(just in case):
<?xml version="1.0" encoding="UTF-8" ?>
<config>
<modules>
    <Vkusen_Kartof>
        <version>0.1.0</version>
    </Vkusen_Kartof>
</modules>

<global>
    <blocks>
        <vkusen_kartof>
            <class>Vkusen_Kartof_Block</class>
        </vkusen_kartof>
    </blocks>
    <models>
        <vkusen_kartof>
            <class>Vkusen_Kartof_Model</class>
            <resourceModel>vkusen_kartof_resource</resourceModel>
        </vkusen_kartof>
        <vkusen_kartof_resource>
            <class>Vkusen_Kartof_Model_Resource</class>
            <entities>
                <kartof>

kartof_table

                </kartof>
            </entities>
        </vkusen_kartof_resource>
    </models>

    <helpers>
        <vkusen_kartof>
            <class>Vkusen_Kartof_Helper</class>
        </vkusen_kartof>
    </helpers>

    <resources>
        <vkusen_kartof_setup>
            <setup>
                <module>Vkusen_Kartof</module>
            </setup>
        </vkusen_kartof_setup>
    </resources>
</global>

<frontend>
    <routers>
        <vkusen_kartof>
            <use>standard</use>
            <args>
                <module>Vkusen_Kartof</module>
                <frontName>vkusen</frontName>
            </args>
        </vkusen_kartof>
    </routers>
</frontend>

<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <vkusen_kartof after="Mage_Adminhtml">Vkusen_Kartof_Adminhtml</vkusen_kartof>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

<adminhtml>
    <layout>
        <updates>
            <vkusen_kartof>
                <file>vkusen/kartof.xml</file>
            </vkusen_kartof>
        </updates>
    </layout>
</adminhtml>
</config>

P.S. Sorry for the long post but I guess it's inevitable.
EDIT:
 http: //i.imgur.com/6N73OIe.png
there's a "space" after "http:"

A: I found out what the problem was. In my form the fields' names weren't the same as the table columns. If I have a column "title", then my field should be:
$fieldset->addField('title', 'text', array(
        'label' => $this->__('Title'),
        'class' => 'required entry',
        'required' => true,
        'name' => 'title',     // MUST match the table column!!!
    ));


text:
Q: Validation of Swift BIC if it is SEPA reachable I would like to know if there is any existing library other than SWIFT directory(As they are not free) , which will validate Swift BIC is sepa reachable.

A: I have used a free sample library for both SWIFT MT and MX messages, as well as SEPA messages and it was good enough. You can check it out here. They also have a nice documentation.


text:
Q: Ble Beacon Gpio read/write I'm not a ble guru, I worked on some modules to expose some simple service with pairing and bla bla :9
One of our customer ask me if it possible to control mcu gpio, with a beacon service running. For what I know beacon standard is only a lighthouse to check the proximity (streaming simple packet uuid, signal strength etc etc), and the only way to do something like this is to expose a new service running concurrently with beacon ( in practice send multi type of packets). I don't want pairing (beacon<->device app) and don't worry about race condition, if multi devices set/reset a gpio, it's not my business.
I found something similar https://community.estimote.com/hc/en-us/articles/217429867-What-is-GPIO-How-to-set-it-up-, what you think about?
There are libraries or eddystone's extensions to do that? Some project on github?
We prefer to work with Nordic ble module, but if you know solution based on other mcu, you are welcome.
Thanks for your help

A: Standard beacons (iBeacon, Eddystone, AltBeacon) are transmit only devices.  They simply send out advertisements at a fixed rate with a unique identifier.  Some manufacturers expose proprietary configuration interfaces as read-write Bluetooth LE GATT Services.  But there is no standard GATT Service that does this, and the manufacturer-specific schemes are designed specifically to set beacon identifiers and other operating parameters.
I don't think there are beacon-specific libraries or extensions that will help with this, beyond standard Bluetooth LE SDKs for iOS and Android.  In order to accomplish this goal with a Nordic BLE module you would need to build your own custom system:

*

*Write custom Nordic firmware (that sits alongside beacon transmission firmware) that exposes a new Bluetooth LE GATT Service.  The service would expose a writable GATT Attribute that would control the GPIO pin.

*Write custom mobile app code that connects to this GATT Service (CoreBluetooth on iOS and android.bluetooth on Android), and writes to the GATT attribute to control the pin.
One thing you must be careful of is that connecting to to a GATT Service will typically stop a Bluetooth Peripheral from advertising (meaning it won't transmit as a beacon).  So you may wish to drop the connection quickly to prevent mobile devices or other Bluetooth Centrals from stoping the beacon transmissions.


text:
Q: PHP in Edit Post link What is the best way to add php to the edit link?
For example: insert <?php echo of_get_option('dappo_actionbtncolor', 'dappblue' ); ?> into the span tag of <?php edit_post_link( __( 'Edit this', 'mytheme' ), '', '' ); ?>

A: The easiest way might be to use get_edit_post_link() (Codex ref), which returns just the link, allowing you to use it however you need, according to your purposes.


text:
Q: Running out of memory, or running out of disk space? I'm running a database loading process (osm2pgsql) which is failing:
Processing: Node(17404k 148.8k/s) Way(1351k 6.38k/s) Relation(9520 29.94/s)way_done failed: ERROR:  could not extend file "base/140667/152463": No space left on device
HINT:  Check free disk space.
(7)
Arguments were: 187226311,

At the start of the import, mem reports:
             total       used       free     shared    buffers     cached
Mem:           31G        29G       2.4G         0B       178M        24G
-/+ buffers/cache:       4.5G        26G
Swap:           0B         0B         0B

Shortly before the end:
             total       used       free     shared    buffers     cached
Mem:           31G        31G       227M         0B       178M        26G
-/+ buffers/cache:       4.8G        26G
Swap:           0B         0B         0B

Meanwhile, df at the start:
Filesystem     1K-blocks      Used Available Use% Mounted on
/dev/vda1       10309828   7879412   1997036  80% /
udev            16470572        12  16470560   1% /dev
tmpfs            6590080       260   6589820   1% /run
none                5120         0      5120   0% /run/lock
none            16475196         0  16475196   0% /run/shm
none              102400         0    102400   0% /run/user
/dev/vdb       247709760 105978300 129148548  46% /mnt

And from about 3/4 of the way through the process. Use sits at 100%.
Filesystem     1K-blocks      Used Available Use% Mounted on
/dev/vda1       10309828   9854348     22100 100% /
udev            16470572        12  16470560   1% /dev
tmpfs            6590080       260   6589820   1% /run
none                5120         0      5120   0% /run/lock
none            16475196         0  16475196   0% /run/shm
none              102400         0    102400   0% /run/user
/dev/vdb       247709760 105978300 129148548  46% /mnt

I'm unable to identify any actual files on disk that are filling up /dev/vda1:
du -h -d 3 / 2>/dev/null | grep -v ^0 > /tmp/o2p1.txt
[start import]
du -h -d 3 / 2>/dev/null | grep -v ^0 > /tmp/o2p2.txt

diff /tmp/o2p1.txt /tmp/o2p2.txt

That reveals nothing.
What's going on?

A: Ok, it was simple. The Postgres database was on /dev/vda1 and was getting huge. It didn't show up in the du command because I wasn't running that as root.
I guess after the disk fills up, Postgres stops saving to disk and keeps it all in memory - until memory runs out as well.


text:
Q: Mongodb subdocument array lookup to subdocument array I am new to mongo. i have following collections.
Document:
{
    "_id" : ObjectId("5eb256c9e519051af2eeb5f7"),
    "name" : "Income",
    "types" : [
        {
            "typeId" : ObjectId("5eb257a3e519051af2eeb624"),
            "name" : "W2",
            "tenantId" : null,
            "message" : "",
            "createdOn" : null,
            "createdBy" : 1.0,
            "isActive" : true
        },
        {
            "typeId" : ObjectId("5eb257a3e519051af2eeb639"),
            "name" : "Salary Slip",
            "tenantId" : 1,
            "message" : "",
            "createdOn" : null,
            "createdBy" : 1.0,
            "isActive" : true
        }
    ]
}

Request:
{
    "_id" : ObjectId("5eb25d1fe519051af2eeb72d"),
    "employeeId" : 1234,
    "customerId" : 1275,
    "tenantId" : 1,
    "createdOn" : ISODate("2013-10-01T00:00:00.000Z"),
    "loanApplicationId" : 1.0,
    "status" : "requested",
    "message" : "Dear John, please send following documents.",
    "documents" : [
        {
            "typeId" : null,
            "displayName" : "W2 2016",
            "message" : "please upload salary slip for year 2016",
            "status" : "requested",
            "files" : []
        },
        {
            "typeId" : ObjectId("5eb257a3e519051af2eeb624"),
            "displayName" : "W2 2016",
            "message" : "please upload salary slip for year 2016",
            "status" : "requested",
            "files" : []
        }
    ]
}

typeId in the document collection is the id for the document type where typeId in the request is the foreign field that can be nullable as well. how can i get the below output.
{
    "_id" : ObjectId("5eb25d1fe519051af2eeb72d"),
    "employeeId" : 1234,
    "customerId" : 1275,
    "tenantId" : 1,
    "createdOn" : ISODate("2013-10-01T00:00:00.000Z"),
    "loanApplicationId" : 1.0,
    "status" : "requested",
    "message" : "Dear John, please send following documents.",
    "documents" : [
        {
            "typeId" : null,
            "typeInfo": null,
            "displayName" : "W2 2016",
            "message" : "please upload salary slip for year 2016",
            "status" : "requested",
            "files" : []
        },
        {
            "typeId" : ObjectId("5eb257a3e519051af2eeb624"),
            "typeInfo": {
            "name": "W2"
            },
            "displayName" : "W2 2016",
            "message" : "please upload salary slip for year 2016",
            "status" : "requested",
            "files" : []
        }
    ]
}

A: I loved to solve this problem, it was a tricky, long and complex. Well, I am also a beginner, so I used all the basic concepts. You can try the below code:
db.request.aggregate([
  {
    $unwind: "$documents"
  },
  {
    $lookup: {
      from: "document",
      let: {
        req_typeId: "$documents.typeId"
      },
      pipeline: [
        {
          $unwind: "$types"
        },
        {
          $match: {
            $expr: {
              $eq: [
                "$$req_typeId",
                "$types.typeId"
              ]
            }
          }
        }
      ],
      as: "documents.example"
    }
  },
  {
    $unwind: {
      path: "$documents.example",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: "$_id",
      employeeId: {
        $first: "$employeeId"
      },
      customerId: {
        $first: "$customerId"
      },
      tenantId: {
        $first: "$tenantId"
      },
      createdOn: {
        $first: "$createdOn"
      },
      loanApplicationId: {
        $first: "$loanApplicationId"
      },
      status: {
        $first: "$status"
      },
      message: {
        $first: "$message"
      },
      documents: {
        $push: {
          typeId: "$documents.typeId",
          typeInfo: {
            $cond: [
              {
                $eq: [
                  "$documents.example",
                  undefined
                ]
              },
              null,
              {
                name: "$documents.example.types.name"
              }
            ]
          },
          displayName: "$documents.displayName",
          message: "$documents.message",
          status: "$documents.status",
          files: "$documents.files"
        }
      }
    }
  }
])

If you get stuck at any point, I have provided MongoPlayGround Link, here you can execute the query stage by stage of the aggregation pipeline, else reach out for me. It's a long query, it will take time to understand. At the same time, I will be trying to shrink it. If I get anything, I will update it here.
Edits:
I have shortened the query by almost 50% (in terms of lines). Here is my previous approach's link

A: With the default $lookup syntax, you can join with atomic / array values and store the result inside tmp variable. In the next step, we iterate over documents field and find within tmp variable items with the same typeId.
Note: If you need more fields than name, just change to {typeInfo: "$$this"}.
Try this one:
db.Requests.aggregate([
  {
    $lookup: {
      from: "Documents",
      localField: "documents.typeId",
      foreignField: "types.typeId",
      as: "tmp"
    }
  },
  {
    $addFields: {
      tmp: "$$REMOVE",
      documents: {
        $map: {
          input: "$documents",
          as: "doc",
          in: {
            $mergeObjects: [
              "$$doc",
              {
                $reduce: {
                  input: {
                    $reduce: {
                      input: "$tmp.types",
                      initialValue: [],
                      in: {
                        $concatArrays: [
                          "$$value",
                          "$$this"
                        ]
                      }
                    }
                  },
                  initialValue: {},
                  in: {
                    $cond: [
                      {
                        $eq: [
                          "$$this.typeId",
                          "$$doc.typeId"
                        ]
                      },
                      {
                        typeInfo: {
                          name: "$$this.name"
                        }
                      },
                      "$$value"
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

MongoPlayground


text:
Q: Application takes more time to load in extjs I have three different app with JAVA code (business logic), i tested my application and took production build using sencha cmd. Its work fine in local. When i moved my same application to production server it takes 39 sec to load app (minified version of js). I need some guidance in taking build.

A: First you have to identify the code where it is taking time like if some unnecessary requests are sent to server or some other code is executing which is not needed while loading the app.


text:
Q: How to clone source code of Android marshallow I'm trying to clone source code of Android Marshallow
from this link.
In the section
Initializing a Repo client

Third point
Run repo init to bring down the latest version of Repo with all its most recent bug fixes. You must specify a URL for the manifest, which specifies where the various repositories included in the Android source will be placed within your working directory.
$ repo init -u https://android.googlesource.com/platform/manifest

So I provide this url for manifest
$ repo init -uhttps://android.googlesource.com/platform/manifest/+/refs/heads/android-6.0.1_r9

Then I got this
gpg: keyring `/home/shyam/.repoconfig/gnupg/secring.gpg' created
gpg: keyring `/home/shyam/.repoconfig/gnupg/pubring.gpg' created
gpg: /home/shyam/.repoconfig/gnupg/trustdb.gpg: trustdb created
gpg: key 920F5C65: public key "Repo Maintainer <repo@android.kernel.org>" imported
gpg: key 692B382C: public key "Conley Owens <cco3@android.com>" imported
gpg: Total number processed: 2
gpg:               imported: 2  (RSA: 1)

Get https://gerrit.googlesource.com/git-repo/clone.bundle
Get https://gerrit.googlesource.com/git-repo
remote: Finding sources: 100% (15/15)
remote: Total 15 (delta 1), reused 15 (delta 1)
Unpacking objects: 100% (15/15), done.
From https://gerrit.googlesource.com/git-repo
   79fba68..8b39fb4  master     -> origin/master
Get https://android.googlesource.com/platform/manifest/+/refs/heads/android-6.0.1_r9
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (22) The requested URL returned error: 404 Not Found
Server does not provide clone.bundle; ignoring.
fatal: remote error: Git repository not found
fatal: remote error: Git repository not found


text:
Q: Geofence PendingIntent is always getting as null I have implemented geofencing in the application. But the issue is whenever I open the application the geofence is added again. Thus it immediately results in triggering an entry alert if we are within a geofencing area.
Current implementation - workflow:

*

*User opens the App

*A service called GeoFenceMakerService is started from the main activity.

*GeoFenceMakerService invoke an API call and fetches the details of the places (Lat, Long, Place Id, Place Name, Radius, etc) from the server. There can be one or more places.

*The place details (API result) will be saved to the local database.

*If there are 1 or more places, then it builds the geofence object for each place (initializeGeoFence).

*Build the geofencing request and create pending intent. This will be passed to the Geofencing client to add the geofence. (geofencingClient.addGeofences(getGeofencingRequest(), createGeoFencePendingIntent()))

*Stop the GeoFenceMakerService after adding the geofences.

Issue:
The createGeoFencePendingIntent() is always creating new Pending intent and may trigger an entry alert if we are within a geofencing area whenever we open the application.
Similar solution found from stack overflow: Was to implement a check using Shared preferences for pending intent. You can see the full solution from here. But am not satisfied with this because, "it is better to check if the pending intent exists instead of writing in the sharedpreferences that we have added the geofences, because when we reboot the phone or change the location accuracy, they are removed and the pending intent does not exist anymore, but the sharedpreferences would not be updated" - (One already mentioned there as comment for the solution mentioned).
Current solution required:
Need to check whether the Geofence is already added or not and add geofence only if none exists.
I am attaching the entire GeoFenceMakerService code for reference.
package com.****.*****.services;

import android.Manifest;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.****.****.api.Api;
import com.****.****.api.ApiMethods;
import com.****.****.models.Place;
import com.****.****.models.response.PlacesListResponse;
import com.****.****.receiver.GeofenceBroadcastReceiver;
import com.****.****.utils.DatabaseManager;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GeoFenceMakerService extends Service {

    public static final String TAG = "GeoFenceMakerService";
    private ArrayList<Place> places = null;
    private GeofencingClient geofencingClient = null;
    private ArrayList<Geofence> geofenceList = null;
    private PendingIntent geoFencePendingIntent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "GeoFenceMakerService Created");
        geofencingClient = LocationServices.getGeofencingClient(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //handleStart(intent, startId);
        Log.d(TAG, "Inside onStartCommand");
        getPlacesList();
        return START_NOT_STICKY;
    }

    private void getPlacesList() {
        Log.i(TAG, "getPlacesList: ");
        ApiMethods apiMethods;
        Call<PlacesListResponse> listResponseCall;
        apiMethods = Api.getInstance(this);
        listResponseCall = apiMethods.getAllPlacesList();
        Log.i(TAG, "Getting places list from API");
        listResponseCall.enqueue(new Callback<PlacesListResponse>() {
            @Override
            public void onResponse(Call<PlacesListResponse> call, Response<PlacesListResponse> response) {
                if (response.code() == Api.STATUS_200) {
                    handlePlacesList(response.body());
                } else {
                    Log.e(TAG, "Get places list api failed with code: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<PlacesListResponse> call, Throwable t) {
                Log.e(TAG, "Get places list api failed" + t.getLocalizedMessage());
            }
        });
    }

    private void handlePlacesList(PlacesListResponse placesListResponse) {
        Log.i(TAG, "handlePlacesList: ");
        DatabaseManager databaseManager = new DatabaseManager(this);

        if (placesListResponse != null) {

            Log.i(TAG, "Got places list response");
            places = placesListResponse.getPlaces();
            databaseManager.savePlacesToDatabase(places);
            if (!(places.size() == 0)) {
                initializeGeoFence();
                addGeoFence2();
            }
           /* initializeGeoFence();
            addGeoFence2();*/
        } else {

            Log.e(TAG, "Places list response is null");

        }
    }

    private void initializeGeoFence() {
        // Toast.makeText(this, "initializing geo fence", Toast.LENGTH_LONG).show();
        Log.i(TAG, "initializing geo fence");
        Geofence geofence;
        geofenceList = new ArrayList<>();
        for (Place place : places) {
            Log.i(TAG, "Adding geofence at " + place.getLatitude() + ", " + place.getLongitude());
            // @TODO Fetch and set the Geofence Radius dynamically
            geofence = new Geofence.Builder()
                    // Set the request ID of the geofence. This is a string to identify this
                    // geofence.
                    .setRequestId(place.getPlaceId() + "")
                    .setCircularRegion(
                            place.getLatitude(),
                            place.getLongitude(),
                            500f)
                    .setExpirationDuration(60 * 60 * 1000)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            geofenceList.add(geofence);
        }
    }

    private void addGeoFence2() {
        Log.i(TAG, "addGeoFence2: ");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Make sure permission is granted before starting the service. NOTE: Requesting permission from Service is not allowed.
            return;
        }
        geofencingClient.addGeofences(getGeofencingRequest(), createGeoFencePendingIntent())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.i(TAG, "Geo fence added");
                        // Toast.makeText(HomeActivity.this, "Geo fence added", Toast.LENGTH_LONG).show();
                        GeoFenceMakerService.this.stopSelf();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "Geo fence add failed. ");
                        e.printStackTrace();
                        // Toast.makeText(HomeActivity.this, "Geo fence add failed", Toast.LENGTH_LONG).show();
                        GeoFenceMakerService.this.stopSelf();
                    }
                });
    }

    private GeofencingRequest getGeofencingRequest() {

        // Toast.makeText(this, "getGeofencingRequest", Toast.LENGTH_LONG).show();
        Log.i(TAG, "getGeofencingRequest");
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofences(geofenceList);
        return builder.build();
    }

    private PendingIntent createGeoFencePendingIntent() {
        Intent intent;

        Log.d(TAG, "createGeoFencePendingIntent");

        if (geoFencePendingIntent == null) {
            Log.i(TAG, "GeoFence pending intent is null. Creating new instance");

            intent = new Intent(this, GeofenceBroadcastReceiver.class);
            // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
            // calling addGeofences() and removeGeofences().
            geoFencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.
                    FLAG_UPDATE_CURRENT);

        }

        return geoFencePendingIntent;
    }

}

A:
An Intent sent from Location Services can trigger various actions in
  your app, but you should not have it start an activity or fragment,
  because components should only become visible in response to a user
  action. In many cases, a BroadcastReceiver is a good way to handle a
  geofence transition. A BroadcastReceiver gets updates when an event
  occurs, such as a transition into or out of a geofence, and can start
  long-running background work.

check here
private PendingIntent getGeofencePendingIntent() {
    if (geofencePendingIntent != null) {
        return geofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);

    geofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return geofencePendingIntent;
}


text:
Q: Recursive `setTimeout` doesn't engage in expected way I have a range input field with a numeric value which changes when I drag:

When I drag all the way to the right, the max value of the input increases. Then, when I release (onMouseUp or onTouchEnd), the max value decreases so that I can drag further and continue increasing max by dragging:

When I drag all the way to the left, the min value of the input decreases. Then, when I release (onMouseUp or onTouchEnd), the min value increases so that I can drag further and continue decreasing min by dragging:

I should always have a range of 99. For example, if I have increased the max value to 530, the min value will be 431.
PROBLEM:
I have two recursive setTimeouts set for the min and max values changing.
When the user first drags all the way to either side, the number should slowly change. If they hold it for 2 seconds, the number should increase more quickly. Relevant code:
// After arbitrary period, increase the rate at which the max value increments
this.fasterChangeStake = setTimeout(() => {
  this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
}, 2000);

This works the first time. But subsequent times, it latches onto the faster timeout first:

This is despite my clearing of timeouts when the drag ends:
clearTimeout(this.increaseStakeLimits);
clearTimeout(this.decreaseStakeLimits);
clearTimeout(this.timer);

Why is the first (slower) timeout not engaging?
Codepen: https://codepen.io/alanbuchanan/pen/NgjKMa?editors=0010
JS:
const {observable, action} = mobx
const {observer} = mobxReact
const {Component} = React

@observer
class InputRange extends Component {
  constructor() {
    super();
    this.INITIAL_STAKE_CHANGE_TIMEOUT = 200;
    this.FAST_STAKE_CHANGE_TIMEOUT = 20;
    this.SNAP_PERCENT = 10;
    this.increaseStakeLimits = this.increaseStakeLimits.bind(this);
    this.decreaseStakeLimits = this.decreaseStakeLimits.bind(this);
  }

  @observable min = 0;
  @observable max = 99;
  @observable stakeChangeTimeout = this.INITIAL_STAKE_CHANGE_TIMEOUT;
  @observable isIncreasing = false;
  @observable isDecreasing = false;
  @observable stake = 0;
  @action updateStake = (amount) => {
    if (amount > -1) {
      this.stake = amount
    }
  };

  increaseStakeLimits() {
    const { updateStake } = this;

    this.max = this.max += 1;
    this.min = this.max - 99
    updateStake(this.max);

    // After arbitrary period, increase the rate at which the max value increments
    this.fasterChangeStake = setTimeout(() => {
      this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
    }, 2000);

    // Recursive call, like setInterval
    this.timer = setTimeout(this.increaseStakeLimits, this.stakeChangeTimeout);
    this.isIncreasing = true;
  }

  decreaseStakeLimits() {
    console.warn('this.stake:', this.stake)
    const { stake } = this
    const { updateStake } = this;

    this.min = this.min -= 1;
    this.max = this.min + 99
    updateStake(this.min);

    // After arbitrary period, increase the rate at which the max value increments
    this.fasterChangeStake = setTimeout(() => {
      this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
    }, 2000);

    // Recursive call, like setInterval
    this.timer = setTimeout(this.decreaseStakeLimits, this.stakeChangeTimeout);
    this.isDecreasing = true;

  }

  handleStakeChange = e => {
    clearTimeout(this.increaseStakeLimits);
    clearTimeout(this.decreaseStakeLimits);
    clearTimeout(this.timer);

    const { updateStake } = this;
    const { stake } = this;

    const val = Number(e.target.value)

    // User has scrolled all the way to the right
    if (val >= this.max) {
      console.warn("scrolled to right")
      this.increaseStakeLimits();

    // User has scrolled all the way to the left
    } else if (val <= this.min) {
      console.warn("scrolled to left")
      if (val > -1) {
        this.decreaseStakeLimits();
      }
    } else {
      updateStake(val);
    }
  };

  handleRelease = () => {
    console.warn("RANGE:", this.max - this.min)
    console.warn("released");
    clearTimeout(this.fasterChangeStake);
    clearTimeout(this.timer);
    // Reset the timeout value to the initial one
    this.stakeChangeTimeout = this.INITIAL_STAKE_CHANGE_TIMEOUT;
    this.SNAP_PERCENT = 10
    const snapAmount = this.SNAP_PERCENT
    if (this.isIncreasing) {
      this.max += snapAmount
    }

    if(this.isDecreasing && this.min > 0) {
      this.min -= snapAmount
    }

    this.isIncreasing = false;
    this.isDecreasing = false;
  };

  render() {
    const { stake } = this;

    const style = {
      backgroundSize:
        (stake - this.min) * 100 / (this.max - this.min) + "% 100%"
    };

    return (

{this.stake}

          <input
            id="betRangeId"
            type="range"
            min={this.min}
            max={this.max}
            step="1"
            ref={input => {
              this.textInput = input;
            }}
            value={this.stake}
            onChange={this.handleStakeChange}
            onTouchEnd={this.handleRelease}
            onMouseUp={this.handleRelease}
            style={style}
          />

    );
  }
}

ReactDOM.render(<InputRange />, document.getElementById('root'))

A: That's a really clever UI!
increaseStakeLimits() fires continuously the whole time the user holds the slider to the far right, so you're continually setting new setTimeouts to change this.stakeChangeTimeout to the shorter interval after two seconds (and continually setting new values for this.fasterChangeStake).  These continue to fire even after handleRelease() tries to reset the interval to the longer value, which forces it back into fast mode until all of them have fired (the clearTimeout in handleRelease() only catches one of them.)
You can fix this by only setting that timeout once:
if (!this.fasterChangeStake) {
  this.fasterChangeStake = setTimeout(() => {
    this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT;
    this.fasterChangeStake = false; // <-- also do this in handleRelease() after clearing the timeout
  }, 2000);
}

https://codepen.io/anon/pen/OgmMNq?editors=0010


text:
Q: Gradle copy file task fails to copy to mapped network drive via Jenkins I am using Jenkins and running Gradle tasks to build a jar, executable and a setup.exe file. One of my gradle tasks is to copy the built setup.exe file to  mapped network drive on the agent in runs on.
I am trying to copy the setup file to a folder on the mapped drive called 2.x.
I get the error:
"Cannot convert URL 'z:/Developers/Projects/builds/v2.x/' to a file."
task copySetup(type: Copy) {
from file("${projectDir}/Setup.exe")
into file ("z:/Developers/Projects/builds/v2.x")
}

If I run the task myself in the workspace then it works. Only fails when Jenkins runs it. I use a Gradle wrapper so it shouldn't be a Gradle version issue I think.

A: So I got my answer from this post by ForcePush: Map a network drive to be used by a service
Even though Jenkins runs as the user account I used to map the network drive, the service does not see any mapped network drives. The answer by ForcePush solves this problem.


text:
Q: Using objects to insert variable array into nested table I have a series of tables and objects I have defined.  I have an object nested table that I am trying to insert values into.  The values are in the form of a variable array but I don't know how to insert them.  my tables and code are as follows.
Table  wu.classes
crn number(5)
department varchar2(8)
title carchar2(25)

Table wu.students
student_id char(11)
name varchar2(10)
dept varchar2(8)
advisor varchar(10)

classes wu.classes_va

wu.classes_va varray(5) of number (5)

create type classes_ty as object(crn varchar2(5),department varchar2(8), coursetitle varchar2(25)

create table classes_ot of classes_ty;

insert into classes_ot select crn,department,title from wu.classes;

create or replace type classes_ref_ty as table of ref classes_ty;

create table student_plus(student# varchar2(11),student_name varchar2(10),major varchar2(8), advisor (10), enrolled classes_ref_ty) nested table enrolled store as classes_ref_ty_tab;

Problem here (I need to loop through to fill the table but I just need to know how to do it for one values and i can figure the rest out):
begin
insert into student_plus values('700-123-948','Hooker','CS','VanScoy',classes_ref_ty();

insert into table(select enrolled from student_plus where student#='700-123-948')
select ref(c) from classes_ot c where ???
end;
/

I don't know how to access the variable array and use it with the classes_ref_ty.


text:
Q: Is there a 'getZoomForResolution' in OpenLayers 3? OpenLayers 2 used to have a getZoomForResolution method that would give you the zoom level (or closest zoom level) of a given resolution.
I don't see any such method in ol3, for the ol.View object that is.  Is there a way to achieve this with what ol.view currently have ?

A: This will give the next closest integer zoom for a give resolution:
function zoomForResolution(resolution) {
    var zoom = 0;
    var r = 156543.03390625; // resolution for zoom 0
    while (resolution < r) {
        r /= 2;
        zoom++;
        if (resolution > r) {
            return zoom;
        }
    }
    return zoom; // resolution was greater than 156543.03390625 so return 0
}

zoomForResolution(40); // 12

My brother suggested:
var zoom = Math.ceil( (Math.log(resolution) - Math.log(156543.03390625) ) / Math.log(0.5))

refining the logarithmic solution for browsers with Math.log2()
var zoom = Math.log2(156543.03390625) - Math.log2(resolution);

and for IE which does not have log2()
var zoom = Math.log(156543.03390625) * Math.LOG2E  - Math.log(resolution) * Math.LOG2E;


text:
Q: Django Rest Framework | Foreign key object not saving Whenever I make POST request to my django app , it throws an error
'Genre' instance expected, got (<Genre: Adventure>, False)

I am unable to understand why this is happening.Please help with the serializer. My Movie object is getting saved but the Genre objects is not because of this error.
Model
class Movie(models.Model):
    popularity = models.FloatField()
    director = models.CharField(max_length=255)
    imdb_score = models.FloatField()
    name = models.CharField(max_length=255,)

    def __unicode__(self):
        return u'%s' % (self.name)

class Genre(models.Model):
    name =  models.ForeignKey(Movie,related_name='genres',blank=True, null=True)
    genre = models.CharField(max_length=255)

    def __unicode__(self):
        return u'%s' % (self.genre)

Serializer
class CreatableSlugRelatedField(serializers.SlugRelatedField):

    def to_internal_value(self, data):
        try:
            return self.get_queryset().get_or_create(**{self.slug_field: data})
        except ObjectDoesNotExist:
            self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data))
        except (TypeError, ValueError):
            self.fail('invalid')

class MovieSerializer5(serializers.ModelSerializer):
    genres = CreatableSlugRelatedField(many=True,slug_field='genre',queryset=Genre.objects.all())
    class Meta:
        model = Movie
        fields = ('popularity', 'director','imdb_score', 'name', 'genres')

View
class MovieList(APIView):
    def post(self, request, format=None):
        if not request.user.is_superuser:
            return Response("User is not permitted this action")

        serializer = MovieSerializer5(data=request.data)
        print serializer.initial_data
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

A: When you use the helper get_or_create it returns a tuple with the object (created or not), and a boolean that indicates you if the object was created or it was already on the db, watch out with that ;)

A: get_or_create returns a tuple of (object, created), so in to_internal_value on your serializer, you need something like:
return self.get_queryset().get_or_create(**{self.slug_field: data})[0]

to access the object that was created or retrieved.

A: You need to return only the created object.
get_or_create actually returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.
You can do something like:
obj, created = self.get_queryset().get_or_create(**{self.slug_field: data})
return obj # return the created object