text:
Q: How can I know the row of char/string in a CSV file For example, I have a CSV file:
1 ,2 ,3 ,4
5 ,6 ,7 ,8
a ,b ,c ,d
e ,f ,g ,h

and I want to know which row contains the char 'c'.
How can I know it?
i
below its my code
FILE* srcFile = fopen(argv[ONE], "r");

char str[MAX_LETTERS] = { 0 };
char letter = ' ';
char copy = ZERO;
int count = 1;

fgets(str, MAX_LETTERS, stdin);
str[strcspn(str, "\n")] == ZERO;
copy = fgetc(srcFile);
while (copy != EOF)
{
    if (copy == str)
    {
        printf("find %d", count);
        break;
    }
    else if (copy == "\n")
    {
        printf("nextLine");
        count++;
    }
    copy = fgetc(srcFile);
}

A: Assuming that you are reading the file line by line, you could just create a counter and for every line read in increment the counter by one. If you are reading in character by character you can count the number of newlines.

A: The double equals signs == in C are used for comparison, a single equals sign is for assignment.
It appears the line,
str[strcspn(str, "\n")] == ZERO;
is doing a comparison instead of setting the character at the given index of the str array to ZERO.
Change this to a single equals sign if you are trying to terminate your string at the newline character.


text:
Q: Validation in php for dropdown menu I have a html form which has 20 dropdown field generated by the function as below....
<?php
      $sub_1 = subject_show (subject_1, $scl_unique_id, $cls_sec_bat);
      if ($sub_1)
      {?>

        <?php echo $sub_1;?>
        <select name="subject_1" id="subject_1" style="min-width:100px">
          <?php
          if(isset($subject_1)){?>
          <option value="<?php echo $subject_1; ?>" selected="selected"><?php echo $subject_1; ?></option>
          <?php }else{ ?>
          <option value="<?php echo $sub_1;?>" disabled="disabled" selected="selected"><?php echo $sub_1;?></option>
          <?php } ?>
          <option value="<?php echo MAR_ABS;?>"><?php echo MAR_ABS;?></option>
          <option value="<?php echo MAR_NA;?>"><?php echo MAR_NA;?></option>
          <?php
          for ($i=0; $i<=100; $i++)
          {
            echo '<option value="'.$i.'">'.$i.'</option>';
          }
          ?>
          </select>

     <?php
      }
      ?>

In the code, if the function has the value on $sub_1 then the drop down field printed on html output with a name subject_1. If not it will not printed.
The same code I have 20 times. If the function has value in $sub_2 or $sub_3 or $sub_4 till $sub_20 the field printed with a name as subject_2 or subject_3 or subject_4 till subject_20.
Any dropdown field can be printed depending on the userinput and function output.
When the reading time, I am reading all the 20 names like
if (isset($_POST['save_exit']))
    {
        $roll_number = strtoupper(trim(implode(' ', preg_split('/\s+/', $_POST["roll_number"]))));
        $subject_1 = $_POST["subject_1"];
        $subject_2 = $_POST["subject_2"];
        $subject_3 = $_POST["subject_3"];
        $subject_4 = $_POST["subject_4"];
        $subject_5 = $_POST["subject_5"];
        $subject_6 = $_POST["subject_6"];
        $subject_7 = $_POST["subject_7"];
        $subject_8 = $_POST["subject_8"];
        $subject_9 = $_POST["subject_9"];
        $subject_10 = $_POST["subject_10"];
        $subject_11 = $_POST["subject_11"];
        $subject_12 = $_POST["subject_12"];
        $subject_13 = $_POST["subject_13"];
        $subject_14 = $_POST["subject_14"];
        $subject_15 = $_POST["subject_15"];
        $subject_16 = $_POST["subject_16"];
        $subject_17 = $_POST["subject_17"];
        $subject_18 = $_POST["subject_18"];
        $subject_19 = $_POST["subject_19"];
        $subject_20 = $_POST["subject_20"];

I dont want user to submit empty dropdown list so I am wrinting validation as
if(empty(subject_1))
{
say error
}

if(empty(subject_2))
{
say error
}

I am wrting this 20 times for all subject.
The problem is when the user has only three subject with a name like subject_1 and subject_2 and subject_3 in the forum. It will give the error for all the remaining 17 subjects.
How can I read validate only the subjects available on the form??
Please let me know if its not clear.

A: you can do it in less code like the following
for ($i=1;$i<=20;$i++){
    $var = "subject_$i";
    if (isset($$var) && empty($$var)){echo "error";}
}

If you don't need all those $subject_ variables you can directly validate $_POST
for ($i=1;$i<=20;$i++){
    if (isset($_POST["subject_$i"]) && empty($_POST["subject_$i"])){echo "error";}
}

A: Try posting the subjects as an array to your form handler.
Then, you can check easily:
if (count($subject) < $_POST['numberNeeded']) {
   // say error
}

In $subject[0] you'd find the first subject, $subject[1] would contain the second, etc.
In your form:
<select name="subject[]" id="subject_1" style="min-width:100px">

</select>
<select name="subject[]" id="subject_2" ...

Below, add the following field (calculated using php). In this example, let's assume you'd need 5 subjects.
<input type="hidden" name="numberNeeded" value="5" />

As an added remark: you might also want to consider JavaScript validation as a plus...

redpajama_set_name: RedPajamaStackExchange


text:
Q: No bootloader menu after attempting to install Ubuntu alongside Windows 7 I wanted to use Ubuntu alongside my Windows 7, so I installed it from a USB. During installation, it didn't detect my existing Windows. So, I chose "Something Else". From there, I formatted a drive with settings:
Size: 20 Gb
type: primary partition,
file system: ext4.
and mount point: ""
Then I allocated 4GB extra for "swap".
Then I installed Ubuntu and it completed smoothly. Then it asked me to reboot. After rebooting, I was expecting a menu to choose between Linux and Windows, but I didn't get any menu at all. My Windows booted normally.
What do I need to configure to get my dual boot system working?

A: Don't worry. This happened to me when I installed Ubuntu myself. the "menu" you're talking about is called a "bootloader". The "windows boot loader" does not detect anything but windows. That's why Ubuntu should install "grub" which detects Ubuntu and will detect windows.
Now to install grub you need the Ubuntu live usb again. Boot the computer from it
...then you have two options; one is getting a program from the internet that does the whole trick. It's called boot repair. It's the easy choice. You can follow the link commented by vivid_vibe Windows 7 and Ubuntu 13.04 dual boot, GRUB menu not showing
or if for example you have trouble connecting to the internet then there are a set of instructions that you can do manually from a terminal to fix the problem but it's not as easy as the program . Here's how to do it How can I repair grub? (How to get Ubuntu back after installing Windows?)
feed me back

A: Boot from the USB again into Ubuntu and follow the instructions below:
Open Terminal, and type:
sudo mount /dev/sdX /mnt

sudo mount --bind /dev /mnt/dev && sudo mount --bind /dev/pts /mnt/dev/pts && sudo mount --bind /proc /mnt/proc && sudo mount --bind /sys /mnt/sys
sudo chroot /mnt
grub-install /dev/sdX
grub-install --recheck /dev/sdX
update-grub
exit && sudo umount /mnt/dev && sudo umount /mnt/dev/pts && sudo umount /mnt/proc && sudo umount /mnt/sys && sudo umount /mnt

Where /dev/sdX is your partition, like /dev/sda or /dev/sdb.


text:
Q: TableView cell on iPad refusing to accept clear color I am using a github project called SWTableViewCell.h by Chris Wendel. On the iPhone, clear color works. However, on an iPad it refuses to make the tableview cell clear. Instead, it makes it white. I have been wracking my brain how to fix this but cannot. I have even tried to set the background based on a png, but it just will not work. What types of alternatives can I go about to solve this?

A: In the documentation for the project on GitHub, there is a method:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Set background color of cell here if you don't want default white
}

Change it to this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor clearColor]];
}


text:
Q: US/Imperial units with Java's Units of Measurement API I'm only seeing metric units in the Indriya 2.0.4 reference implementation of the Java Units of Measurement standard. Surely other people have wanted to work with feet, inches, and miles, but I can't find anything about that. Can anyone tell me what I'm missing here?
I can do Quantity<Mass> weight = Quantities.getQuantity(1, Units.KILOGRAM);, so where is Quantity<Mass> weight = Quantities.getQuantity(1, Units.POUND);?

A: For measurements which are wider than just SI units, you can use some of the other APIs in the Units of Measurement project (which includes the indriya API).
Specifically, the CLDR and USCustomary classes may be of interest. However, I have not had success combining units from different classes, e.g. for conversions (see the commented-out code below).
Some examples:
import javax.measure.Quantity;
import javax.measure.quantity.Length;
import javax.measure.quantity.Mass;

import systems.uom.unicode.CLDR;
import systems.uom.common.USCustomary;

import tec.units.ri.quantity.Quantities;
import tec.units.ri.unit.Units;

...

Quantity<Mass> weight1 = Quantities.getQuantity(1, Units.KILOGRAM);
Quantity<Mass> weight2 = Quantities.getQuantity(1, USCustomary.POUND);

// javax.measure.IncommensurableException: kg is not compatible with lb
//Double d2 = Units.KILOGRAM.getConverterTo(CLDR.POUND).convert(1);

Quantity<Mass> weight3 = Quantities.getQuantity(123.45, CLDR.GRAM);
Quantity<Mass> weight4 = Quantities.getQuantity(123.45, CLDR.OUNCE);
Quantity<Mass> weight5 = Quantities.getQuantity(123.45, CLDR.OUNCE_TROY);

Double ounces = CLDR.GRAM.getConverterTo(CLDR.OUNCE)
        .convert(weight3.getValue()).doubleValue();
System.out.println(weight3.getValue() + " grams = " + ounces + " ounces");

Quantity<Length> dist1 = Quantities.getQuantity(123.45, CLDR.KILOMETER);
Double miles = CLDR.KILOMETER.getConverterTo(CLDR.MILE)
        .convert(dist1.getValue()).doubleValue();
