text:
Q: Java app calls C++ DLL via JNI; how best to allocate memory? Basic summary of question is:
How do I best optimize my memory allocation to give as much memory to the DLLs I access through JNI as possible?  What should I aim to minimize, what should I aim to maximize, etc.
SYSTEM:
Running JBoss 6 as a Windows 32 Service in a 32-bit system with 4 GB RAM.  I do understand there are maximum restrictions on memory for Java Heap.  JVM is JRE1.6.0_26
SERVICE:
Installed under JBoss is a webapp which receives requests from clients; each request calls the C++-built DLL through JNI to process an image file in some fashion or other.
ISSUE:
Occasionally, with larger or some (not all) LZW-compression images, the calling java class receives a message that the DLL experienced a Global Memory Depletion and failed to complete the requested process.
There is nothing else actively running on the server beyond basic windows processes.
Current JBOSS App Server memory settings are as follows, but may be excessive:
-Xms1024m -Xmx1024m -Xss1024k -XX:MaxPermSize=128m
I am trying to determine the best memory settings to give as much resources to the JNI DLL, as I understand JNI does not use any memory allocated to the Java Heap.
I have read these, but did not find them helpful to answer my question:
Java JNI : Memory allocation / partitioning
Can jconsole be used to identify memory leaks in JNI C++ objects?
The two answers currently supplied do not address the inherient question.
Current memory of JBoss server after one week with JVM params set as above (TaskManager indicates java.exe process at 750,672k)
Total Memory Pools: 5

Pool: Code Cache (Non-heap memory)

    Peak Usage : init:2359296, used:7317312, committed:7438336, max:50331648
    Current Usage : init:2359296, used:7306496, committed:7438336, max:50331648

        |---------| committed:7.09Mb
        +---------------------------------------------------------------------+
        |/////////| | max:48Mb
        +---------------------------------------------------------------------+
        |---------| used:6.97Mb

Pool: PS Eden Space (Heap memory)

    Peak Usage : init:268500992, used:354811904, committed:354811904, max:355991552
    Current Usage : init:268500992, used:270153472, committed:354091008, max:354156544

        |--------------------------------------------------------------------| committed:337.69Mb
        +---------------------------------------------------------------------+
        |///////////////////////////////////////////////////// || max:337.75Mb
        +---------------------------------------------------------------------+
        |----------------------------------------------------| used:257.64Mb

Pool: PS Survivor Space (Heap memory)

    Peak Usage : init:44695552, used:44694896, committed:78643200, max:78643200
    Current Usage : init:44695552, used:0, committed:1835008, max:1835008

        |---------------------------------------------------------------------| committed:1.75Mb
        +---------------------------------------------------------------------+
        | | max:1.75Mb
        +---------------------------------------------------------------------+
        | used:0b

Pool: PS Old Gen (Heap memory)

    Peak Usage : init:715849728, used:123671968, committed:715849728, max:715849728
    Current Usage : init:715849728, used:104048648, committed:715849728, max:715849728

        |---------------------------------------------------------------------| committed:682.69Mb
        +---------------------------------------------------------------------+
        |////////// | max:682.69Mb
        +---------------------------------------------------------------------+
        |---------| used:99.23Mb

Pool: PS Perm Gen (Non-heap memory)

    Peak Usage : init:16777216, used:91989664, committed:134217728, max:134217728
    Current Usage : init:16777216, used:90956472, committed:90963968, max:134217728

        |----------------------------------------------| committed:86.75Mb
        +---------------------------------------------------------------------+
        |//////////////////////////////////////////////| | max:128Mb
        +---------------------------------------------------------------------+
        |----------------------------------------------| used:86.74Mb

A: Memory allocated by the native code wrapped by JNI is allocated to the JVM process, but is not under the control of your Java code.  It is not part of the heap, and is not tunable via JVM parameters.  Basically, anything allocated with a native malloc must be managed by that native code.  If you are in control of the libraries you are using, its imperative that you go through it and check for resource leaks.  This is especially important if this is being used in a long lived process.
In my experience the best approach would be to examine your actual memory use by pulling the JMX stats exposed by the JVM.  Once you have an idea about how much memory your Java app consumes You'll have a better idea about where to set your max heap settings.  Permgen space is used for class definitions and such, so you really shouldn't need much memory there unless you are doing a bunch of dynamic class loading.
While you cannot tune the memory available for the JNI library, tuning the memory reserved for your heap and such will potentially free up resources for use by the library.
As would be expected, adding the heap memory peaks together it comes out to about 1022.19 (the max size of your heap).  When the heap is exhausted a full GC run is kicked off and dirty heap is reclaimed.  Based on the numbers that you have provided, I'd suggest starting with a Xmx512m.  This will give your JNI code room to breath.
If you find that the JVM is thrashing due to excessive garbage collection, meaning that you're running out of Java heap too quickly, you could grow that allocation.  However, if it is eating up 512mb rapidly enough to cause a noticeable performance impact, its unlikely that anything short of a significant increase will have much effect.  This all depends heavily on your program, how quickly it eats the Java heap, and how effective the full GC run is.


text:
Q: Date Picker max date issue in lollipop devices I am working on a project where i have a datepicker. I am trying to set the max date and min date for it.The min date is 1 day after today and the max date is 11 days after today.But the issue is in lollipop devices the last max day is shown as available but i am not able to select it.This issue is not there in lower android versions.The following is what i have tried:
I call the datepicker method:
selectdate.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        showDialogBox(999);
    }
});