System.out.println(dist1.getValue() + " kilometers = " + miles + " miles");

The outputs from the above examples are:
123.45 grams = 4.354570602675702 ounces
123.45 kilometers = 76.70827368169888 miles

My POM dependencies for this are:
<dependencies>
    <dependency>
        <groupId>javax.measure</groupId>
        <artifactId>unit-api</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
        <groupId>tec.units</groupId>
        <artifactId>unit-ri</artifactId>
        <version>1.0.3</version>
    </dependency>
    <dependency>
        <groupId>systems.uom</groupId>
        <artifactId>systems-unicode</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>systems.uom</groupId>
        <artifactId>systems-common</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>systems.uom</groupId>
        <artifactId>systems-quantity</artifactId>
        <version>2.0.2</version>
    </dependency>
</dependencies>


text:
Q: How does one reduce the Maximum Likelihood rule to a pairwise comparison of the probability densities? I am studying an article, where the authors have discussed something about "the ML decision rule reducing to a pairwise comparison of the conditional PDFs" because the means and variances are in ascending order.
To remove confusion, I am attaching a screengrab. As you can see, they use condition (11) to invoke the pairwise comparison of the PDFs in (12). I have checked the reference that they cited, that is, [31], but I did not find anything related to that discussion.
Why are the PDFs equal?
Could anyone explain how this works?
I'm not sure if I'm asking the right questions here, feel free to direct me towards the right questions.

A: The distributions in (12) are equal because the decision thresholds $\eta_1, \dots, \eta_{M-1}$ are chosen to make them equal.
Consider a simple case, where you have two distributions and you want to assign an observation to one of them.  If your decision rule is, essentially, "assign the observation to whichever distribution is most likely to have generated it", clearly you will choose the one with the highest probability density at the observed value.   The decision threshold will be the value at which the two probability densities are equal; observations that fall below the threshold will be assigned to one distribution, and those that fall above the threshold will be assigned to the other.

In this case, the two distributions are equal at the value $-0.0636$, which becomes the decision threshold.  Equation (12) is simply a mathematical expression of this relationship between the decision thresholds and the distribution values at those thresholds, extended to more than two distributions.  To the left of the threshold, the observation is more likely to have come from the black distribution, so we would assign it to that one, and similarly for an observation to the right of the threshold.  At the threshold, the likelihood that an observation comes from the black distribution is equal to the likelihood that it comes from the blue distribution, so it doesn't matter - mathematically - which one we assign it to.


text:
Q: Fake Stack Overflow in Google Search I came across a fake/scraped version of Stack Overflow when Googling.
Here's a link (BE CAREFUL)
At first I thought it was just rogue Javascript popup ads that you guys might want to hear about but then my colleague pointed out that the site wasn't actually legitimate.
I've reported the site to Google is there anything else I should do?
It looks like it's scraping the real site as some of the results in the background are releveant to my original query, or is that just a coincidence?
EDIT:
After further navigating the site it looks like the real site with adverts on the top of it.


text:
Q: keypad function return wrong number in ScanKey function which is for keypad 3*4 its work well until numbers length under 4
it works like this number = (number * 10) but for a number like this 123456 which have more than 4 number it gives me other numbers what should I do? my program works with an int that's I use integer.
when I enter a number like 555555 it changes to 31267.
IDE CodeVisionAVR
C language for ATmega16a
struct User
{
    unsigned long int username;
    unsigned long int password;
    bool role;
};

unsigned long int username;
unsigned long int password;

 do
            {
                lcd_clear();
                lcd_putsf("Enter Username:");
                lcd_gotoxy(0, 1);
                sprintf(show, "%d", username);
                lcd_puts(show);
                lcd_gotoxy(0, 2);
                lcd_putsf("Enter Password:");
                lcd_gotoxy(0, 3);
                password = ScanKey();
                if (!password)
                {
                    break;
                }
                else if (password / 10 < 10)
                {
                    PORTC .1 = 1;
                    lcd_clear();
                    lcd_putsf("At least 3 numbers !");
                    delay_ms(150);
                    PORTC .1 = 0;
                }
            } while (password / 10 < 10);

        if (username && password)
        {
            user[UL].role = false;
            lcd_clear();
            if (currentUser < 0 && !currentUser)
            {
                lcd_putsf("Promote to admin ? ");
                lcd_gotoxy(0, 1);
                lcd_putsf("Yes press 1");
                lcd_gotoxy(0, 2);
                lcd_putsf("No press 2");
                if (ScanKey() == 1)
                {
                    user[UL].role = true;
                }
                lcd_gotoxy(0, 3);
            }
            user[UL].username = username;
            user[UL].password = password;
            UL++;
            PORTC .0 = 1;
            lcd_putsf("User added !!");
            delay_ms(150);
            PORTC .0 = 0;
        }