I set the max date and min date as follows(Min day is one day after today, and the max date is 11 days after today):
public void showDialogBox(int x)
{
    Calendar cmin = Calendar.getInstance();
    cmin.add(Calendar.DATE, 1);
    int miny = cmin.get(Calendar.YEAR);
    int minm = cmin.get(Calendar.MONTH)+1;
    int mind = cmin.get(Calendar.DAY_OF_MONTH);

    String minDate=mind+"/"+minm+"/"+miny;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date dateMin = null;
    try {
        dateMin = sdf.parse(minDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long minlong=dateMin.getTime();

    Calendar cmax = Calendar.getInstance();
    cmax.add(Calendar.DATE, 11);
    int maxy =cmax.get(Calendar.YEAR);
    int maxm = cmax.get(Calendar.MONTH)+1;
    int maxd = cmax.get(Calendar.DAY_OF_MONTH);

    String maxDate=maxd+"/"+maxm+"/"+maxy;
    Date dateMax = null;
    try {
        dateMax = sdf.parse(maxDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long maxlong=dateMax.getTime();

    if (x== 999) {
        dpd=new DatePickerDialog(TheatreActivity.this, myDateListener, year, month, day);
        dpd.getDatePicker().setMaxDate(maxlong);
        dpd.getDatePicker().setMinDate(minlong);
        dpd.show();
    }
}

The listener for the datepicker:
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        // arg1 = year
        // arg2 = month
        // arg3 = day
        showDate(arg1, arg2+1, arg3);
    }
};

The following code sets the date in the textview:
private void showDate(int year, int month, int day) {

    String dayy=day+"";
    String monthh=month+"";
    if(dayy.length()==1)
    {
        dayy="0"+dayy;
    }
    if(monthh.length()==1)
    {
        monthh="0"+monthh;
    }
    selectdate.setText(new StringBuilder().append(dayy).append("-")
            .append(monthh).append("-").append(year));
    dateparam=year+"-"+monthh+"-"+dayy;
}

Please Help.
edit:
issue is fixed by the following way
DatePickerDialog dpd=new DatePickerDialog(TheatreActivity.this,android.R.style.Theme_Holo_Light_Dialog, myDateListener, year, month, day);

A: Try This One
This will work on All devices Lollipop & Marshmallow
 mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
        mcurrentDate.add(Calendar.MONTH, 6);
        mDatePicker.getDatePicker().setMaxDate(mcurrentDate.getTimeInMillis() + (1000 * 60 * 60 * 1));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting the values from array to ascii? #include<stdio.h>
#define msize 4096
struct memory
{
int a[msize];
};

void read(struct memory *m)
{
int i;
for(i=0;i<sizeof(msize);i++)
 {
    scanf("%d",&m->a[i]);
 }
}

int main()
{
struct memory m;
m.a[0]=250; // temperature value of 25,0
m.a[4]=01; // heater status OFF
m.a[8]=240; // temperature value of 24,0
m.a[12]=00; // heater status ON
m.a[16]=220; // temperature value of 22,0
m.a[20]=00; // heater status ON
read(&m);
return 0;
}

I have created a structure of a particular memory size and inserted some values to the array and reading those values from the array. I have a difficulty to convert this value to ASCII.

A: In for(i=0;i<sizeof(msize);i++), it will not be i<4096,rather it will compare i to the size of an integer on your platform.In 32-bit systems,it will be 4.So the loop will exit after just 4 iterations.
Further in your function, &m->a[i] will be m->a[i] as m is a pointer.
PS There is something very wrong with the logic of your program.You are assigning some values to the array elements in main(),but are overwriting the same in the function read().
As for converting integer values from an array to ASCII, it's fairly simple.You just have to use the %c format specifier and pass the array  elements are arguments.But I must point out there aren't 450 ASCII values to print.Since a character only has one byte,the max you can manage with it is 256 characters.
PS Many of the ASCII characters you want to print are not print-able.One is whose ASCII value equals 0.

A: My suggestion is inputting by character if you want to store in ASCII.
like this
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define msize 4096
struct memory {
    char a[msize];
};

/*
m.a[0]=250; // temperature value of 25,0
m.a[4]=01;  // heater status OFF
m.a[8]=240; // temperature value of 24,0
m.a[12]=00; // heater status ON
m.a[16]=220;// temperature value of 22,0
m.a[20]=00; // heater status ON
*/

int read(struct memory *m){
    char inputbuff[4+1];
    int i=0;

    memset(m->a, ' ', sizeof(m->a)/sizeof(m->a[0]));//initialize by space
    while(i<msize/(4+4)){
        printf("input temperature value e.g.25,0 : 250(and enter)\n");
        fgets(inputbuff, sizeof(inputbuff), stdin);
        strncpy(m->a + i*4, inputbuff, 3);
        //i+=1;
        printf("input heater status ON or OFF e.g.ON : 00 , OFF : 01(and enter)\n");
        fgets(inputbuff, sizeof(inputbuff), stdin);
        strncpy(m->a + (i+1)*4, inputbuff, 2);
        i += 1;
        printf("continue input? (y or n) : ");
        fgets(inputbuff, sizeof(inputbuff), stdin);
        if(*inputbuff=='n' || *inputbuff=='N'){
            break;
        }
    }
    return i;
}

int main(void){
    struct memory m;
    read(&m);
    {
        //check print
        m.a[msize-1]='\0';
        printf("%s\n", m.a);
    }

    return 0;
}

ADD for more
#include <stdio.h>
#include <string.h>

#define msize 4098

int *storeInt(void *address){
    int *ip =(int*)address;
    *ip = 777;//ip[0]=777;ip[1]=888;...
    return ip;
}

char *storeChars(void *address){
    char *cp =(char*)address;
    strcpy(cp, "hello");
    return cp;
}

void dump(void *address, size_t length){
    unsigned char *cp = (unsigned char*)address;
    size_t i;
    for(i=0;i<length;++i){
        if(i % 16 == 0) printf("\n");
        printf("%02X ", *cp++);
    }
}

int main(void){
    static char memory[msize];//create a static memory of a particular size
    char *block1, *block2;

    block1 = &memory[0];
    block2 = &memory[1024*2];//split a virtual

    int *ip;
    ip=storeInt(block1);//store some values in the memory
    printf("%d\n", *ip);//read the values from the memory

    char *cp;
    cp=storeChars(block2);//set hello\0
    printf("%s\n", cp);//say hello

    char ascValue[12];
    int value = *ip;//777
    //convert "value of int" to Ascii
    sprintf(ascValue, "%d", value);
    //Display it
    printf("value is %s\n", ascValue);

    dump(block1, 8);
    dump(block2, 8);

    return 0;
}

A: If your read() function is intended to read from memory and print to a terminal then you should be using printf() instead of scanf().  printf() will convert integer values to ASCII through the %d format string.  scanf() reads from the standard input and stores to memory.  scanf() converts from ASCII to integer through the %d format string.


text:
Q: storing multiple values in a map against single key I have the following file named ght.txt in my c: and it contains the following data
Id|ytr|yts
1|W|T
2|W|T
3|W|T

Now the thing is that positions of this columns (Id|ytr|yts) is also not in order means they can be reshuffled also..for ex
Id|ytr|dgfj|fhfjk|fgrt|yts

or they can be as ..
Id|wer|ytr|weg|yts

so I have done the following way and read them in java as shown below
String[] headers = firstLine.split("|");
int id, Ix, Ixt, count = 0;

for(String header : headers) {
    if(header.equals("Id")) {
        idIx = count;
    }elseif (header.equals("Ix")) {
        Ixt = count;
    } elseif (header.equals("Ixt")) {
        Ixt = count;
    }
    count++;
}

Now I need to store them in a map in such a way that against id I will get the value of column ytr and yts so in map there should be single key but against that key value could be multiple please advise how to store in map in such a way

A: Using a Map<Integer,List<String>> sounds like a viable first approach.
As it sound like your value is structured, it might be even better to create a value class to hold this, eg. Map<Integer, YourValueClass> where
class YourValueClass
{
    String ix;
    String ixt;

    // constructor, getters and setters
}

Basically, you should think in terms of classes/objects - don't be in object denial :-)
Cheers,

A: I'm not quite sure what you mean, but if I get it right, you are looking for a multimap.
You can roll one yourself, as @Anders R. Bystrup suggests.
Or you can use an existing implementation like the Google Collections Multimap.

A: Don't store one key and multiple values. Instead, you can store a Key and Values as a List.

A: You can use MultiMap from Guava Library:
MultiMap<String,String> map = ArrayListMultimap.create();
map.put("key","value1");
map.put("key","value2");

By using:
System.out.println(map.get("key");

Prints:
["value1","value2"]

A: Value Class
class TextValues {
    final int id;
    final String ix;
    final String ixt;

    private TextValues(final int id, final String ix, final String ixt){
        this.id = id;
        this.ix = ix;
        this.ixt = ixt;
    }

    public static TextValues createTextValues(int id, String ix, String ixt) {
        return new TextValues(id, ix, ixt);
    }
}

Usage:
Map<Integer, TextValues> map = new HashMap<Integer, TextValues>();
map.put(1, TextValues.createTextValues(1, "ix value ", "ixt value"));

A:  public static void main(String[] args) {

Map<String, List<String>> map = new HashMap<String, List<String>>();

List<String> valSetOne = new ArrayList<String>();
valSetOne.add("ABC");
valSetOne.add("BCD");
valSetOne.add("DEF");

List<String> valSetTwo = new ArrayList<String>();
valSetTwo.add("CBA");
valSetTwo.add("DCB");

map.put("FirstKey", valSetOne);
map.put("SecondKey", valSetTwo);

for (Map.Entry<String, List<String>> entry : map.entrySet()) {

    String key = entry.getKey();

    List<String> values = entry.getValue();

    System.out.println("Value of " + key + " is " + values);

}

}
You can use Set or List based on your requirement i.e you need elements in ordered or unordered collection.This is a simple method of having single key with multiple values.


text:
Q: Reset Xorg idle time upon RPi GPIO event, maybe through NodeRed I have a Raspberry Pi 4 running a NodeRed server.
This Pi has no mouse or keyboard, but it does have a regular HDMI display.
It runs a minimal Xorg setup and a Midori browser connects as a client to the NodeRed server itself.
The user can interact with NodeRed through some buttons wired to the GPIO.
So far so good.
I set up a little python script which starts a screensaver (feh) when the user is idle for a while (xprintidle).
Now I would like to stop the screensaver when the user presses a button.
I tried to bind those GPIO pins with the RPi.GPIO library, but it says that they're already bound to something else (NodeRed) and the even won't fire when the button is pressed.
I tried to look at /sys/class/gpio/ but I don't see those exports changing when I click the button, and besides, I would have to use a bash script which constantly poll those sys-files. I'd rather use events/interrupts.
How would you go about achieving this?
Is there some lower system way of getting interrupts from the GPIO?
Maybe is it possible to have NodeRed kill Feh (or feed a fake user input to xorg), somehow?

A: maybe I gave up too soon. I later realized that it's not that difficult to manage the host system processes with NodeRed.
That way I was also able to intercept all the button pushes and make sure that the screensaver is not running, before performing the required action.


text:
Q: C#/SQL Checking for duplicate entries I am working on a project, and I have hit a brick wall. My code adds dates with a type to a database, but I need to create an error when there is already a similar entry within the code. However, I cannot get my loop to check for duplicates, and instead it adds duplicates! I am not very good at loops so I'm a bit stuck at this. Any help to check for duplicate entries and to stop it from creating too many would be a great help! Changed my code within this text area so it's not exactly the same variable names.
Here is my code: -
if (DT != null && DT.Length > 0 || DF != null && DF.Length > 0)
            {
                for (int t = 0; t < Type.Length; t++)
                {
                    DateTime checkDate;

                    if (Type.IsSelectionValid(8, out typeError) && DateTime.TryParse(DF, out typeError) && DateTime.TryParse(DT, out checkDate))
                    {
                            TypeValid = true;
                            error.Error = false;
                        }
                        else
                        {
                            error.Errors = "Type-Invalid";
                            absenceTypeValid = false;
                            break;
                        }
                    }
                    else
                    {
                        error.Errors = "Type-Duplicate";
                        TypeValid = false;
                        break;
                    }
                }
            }

A: I'm 'fairly' sure you are going out of your way to make a problem more difficult than it is here, but I can't say for sure since I'm not entirely sure what this is doing.
But here are the conditions that need to be met to get to your Type-Duplicate Error line:
1) Either DT or DF have to not be empty to get past the first if statement
2) Either IsSelectionValid() has to return false or either DT or DF have to be an invalid DateTime.
None of those things constitute a duplicate.
Let me try to explain what I see here:
I first see variables called DT, DF.  I can see these are dates, but that's all I know about them.  I see 'Type' which I understand even less about than DT and DF.  I see that you are doing a loop for Type.Length number of iterations... but what does this mean to me if I don't have a clue what Type is?
If you had comments explaining what things are I 'might' be able to help you, but there's just really not enough information to know what's happening here.
If you simply want to know how to avoid adding duplicates to a database, then I would suggest adding a constraint or index to the column in the database and then you can just catch the exceptions that are thrown when you try to insert a duplicate and deal with it that way.  Alternatively, account for it in your insert statement.


text:
Q: Run uninstall.php if a checkbox is checked from settings page I am building a custom plugin and when the plugin is activated it creates 2 tables inside the wp database. What I want is, to add a checkbox is my custom plugin settings page, and if the checkbox is checked, the tables to be deleted from the database. I am using and uninstall.php file to delete my tables but that happens when I delete the plugin. I would like to fire that uninstall.php file which have the scripts to delete my tables, if the checkbox is checked.
Here is my code
<form action="options.php" method="POST" id="my-form">
<?php
    settings_fields("customfields");
    do_settings_sections("support");
    submit_button("Save Data");
    ?>
</form>

Delete Database? <?php echo get_option("delete_database"); ?>

<?php
add_settings_section("section", null, null, "support");
add_settings_field("wp_delete_database", "Delete Database?", array($this, "HTML"), "support", "section");
register_setting("customfields", "wp_delete_database", array("sanitize_callback" => "sanitize_text_field", "default" => "Placeholder"));
?>

A: You should have a function (single class, or method in a class) for the task to remove all the data from the plugin, like database or options entries.
On your settings page, call after an active checkbox this function, after sending a request, like via Button. In the uninstall.php have you also the possibility to use this function.
So you have only one function to do the same goal and no redundancy.
register_uninstall_hook
For the un-installion of the plugin via Core Function, Gui in the admin backend use the function register_uninstall_hook.
The uninstall.php
could look like this
<?php
/**
* Uninstallation script
* This file is called automatically by WP when the admin deletes the plugin from the installation.
*/

! defined( 'WP_UNINSTALL_PLUGIN' ) && exit;

require_once __DIR__ . '/src/settings.php';
// Use core function to delete items in the options table
delete_site_option( Your_Class_Settings::OPTION_NAME );
// Call method from class
Your_Class_Settings->uninstall();