unsigned long int ScanKey(void)
{
    unsigned long int num = 0;
    _lcd_write_data(0x0F);
    PORTC .2 = 1;
    while (1)
    {
        PORTD .0 = 0;
        PORTD .1 = 1;
        PORTD .2 = 1;
        delay_ms(5);
        if (PIND .3 == 0)
        {
            while (PIND .3 == 0)
                ;
            lcd_putchar('1');
            num = (num * 10) + 1;
        }
        else if (PIND .4 == 0)
        {
            while (PIND .4 == 0)
                ;
            lcd_putchar('4');
            num = (num * 10) + 4;
        }
        else if (PIND .5 == 0)
        {
            while (PIND .5 == 0)
                ;
            lcd_putchar('7');
            num = (num * 10) + 7;
        }
        else if (PIND .6 == 0)
        {
            while (PIND .6 == 0)
                ;
            _lcd_write_data(0x10);
            lcd_putchar(' ');
            _lcd_write_data(0x10);
            num /= 10;
        }

        PORTD .0 = 1;
        PORTD .1 = 0;
        PORTD .2 = 1;
        delay_ms(5);
        if (PIND .3 == 0)
        {
            while (PIND .3 == 0)
                ;
            lcd_putchar('2');
            num = (num * 10) + 2;
        }
        else if (PIND .4 == 0)
        {
            while (PIND .4 == 0)
                ;
            lcd_putchar('5');
            num = (num * 10) + 5;
        }
        else if (PIND .5 == 0)
        {
            while (PIND .5 == 0)
                ;
            lcd_putchar('8');
            num = (num * 10) + 8;
        }
        else if (PIND .6 == 0)
        {
            while (PIND .6 == 0)
                ;
            lcd_putchar('0');
            num = (num * 10) + 0;
        }

        PORTD .0 = 1;
        PORTD .1 = 1;
        PORTD .2 = 0;
        delay_ms(5);
        if (PIND .3 == 0)
        {
            while (PIND .3 == 0)
                ;
            lcd_putchar('3');
            num = (num * 10) + 3;
        }
        else if (PIND .4 == 0)
        {
            while (PIND .4 == 0)
                ;
            lcd_putchar('6');
            num = (num * 10) + 6;
        }
        else if (PIND .5 == 0)
        {
            while (PIND .5 == 0)
                ;
            lcd_putchar('9');
            num = (num * 10) + 9;
        }
        else if (PIND .6 == 0)
        {
            while (PIND .6 == 0)
                ;
            break;
        }
    }
    PORTC .2 = 0;
    _lcd_write_data(0x0C);
    return num;
}```


text:
Q: Pass data from Bean to javascript on jsf page. Google api directions I need to pass waypoints to google maps javascript directions api from ManagedBean to jsf page.
I'm trying to make JSONArray and pass it to jsf:
private JSONArray routesJSON;

with getters and setters.
Than im creating JSON : in loop im adding Strings with LatLang of waypoints to List<String>
routes.add("new google.maps.LatLng(" + o.getLatitude() + "," + o.getLongitude()+")");

And im getting JSON :
[{"location":"new google.maps.LatLng(50.495121,22.1705)"},{"location":"new google.maps.LatLng(50.57082,22.06813)"},{"location":"new google.maps.LatLng(50.570549,22.047871)"},{"location":"new google.maps.LatLng(50.521389,21.912695)"},{"location":"new google.maps.LatLng(50.495121,22.1705)"}]

from:
for()
array.put(obj);
}
System.out.println(array);

in JSF function for displaying route : (it works with hardcoded data)
function calcRoute() {

              var waypts = [];
              var start = new google.maps.LatLng(#{someBean.startLatitude}, #{someBean.startLongitude});
              var end = new google.maps.LatLng(49.712112, 21.50667);
              var way = #{someBean.routesJSON};
              var request = {
              origin:start,
              destination:end,
              optimizeWaypoints: true,
              waypoints:way;
              travelMode: google.maps.TravelMode.DRIVING
              };
              directionsService.route(request, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(result);
                }
              });
            }

But when im displaying that page map doesnt appear. I know it's probably because of " in JSON but i dont know how to remove it. Or may there are easiest ways to pass waypoint data from Bean to jsf page?

A: Instead of returning a JSON data packet that contains javascript statements like "new google.maps.LatLng(50.495121,22.1705)", it's more sensible to return just the coordinates.
So if you had a JSON packet that looks like this in your javascript (I don't know how to pass data between your Java and Javascript):
var routes = [
  {"lat":"50.495121", "lng":"22.1705"},
  {"lat":"50.57082", "lng":"22.06813"},
  {"lat":"50.570549", "lng":"22.047871"},
  {"lat":"50.521389", "lng":"21.912695"},
  {"lat":"50.495121", "lng":"22.1705"}
]

You can turn this into an array like so:
var way = [];
for (var i = 0; i < routes.length; i++) {
  way.push(new google.maps.LatLng(parseFloat(routes[i].lat), parseFloat(routes[i].lng)));
}

NB: the use of parseFloat to convert strings like "50.495121" into floating point numbers.


text:
Q: Centering Floating Action Button in navigation bar Flutter I have created a navigation bar in flutter, now I want to add a button in between the navbar icons as shown in this image.
I want this
But I am getting this. I am getting this
I brought the button in the middle with following code:
floatingActionButton: FloatingActionButton(
  onPressed: () {},
  child: const Icon(PhosphorIcons.plusLight,color: navBarColor),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,

Is there any way to bring it in the middle of the navbar?
If there is a there is a way to give circle background color to a navbar destination, then it would be better.

A: Try adding an alignment to the fab
floatingActionButtonLocation:
              FloatingActionButtonLocation.centerDocked,
          floatingActionButton: Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              padding: const EdgeInsets.only(bottom: 6.0),

              child:  FloatingActionButton(
                onPressed: () {},

                child: Icon(Icons.add),
              ),
            ),
          ),

A: floatingActionButton: Stack( [ Position( bottom: -20, FloatingActionButton( onPressed: () {}, child: const Icon(PhosphorIcons.plusLight,color: navBarColor), ) ) ]), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,

A: Do not use a FloatingActionButton with a navbar like that. Just add the + action as another button in the middle of the navbar.


text:
Q: How to get the last event fired on ExtJs I'm trying to create a costume Error handler. So far I'm able to retrieve the errors triggered by the system with the following code:
window.onerror = function(message, source, lineno, colno, error) {
             me.errorHandler(error, true);
             return true;
        };

My problem is: I would love to specify what kind of event or action triggered my error.
Is there any way to find out what Events/Listeners/Actions were triggered? Something like using Ext.util.Observable

A: I've found my solution.
Its something like this;
    //object is the main Page/Menu that i want to "Observate"
    Ext.util.Observable.capture(object, function(){
        //arguments have the listener, page and component
        doStuff(arguments)
        });

Doing this, every time an event is fired on the "object" this function will be triggered, and i can log the error or the event fired.


text:
Q: Spring boot Enity failed to add entity with ManyToOne I have these entities in my learning project and I could not figure out why I am not able to add an Employee:
@Entity
@Table(name = "department")
@Data
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "department_id")
    @JsonProperty("department_id")
    private Long department_id;

    @Column(name = "department_name")
    @JsonProperty("department_name")
    private String department_name;
}

@Entity
@Table(name = "office")
@Data
public class Office {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "office_id")
    @JsonProperty("office_id")
    private Long office_id;

    @Column(name = "office_name")
    @JsonProperty("office_name")
    private String office_name;
}

@Entity
@Table(name = "employee")
@Data
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "employee_id")
    @JsonProperty("employee_id")
    private Long employee_id;

    @Column(name = "employee_name")
    @JsonProperty("employee_name")
    private String employee_name;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "department_id")
    private Department department;

    private Long office_id;
}

Using Postman, I send a POST to add an employee in department 'engineer' using the http://localhost:9096/employee endpoint generated by Spring Data REST with the following JSON body:
{
    "employee_name": "Tim",
    "office_id" : 1,
    "department": {
        "department_id": 1
    }
}

I always get an exception: "Column 'department_id' cannot be null".
What should be the correct way to solve this problem?
the complete project can be found at https://github.com/txt8888/sping-mysql-db

A: I'm not sure if Spring Data REST supports embedding the department like that (by using { "department_id": 1 }. By default, if you want to link a resource (eg. a department) to another (eg. an employee), you use the resource link, for example:
{
    "employee_name": "Tim",
    "office_id" : 1,
    "department": "http://localhost:9096/departments/1"
}

This will create a new employee linked to the department with ID 1. If you want to link the employee to a new department, you likely will have to create the department first, and link it to the employee in the same manner.

A: Seems the department_id doesn't exist in your database or your ManyToOne configuration is not properly. So it causes that errors. You can refer to this ManyToOne relationship below
@Entity
@Table(name = "course")
public class Course  implements Serializable{

    private int id;
    private Set<Student> students;

    public Course(){

    }
    @OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
    public Set<Student> getStudents() {
        return students;
    }
}

@Entity
public class Student implements Serializable{
    private int id;
    private Course course;

    public Student() {

    }

    @ManyToOne
    @JoinColumn(name = "course_id")
    public Course getCourse() {
        return course;
    }
}

You can check the working example from the post Spring Boot JPA One to Many Relationship Mapping


text:
Q: Highcharts line charts not displaying all the dates I have a line chart that displays the data from a Google Spreadsheet, the datetime data is being updated every 3 to 4 seconds and I want the chart to only display some of it, like the hour for example. I can't use any of the highstocks funcionalities because it doesn't support the Google Spreadsheet service, at least that I know and feeding the CSV or JSON to highchart doesnt update automatically. Again, as far as I know.
So I'm stuck with Highcharts line chart, but I dont want the X axis to look so crowded. Take a look at the fiddle. http://jsfiddle.net/AYYCv/167/light/  And there's only little data.
Highcharts.setOptions({
chart: {
    zoomType: 'x'
},
plotOptions: {
    series: {
        visible: false,
    }

},
    legend: {
    enabled: true,
    align: 'right',
    backgroundColor: '#FFFFFF',
    borderColor: 'white',
    borderWidth: 2,
    layout: 'vertical',
    verticalAlign: 'top',
    y: 100,
},
title: {
    text: 'Produccion de Energía Solar'
},
xAxis: {
    type: 'datetime'
},
yAxis: {
    title: {
        text: 'Magnitud'
    }
}

});
$('#container4').highcharts({
data: {
    googleSpreadsheetKey: '0Aj8kPfvDA7mOdHpVMDVFbktmM0E4YjFIUkVUVC1RYlE'
},
plotOptions: {
    series: {
        visible: false
    }
}
 function(chart) {
chart.series[0].show();
});`

A: You can increase tickInterval parameter

A: Change the XAxis like this... It will rotate labels to specified degrees
xAxis: {
    type: 'datetime', labels:{rotation: -40}
  },

Thisl link helps for date formating
http://api.highcharts.com/highstock#xAxis.dateTimeLabelFormats


text:
Q: Is private method in spring service implement class thread safe I got a service in an project using Spring framework.
public class MyServiceImpl implements IMyService {
    public MyObject foo(SomeObject obj) {
       MyObject myobj = this.mapToMyObject(obj);
       myobj.setLastUpdatedDate(new Date());
       return myobj;
    }

    private MyObject mapToMyObject(SomeObject obj){
       MyObject myojb = new MyObject();
       ConvertUtils.register(new MyNullConvertor(), String.class);
       ConvertUtils.register(new StringConvertorForDateType(), Date.class);
       BeanUtils.copyProperties(myojb , obj);
       ConvertUtils.deregister(Date.class);
       return myojb;
    }
}

Then I got a class to call foo() in multi-thread;
There goes the problem. In some of the threads, I got error when calling
BeanUtils.copyProperties(myojb , obj);
saying Cannot invoke com.my.MyObject.setStartDate - java.lang.ClassCastException@2da93171
obviously, this is caused by ConvertUtils.deregister(Date.class) which is supposed to be called after BeanUtils.copyProperties(myojb , obj);.
It looks like one of the threads deregistered the Date class out while another thread was just about to call BeanUtils.copyProperties(myojb , obj);.
So My question is how do I make the private  method mapToMyObject() thread safe?
Or simply make the BeanUtils thread safe when it's used in a private method.
And will the problem still be there if I keep the code this way but instead I call this foo() method in sevlet? If many sevlets call at the same time, would this be a multi-thread case as well?

A: Edit: Removed synchronized keyword since it is not neccessary, see comments below.
Instead of using the static methods in the BeanUtils class, use a private BeanUtilsBean instance (http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtilsBean.html). This way, you don't need to register/deregister your converters each time the method is called.
public class MyServiceImpl implements IMyService {
    private final BeanUtilsBean beanUtilsBean = createBeanUtilsBean();

    private static BeanUtilsBean createBeanUtilsBean() {
        ConvertUtilsBean convertUtilsBean = new ConvertUtils();
        convertUtilsBean.register(new MyNullConvertor(), String.class);
        convertUtilsBean.register(new StringConvertorForDateType(), Date.class);
        BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean);
        return beanUtilsBean;
    }

    public MyObject foo(SomeObject obj) {
       MyObject myobj = this.mapToMyObject(obj);
       myobj.setLastUpdatedDate(new Date());
       return myobj;
    }

    private MyObject mapToMyObject(SomeObject obj){
        MyObject myojb = new MyObject();
        beanUtilsBean.copyProperties(myojb , obj);
        return myojb;
    }
}

A: add a synchonized block to the sensitive portion of your code or synchronize the method:
http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html


text:
Q: Load files and then call a call back function In my project, I am loading some js and css files by default in index.html file. But I need to load some other js/css files using javascript later (dynamically) and then after those dynamic files are loaded successfully, I need to call a callback function.
I checked jQuery.getScript(), which is calling callback function after each file is loaded but not all files are loaded.
I tried this:
function loadFiles(payload, callbackFunc) {
    var head = document.head || document.getElementsByTagName("head")[0];
    var fileref = null;
    if (payload.js) {
        var js = payload.js;
        for (var i = 0; i < js.length; i++) {
            var file = this.getPath("files", js[i]);
            if (!file.loaded) {
                var fileref = document.createElement('script');
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", file.path);
                fileref.onreadystatechange = callbackFunc;
                fileref.onload = callbackFunc;
                head.appendChild(fileref);
                file.loaded = true;
            }
        }
    }
    if (payload.css) {
        var css = payload.css;
        for (var i = 0; i < css.length; i++) {
            var file = this.getPath("files", css[i]);
            if (!file.loaded) {
                var fileref = document.createElement('link');
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", file.path);
                fileref.onreadystatechange = callbackFunc;
                fileref.onload = callbackFunc;
                head.appendChild(fileref);
                file.loaded = true;
            }
        }
    }
}

Please someone help me on how to solve this issue.
Answer:
Somehow the below answers didn't work for me. I wasn't able to see the dynamically added scripts in developer tool of chrome. So, I ended up modifying my above code by referring @jfriend00's answer:
function loadFiles(list, fn){
    var counter = 0;
    var head = document.head || document.getElementsByTagName("head")[0];
    for (var i = 0; i < list.length; i++) {
        var fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", list[i]);
        fileref.onload = function(){
            counter++;
            if(counter === list.length){
                fn();
            }
        }
        head.appendChild(fileref);
    }
    if(list.length === 0){
        fn();
    }
}