text:
Q: What encryption does a phpbb forum use on a domain without SSL? I have set up a phpbb forum on one of my domains and as far as I know the site doesn't have SSL encryption (I'm not willing to buy one and neither does the site have a self-signed certificate, because when I access it I get no security warnings). May I ask what encryption does that phpbb system use and is it secure to run this forum software without encryption?

A: The danger with phpbb (or anything else for that matter) is not whether you run the site with SSL or not How you manage user input is far more likely to compromise your site.
SSL is ONLY used to protect user information between the client and server and to certify that the server is what you expect it to be.
Bugs or design errors in phpbb that attackers can utilize to gain control of your site is what you should worry about. SSL cannot protect you from that.
Passwords for phpbb should be salted and hashed in the database in case the site is compromised. This will make it harder for attackers to gain access to other users data.
Blog posts I believe are NOT encrypted in the database and thus will be revealed if there would be a successfull attack.


text:
Q: Error regarding proper implementation of the interface So, this program requires the user to calculate the total tuition based on the cred it hours and student status. IF US student then 700 dollars per cred hr and 400 dollar registration fee. If Intl student then 1000 dollar per cred hr and 500 dollar registration fee. And if MI student then 500 dollar per cred hr and 200 dollar registration fee
My problem with the program is that the output should be:
Jack's bill:    $ 6,700
Lucy's bill:    $10,900
Hao's bill:     $12,500
The total tuition revenue is $30,100
But, I am getting this output (I feel like the value of both name and the cred hrs is not being fetched properly):
null's bill:    $   200
null's bill:    $   400
null's bill:    $   500
The total tuition revenue is $ 1,100
IStudent.java
public interface IStudent {

    // return the name of the student;
    String getName();

    // return the number of credit hours that this student registered
    int getCreditHours();

    // calculate the tuition for this student
    int calculateTuition();
}

IUniversity.java
public interface IUniversity {

    // return a list of students
    ArrayList<IStudent> getStudentList();

    // return a list of students
    int calculateTotalTuition();

    // add a student to student list
    void addStudent(IStudent student);
}

Main.java
public class Main {

    public static void main(String[] args) {
        IUniversity mu = new University();
        IStudent  stu1 = new MichiganStudent("Jack",13);
        mu.addStudent(stu1);
        IStudent  stu2 = new USStudent("Lucy",15);
        mu.addStudent(stu2);
        IStudent  stu3 = new InternationalStudent("Hao",12);
        mu.addStudent(stu3);

        for(int i = 0; i < mu.getStudentList().size(); i++) {
            System.out.print(mu.getStudentList().get(i).getName() +
                    "'s bill:");
            System.out.printf("\t$%,6d\n", mu.getStudentList().get(i).calculateTuition());
        }
        System.out.printf("\nThe total tuition revenue is $%,6d\n",
                mu.calculateTotalTuitution());
    }
}

This is my code:
For University class:
public class University implements IUniversity {

    ArrayList<IStudent> mu = new ArrayList<IStudent>();

    public ArrayList<IStudent> getStudentList() {
        // TODO Auto-generated method stub
        return mu;
    }

    public int calculateTotalTuition() {
        // TODO Auto-generated method stub
        int tuition = 0;
        for( int i = 0; i < mu.size(); i++ ) {
            tuition = tuition + mu.get(i).calculateTuition();
        }
        return tuition;
    }

    public void addStudent(IStudent student) {
        // TODO Auto-generated method stub
        mu.add(student);
    }

}

And one of the student class:
public class USStudent implements IStudent {

    public USStudent(String string, int i) {
        // TODO Auto-generated constructor stub
    }

    private String name;
    private int credhrs;

    public String getName() {
        // TODO Auto-generated method stub
        return name;
    }

    public int getCreditHours() {
        // TODO Auto-generated method stub
        return credhrs;
    }

    public int calculateTuition() {
        // TODO Auto-generated method stub
        int total = 0;
        total = total + 400 + (700 * credhrs);
        return total;
    }
}

A: You missed to store the values into the instance variables.
public USStudent(String string, int i) {
    this.name = string;
    this.credhrs = i;
}

A: If you provide no explicit initialization to instance variables, they will be initialized to the default initial values, based on the data type of the variable. This is the default JVM behavior.
In your snippet, what JVM did it as mentioned below:
private String name = null;
private int credhrs=0;

As you are using parameterized constructor and your intention is to use the value passed along with object. So, lnitialize the private variables in the constructor it will solve this problem.
example mentioned by user7 same as above.


text:
Q: Converting word symbols to unicode characters I have a number of word documents containing symbols from the "Symbol Font" in word - a delta, for example. Those are treated specially in the sense that if you double-click on them in Word 2010, the symbol's dialog opens. With this dialog it is also possible to add corresponding characters using unicode codepoints - a unicode delta, for example.
The unicode delta doesn't open the symbol's dialog and can be exported as unicode as one would expect (this is my actual problem), unlike the symbols using the "Symbol Font".
So my question: Is there a way in word or an external tool, with which I can mass-process a larger number of word files to replace all the symbols with unicode characters?


text:
Q: Twitter and dribble anchors not working on mobile I have a div with four icons pointing to twitter, dribbble, GitHub and Gmail respectively. I have wrapped them around anchor tags to create links to these websites. I notice that the links work perfectly across all browsers on desktop, but on mobile, only GitHub works, and the Gmail icon opens up the default mail app on the phone. The twitter and dribbble icons dont work.
I checked the pointer-eventsin css and they are set to auto, and I can't find any reason whatsoever why two of the links won't work.
Any help would be most appreciated! Thank you!
HTML:

Link to the website: https://hackertronix.com

A: Using following code twitter and dribble anchors workon mobile:

@media (max-width: 767px) {
 #section4 .right {
    z-index: 50;
  }
}


text:
Q: How can I get PID to kill a process using PowerShell I'd like to kill all process that are not in a text file $fileServices,
I use a loop to got PID to send it to Stop-Process.
Runs without error. But the process isn't killed and my loop is not good.
How can I got PID to kill this process using PowerShell please?
$ServiceName = Get-WmiObject Win32_Process -Filter "name = 'service.exe'" |
               Select-Object CommandLine
$procId = Get-WmiObject Win32_Process -Filter "name = 'service.exe'" |
          Select-Object ProcessId
$fileServices = Get-Content C:\serviceNotStop.txt

$totalcount = Get-Content C:\serviceNotStop.txt | Measure-Object -Line
$number = $totalcount.Lines

$get_path = $ServiceRunName.CommandLine
$output_file = 'C:\service_name.txt'
$get_path | Out-File -FilePath $output_file

if ($fileServices -ne $null) {
    foreach ($process in $get_path ) {
        foreach ($id in $procId ) {
            $nameExtracted = ($process -split '//')[2]
            $counter = 1
            foreach ($line in $fileServices) {
                if ($line -ne $nameExtracted) {
                    $counter++
                    "continue search file, $counter"
                    if ($counter -gt $number) {
                        " kill process after all search"
                    } else {
                        continue
                    }
                } elseif ($line -eq $nameExtracted) {
                    "keep process $line "
                    break
                }
            }
        }
    }
} else {
    "the file is empty"
}

A: List.txt contents
    notepad
    chrome
    calculator
$list = Get-Content -Path C:\Users\username\Desktop\TEMP\list.txt -Raw

Get-Process | Where-Object ProcessName -Like $list | kill -Force

I almost have this working, just have to figure out how to get multiple lines in the txt file to be iterated through like an array


text:
Q: how read vaadin grid header column key stored? hello in debug mode i need this property but have private method
getGrid().getHeaderRows().stream()
  .findAny()
  .get()
  .getCells()
  .get(0).getColumn().columnKey

exist other property for read this value?
tnx

A: Why do you think you need to get the column key?
Just set it when you create the Grid column. Example
grid.addColumn(ClubRecord::getName)
    .setHeader(getTranslation("Name"))
    .setSortable(true)
    .setAutoWidth(true)
    .setKey("club_name");


text:
Q: Automatic constructor generation in C++? imagine I have
struct Foo
{
   int a;
   string s;
   float f;
}

So now when I need to create new Foo I need to add a constructor:
struct Foo
    {
       int a;
       string s;
       float f;
       Foo(int a, string s, float f)
       {
          this->a = a;
          this->s = s;
          this->f = f;
       }
    }

However this method of manually writing constructors is really time consuming, especially with structs/classes with 10+ properties. My questions is: Is there a way to automatically generate such constructors?

A: struct Foo
{
  int a;
  std::string s;
  float f;
};

Foo f{42,"Foo",0.0};

works just fine, but a constructor gives you more control e.g. check of init value.

A: First if you want to write the constructor by yourself it is better to do it like this:
struct Foo
{
   int a;
   string s;
   float f;
   Foo()=default;// this is needed if Foo needs to be default constructable (Thanks to @ NathanOliver)
   Foo(int a, string s, float f):a(a),s(s),f(f){
   }
};

If you do not want to do it manually (the manual option is definitely better and more controllable), you may use this:
struct Foo
{
  int a;
  std::string s;
  float f;
  //The default constructor is exist by default here
};
Foo obj{0,"",0.0f};

A: If your structs are PODs, you can use {} to initialize them.
struct A {
  int a;
  int b;
} foo = {2,3};

In more modern C++, the restrictions for this syntax have been relaxed. It's called list initialization

A: While I personally would recommend, using a constructor, as the constructor has the advantage of checking it's type parameters, for errors, there is a method for initializing data members, introduced in C++11, called list-initialization, that uses a list written by the user that automatically assigns data members consecutively. Here is an example for a sample struct foo
struct Foo
{
    int a;
    int b;
};
int main()
{
    Foo bar {27,86}; // Note the use of curly braces here to initialize the list. There is
                     // no range or error checking, but a and b are consecutively initialized
    return 0;
}

If you didn't read my comment in the code, here it is:
Note the use of curly braces here to initialize the list. There is no range or error checking, but a and b are consecutively initialized
What if my compiler doesn't support C++11?
If a compiler doesn't support C++11, Uniform Initialization, a feature that has always been in C++, would come in handy for you. An example below for the same struct Foo:
Foo baz = {22,33}; //Note the '=' sign here, that separates it from list-initialization.