A: Here's a way to use $.getScript() to load multiple files using a counter:
function getScripts(list, fn) {
    var cntr = list.length;
    for (var i = 0; i < list.length; i++) {
        $.getScript(list[i], function() {
            --cntr;
            if (cntr === 0) {
                fn();
            }
        });
    }
}

getScripts(["file1.js", "file2.js"], function() {
    // all scripts loaded here
});

Here's a way using promises:
function getScripts(list) {
    var promises = [];
    for (var i = 0; i < list.length; i++) {
        promises.push($.getScript(list[i]));
    }
    return $.when.apply($, promises);
}

getScripts(["file1.js", "file2.js"]).then(function() {
    // all scripts loaded here
});

You can use these same concepts for your CSS files.

A: To call callback function only once you need to do this check:
var count = 0;
fileref.onload = function() {
    if (payload.js.length + payload.css.length == ++count) {
        callbackFunc();
    }
};


text:
Q: Transfer ERC20 Token Failed: web3.exceptions.ContractLogicError: execution reverted: ERC20: transfer from the zero address So I tried on interacting with ERC20 smart contracts with the transfer function and it works perfectly running the example below will deduct the first account's ERC20 token balance and add it to the second account's ERC20 token balance.
import json

from web3 import Web3
from web3.middleware import geth_poa_middleware

if __name__ == "__main__":
    w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545', request_kwargs={'timeout': 60}))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    print(w3.clientVersion)

    first_account = w3.eth.accounts[0]
    fist_account = w3.toChecksumAddress(first_account)
    print(first_account)

    first_account_ether_balance = w3.eth.get_balance(first_account)
    print(f"ether balance for {first_account} is {first_account_ether_balance}")

    ABI = '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"}]'
    ABI = json.loads(ABI)

    second_account = "0x2ee7304bad7c1aef6292f1e70124e77370007924"
    second_account = w3.toChecksumAddress(second_account)
    ether_balance_second_account = w3.eth.get_balance(second_account)
    print(f"ether balance for {second_account} is {ether_balance_second_account}")

    gldd_contract_address = "0xe9814432a38b18d0730b9e0e277eab759b6019d7"
    contract_address = w3.toChecksumAddress(gldd_contract_address)
    gldd_goerli_contract = w3.eth.contract(contract_address, abi=ABI)

    contract_name = gldd_goerli_contract.functions.name().call()
    print(f"Contract name is {contract_name}")

    contract_symbol = gldd_goerli_contract.functions.symbol().call()
    print(f"Contract symbol is {contract_symbol}")

    decimals = gldd_goerli_contract.functions.decimals().call()
    DECIMALS = 10 ** decimals

    # total_supply = gldd_goerli_contract.functions.totalsupply().call()
    # print(f"Total supply {total_supply}")

    first_account_gldd_balance = gldd_goerli_contract.functions.balanceOf(first_account).call()
    print(f"First account GLDD balance {first_account_gldd_balance}")

    second_account_gldd_balance = gldd_goerli_contract.functions.balanceOf(second_account).call()
    print(f"Second account GLDD balance {second_account_gldd_balance}")

    # print("Trying to send GLDD the first way")
    # transaction = {
        # 'from': first_account,
        # 'to': second_account,
        # 'nonce': w3.eth.getTransactionCount(Web3.toChecksumAddress(first_account)),
        # 'gas': 1000000,
        # "gasPrice": w3.eth.gas_price,
        # 'data' : gldd_goerli_contract.caller.transfer(Web3.toChecksumAddress(second_account), 100),
    # }
    # tx_hash = w3.eth.send_transaction(transaction)
    # tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    # print(tx_receipt)

    print("Trying to send GLDD the second way")
    tx_hash = gldd_goerli_contract.functions.transfer(second_account, 1000).transact({'from': first_account})
    tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    print(tx_receipt)

    first_account_gldd_balance = gldd_goerli_contract.functions.balanceOf(first_account).call()
    print(f"First account GLDD balance {first_account_gldd_balance}")

    second_account_gldd_balance = gldd_goerli_contract.functions.balanceOf(second_account).call()
    print(f"Second account GLDD balance {second_account_gldd_balance}")

Now if I comment line for the 1st transaction with the
    # print("Trying to send GLDD the first way")
    # transaction = {
        # 'from': first_account,
        # 'to': second_account,
        # 'nonce': w3.eth.getTransactionCount(Web3.toChecksumAddress(first_account)),
        # 'gas': 1000000,
        # "gasPrice": w3.eth.gas_price,
        # 'data' : gldd_goerli_contract.caller.transfer(Web3.toChecksumAddress(second_account), 100),
    # }
    # tx_hash = w3.eth.send_transaction(transaction)
    # tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    # print(tx_receipt)

it seems that the transaction failed with an error web3.exceptions.ContractLogicError: execution reverted: ERC20: transfer from the zero address.
Does anyone know what is happening here? I want to know the reasoning behind this error.

A: I just found the error, you need to write down the first transaction like as follows
    print("Trying to send GLDD the first way")
    transaction = {
        'from': first_account,
        'to': second_account,
        # 'nonce': w3.eth.getTransactionCount(Web3.toChecksumAddress(first_account)),
        'gas': 2000000,
        'gasPrice': w3.eth.gas_price,
        'value': "0x0",
        'data' : gldd_goerli_contract.functions.transfer(second_account, 1000).transact({'from': first_account}),
    }
    tx_hash = w3.eth.send_transaction(transaction)
    tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    print(tx_receipt)


text:
Q: define a map over boolean scala I am trying to change the value of an array based on the value of a different array. In particular these are the arrays I am working with:
val inpoly: Array[Boolean]=Array(false, true, true, false)
val idx1: Array[Boolean]=Array(true, false, false, false)

I would like to check the array idx1 and where it is true I would like to assign to a new vector the opposite value of the array inpoly in that specific position, otherwise, just leave the value that inpoly already has.
My expectation would be to have this array:
final_vector= true, true, true, false

since the first value of idx1 is true, change the first value of inpoly. All the other values of idx1 are false, so leave the inpoly as it is
I tried with the following code:
idx1.map({
case true => !inpoly
case false => inpoly}
)

However i get the following error:
<console>:73: error: value unary_! is not a member of Array[Boolean]
              case true => !inpoly
                           ^

Can anyone help?

A: You are doing an element-by-element comparison of two collections. The best way to do this is to zip them together and then map the two values to give the answer:
inpoly.zip(idx1).map{ case (poly, idx) => poly ^ idx }

In this case the two values are xor-ed, but clearly you can use any combination of the two values to generate the result.


text:
Q: Ext JS form.getValues() retrieves bad values for checkboxes So I have a form with two checkboxes. When I call form.getForm().getValues() and I log the values, it retrieves checkbox values like this: if it is checked then the value looks like this - SomeCheckbox: "on", and if it's not checked than the value is not there at all. And then I encode those values into JSON and send it to ASP.NET MVC and the values ASP retrieves for these checkboxes are always false. The solution I came up with is to set the SomeCheckbox properties of the values I retrieve from form after getting form values and it works just fine, but is not there any other way ?

SOLUTION:
call form's getFieldValues() method instead of getValues()

A: call form's getFieldValues() method instead of getValues()

A: You need to add an inputValue config to the checkbox.
{
    boxLabel  : 'Anchovies',
    name      : 'topping',
    inputValue: 'anchovies'
}

http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.field.Checkbox-cfg-inputValue


text:
Q: How to get a form data in flask route I have a login route which a user can login to the account. I want to get the form data of that login route from another route. But it always fails.
@app.route('/attendance', methods = ['GET', 'POST'])
def attendance():
    O_id = request.form.get('O_id')
    print('Welcome', O_id)
    emp_nums = {'1000': 'DEV', '1001': 'ANA'}
    value = emp_nums.get(O_id,"")
    print('team is',value)

    userDetails = Employee_data.query.filter_by(team = value).all()
    return render_template('take_attendance.html', userDetails=userDetails)

I use this simple HTML form
 <form action="" method="POST" margin="center">
      ID
      <input type="text" name="U_id" value
      {{request.form.U_id}}">

      Password
      <input type="password" na`enter code here`me="password" value="{{request.form.password}}">

      <button type="submit" class="btn btn-primary">Submit</button>
      </form>

The Employee_data model is
class Employee_data(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    O_id= db.Column(db.String(20), unique=True, nullable=False)
    team = db.Column(db.String(50), nullable=False)
    name = db.Column(db.String(100), nullable=False)
    location = db.Column(db.String(100), nullable=False)

def __repr__(self):
    return 'Employee_data %r' % self.oracle_id,self.name

I only need to get the name and O_Id
Is there anything i miss here?

A: Here is the method to use when using GET or POST
html
<form method="GET" action="/search" >
    <input type="text" name="make"/>
    <input type="text" name="model"/>
    <input type="submit" value="Submit"/>
</form>

<form method="POST" action="/search_post">
    <input type="text" name="make"/>
    <input type="text" name="model"/>
    <input type="submit" value="Submit"/>
</form>

Python
    # Getting arguments from a GET form
@app.route("/search")
def do_search():
    make = request.args.get('make')
    model = request.args.get('model')
    return "You search for car make: {0}, and car model: {1}".format(make, model)

# Getting arguments from a POST form
@app.route("/search_post", methods = ['POST'])
def do_post_search():
    make = request.form.get('make')
    model = request.form.get('model')
    return "You search for car make: {0}, and car model: {1}".format(make, model)


text:
Q: Configuring postgresql driver through Spring xml datasource I've been trying to configure the connections made with a postgresql datasource declared in a xml Spring configuration file.
<bean id="myDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/dbname" />
        <property name="username" value="postgres" />
        <property name="password" value="" />
        <property name="socketTimeout" value="10"/>
    </bean>

I know, I shouldn't be using the DriverManagerDataSource class from spring, (we will soon move to C3p0 or DBCP) because it's not a real pooling.
I'm trying to set the socketTimeout value of a postgresql connection ( described here https://jdbc.postgresql.org/documentation/head/connect.html ) but of course, "socketTimeout" is not a property of the datasource, so it doesn't work.
Is it possible to do this through the datasource xml's configuration ? Or should I do it somewhere else ? Because the data source manages the connection I don't think I'll be able to do a
props.setProperty("timeout",30);
Connection conn = DriverManager.getConnection(url, props);

Can I even do this with the DriverManagerDataSource ? I tried to search, but I didn't find anything usefull, as not a lot of people are really using it.

A: Thank you M. Deinum, I was able to find how.
Actually, even knowing the property was named "connectionProperties", I didn't found a lot answers (maybe people rarely use it this way ?). So I'm posting it:
<bean id="myDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/dbname" />
        <property name="username" value="postgres" />
        <property name="password" value="" />
        <!--<property name="socketTimeout" value="10"/>-->

        <property name="connectionProperties">
            <props>
                <prop key="socketTimeout">10</prop>
            </props>
        </property>
   </bean>

If anyone has a better/more complete answer, I'll check it out ;)


text:
Q: filp->private_data equivalent in freeBSD I am porting my linux driver to freebsd. I use "filp->private_data" variable to store some information required by driver. (To avoid locks in multi-threaded cases). I found BSD does not use "file" structure in linux and instead uses cdev. cdev does not have "private_data" variable. But I am sure there must be some other variable in BSD?
Does anyone know how to achieve what I am trying to do.
Thanks.

A: You have an instance of your softc structure for each instance of your device. That would usually have a mutex. You can use the si_drv1 member of the cdev to keep a pointer back to the softc. Something like:
struct mydev_softc {
    struct mtx m_lock;
    struct cdev* m_cdev;
    device_t m_dev;
    /* ... whatever else you need ... */
};

static int mydev_attach(device_t dev)
{
    struct mydev_softc* sc = device_get_softc(dev);

    mtx_init(&sc->m_lock);
    sc->m_cdev = make_dev(...);
    sc->m_cdev->si_drv1 = sc;
    sc->m_dev = dev;
    /* Plus whatever else you need */
 }

I have left out all the other driver initialisation stuff so you can see this part.


text:
Q: Serialization issue with Morphia Using Morphia 1.1.1. with Mongo 4.0.5 Snapshot, storing User objects from Twitter4J.
I get this error when retrieving an Object "User" from Mongo:
org.mongodb.morphia.mapping.MappingException: No usable constructor for [Ltwitter4j.GeoLocation;

The relevant part of the object, serialized in Json in Mongo looks like:
    "favoriteCount" : 4,
    "place" : {
        "name" : "Kewaunee",
        "countryCode" : "US",
        "id" : "0114d7a909aa6731",
        "country" : "United States",
        "placeType" : "city",
        "url" : "https://api.twitter.com/1.1/geo/id/0114d7a909aa6731.json",
        "fullName" : "Kewaunee, WI",
        "boundingBoxType" : "Polygon",
        "boundingBoxCoordinates" : [
            {
                "className" : "[Ltwitter4j.GeoLocation;"
            }
        ],
        "accessLevel" : 0
    },

I checked and actually added a no-arg public constructor in the source of the GeoLocation class. And what's this "[L" thing in front of the package name, and the ";" at the end?

A: GeoLocation needs a no-arg constructor to be deserialized.  So it's probably not going to work to use that directly.  The [L bit means that the type is an array.
Also, what is Mongo 4.0.5 Snapshot?  There's nothing from Mongodb with a name/version like that.  The latest database version 3.2.6(? i think i just saw that release) and the Java driver is at 3.2.2.


text:
Q: Codemagic versioning for iOS of Flutter I've faced the next issue with Codemagic: at the beginning in Info.plist were
${CURRENT_PROJECT_VERSION} for Bundle Version and ${MARKETING_VERSION} for Bundle Version string (short) and these lines above did not work
The place to put these lines in Codemagic
--build-name=2.0.$BUILD_NUMBER --build-number=$BUILD_NUMBER
--build-name=2.0.$PROJECT_BUILD_NUMBER --build-number=$PROJECT_BUILD_NUMBER

But after I changed to ${FLUTTER_BUILD_NUMBER} and ${FLUTTER_BUILD_NAME} for Bundle Version and Bundle Version string (short) respectively lines above in Codemagic started to do magic, they start to work.
Could someone explain why at the beginning with ${CURRENT_PROJECT_VERSION} and ${MARKETING_VERSION} Codemagic could not set the version that I wrote? Thanks.

A: This seems to be a Flutter build command that you are using and specific to flutter build command rather than CI/CD service provider.
If you are settings build version and name from build arguments then the build command determines the outcome. see: https://flutter.dev/docs/deployment/ios#updating-the-apps-version-number
specifically from docs:

In iOS, build-name uses CFBundleShortVersionString while build-number
uses CFBundleVersion. Read more about iOS versioning at Core
Foundation Keys on the Apple Developer's site.


text:
Q: IPTables block all traffic and only allow certain ports I am trying to configure iptables on a CentOS 6.5. I am trying to block all traffic to the server and then only open certain ports that I need, such as port 80. At the moment I've removed port 80 from the iptables config file in /etc/sysconfig/iptables and restarted it but I can still access the web pages.
Below is my current iptables config file:
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter :INPUT DROP [0:0] :FORWARD DROP [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i eth+ -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
# -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -i lo -j ACCEPT
-A FORWARD -i eth+ -j ACCEPT
-A FORWARD -o eth+ -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT

As you can see from the above, port 80 is currently commented out so when IP tables restarts, I expect to no longer be able to access the web pages on my server, however, I still can access them.

A: You chose to accept all traffic on all eth interfaces. Re-run system-config-firewall and turn that off.


text:
Q: .NET Multilanguage web project not working in production - Resx issue I am working on a web site application developed with VS 2008.
I am in the process of localizing a web application. I can generate the resx files and I can read the values from those files without any problem. When I ran the website in the localhost it works great in any language. The issue occurs when I deploy our website in the production servers.
It seems that the values from the resx files are not read.
I read lots of blogs and questions about this and I tried several solutions. I tried most of the possible configurations for the resx file.
The first configuration I tried is this:

*

*Build Action: Embedded Resource.

*Copy To Output Directory: None.

*Custom Tool: PublicResXFileCodeGenerator.

*Custom Tool Namespace: [empty].

As I mentioned before, this works great in localhost but not in the production server.
Then I changed the Copy To Output Directory property to "Copy Always" but the result is the same.
So, I decided to change the Build Action to "Content" but we get a System.Resources.MissingManifestResourceException when we try to access the resource file from code behind. The way we access the Resx Property is the Following:
wImage.AlternateText = App_LocalResources.SelectRecordSet_aspx.wImageActive;
This happens in localhost and in production.
As I read in this post: http://www.mojoportal.com/Forums/Thread.aspx?pageid=5&t=6062~-1 I changed the Custom Tool Namespace To Resources and I renamed the way I accessed the property:
wImage.AlternateText = Resources.SelectRecordSet_aspx.wImageActive;
But that didn't work.
I've been struggling with this issue for a couple of days and I still can not find the proper solution.
Any help would be appreciated.
Thanks!


text:
Q: Is flask-security concerned with User table only? Am asking a very simple, rather a silly, question about flask-security.
 I have read docs, researched stackoverflow questions, but I really didn't get anything
 except that - Flask-security handles login/logout of the Users, along with
certain other related functions.
Is it concerned only with Users table in the database?
What about other tables, for eg. in a banking website there are Branch, Accounts, city...
How do I use these tables if I want to use Flask-security, am really confused?
Flask-security is very new to me,
any help from you guys would be deeply appreciated,
 thanks.

A: Flask Security comes with a User and Role Model out of the box See here for a quick overview, but you can also create your own custom models and even extend the User to include additional fields.
It all depends on what you are trying to build & how advanced your current Python/Flask skill set is.
What it is really good at, is giving you some predefined automation for user setup, to stop you from building everything from scratch. Not sure if this helps, but hope it does.


text:
Q: Why getting compilation error while calling overloaded method and deciding argument type using if-else as parameter I am trying to call the overloaded method using if-else statement to decide which type of argument to pass so that appropriate method can be invoked. I am getting compilation error.
any idea why I am getting compilation error ? If call method separately using if-else check outside , it works fine.
public class A {
}

public class B {
}

public class RuleCheck {

    public void check(A a) {

    }

    public void check(B b) {

    }
}

public class Test {

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        testRule(a);
        testRule(b);
    }

    private static void testRule(Object o) {

        RuleCheck ruleCheck = new RuleCheck();
        ruleCheck.check(o instanceof A ? (A) o : (B) o);//Compilation problem here : Cannot resolve method 'check(java.lang.Object)'

       //Following code works fine
       if (o instanceof A)
           ruleCheck.check((A) o);
       else if (o instanceof B)
           ruleCheck.check((B) o);
       }

}


text:
Q: Get ID of saved pivot-item I would like to solve the following problem:
I have a model (Car) that is loaded as a relation to another model (Driver) with a pivot table.
Car -> belongsToMany Driver (with pivot)  -> belongsToMany Accessoires (with Pivot).
The model in turn has relations (accessories) that are loaded with pivot.
The problem: The model Accessories has two pivot tables which can be loaded depending on other factors. If the model Accessories is loaded as a relation of Driver as a relation of Car, the pivot tables should be output correctly.
This is what it looks like at the moment:
 collect($request->input('data.driver'))->each(function ($driver) use
        (
            $car
        ) {

            $ndriver = Driver::findOrFail($driver['id']);

            $added = $car->driver()->save($driver, [
                'custom' => $driver['custom'],
                'title' => $driver['title'],
                'factor' => $driver['factor'],
            ]);

            /*Save attributes*/
            $added->syncDriverAttributes($driver['attributes']],
                $car->id);
        });

Now I should actually specify in $added->syncDriverAttributes($driver['attributes'], $car->id); the pivot ID of the created pivot data in $added. Unfortunately I can't find out what the pivot ID is at the moment, because it is not returned in $added.
The problem: I can't find out the last pivot ID from the timestamp either, because all entries have the same timestamp.
So my question is: How can I solve that?

A: You can of course do it but you should use withPivot method when defining your relationship to tell what additional fields you want to have:
public function driver()
{
   return $this->belongsToMany(Driver::class)->withPivot(['id']);
}


text:
Q: Associated barrelled topology of norm topology on $C_c(X)$ Let $X$ be a locally compact Hausdorff space, $C(X; K)$ the Banach space of continuous functions on $X$ with support in $K$, for compact $K \subseteq X$, and $C_c(X) = \lim_K C(X; K)$ the locally convex inductive limit with inclusion linking mappings $C(X; K) \to C_c(X)$. Denote the locally convex inductive limit topology on $C_c(X)$ by $\tau$, so that $\tau$ is the finest locally convex topology on $C_c(X)$ such that $C(X; K) \to C_c(X)$ is continuous. Denote also the norm topology by $\eta$. Then $\eta \subseteq \tau$. Moreover, $\tau$ is ultrabornological (therefore also barrelled and bornological), but $\eta$ is generally not barrelled.
Define $\eta^\beta$ as the strong topology $\beta(C_c, (C_c, \eta)')$ and $\eta^b$ as the associated barrelled topology (the coarsest barrelled topology finer than $\eta$; note that the finest locally convex topology is barrelled) and similarly $\eta^{ub}$ as the associated ultrabornological topology. Then
$$\eta \subseteq \eta^\beta \subseteq \eta^b \subseteq \eta^{ub} \subseteq \tau.$$
I would like to know whether $\eta^\beta = \tau$ or maybe just $\eta^b = \tau$ or at least $\eta^{ub} = \tau$. What if $X$ is assumed to be paracompact?
For $\sigma$-compact $X$ it holds $\eta^\beta = \tau$, see here (the proof uses a weighted seminorms approach).
Note also that for $X = [0, \omega_1)$ (the first uncountable ordinal), it holds $C_c(X) = C_0(X)$ (because continuous functions on $X$ are eventually constant) and therefore the norm topology $\eta$ is a Banach space topology. $X$ is not paracompact.


text:
Q: Exclude dates in scheduleExpression I have an EJB timer with timing specified in a scheduleExpression. Is there a way to exclude a list of dates in the schedule, i.e.:
Do not run on weekends and some list of other dates?

A: It's easy to execute it on all days not week-ends : you can set
scheduleExpression.dayOfWeek("Mon-Fri")

To exclude a discrete list of specific dates with just one schedule expression would be more tricky in my opinion. Maybe you could use more than one and use the start and end fields.
More details here : http://docs.oracle.com/javaee/6/api/javax/ejb/ScheduleExpression.html


text:
Q: Navigation Drawer onNavigationDrawerItemSelected called before MainActivity onCreate? I have setup a new project with the template implementation of Navigation Drawer Fragment and a MainActivity.
It provides me with the following relevant methods:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = getIntent();
    token = intent.getStringExtra(EXTRA_TOKEN);

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mNavigationDrawerFragment.activityMain = this;

    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

My MainActivity is started by a splash activity which gets a saved access token via the EXTRA_TOKEN.
This is the override of the Navigation Drawer item select listener in the MainAcitivity:
@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    onSectionAttached(position + 1);

    switch(position) {
        case 0:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FeedFragment.newInstance(token, ""))
                    .commit();
            break;

        case 1:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, PeopleFragment.newInstance("", ""))
                    .commit();
            break;

        case 2:
            if(qbloggedin) {
                fragmentManager.beginTransaction()
                        .replace(R.id.container, MessagesFragment.newInstance(token, ""))
                        .commit();
            }
            break;

        default:
            break;
    }
}