text:
Q: Given the sequence of real numbers with the restrictions $0\frac{1}{4}$, show that $\lim_{n\to\infty} x_n=\frac{1}{2}$ Given the sequence of real numbers with the restrictions $0<x_n<1$ and $(1-x_n)x_{n+1}>\frac{1}{4}$, show that $\lim_{n\to\infty} x_n=\frac{1}{2}$.
I am having trouble approaching this problem since it does not give an explicit recursive formula.
I would like to say that the sequence is strictly increasing and perhaps find a bound, but in terms of computation it is hard for me to work with.
Thanks

A: We know $\forall n \in \mathbb{N}: (x_n-1/2)^2\geq 0$, hence $x_n^2-x_n+1/4\geq 0$, so $1/4\geq x_n-x_n^2$, i.e. $1\geq 4(x_n-x_n^2)$, or equivalently $\frac{1}{4(x_n-x_n^2)}\geq 1$ (note that $x_n-x_n^2>0$, as $0<x_n<1$).
We are given that $\forall n\in \mathbb{N}: (1-x_n)x_{n+1}>1/4$, hence, dividing by $1-x_n>0$: $x_{n+1}>\frac{1}{4(1-x_n)}$. Divide this by $x_n>0$: $\frac{x_{n+1}}{x_n}> \frac{1}{4(x_n-x_n^2)}$. The last member is, as we found out earlier, greater or equal to $1$. Hence we have $\forall n \in \mathbb{N}: \frac{x_{n+1}}{x_n}>1$, i.e. $(x_n)_{n\in \mathbb{N}}$ is increasing.
As  $(x_n)_{n\in \mathbb{N}}$ is bounded (by $1$), it must converge to some $l\in [0,1]$ (we know that $l$ is in this interval, because the sequence only lives between $0$ and $1$).
Now, taking the limit on the given inequality: $\lim_{n\to +\infty} (1-x_n)x_{n+1}\geq 1/4$ (note that you always need to replace $>$ by $\geq$ in the limit). Hence: $(1-l)l\geq 1/4$, so $-l^2+l-1/4 \geq 0$, i.e. $l^2-l+1/4 \leq 0$. The left member equals $(l-1/2)^2$, so we obtain $(l-1/2)^2 \leq 0$. Thus $l=1/2$.

A: hint: suppose $\lim_{n\to\infty} x_n=l$ exists
so $$(1-x_n)x_{n+1}>\frac{1}{4}\\(1-l)l>\frac{1}{4}\\4-4l^2>1\\4l^2-4l<-1\\4l^2-4l+1<0\\(2l-1)^2<0$$ that is impossible...if only $(2l-1)^2 \to 0$


text:
Q: How to build Vue components as a library for Nuxtjs with SSR support? I have two packages in a monorepo environment,

*

*A nuxtjs app.

*A Vue 2 components library.

I'm trying to build the components package as a "Library" so that I can import the components in the Nuxt app.
After building-installing-importing the library, the nuxt raises the following error:
document is not defined

inside the library build
function o(e) {
  var t, n, i = document.querySelector('style[data-vue-ssr-id~="' + e.id + '"]');
  if (i) {
    if (f) return g;
    i.parentNode.removeChild(i)
  }
  if (m) {

I get that it's because nuxt is encountering the browser's document object when it's attempting to render the page on the server-side.
Just a thought, is it because I'm using in-component styles?
It'd be great if someone could confirm it?

A: If you want to create a full Vue SSR library, you can follow this very useful guide.
Otherwhise you can tell Nuxt to load your library only on client side in this way:

*

*In your Nuxt application create the file plugins/my-vue-library-plugin.js

*Fill it with this content for import your Vue component library:
import Vue from 'vue'
import MyLibrary from 'my-vue-library-path'

Vue.use(MyLibrary)

*Then add the file path inside the plugins key of our nuxt.config.js
 export default {
   plugins: [
     { src: '~/plugins/my-vue-library-plugin.js', mode: 'client' }
   ]
 }

How you can see the mode: 'client' property is the key because tells Nuxt to load the library only on client side, so your document is not defined error should disappear.
Let me know if it helps.


text:
Q: server encountered an unexpected condition that prevented it from fulfilling the request Premiss: I'm a java newbie and this is my first question on stack, I looked over the internet but I can't find any answer.
I started working on a dynamic web project on a windows pc, on eclipse, connected to a mysql database and it was working just fine.
I came home and I wanted to work on it on a mac but I have this problem with the server I guess..

Description: "The server encountered an unexpected condition that
  prevented it from fulfilling the request."
Exception: java.lang.NullPointerException

I already changed the jdbc and everything but I'm having the same error.
Do you have any idea or suggestion to help me solve this problem?
Thank you
Edit 1
Full Stack

mar 30, 2018 2:09:45 AM org.apache.catalina.core.StandardWrapperValve
  invoke GRAVE: Servlet.service() for servlet [webUI.PersonaServlet] in
  context with path [/WebSalari] threw exception
  java.lang.NullPointerException    at
  database.DbAccessore.eseguiSelect(DbAccessore.java:73)    at
  database.FilmDbAccess.caricaTutteLePersone(FilmDbAccess.java:14)  at
  contenitori.ContenitoreFilm.caricaDati(ContenitoreFilm.java:24)   at
  webUI.PersonaServlet.processRequest(PersonaServlet.java:83)   at
  webUI.PersonaServlet.doPost(PersonaServlet.java:49)   at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:661)  at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:742)  at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at
  org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at
  org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at
  org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at
  org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at
  org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