It starts three different fragments depending on which item is selected in the NavDrawer. While instantiating the new fragments, the token string is passed into its constructor, which is saved in the fragment's class for further use.
On the first start of the App however, it seems that onNavigationDrawerItemSelected is called before onCreate! This results me passing a null value token into the fragments, causing them to be all messed up.
How is this possible? As I understand it, the NavigationDrawerFragment should not have been setup yet!
I set breakpoints on both onCreate and on onNavigationDrawerItemSelected switch position = 0. onNavigationDrawerItemSelected is indeed hit before onCreate.
How can I make sure to get the token first before trying to handle the onNavigationDrawerItemSelected?
Any help would be appreciated.

A: I believe I figured this out as it was happening to me for anyone who searches this and can't find the answer.
If you use the Android Studio DrawerActivity then there is boilerplate code that they create for you. In this code in the activity_main.xml or whichever XML your DrawerActivity sets as its' content view, there is a  tag.
When setContentView() is called in onCreate(), this fragment is automatically created and so technically onCreate() is still being called first but then the onNavigationDrawerItemSelected() method is called before anything else in create. Since setContentView is typically kept up top, this causes problems when trying to store the state of the fragments in your drawer.
Simply move any code that checks for savedInstanceBundle above setContentView() and it will fix the problem.
Example with comments:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // THIS IS WHERE YOU CHECK FOR SAVED INSTANCE
    // Check for frag
    if (savedInstanceState != null) {
        Log.i(TAG, "Get QuestionDayFragment");
        mQuestionDaysFragment = (QuestionDaysFragment) getSupportFragmentManager().getFragment(savedInstanceState, QUESTION_DAY_FRAGMENT);
    }

    // View injection
    setContentView(R.layout.activity_main);
    ButterKnife.inject(this);

    // THIS IS WHERE THE CODE WAS BEFORE
    // THIS WOULD BE CALLED AFTER onNavigationDrawerItemSelected()

    // Singleton injection
    LifeboxApplication.graph().inject(this);

    // Toolbar
    setSupportActionBar(mToolbar);

    // FB
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    // Drawer
    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

}

A: You could move the intent to a constructor and save your tokens there like so:
Intent i;

......

public FragmentConstructor() {

     i = getIntent();
     token = intent.getStringExtra(EXTRA_TOKEN);

}