I'm also getting this ClassNotFoundException when trying to connect to the database
Edit 2
Here's my DBAccessore.eseguiSelect method
Connection conn;

    public ResultSet eseguiSelect(String p_sql) {
        ResultSet rs = null;

        try {
            Statement comando = conn.createStatement(); // Line 73
            rs = comando.executeQuery(p_sql);
        } catch (SQLException sqle) {
            LogManager.scriviLog("Errore nella esecuzione della
            query! Dettagli:");
        LogManager.scriviLog(sqle.getMessage());
        }

        return rs;
    } // end method


text:
Q: Going up a directory in relative paths within models For an oData Model, I need to go up a directory.
This is an approximation of the structure:
EditModel:
-->Entity A
    -->Entity B
    -->Entity C

I need a ComboBox inside the Entity B Table that pulls from the Entity C table. I can't do an absolute path, and binding shared comboboxes is painful.
So in the Path for ComboBox items, I need a relative path that looks like:

path = editModel>../C

('..' as in 'cd ..' - for up directory)
Essentially, I need to be able to back out one directory, to view the other. Any ideas? Thanks in advance.

A: A backward property doesn't exist in OData, but you could leverage (forward) navigation properties as well, e.g.:
-->Supplier A
    --> Product A
    --> Product B

In this case, you would see all products of supplier A by querying: Suppliers('A')/Products
If the service is configured nicely, the opposite would work as well:
--> Product A
    --> Supplier A
--> Product B
    --> Supplier A

To find out which supplier supplies Product A, you could then query: /Product('A')/Supplier.
If the Product entity doesn't have a navigation property Supplier, you may need to talk to your ABAP/Gateway folks to see if it's possible to get this implemented.


text:
Q: Show that the set of all idempotent elements of a commutative ring is closed under multiplication I have a commutative ring $R$ and I defined $S = \{a\in R | a^2 = a\}$, and I want to show that $S$ is closed under multiplication. So far I have this:
For $x,y \in S$ we know that $x^2 = x$ and $y^2 = y$. I want to consider $x*y = y*x = x^2*y^2 = y^2*x^2$ (because $R$ is commutative). Is it logical to deduce that because $S$ is a subset of $R$ and multiplication is associative on the ring, it is also associative on this subset? This would easily allow me to do this proof.

A: If $x,y\in S$ then we have
$$(xy)^2=(xy)(xy)=x^2y^2=xy$$
so $xy\in S$. Notice that we used in the above equalities the commutativity of $R$ and the fact that $x=x^2$ and $y=y^2$.


text:
Q: query properites from promise object and save in variable I am using an axios get request, and returning an object of response.data.But i want to be able to query the properties of response.data and save those as variables and use it in another class.
export class myClass {
    public async getData() {
        return axios.get(url)
            .then(response => response.data)
            .catch((error) => {
                console.log(error);
            });
        }
    }

I want to access these properties from the response, and save as values:
response.data.name
response.data.address
response.data.company

I can console log the properties, but if i try to use it as a value somewhere, i get undefined.
public async getName() {
    return this.getData().then((response: any) => {
        console.log(response.data.name);
        return response.data.name;
    });
}

Call :
const name = new myClass().getName();
NAME: name(undefined)

A: By default, async function returns a Promise, you should implement it that way, more understandable :
myClass
export class myClass {
    ...
    public async getData() {
        return axios.get(url);
    }

    public async getName() {
        try {
            const response = await this.getData();
            return response.data.name;
        } catch (error) {
            // handle errors here
        }
    }
    ...
}

call to getName()
const myClass = new myClass();
const name = await myClass.getName();


text:
Q: Given Circle $E$ inscribed in square $ABCD,$ prove that its radius is equal to half the length of the square's side length. Given Circle $E$ inscribed in square $ABCD$, prove that its radius is equal to half the length of the square's side length. I'm stuck on this proof but I've got a few ideas. If anyone could help that would be awesome.

*

*Draw radii $EF$ and $EG$ so that $EF$ is perpendicular to $CD$ and $EG$ is perpendicular to $AD$

*With this, we now have a quadrilateral $EFDG$.

*The presence of congruent and opposite angles implies that the new quadrilateral formed is a rectangle.

*$EF$  is congruent to $GD$ and $EG$ is congruent to $FD$.


text:
Q: AWS CloudFormer stack creation failed with (Failed to receive 1 resource signal(s) within the specified duration) I was trying to use AWS CloudFormer to create a template for my existing resources, however, the CloudFormer stack creation failed multiple times without an obvious reason. below you can find the full log, I tried to increase the timeout in the options to 100 minute and I got the same results:
22:16:49 UTC+0300   CREATE_FAILED   AWS::EC2::Instance  WebServer   Failed to receive 1 resource signal(s) within the specified duration
21:45:58 UTC+0300   CREATE_IN_PROGRESS  AWS::EC2::Instance  WebServer   Resource creation Initiated
21:45:56 UTC+0300   CREATE_IN_PROGRESS  AWS::EC2::Instance  WebServer
21:45:54 UTC+0300   CREATE_COMPLETE AWS::IAM::InstanceProfile   CFNInstanceProfile
21:43:54 UTC+0300   CREATE_COMPLETE AWS::IAM::Policy    CFNRolePolicy
21:43:54 UTC+0300   CREATE_IN_PROGRESS  AWS::IAM::Policy    CFNRolePolicy   Resource creation Initiated
21:43:53 UTC+0300   CREATE_IN_PROGRESS  AWS::IAM::InstanceProfile   CFNInstanceProfile  Resource creation Initiated
21:43:53 UTC+0300   CREATE_IN_PROGRESS  AWS::IAM::Policy    CFNRolePolicy
21:43:52 UTC+0300   CREATE_IN_PROGRESS  AWS::IAM::InstanceProfile   CFNInstanceProfile
21:43:50 UTC+0300   CREATE_COMPLETE AWS::IAM::Role  CFNRole
21:43:44 UTC+0300   CREATE_COMPLETE AWS::EC2::SecurityGroup WebServerSecurityGroup
21:43:43 UTC+0300   CREATE_IN_PROGRESS  AWS::EC2::SecurityGroup WebServerSecurityGroup  Resource creation Initiated
21:43:39 UTC+0300   CREATE_IN_PROGRESS  AWS::IAM::Role  CFNRole Resource creation Initiated
21:43:27 UTC+0300   CREATE_IN_PROGRESS  AWS::EC2::SecurityGroup WebServerSecurityGroup
21:43:27 UTC+0300   CREATE_IN_PROGRESS  AWS::IAM::Role  CFNRole
21:43:18 UTC+0300   CREATE_IN_PROGRESS  AWS::CloudFormation::Stack  AWSCloudFormer  User Initiated

A: In Parameters, specify a username and password. It is mandatory to create the instance.

A: CloudFormation is waiting from a notification from the CloudFormer WebServer instance, specified in the CloudFormer template using a CreationPolicy.
The bootstrapping script which installs the CloudFormer application is failing at or before the final step which to run /opt/aws/bin/cfn-signal to inform CloudFormation that the application installed correctly.
The bootstrapping scripts log to /var/log/setup_cloudformer.log so you might be able to get more information about why it's failing by looking in there.
To try and investigate you could choose the Launch More Like This action on the EC2 instances page to launch another CloudFormer WebServer instance. You can then provide a keypair and update the Security Group to allow SSH access to look at the logs.

A: In addition to the answer from Anush Arvind, you also must take care not to include special characters in the password.
From the official docs:

You can't leave the password blank, and you can't use special
  characters in the password (such as ; & ! " £ $ % ^ ( ) / ).

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-cloudformer.html


text:
Q: Adding a variable to PHP script causes another line to create an error Quick question...
I'm using this code to communicate with my flash application:
<?php
// Only run this script if the sendRequest is from our flash application
if ($_POST['sendRequest'] == "parse") {
// Print the var to flash
print "var1=The user's name is Harry";

}

?>

Now this works fine but as soon as I add a variable:
<?php
// Only run this script if the sendRequest is from our flash application
if ($_POST['sendRequest'] == "parse") {
$uname = "Name"
// Print the var to flash
print "var1=The user's name is Harry";

}

?>

I get an error stating:
Parse error: syntax error, unexpected T_PRINT in /home/a4935911/public_html/usersOnline.php on line 7

Where line 7 is my print statement. Why is this happening??? Please can someone help. PHP is driving me crazy...

A: Missing semi-colon in $uname = "Name"
change it to $uname = "Name";
Rewrite:
<?php
// Only run this script if the sendRequest is from our flash application
if ($_POST['sendRequest'] == "parse") {
$uname = "Name";
// Print the var to flash
print "var1=The user's name is Harry";

}

?>

Added note: A semi-colon can be omitted if it's the last line of code with nothing else that will be executed/included thereafter.

A: PHP requires that you end lines with a semicolon unless it is the last line. This is because if the semicolon is omitted, it will be evaluated as the same expression as the next line. Change this:
$uname = "Name"

To this:
$uname = "Name";

A: write it like this
just add ; at the end
$uname = "Name";

A: Missing a semicollen.
$uname = "name";

A: You need to end each statement with a semicolon ;
This error most often means you forgot one of these
' ; ' " ) ( [ ]

Change
$uname = "Name"

with
$uname = "Name";


text:
Q: How are the services distributed in an intra-cluster couchbase server? I have been studying Couchbase Server.
I found that there are some words that help us get through with the architecture  of it.
I wanted to know, in a intra-cluster, what means an active and replica vbuckets? How do these work with the services that exist in each node?

A: vbuckets, as you know, are Couchbase Server's data partitioning mechanism.  The Data Service is responsible for managing the vbuckets, active and replica, across all nodes running the Data Service. The active vbuckets store the documents.  The replica vbuckets increase availability of those documents.
In the event of a node failure, replica vbuckets may be promoted to active vbuckets, this is called Failover. Or the replica vbuckets may be used when a failed node is replaced by a new node and the cluster is Rebalanced, restoring the active vbucket in the new node.
A node running a Data Service has a Projector and Router process that monitors document mutations and reports relevant changes to the Index Services so they can update their indexes.
The Query Service handles N1QL queries. It uses the Index Service to perform scans and the Data Service to retrieve data from active vbuckets.
With Couchbase Community Edition you have to run all the services on each node in the cluster, while the Enterprise Edition lets you pick and choose which services to run on each node. This Enterprise feature is Multidimensional Scaling.
This image shows some of the interactions between the three services.  It does not show the Query Service interaction with the Data Service, though.

Clients have Cluster Maps that help them find data and services in the cluster. The cluster map, for example, knows in which active vbucket a document belongs (by creating a hash from the document key or ID). It also knows where the replica of that document resides, if there is a replica. Clients may use the replicas if data retrieval from the active vbucket is too slow or that node has failed.


text:
Q: Single for loop giving different result than many for loops I am trying to learn programming and I wrote a code for adding items into ArrayList. There are many for loops and every loop is running for a specific interval and this give me correct result.
But rather than many for loops I tried just one for loop with IF Else statement and this doenots give me correct result
Please can anyone check and tell what is wrong?
  ArrayList dogs = new ArrayList();
        ArrayList cats = new ArrayList();
        ArrayList rabbits = new ArrayList();
        ArrayList guineaPigs = new ArrayList();
        ArrayList birds = new ArrayList();
        ArrayList ferrets = new ArrayList();

        //Before
        for (int i = 0; i < 20; i++)
        {
            dogs.Add(new Animal(240.00, "D-PUP" + i));
        }
        for (int i = 0; i < 15; i++)
        {
            dogs.Add(new Animal(190.00, "D-JUN" + i));
        }
        for (int i = 0; i < 10; i++)
        {
            dogs.Add(new Animal(120.00, "D-ADU" + i));
        }
        for (int i = 0; i < 5; i++)
        {
            dogs.Add(new Animal(60.50, "D-SEN" + i));
        }
        //Before
        for (int i = 0; i < 25; i++)
        {
            cats.Add(new Animal(220.00, "C-KIT" + i));
        }
        for (int i = 0; i < 30; i++)
        {
            cats.Add(new Animal(180.50, "C-JUN" + i));
        }
        for (int i = 0; i < 15; i++)
        {
            cats.Add(new Animal(120.00, "C-ADU" + i));
        }
        for (int i = 0; i < 10; i++)
        {
            cats.Add(new Animal(50, "C-SEN" + i));
        }
        //Before
        for (int i = 0; i < 15; i++)
        {
            rabbits.Add(new Animal(120.75, "R-KIT" + i));
        }
        for (int i = 0; i < 15; i++)
        {
            rabbits.Add(new Animal(40.00, "R-ADU" + i));
        }
        //Before
        for (int i = 0; i < 5; i++)
        {
            guineaPigs.Add(new Animal(15.00, "G-PUP" + i));
        }
        for (int i = 0; i < 10; i++)
        {
            guineaPigs.Add(new Animal(7.50, "G-ADU" + i));
        }
        //Before
        for (int i = 0; i < 2; i++)
        {
            birds.Add(new Animal(90.00, "B-CHI" + i));
        }
        for (int i = 0; i < 5; i++)
        {
            birds.Add(new Animal(65.00, "B-ADU" + i));
        }
        //Before
        for (int i = 0; i < 1; i++)
        {
            ferrets.Add(new Animal(150.00, "F-PUP" + i));
        }
        for (int i = 0; i < 3; i++)
        {
            ferrets.Add(new Animal(120.00, "F-ADU" + i));
        }
        for (int i = 0; i < 2; i++)
        {
            ferrets.Add(new Animal(30.50, "F-SEN" + i));
        }
        //After
        int j = 30;
        int i;
        for(i = 0; i < j; i++)
        {
            if(i < 1)
            {
                ferrets.Add(new Animal(150.00, "F-PUP" + i));
            }
            if(i < 2)
            {
                birds.Add(new Animal(90.00, "B-CHI" + i));
                ferrets.Add(new Animal(30.50, "F-SEN" + i));
            }
            if(i < 3)
            {
                ferrets.Add(new Animal(120.00, "F-ADU" + i));
            }
            if(i < 5)
            {
                dogs.Add(new Animal(60.50, "D-SEN" + i));
                guineaPigs.Add(new Animal(15.00, "G-PUP" + i));
                birds.Add(new Animal(65.00, "B-ADU" + i));
            }

            if(i < 10)
            {
                dogs.Add(new Animal(120.00, "D-ADU" + i));
                cats.Add(new Animal(50, "C-SEN" + i));
                guineaPigs.Add(new Animal(7.50, "G-ADU" + i));
            }
            if(i < 15)
            {
                dogs.Add(new Animal(190.00, "D-JUN" + i));
                cats.Add(new Animal(120.00, "C-ADU" + i));
                rabbits.Add(new Animal(120.75, "R-KIT" + i));
                rabbits.Add(new Animal(40.00, "R-ADU" + i));
            }
            if(i < 20)
            {
                dogs.Add(new Animal(240.00, "D-PUP" + i));
            }
            if(i < 25)
            {
                cats.Add(new Animal(220.00, "C-KIT" + i));
            }
            if(i < 30)
            {
                cats.Add(new Animal(180.50, "C-JUN" + i));
            }
        }

A: It's not a best way to write a code, because it confusing and, as you can see, makes things complex to understand. It's really complex to understand that you need 30 cats "C-JUN"
keep your first option with separate for loops, or Change to dogs.AddRange(Enumerable.Range(0, 20).Select(i=>new Animal(240.00, "D-PUP" + i)))


text:
Q: How to find all that don't belong to a specific id in belongsToMany? I have the following models:
const users = sequelize.define('users', { /* definition */ }
const messageGroups = sequelize.define('message_groups', { /* definition */ }

They are associated like this:
models.messageGroups.belongsToMany(models.users, {through: 'user_message_groups'})
models.users.belongsToMany(models.messageGroups, {through: 'user_message_groups'})

How can I return a list of users that are not in a messageGroup with a specific id?
For example, let's say my tables look like this
users

id
name

1
Foo

2
Bar

3
Baz

message_groups

id
name

1
Admin

2
Users

user_message_groups

userId
messageGroupId

1
1

1
2

2
2

Given a message_groups id of 1 (Admin), how can I construct a query that returns the two users that are not in that message_group? (Should return users Bar and Baz)

A: If you are passing id as a variable, one option is to use just users and user_message_groups table.
First, you need a model definition for user_message_groups.
const userMessageGroups = sequelize.define('user_message_groups', {
    userId: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    messageGroupId: {
        type: DataTypes.INTEGER,
        allowNull: false
    }
});

Next, create an association between users and user_message_groups table.
models.users.hasMany(models.userMessageGroups);

Then query with exclusive LEFT JOIN.
models.users.findAll({
    include: {
        model: models.userMessageGroups,
        required: false,
        where: {
            messageGroupId: 1
        }
    },
    where: models.sequelize.literal('`user_message_groups.messageGroupId` IS NULL')
});


text:
Q: Find unique pairings of entries in a character vector I have a vector fruit with three entries Peach, Plum, Pear. I would like to find each unique pairing in fruit and create a new, two column data.frame (e.g. df.new below). How might I do this in r for an even larger data.set? expand.grid results in pear-plum and plum-pear which are not unique pairings, or not the ones I am seeking. Any suggestions?
fruit <- c("Peach", "Plum", "Pear")

fruit1 <- c("Peach", "Peach", "Plum")
fruit2 <- c("Plum", "Pear", "Pear")
df.new <- data.frame(fruit1, fruit2)

#df.new
fruit1 fruit2
1  Peach   Plum
2  Peach   Pear
3   Plum   Pear

# attempt
fruit.y <- fruit
df.expand <- expand.grid(fruit,fruit.y)

A: Using your initial strategy, you can still try expand grid:
fruit_df <- expand.grid(fruit,fruit)
Then sort each row by fruit and delete the duplicates:
fruit_df2 <- as.data.frame(unique(t(apply(fruit_df, 1, function(x) sort(x)))))
     V1    V2
1 Peach Peach
2 Peach  Plum
3 Peach  Pear
4  Plum  Plum
5  Pear  Plum
6  Pear  Pear

Another strategy is to generate all combination of pairs in fruit, try:
combn(fruit,2)
     [,1]    [,2]    [,3]
[1,] "Peach" "Peach" "Plum"
[2,] "Plum"  "Pear"  "Pear"

Or to make your output as a data frame, transpose the results and recast:
as.data.frame(t(combn(fruit,2)))
Note that using combn you will not get the plum-plum.


text:
Q: Is there a special way to type in icon font URLs? Mine just appear as unicodes The website is here:
http://rjdlee.com/projects/mobile/index.html
Even in my local copy, I was experiencing some issues where the font wouldn't refresh after changing it. I've checked the url it is attempting to read for the font and it appears to be right. Is there something wrong?
Here is the code:
@font-face {
    font-family: 'icons';
font-weight: normal;
    font-style: normal;
    src:url('../fonts/icons.eot?-gbp2x2');
    src:url('../fonts/icons.eot?#iefix-gbp2x2') format('embedded-opentype'),
        url('../fonts/icons.ttf?-gbp2x2') format('truetype'),
        url('../fonts/icons.woff?-gbp2x2') format('woff'),
        url('../fonts/icons.svg?-gbp2x2#icons') format('svg');
}

Here is the error:
[16:21:58.083] downloadable font: download failed (font-family: "icons" style:normal weight:normal stretch:normal src index:1): status=2147746065
source: http://rileedesign.com/projects/mobile/fonts/icons.ttf?-gbp2x2 @ http://rileedesign.com/projects/mobile/css/main.css

A: Do you have access to your .htaccess file? This can happen if certain file types are forbidden/excluded. I had the issue before and it was fixed by adding the font types as allowed, e.g.:
<FilesMatch ".*\.(js|JS|css|CSS|jpg|JPG|gif|GIF|png|PNG|swf|SWF|xsl|XSL|svg|eot|ttf|woff)$">
  Order Allow,Deny
  Allow from all
</FilesMatch>

A: Turns out the issue was with my hosting provider.


text:
Q: State of the pylab import? There is a proposal to unify, simplify and build consistency within the scipy, numpy and matplotlib namespaces so that:
from pylab import *

is equivilent to:
from scipy import *
from numpy import *
from pylab import * (although I personally think it should be from matplotlib)

It's been over 3 years since http://www.scipy.org/PyLab was first written (refer to mailling list discussion linked from that proposal http://matplotlib.1069221.n5.nabble.com/Pylab-import-error-due-to-dateutil-td39346.html)
Is there an update on progress on this or has it stalled? This question is really calling out to someone who has been following the dev mailling lists of the relevant packages numpy, scipy, matplotlib, ipython etc
[EDIT]
There is more to this than just polluting the toplevel namespace. It is about unifying the API of the four aforementioned packages and streamlining the process for scientific programming. Personally in my work, I find that if I need numpy, I always need matplotlib and I often require something from scipy.

A: It doesn't look like it has been discussed since 2009 (although the wiki page was updated a couple of months ago).
I agree with the sentiment of one of the posts in the mpl mailing list:
>>> import this
The Zen of Python, by Tim Peters
...
Namespaces are one honking great idea -- let's do more of those!

I can see the benefit of having a consistent documentation strategy between the projects, but having one monolithic namespace I am less than convinced on...
In terms of implementation, the matplotlib pylab namespace is still around on master today (and therefore will be part of the upcoming 1.2 release), so there is certainly no short term plan for this to be taken forward. I would consider getting in touch with the author of the page you are referring to to see what their plans are.
HTH


text:
Q: ElementNotVisibleException when use headless Chrome browser When I run test script in headless mode chrome browser, element link is not visible, is not able to do linkElement.click(). in head mode is everything OK. All other info are in stacktrace.
Anyone knows what to do, please?
StackTrace:

ERROR occurred: Message: element not visible
   (Session info: headless chrome=60.0.3112.90)
    (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 6.1.7601 SP1 x86_64)
  Traceback (most recent call last):
    File "C:\nik-x.py", line 148, in main
      func(nik)
    File "C:\lib\support.py", line 121, in wrapper
      raise ret
    File "C:\lib\support.py", line 108, in newFunc
      res[0] = func(*args, **kwargs)
    File "C:\testcases\nik-1003.py", line 37, in testcase
      i.click()
    File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 7
  7, in click
      self._execute(Command.CLICK_ELEMENT)
    File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 4
  93, in _execute
      return self._parent.execute(command, params)
    File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 25
  6, in execute
      self.error_handler.check_response(response)
    File "C:\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line
   194, in check_response
      raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
    (Session info: headless chrome=60.0.3112.90)
    (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 6.1.7601 SP1 x86_64)

Here is my piece of code:
icons = nik.elementLeftmenuSportIcons()
    for i in icons[:-1]:
        try:
            i.click()
HTML from testing page:
                    Futbal

A: You can do this in two ways as below.
1.Passing window size in chrome options as mentioned below(Before instantiating driver instance):
ChromeOptions options = new ChromeOptions()
options.addArguments("headless");
options.addArguments("window-size=1200,1100");
WebDriver driver = new ChromeDriver(options);

2.Set window size after instantiating chrome driver:
WebDriver webDriver= new ChromeDriver();
webDriver.manage().window().setSize(new Dimension(1200,1100));

A: I think the problem is, that the Element is really not visible in the default viewbox (600x800) of Headless Chrome.
The window size of the Headless Browser must be set as a Argument when starting chrome. I'm using javascript (I think the API looks similar under python):
var Options = require('selenium-webdriver/chrome').Options;
var options = new Options();
options.addArguments('headless');
options.addArguments('disable-gpu');
options.addArguments('window-size=1200,1100');

browser = builder.forBrowser('chrome').setChromeOptions(options).build();

Additional Info
I'm setup up the window size also by webdriver with browser.manage().window().setSize(1200,1100); But this command is not sufficient in headless chrome. In the non headless variant this is working.

A: options.addArguments('window-size=1200,1100');
Worked for me in headless chrome mode :) Thanks a lot @powerpete
Below are the complete settings for headless chrome in groovy:-
        ChromeOptions options = new ChromeOptions()
        DesiredCapabilities capabilities = DesiredCapabilities.chrome()
        options.addArguments('headless','disable-gpu','--test-type','--ignore-certificate-errors')
        options.addArguments('window-size=1200,1100');
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setCapability(ChromeOptions.CAPABILITY, options)
        driver = {new ChromeDriver(capabilities)}

A: options.AddArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36");
Adding this helped me

A: Adding this here as a reference for the future, as I faced the same problem. The problem was that the website I was trying to access banned my IP and I was using PROXY_TOOL to access it.
In Full mode, it worked fine, but in Headless mode, it showed that it was unable to find an element. So, I took a screenshot with this function before it showed that it was unable to find an element. (Python 3.9.5)
    def get_screenshot(self, filename):
    screenshot_bytes = self.driver.get_screenshot_as_png()
    with open(filename, "wb") as file:
        file.write(screenshot_bytes)

After saving the screenshot I saw that site was giving an IP blocked error. So, I used PROXY_IP="127.0.0.1", PROXY_PORT=9666 as arguments. On which PROXY_TOOL was serving the proxy access. And it worked.
options.add_argument("--proxy-server=socks5://" + str(PROXY_IP) + ":" + str(PROXY_PORT))

Use the screenshot function to see what is visible on the website in headless mode. See what kind of problem there is if the element is not visible use window size adjustment to make it visible. And adjust according. This might not be the right answer but it is directed to the same problem.

A: If changing the window size doesn't work for anyone like me, it may be that the HTML actually changes between headless mode and headed mode.
I had a similar issue, but the headless worked in FireFox and not Chrome. The Xpath for the Chrome element worked only in headed mode. I found out the HTML was changing slightly in Chrome's headless mode.
I fixed this by substituting the Xpath from the element on Chrome with the Xpath from the element on FireFox when using headless mode in Chrome.


text:
Q: Is there any option to change the videoplayer in kivy? I have a project that is built with kivy. It has one video background, one video that is over the background and the third layer of text. It works fine on windows, but when I run it on raspberry pi 4 4gb the videos are playing with 5fps.
I want to change the kivy video player(gstream) with something else.  I wish i was playing it with omxplayer inside of kivy, so I have the control over the second video size and position.
Thank you.

A: Sorry I can't make a comment yet, but I did kind of a similar integration and I managed to use omxplayer by following this guys blog. Hope that helps
https://www.codedesigner.de/articles/omxplayer-kivy-overlay/


text:
Q: Overloading and, or, not operators I would like to overload the AND, NOT and OR operators for temporal booleans, i.e., boolean that varies on time.
When declaring
CREATE OPERATOR and (
    PROCEDURE = andMov,
    LEFTARG = booleanTP,
    RIGHTARG = boolean
);

I receive the error message
ERROR:  Syntax error near or at « and »
LINE 1: CREATE OPERATOR and (
                        ^

Obviously I can rename the operator to andMov or something else, but that would be less intuitive. I am using version 9.4.1 of PostgreSQL.

A: In postgres (and in SQL in general) there are some "reserved" words that can not be "redefined". and is one of them.
Full list of reserved words: http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html


text:
Q: Problem in limits Suppose f(x) is a differentiable function and $$\lim_{x \to \infty}{f'(x)} = 0. \\ \text{If } g(x) = f(x+1) - f(x), \text{ show that } \lim_{x \to \infty}{g(x)} = 0.$$
Does anyone have any idea?

A: Hint: Apply the Mean Value Theorem to $f$ on $[x,x+1]$.


text:
Q: Several errors when running testing android application I am trying to test a simple android application from an android development book and I reached a point when running the application gets me an error message. Unfortunately app has stopped.
(When I take out setStarUpScreenText(); the application runs but the desired text does not appear.
MainActivity
package chaper.two.hello_world;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    WorldGen earth = new WorldGen("Earth", 5973, 9.78);       //Create a World Object
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStartUpWorldValues();
        setStarUpScreenText(); //when this is removed, application runs but text from object is not displayed.
    }
    protected void setStartUpWorldValues(){
        earth.setPlanetColonies(1);                      //Set Planet Colonies to one
        earth.setPlanetMilitary(1);                      //Set Planet Military Bases to on
        earth.setColonyImmigration(1000);                //Set Planet Population to 1,000
        earth.setBaseProtection(100);                    //Set  Planet Armed Forces to 100
        earth.turnForceFieldOn();                        // Turn On the Planet Forcefield
    }
    protected void setStarUpScreenText(){
        //sets up text for each View
        TextView planetNameValue = (TextView)findViewById(R.id.DataView1);
        planetNameValue.setText(earth.planetName);
        TextView planetMassValue = (TextView)findViewById(R.id.DataView2);
        planetMassValue.setText(earth.planetMass);
        TextView planetGravityValue = (TextView)findViewById(R.id.DataView3);
        planetGravityValue.setText(String.valueOf(earth.planetGravity));
        TextView planetColoniesValue = (TextView)findViewById(R.id.DataView4);
        planetColoniesValue.setText(String.valueOf(earth.planetColonies));
        TextView planetPopulationValue = (TextView)findViewById(R.id.DataView5);
        planetPopulationValue.setText(String.valueOf(earth.planetPopulation));
        TextView planetMilitaryValue = (TextView)findViewById(R.id.DataView6);
        planetMilitaryValue.setText(String.valueOf(earth.planetMilitary));
        TextView planetBasesValue = (TextView)findViewById(R.id.DataView7);
        planetBasesValue.setText(String.valueOf(earth.planetBases));
        TextView planetForceFieldValue = (TextView)findViewById(R.id.DataView8);
        planetForceFieldValue.setText(String.valueOf(earth.planetProtection));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

MainActiviy XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_name_label" />
    <TextView
        android:id="@+id/TextView2"
        android:layout_below="@+id/TextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_mass_label" />
    <TextView
        android:id="@+id/TextView3"
        android:layout_below="@+id/TextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_gravity_label" />
    <TextView
        android:id="@+id/TextView4"
        android:layout_below="@+id/TextView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_colonies_label" />
    <TextView
        android:id="@+id/TextView5"
        android:layout_below="@+id/TextView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_population_label" />
    <TextView
        android:id="@+id/TextView6"
        android:layout_below="@+id/TextView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_military_label" />
    <TextView
        android:id="@+id/TextView7"
        android:layout_below="@+id/TextView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_bases_label" />
    <TextView
        android:id="@+id/TextView8"
        android:layout_below="@+id/TextView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/planet_forcefield_label" />
    <TextView
        android:id="@+id/DataView1"
        android:layout_toRightOf="@+id/TextView1"
        android:layout_marginLeft="36dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/DataView2"
        android:layout_toRightOf="@+id/TextView2"
        android:layout_below="@+id/DataView1"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/DataView3"
        android:layout_toRightOf="@+id/TextView3"
        android:layout_below="@+id/DataView2"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/DataView4"
        android:layout_toRightOf="@+id/TextView4"
        android:layout_below="@+id/DataView3"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/DataView5"
        android:layout_toRightOf="@+id/TextView5"
        android:layout_below="@+id/DataView4"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/DataView6"
        android:layout_toRightOf="@+id/TextView6"
        android:layout_below="@+id/DataView5"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/DataView7"
        android:layout_toRightOf="@+id/TextView6"
        android:layout_below="@+id/DataView6"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/DataView8"
        android:layout_toRightOf="@+id/TextView8"
        android:layout_below="@+id/DataView7"
        android:layout_alignStart="@+id/DataView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

My logcat errors:
10-14 04:16:58.866: E/AndroidRuntime(853): FATAL EXCEPTION: main
10-14 04:16:58.866: E/AndroidRuntime(853): java.lang.RuntimeException: Unable to start activity ComponentInfo{chaper.two.hello_world/chaper.two.hello_world.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.os.Looper.loop(Looper.java:137)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.ActivityThread.main(ActivityThread.java:5103)
10-14 04:16:58.866: E/AndroidRuntime(853):  at java.lang.reflect.Method.invokeNative(Native Method)
10-14 04:16:58.866: E/AndroidRuntime(853):  at java.lang.reflect.Method.invoke(Method.java:525)
10-14 04:16:58.866: E/AndroidRuntime(853):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-14 04:16:58.866: E/AndroidRuntime(853):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-14 04:16:58.866: E/AndroidRuntime(853):  at dalvik.system.NativeStart.main(Native Method)
10-14 04:16:58.866: E/AndroidRuntime(853): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.content.res.Resources.getText(Resources.java:239)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.widget.TextView.setText(TextView.java:3837)
10-14 04:16:58.866: E/AndroidRuntime(853):  at chaper.two.hello_world.MainActivity.setStarUpScreenText(MainActivity.java:28)
10-14 04:16:58.866: E/AndroidRuntime(853):  at chaper.two.hello_world.MainActivity.onCreate(MainActivity.java:15)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.Activity.performCreate(Activity.java:5133)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-14 04:16:58.866: E/AndroidRuntime(853):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-14 04:16:58.866: E/AndroidRuntime(853):  ... 11 more

After replacing earth.planetMass with Test
10-14 16:11:03.537: W/ResourceType(827): No package identifier when getting value for resource number 0x00001755
10-14 16:11:03.546: D/AndroidRuntime(827): Shutting down VM
10-14 16:11:03.546: W/dalvikvm(827): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-14 16:11:03.556: E/AndroidRuntime(827): FATAL EXCEPTION: main
10-14 16:11:03.556: E/AndroidRuntime(827): java.lang.RuntimeException: Unable to start activity ComponentInfo{chaper.two.hello_world/chaper.two.hello_world.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.os.Looper.loop(Looper.java:137)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.ActivityThread.main(ActivityThread.java:5103)
10-14 16:11:03.556: E/AndroidRuntime(827):  at java.lang.reflect.Method.invokeNative(Native Method)
10-14 16:11:03.556: E/AndroidRuntime(827):  at java.lang.reflect.Method.invoke(Method.java:525)
10-14 16:11:03.556: E/AndroidRuntime(827):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-14 16:11:03.556: E/AndroidRuntime(827):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-14 16:11:03.556: E/AndroidRuntime(827):  at dalvik.system.NativeStart.main(Native Method)
10-14 16:11:03.556: E/AndroidRuntime(827): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.content.res.Resources.getText(Resources.java:239)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.widget.TextView.setText(TextView.java:3837)
10-14 16:11:03.556: E/AndroidRuntime(827):  at chaper.two.hello_world.MainActivity.setStarUpScreenText(MainActivity.java:29)
10-14 16:11:03.556: E/AndroidRuntime(827):  at chaper.two.hello_world.MainActivity.onCreate(MainActivity.java:15)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.Activity.performCreate(Activity.java:5133)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-14 16:11:03.556: E/AndroidRuntime(827):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-14 16:11:03.556: E/AndroidRuntime(827):  ... 11 more
10-14 16:11:16.206: I/Process(827): Sending signal. PID: 827 SIG: 9
10-14 16:11:40.146: W/ResourceType(853): No package identifier when getting value for resource number 0x00001755
10-14 16:11:40.146: D/AndroidRuntime(853): Shutting down VM
10-14 16:11:40.146: W/dalvikvm(853): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-14 16:11:40.166: E/AndroidRuntime(853): FATAL EXCEPTION: main
10-14 16:11:40.166: E/AndroidRuntime(853): java.lang.RuntimeException: Unable to start activity ComponentInfo{chaper.two.hello_world/chaper.two.hello_world.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.os.Looper.loop(Looper.java:137)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.ActivityThread.main(ActivityThread.java:5103)
10-14 16:11:40.166: E/AndroidRuntime(853):  at java.lang.reflect.Method.invokeNative(Native Method)
10-14 16:11:40.166: E/AndroidRuntime(853):  at java.lang.reflect.Method.invoke(Method.java:525)
10-14 16:11:40.166: E/AndroidRuntime(853):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-14 16:11:40.166: E/AndroidRuntime(853):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-14 16:11:40.166: E/AndroidRuntime(853):  at dalvik.system.NativeStart.main(Native Method)
10-14 16:11:40.166: E/AndroidRuntime(853): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.content.res.Resources.getText(Resources.java:239)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.widget.TextView.setText(TextView.java:3837)
10-14 16:11:40.166: E/AndroidRuntime(853):  at chaper.two.hello_world.MainActivity.setStarUpScreenText(MainActivity.java:29)
10-14 16:11:40.166: E/AndroidRuntime(853):  at chaper.two.hello_world.MainActivity.onCreate(MainActivity.java:15)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.Activity.performCreate(Activity.java:5133)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-14 16:11:40.166: E/AndroidRuntime(853):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-14 16:11:40.166: E/AndroidRuntime(853):  ... 11 more
10-14 16:17:27.547: W/ResourceType(941): No package identifier when getting value for resource number 0x00001755
10-14 16:17:27.547: D/AndroidRuntime(941): Shutting down VM
10-14 16:17:27.547: W/dalvikvm(941): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-14 16:17:27.566: E/AndroidRuntime(941): FATAL EXCEPTION: main
10-14 16:17:27.566: E/AndroidRuntime(941): java.lang.RuntimeException: Unable to start activity ComponentInfo{chaper.two.hello_world/chaper.two.hello_world.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.os.Looper.loop(Looper.java:137)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.ActivityThread.main(ActivityThread.java:5103)
10-14 16:17:27.566: E/AndroidRuntime(941):  at java.lang.reflect.Method.invokeNative(Native Method)
10-14 16:17:27.566: E/AndroidRuntime(941):  at java.lang.reflect.Method.invoke(Method.java:525)
10-14 16:17:27.566: E/AndroidRuntime(941):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-14 16:17:27.566: E/AndroidRuntime(941):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-14 16:17:27.566: E/AndroidRuntime(941):  at dalvik.system.NativeStart.main(Native Method)
10-14 16:17:27.566: E/AndroidRuntime(941): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1755
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.content.res.Resources.getText(Resources.java:239)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.widget.TextView.setText(TextView.java:3837)
10-14 16:17:27.566: E/AndroidRuntime(941):  at chaper.two.hello_world.MainActivity.setStarUpScreenText(MainActivity.java:29)
10-14 16:17:27.566: E/AndroidRuntime(941):  at chaper.two.hello_world.MainActivity.onCreate(MainActivity.java:15)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.Activity.performCreate(Activity.java:5133)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-14 16:17:27.566: E/AndroidRuntime(941):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-14 16:17:27.566: E/AndroidRuntime(941):  ... 11 more
10-14 16:17:33.606: I/Process(941): Sending signal. PID: 941 SIG: 9

A: According to LogCat, you are missing the refered string resource:
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1755

In line 28
at chaper.two.hello_world.MainActivity.setStarUpScreenText(MainActivity.java:28)

Wich would be this line:
planetMassValue.setText(earth.planetMass);

It seems that your res/values/strings.xml is missing the string that the atribute planetMass, from the object earth, of class WorldGen is pointing to.
In case the string is there, and you are referring to it correctly, there might be some problem with the R file. So just do a Project -> Clean, so that R file gets rebuilt.


text:
Q: In Bash, what is the string replacement pattern to remove any number of leading hyphens? This strips out any number of the leading hyphens:
§ echo '--nom-nom' | perl -pe 's|^-+||'
nom-nom

What should the replacement pattern look like if I want to use bash string replacement to do the same? This does not work:
§ a=--nom-nom; a="${a/^-+/}"; echo $a
--nom-nom

Replacing all hyphens works, but that is not what I want:
§ a=--nom-nom; a="${a//-/}"; echo $a
nomnom

A: You can capture what you want vs eliminate what you don't want with a Bash regex:
$ s='--nom-nom'
$ [[ $s =~ ^-*(.*) ]] && echo ${BASH_REMATCH[1]}
nom-nom

A: If shell option extglob is set, you can use an extended pattern
$ shopt -s extglob
$ a=--nom-nom; a="${a##*(-)}"; echo $a
nom-nom

If you don't want to always enable extglob, you can use a subshell to temporarily set it:
$ shopt -u extglob
$ a=--nom-nom; a=$(shopt -s extglob; echo "${a##*(-)}"); echo $a

${var##*(-)} uses the "remove longest matching prefix" replacement. You could also use ${var/#*(-)/}; in this context, the # forces the match to be initial. In both cases, *(pattern) means "nothing or any number of repetitions of 'pattern'", similar to regex syntax except that the * comes first and the parentheses are required.
If you want to use regular expressions, you can use the expr command:
$ expr "$a" : '-*\(.*\)'
nom-nom

Note that this is not a bash built-in. But it is required by Posix. It always uses Posix Basic Regular Expressions, which is why the capture parentheses need to be backslashed. (As noted in the documentation, it is expected that there will be precisely one capture group in the regex.)


text:
Q: Image only appears when selected on canvas Fabric JS I am trying to add image on canvas with fabric JS , but the image only appears when clicked or selected its surrounding area which is group object.
The image is supposed to show up immediately when the page finish loading.
Here is the snippet for the source code. Any help would be appreciated.

const canvas = new fabric.Canvas('canvas', {
  selection: false
});

const circle = new fabric.Circle({
  left: 100,
  top: 100,
  radius: 50,
  fill: '#eef',
  originX: 'center',
  originY: 'center'
});

const text = new fabric.Text('Hello World', {
    left: circle.left,
    top: circle.top,
    fontFamily: 'Arial',
    fontWeight: 'bold',
    fontSize: 10,
    fill: 'black',
    originX: 'center',
    originY: 'center',
});

const group = new fabric.Group([circle, text], {
    left: circle.left,
    top: circle.top,
    originX: 'center',
    originY: 'center'
});

canvas.add(group);

fabric.Image.fromURL('http://placekitten.com/200/300', function (img) {

    canvas.add(img.set({
          left: group.left + 20,
          top: group.top,
          perPixelTargetFind: true,
          padding: 0,
          hasBorders: false,
          hasControls: false,
          width: 16,
          height: 16,
          originX: 'center',
          originY: 'center',
      }));

    img.on('click', function () {
        console.log('img clicked');
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
<canvas id="canvas" width="500" height="300" style="border: 2px solid green;"></canvas>

A: You need to use mousedown event not click. And use crossOrigin property for image object, if you are loading from another server.
DEMO

const canvas = new fabric.Canvas('canvas', {
  selection: false
});

const circle = new fabric.Circle({
  left: 100,
  top: 100,
  radius: 50,
  fill: '#eef',
  originX: 'center',
  originY: 'center'
});

const text = new fabric.Text('Hello World', {
  left: circle.left,
  top: circle.top,
  fontFamily: 'Arial',
  fontWeight: 'bold',
  fontSize: 10,
  fill: 'black',
  originX: 'center',
  originY: 'center',
});

const group = new fabric.Group([circle, text], {
  left: circle.left,
  top: circle.top,
  originX: 'center',
  originY: 'center'
});

canvas.add(group);

fabric.Image.fromURL('http://placekitten.com/200/300', function(img) {
  img.set({
    left: group.left + 20,
    top: group.top,
    perPixelTargetFind: true,
    padding: 0,
    hasBorders: false,
    hasControls: false,
    width: 16,
    height: 16,
    originX: 'center',
    originY: 'center',
  })
  canvas.add(img);

  img.on('mousedown', function() {
    console.log('img clicked');
  });

}, {
  crossOrigin: 'annonymous'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
<canvas id="canvas" width="500" height="300" style="border: 2px solid green;"></canvas>

A:

const canvas = new fabric.Canvas('canvas', {
  selection: false
});

const circle = new fabric.Circle({
  left: 100,
  top: 100,
  radius: 50,
  fill: '#eef',
  originX: 'center',
  originY: 'center'
});

const text = new fabric.Text('Hello World', {
    left: circle.left,
    top: circle.top,
    fontFamily: 'Arial',
    fontWeight: 'bold',
    fontSize: 10,
    fill: 'black',
    originX: 'center',
    originY: 'center',
});

const group = new fabric.Group([circle, text], {
    left: circle.left,
    top: circle.top,
    originX: 'center',
    originY: 'center'
});

canvas.add(group);

fabric.Image.fromURL('http://placekitten.com/200/300', function (img) {

    canvas.add(img.set({
          left: group.left + 20,
          top: group.top,
          perPixelTargetFind: true,
          padding: 0,
          hasBorders: false,
          hasControls: false,
          width: 16,
          height: 16,
          originX: 'center',
          originY: 'center',
      }));

/* will not work - use mousedown or you should use events provided by fabric
    img.on('click', function () {
        console.log('img clicked');
    });
*/
// use this option if you want to load image from other domain
}, {crossOrigin: 'anonymous'});

const mouseDownHandler = (e) => {
console.log('mouseDownHandler: yep! someone clicked on canvas');
if(e.target && e .target.type === "image") console.log('mouseDownHandler: and smashed image!');
}

const selectionCreatedHandler = (e) => {
if(e.target && e .target.type === "image") console.log('selectionCreatedHandler: yep! someone selected image')
}

const selectionUpdatedHandler = (e) => {
if(e.target && e .target.type === "image") console.log('selectionUpdatedHandler: yep! someone selected object instead of previously selected')
}

canvas.on('selection:created', selectionCreatedHandler);
canvas.on('selection:updated', selectionUpdatedHandler);
canvas.on('mouse:down', mouseDownHandler);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
<canvas id="canvas" width="500" height="300" style="border: 2px solid green;"></canvas>