A: What I had to do to make it work was to check if the page has loaded before executing onNavigationDrawerItemSelected
    private Boolean loaded=false;

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Your code here
            this.loaded=true;
    }

    public void onNavigationDrawerItemSelected(int position) {
        if (!this.loaded){
            return;
    }

A: I also agree with using a boolean to check if onCreate() has finished loading. My only other suggestions is that for a quick fix you can use onSectionAttached(int number) to process each item selected instead of onNavigationDrawerItemSelected.


text:
Q: Syntax of a functional method call as an FM parameter? I have the following piece of code.
REPORT ZZY.

CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS:
      convert_to_xstring
        IMPORTING
          i_param1 TYPE i
          i_param2 TYPE i
        RETURNING
          VALUE(rv_result) TYPE xstring,
      main.
ENDCLASS.

CLASS lcl_main IMPLEMENTATION.
  METHOD convert_to_xstring.
  ENDMETHOD.

  METHOD main.
    DATA: lt_binary_tab TYPE STANDARD TABLE OF x.

    DATA(lv_result) = convert_to_xstring( i_param1 = 1 i_param2 = 2 ).

    CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
      EXPORTING
        buffer = lcl_main=>convert_to_xstring(
                   EXPORTING
                     i_param1 = 1
                     i_param2 = 2
                 )
      TABLES
        binary_tab = lt_binary_tab.

  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  lcl_main=>main( ).

A functional method call that is not a part of a function module call can be written like that.
DATA(lv_result) = convert_to_xstring( i_param1 = 1 i_param2 = 2 ).

However when I want to use it exactly as written above
CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
  EXPORTING
    buffer                = lcl_main=>convert_to_xstring( i_param1 = 1 i_param2 = 2 )
  TABLES
    binary_tab            = lt_binary_tab.

I get the following syntax error.

Field "CONVERT_TO_XSTRING(" is unknown. It is neither in one of the
  specified tables nor defined by a "DATA" statement. "DATA" statement.

It looks like the compiler needs some guidance in this case to distinguish between an attribute and a method. Why would it be ambiguous for the compiler to let such a case without writing EXPORTING?
CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
  EXPORTING
    buffer                = lcl_main=>convert_to_xstring( EXPORTING i_param1 = 1 i_param2 = 2 )
  TABLES
    binary_tab            = lt_binary_tab.

A: The design of abap is quite bad. There is something like functional method calls, but you can't use it in combination with all commands. For example the WRITE command doesn't work in combination with functional method calls. This seems to be some kind of "partial compatible" with function method calls.
I don't know why(maybe the sap dev folks were drunk), but it is just a fact we have to live with.


text:
Q: How to get CPU usage in javascript For a long time, I was thought that we can't get CPU usage from browser - because of security reason. But today, I saw that Google Meet can do that thing : https://imgur.com/a/hhWoMjj
How did they do that ? Or, it's a hidden Chrome API that only works with Google's product ?


text:
Q: Ionic menu in a specific page that let interactibility on page /!\ english is not my natural language/!\
Their is the context:
On 2 page of my app, their is a map part (where I use leaflet), and a menu for showing data to the user. For now the menus are in my app.composent.html because, when I wanted to put them on the conserned page, I couldn't interact with the map part.
But the problem is that will I'll show specific data, it could be better to have the "show data" menu on the conserned page and not on app.composent.html
Did you know a solution to have my menu on the good html component that hollow me to interact with the rest of the page?

A: I found how to doing it:
Not using a menu. And use a custom component (or a div) that you show or hide like a menu via CSS


text:
Q: Cant Get the activity indicator to show on iPhone app I have a view which is created in IB. inside it I have a scroll view created programmatically. Within the scroll view I connect to a web service and fetch the content and the image. I want to show an activity indicator while doing this. So I have:
- (void)viewDidLoad
{
    [super viewDidLoad];
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    activityIndicator.center = self.view.center;
    [self.view.window addSubview:activityIndicator];

And right after the scrollview is added, I have:
[self.view addSubview:scrollView];
// ADD Scroll View Ends

    //Add the Lisitng Image
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(loadImage)
                                        object:nil];
    [queue addOperation:operation];

And in loadimage I have:
- (void)loadImage {

    [activityIndicator startAnimating];

I've tried [self.view.window addSubview:activityIndicator];, [self->ScrollView addSubview:activityIndicator];, [self.view addSubview:activityIndicator];
but I just can't get the indicator to show. Anyone have any idea what might be wrong?

A: You should do this in you viewDidload
- (void)viewDidLoad
{
    //Start Activity Indicator View
    indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicatorView.frame = CGRectMake(40.0, 20.0, 60.0, 60.0);
    indicatorView.center = self.view.center;
    [self.view addSubview:indicatorView];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [indicatorView startAnimating];

    [self performSelectorInBackground:@selector(loadscroll) withObject:self];
}

Note: "performSelectorInBackground" will show you an activity indicator on the view and your loadScroll method will fetch all data from internet and do other work.
-(void)loadscroll
{
    //Your Scroll View
        //Your other Data Manipulation even from internet
        //When data is fetched display it
       [self removeActivityIndicator]; //To stop activity Indicator
}

- (void)removeActivityIndicator
{
       [indicatorView stopAnimating];
}

A: What I have found so far after multiple times facing above problem with activity indicator.

*

*Activity indicator and the function (or method or piece of code) that is required to be executed after appearance of activity indicator both can't run on main thread. If it is so activity indicator will not appear. The solution is to run activity indicator on main thread and the function in a background thread.

*I have also faced a case in which the function followed by activity indicator can't run in a background thread. In my case it was playing a music file using MPMoviePlayerController that can't be executed in a background thread. What I did to solve this issue was to run activity indicator in the main thread and then used an NSTimer to call my method after a delay that was good enough for activity indicator to appear and start animating.

*I have also found that activity indicator must be called in performSelectorOnMainThread and should be added as a subview on the top view of given viewController once it starts animating.
Once it is not needed it should be removed by calling removeFromSuperView method.


text:
Q: Flat shading in graphics pipeline I have been asked to analyze Flat shading model for 3d lighting and to "discuss how it integrate in the graphics pipeline".

Since flat shading is applied once per face, I was thinking the right place where light is computed is the phase of fragments computation. However I may also be totally wrong...
Can somebody point me to the right direction?

A: That diagram isn't particularly readable. This one is much, much easier on the eyes:

... and also correctly places the stage at which normals are interpolated: before the fragment shader or raster operations, which finalizes the fragments. I think in terms of your diagram, this is the area labelled 'set-up'.
For flat shading, normals are not interpolated across the surface of the polygon. However, they will still be passed through the interpolation stage so that the appropriate normal for a fragment can be determined, where more than one may be available. So, the normals are determined in the rasterization and interpolation however the actual colouring and lighting are determined by the fragment shader. This is the modern approach: In a fixed pipeline (without a fragment shader), it would all be done by the rasterizer.


text:
Q: visual studio 2017 xaml visual designer hidden when debugging When debugging in Visual Studio 2017 it hides the xaml visual designer when opening a xaml document, showing only the xaml text. Is it still possible to show the visual designer when debugging?
I've just started using Visual Studio 2017 Community edition. I was previously using Visual Studio 2013 Ultimate.

A: This is by design (https://developercommunity.visualstudio.com/content/problem/178903/vs2017-hides-xaml-designer-when-debugging.html):

"This is by design starting with 2017. We do not want people to interact with the designer while in a debugging session.", Charles Bissonnette [MSFT]

With the UI Debugging Tools for XAML your running application is the Designer.


text:
Q: use model object, e.g. panelmodel, to flag data used Is it possible in some way to use a fit object, specifically the regression object I get form a plm() model, to flag observations, in the data used for the regression, if they were in fact used in the regression. I realize this could be done my looking for complete observations in my original data, but I am curious if there's a way to use the fit/reg object to flag the data.
Let me illustrate my issue with a minimal working example,
First some packages needed,
# install.packages(c("stargazer", "plm", "tidyverse"), dependencies = TRUE)
library(plm); library(stargazer); library(tidyverse)

Second some data, this example is drawing heavily on Baltagi (2013), table 3.1, found in ?plm,
data("Grunfeld", package = "plm")
dta <- Grunfeld

now I create some semi-random missing values in my data object, dta
dta[c(3:13),3] <- NA; dta[c(22:28),4] <- NA; dta[c(30:33),5] <- NA

final step in the data preparation is to create a data frame with an index attribute that describes its individual and time dimensions, using tidyverse,
dta.p <- dta %>% group_by(firm, year)

Now to the regression
plm.reg <- plm(inv ~ value + capital, data = dta.p, model = "pooling")

the results, using stargazer,
stargazer(plm.reg, type="text") # stargazer(dta, type="text")
#> ============================================
#>                  Dependent variable:
#>              ---------------------------
#>                          inv
#> ----------------------------------------
#> value                 0.114***
#>                        (0.008)
#>
#> capital               0.237***
#>                        (0.028)
#>
#> Constant             -47.962***
#>                        (9.252)
#>
#> ----------------------------------------
#> Observations             178
#> R2                      0.799
#> Adjusted R2             0.797
#> F Statistic   348.176*** (df = 2; 175)
#> ===========================================
#> Note:        *p<0.1; **p<0.05; ***p<0.01

Say I know my data has 200 observations, and I want to find the 178 that was used in the regression.
I am speculating if there's some vector in the plm.reg I can (easily) use to crate a flag i my original data, dta, if this observation was used/not used, i.e. the semi-random missing values I created above. Maybe some broom like tool.
I imagine something like,
dta <- dta %>% valid_reg_obs(plm.reg)

The desired outcome would look something like this, the new element is the vector plm.reg at the end, i.e.,
dta %>% as_tibble()
#> # A tibble: 200 x 6
#>     firm  year   inv value capital plm.reg
#>  * <int> <int> <dbl> <dbl>   <dbl> <lgl>
#>  1     1  1935   318  3078    2.80 T
#>  2     1  1936   392  4662   52.6  T
#>  3     1  1937    NA  5387  157    F
#>  4     1  1938    NA  2792  209    F
#>  5     1  1939    NA  4313  203    F
#>  6     1  1940    NA  4644  207    F
#>  7     1  1941    NA  4551  255    F
#>  8     1  1942    NA  3244  304    F
#>  9     1  1943    NA  4054  264    F
#> 10     1  1944    NA  4379  202    F
#> # ... with 190 more rows

Update, I tried to use broom's augment(), but unforunatly it gave me the error message I had hoped would create some flag,
# install.packages(c("broom"), dependencies = TRUE)
library(broom)
augment(plm.reg, dta)
#> Error in data.frame(..., check.names = FALSE) :
#>   arguments imply differing number of rows: 200, 178

A: The vector is plm.reg$residuals.  Not sure of a nice broom solution, but this seems to work:
library(tidyverse)

dta.p %>%
as.data.frame %>%
rowid_to_column %>%
mutate(plm.reg = rowid %in% names(plm.reg$residuals))

for people who use the class pdata.frame() to create an index attribute that describes its individual and time dimensions, you can us the following code, this is from another Baltagi in the ?plm,
# == Baltagi (2013), pp. 204-205
data("Produc", package = "plm")
pProduc <- pdata.frame(Produc, index = c("state", "year", "region"))
form <- log(gsp) ~ log(pc) + log(emp) + log(hwy) + log(water) + log(util) + unemp
Baltagi_reg_204_5 <- plm(form, data = pProduc, model = "random", effect = "nested")

pProduc %>% mutate(reg.re = rownames(pProduc) %in% names(Baltagi_reg_204_5$residuals)) %>%
            as_tibble() %>% select(state, year, region, reg.re)
#> # A tibble: 816 x 4
#>    state       year  region reg.re
#>    <fct>       <fct> <fct>  <lgl>
#>  1 CONNECTICUT 1970  1      T
#>  2 CONNECTICUT 1971  1      T
#>  3 CONNECTICUT 1972  1      T
#>  4 CONNECTICUT 1973  1      T
#>  5 CONNECTICUT 1974  1      T
#>  6 CONNECTICUT 1975  1      T
#>  7 CONNECTICUT 1976  1      T
#>  8 CONNECTICUT 1977  1      T
#>  9 CONNECTICUT 1978  1      T
#> 10 CONNECTICUT 1979  1      T
#> # ... with 806 more rows

finally, if you are running the first Baltagi without index attributes, i.e. unmodified example from the help file, the code should be,
Grunfeld %>% rowid_to_column %>%
    mutate(plm.reg = rowid %in% names(p$residuals)) %>% as_tibble()


text:
Q: How to create a new process with a lower Integrity Level (IL)? It seems that starting with Windows Vista, processes with a lower integrity level (IL) cannot send messages to processes with higher integrity levels. This makes sense from a security standpoint, but it breaks some of our interprocess communication.
We have a legacy application (Process A) that unfortunately has to run with elevated "admin" privileges (accomplished by setting its shortcut to always run as administrator). At times it needs to instantiate a separate application (Process B). As a result, Process B inherits the same elevated privileges (and IL) as Process A. Therein lies the problem. There might be other independent instances of Process B that do not have elevated privileges, and all of these Process B instances need to be able to send messages to each other. This obviously fails if one instance of Process B is elevated and another is not.
I know we can open holes in the UIPI message filter using the ChangeWindowMessageFilter API method, but this doesn't seem like the ideal solution. Instead, I would much rather have Process A spawn Process B with reduced privileges, specifically so that it can communicate with the other Process B instances. I think by default the other Process B instances run at the "Medium" IL, so therefore I'd like Process A to spawn Process B instances with this same IL.
My searches have led me to the CreateProcessAsUser and CreateRestrictedToken API methods, but despite this documentation, all of the various facets of tokens and security descriptors and such is still very confusing to me.
I've also come across some threads here (Running a process with lowest possible privileges in winapi and Dropping privileges in C++ on Windows), but I can't find any good examples with code.
Can anyone provide me with some simple yet "correct" code that will help me spawn child processes using the appropriate Windows IL? Specifically, I'd like an example of how to take the existing Process A token and convert it so it has the reduced privileges (I'm pretty sure I can figure out the rest). I'm really unclear about whether I need to duplicate the process' token before modifying it as well.

A: I've used the approach described here to accomplish this.  The basic idea is to ask Explorer to run Process B for you.  Since Explorer typically runs at medium integrity level, this gives you what you want.
http://brandonlive.com/2008/04/26/getting-the-shell-to-run-an-application-for-you-part-1-why/
http://brandonlive.com/2008/04/27/getting-the-shell-to-run-an-application-for-you-part-2-how/
The first link will at least give you a good background.

We have a legacy application (Process A) that unfortunately has to run with elevated "admin" privileges (accomplished by setting its shortcut to always run as administrator).

A cleaner way to do that is set the requestedExecutionLevel to the manifest.

A: Warning!  While this approach was probably more or less OK for the original poster, it isn't really a good idea in general.  In particular, note (as per the comment thread) that artificially manipulated tokens have been reported to cause problems in more complicated applications, so if you are using them, be sure to stick to the basic Win32 API.  There are of course also potential security implications.
In most scenarios similar to those of the OP, it would probably be preferable to replace the shortcut that launches the elevated application with a launcher application.  The launcher can then remain running for as long as the elevated application is running, and provide a natural limited token for the elevated application to use to launch non-elevated processes.

There's code for launching a low integrity process, which is analogous to your case, in the Designing Applications to Run at a Low Integrity Level article in MSDN.
First, you duplicate the process token, since you can't (or at least shouldn't) mess about with a token that is already being used.  Then you use SetTokenInformation with the TokenIntegrityLevel class to set the integrity level.  There appears to be a bug in the example code, since the correct SID for low integrity level is S-1-16-4096 rather than S-1-16-1024, but you'll want medium integrity level anyway, which is S-1-16-8192.  These can be found here.
Once you have this working (that is, once you are able to launch medium integrity processes from your high integrity process) you should try using CreateRestrictedToken to create the new token instead of DuplicateToken, and remove the Administrators token and all privileges (except SeChangeNotifyPrivilege).  Otherwise, the new processes will have medium integrity but still have administrator privilege, which could make it easier for any malicious code that might be running in the same session to elevate its privileges.

A: I may not be answering your complete question but as you have mentioned about CreateProcessAsUser and CreateRestrictedToken. I have a code which is working with this API. The code I wrote was written based on the following like.
source:[Windows Vista for Developers – Part 4 – User Account Control] (http://weblogs.asp.net/kennykerr/Windows-Vista-for-Developers-1320-Part-4-1320-User-Account-Control)!
The code is available in the following link.
Example Code : http://pastebin.com/XMUAehF9


text:
Q: Piping a list of two delimeter separated variables to a new command in BASH I need to pipe a list of two delimeter separated variables to a command in BASH.  I deleted my girlfriend's files from her SD card accidentally.  I cloned an image of it using dd and used Sleuth Kit to recover the inode number and names of the deleted files.
fls -d -r bckup_irmasSD1.img | awk 'gsub(/\t|.*\*/,"")' | less

This gives me an example output:
6689308:DCIM/Camera/2014-02-05 20.51.30.jpg
6689560:DCIM/Camera/2013-08-10 16.37.44.jpg
6689563:DCIM/Camera/2013-08-10 16.37.52.jpg
6689566:DCIM/Camera/2013-09-14 19.00.06.jpg
6689567:DCIM/Camera/_I966F~2.MP4
29211:Android/data/com.google.android.apps.maps/cache/_ACHE_~8.M
29298:Android/data/com.google.android.apps.maps/cache/_ACHE_~2.6
29301:Android/data/com.google.android.apps.maps/cache/cache_vts_GMM.7
29304:Android/data/com.google.android.apps.maps/cache/cache_vts_GMM.8
73224:bluetooth/DSC00360.jpg
73227:bluetooth/DSC00360_2.jpg
14728713:.downloadTemp/1616021_716182491801349_1111393555_n.mp4
14728718:.downloadTemp/1616117_10151911525912011_1690760246_n.mp4
18898441:download/1595926_47757
18898445:download/1614824_234800313358133_914357470_n.mp4
18898449:download/_24316~1.MP4

To recover a deleted file by inode number, you can use the command line tool icat:
icat -d /tmp/disk.img 18898449 > /recover/download/_24316~1.MP4

How can I pipe this cleanly to a command to recover all files?

A: fls -d -r bckup_irmasSD1.img |
awk 'gsub(/\t|.*\*/,"")' |
while IFS=: read -r inode filename; do
  mkdir -p /recover/"${filename%/*}"
  icat -d /tmp/disk.img $inode > /recover/"$filename"
done

A: You could use awk again to split your lines and then call your command:
fls -d -r bckup_irmasSD1.img | awk 'gsub(/\t|.*\*/,"")' > indoes.txt
awk -F: '{system("icat -d " $1 " > " #2}' inodes.txt

Make sure none of your filenames contain a : and buy your girlfriend some flowers!


text:
Q: Showing data with index value in grid view Here is my code :
<ion-grid no-padding>
    <ion-row *ngFor="let item of items"  let i=index no-padding>
      <ion-col col-6 col-sm-3 col-md-6 col-lg-4 col-xl-3>
        <ion-card [ngStyle]="{'background': 'url(' + item.PImage + ')'}">

{{item.pName}}

RS: {{item.PPrice}}

        </ion-card>
      </ion-col>
      <ion-col col-6 col-sm-3 col-md-6 col-lg-4 col-xl-3>
          <ion-card [ngStyle]="{'background': 'url(' + item.PImage + ')'}">

{{item.pName}}

RS: {{item.PPrice}}

          </ion-card>
        </ion-col>
    </ion-row>
  </ion-grid>

Now my data is like : { name1, name2, name3, name4, name5, name6 }
But in my screen I am getting like :
name1  name1
name2 name2
name3 name3
name4 name4

But i want like :
name1 name2
name3 name4
name5 name6

Please help me out.How can I achieve this! I know to keep index but don't know how to show that values in the respective grid

A: Wrap the ion-col in ng-container and give condition to enter only for even index
 <ion-grid no-padding>
    <ion-row  no-padding *ngFor="let item of items;let i=index">
      <ng-container *ngIf="i % 2 == 0">
      <ion-col col-6 col-sm-3 col-md-6 col-lg-4 col-xl-3 *ngIf="i < items.length">
        <ion-card [ngStyle]="{'background': 'url(' + items[i].PImage + ')'}">

{{items[i].pName}}

RS: {{items[i].PPrice}}

        </ion-card>
      </ion-col>
      <ion-col col-6 col-sm-3 col-md-6 col-lg-4 col-xl-3 *ngIf="i + 1 < items.length">
       <ion-card [ngStyle]="{'background': 'url(' + items[i+1].PImage + ')'}">

{{items[i+1].pName}}

RS: {{items[i+1].PPrice}}

        </ion-card>
      </ion-col>
      </ng-container>
</ion-row>
</ion-grid>

pls check the demo


text:
Q: Duplicating Xcode 6.0 project I want to duplicate my Xcode project since I need to do a lot of copies with slightly changes, but every time I try o copy it, It lose a lot of Constraints in Storyboard (even some controls disappear), I tried this
Duplicate and rename Xcode project & associated folders
but is in Xcode 4 and is not working for me
EDIT: In my Identity it said that the location is absolute and I can't change it (it is in gray)

A: Ok first of all its always going to transfer.
So please check to see if the references have been removed and if they have just drag and drop them into the file area.
if it does not work you should copy the files from original project, and use them to create a new file to make up for the missing files.
Hope this helps have a good day! :)


text:
Q: Calculating shortest path in Networkx given custom edge weight I am trying to assign length property to each edge and based on those lengths calculate the shortest path from node X to node Y.
However, I am not sure how to correctly reference the length properties that I specified in this part of the code:
nx.shortest_path(G,source='Dehli',target='Pune', weight = ?????)
Code:
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from(["Dehli","Ahmadabad","Kolkata",'Bangalore','Pune','Maduraj'])
G.add_edge('Dehli', 'Ahmadabad', length =890)
G.add_edge('Dehli', 'Kolkata', length =1422)
G.add_edge('Dehli', 'Bangalore', length =2168)
G.add_edge('Dehli', 'Pune', length =1450)
G.add_edge('Dehli', 'Maduraj', length = 2603)

G.add_edge('Ahmadabad', 'Kolkata', length =1902)
G.add_edge('Ahmadabad', 'Bangalore', length =1403)
G.add_edge('Ahmadabad', 'Pune', length =624)
G.add_edge('Ahmadabad', 'Maduraj', length =1807)
G.add_edge('Kolkata', 'Bangalore', length =1778)
G.add_edge('Kolkata', 'Pune', length =1782)
G.add_edge('Kolkata', 'Maduraj', length =2043)

G.add_edge('Bangalore', 'Pune', length =824)
G.add_edge('Bangalore', 'Maduraj', length =404)
G.add_edge('Pune', 'Maduraj', length =1195)

nx.draw(G,pos,node_color='k')

path = nx.shortest_path(G,source='Dehli',target='Pune')
path_edges = zip(path,path[1:])
nx.draw_networkx_nodes(G,pos,nodelist=path,node_color='g')
nx.draw_networkx_edges(G,pos,edgelist=path_edges,edge_color='g',width=7)
print(nx.shortest_path_length(G,source='Dehli',target='Pune'))
plt.show()

A: From the documentation, a call to shortest_path is of the form shortest_path(G, source=None, target=None, weight=None)
The optional argument weight is

weight (None or string, optional (default = None)) – If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.

So in your case, call it as path = nx.shortest_path(G,source='Dehli',target='Pune', weight='length').  Note that Networkx takes the edge attribute length=X and stores it in a dictionary with the key 'length' (a string) and the value X.