text:
Q: Update a table with data from a second table passing a condition from a third I having some difficulty to update a table column based on the following conditions and scenario.
Condition Table:
EmpID   Consulting-A    Consulting-B    Consulting-C
A1      0               10              20
A2      50              30              0
A3      0               0               70

Data Table:
EmpID   Consulting-A    Consulting-B    Consulting-C
A1      10000           20000           30000
A2      0               35000           15000
A3      0               8000            0

Input Table:
EmpID   [Total Valid Consulting]
A1      20000 + 30000 = 50000
A2      0 + 35000 = 35000
A3      0

At the end of the day, I want to have the Input Table Total Valid Consulting having the sum of Data Table when it has value greater than zero in the Condition Table.
For example, the Total Valid Consulting for EmpId A1 is only Consulting-B + Consulting-C (from Data Table) since in the Condition Table the EmpID A1 only have Consulting-B and Consulting-C value of greater than zero.
So I want to add only the columns data that has the value from the other table that are greater than zero. Is there a way to do so in SQL Server? This is for my update statement that I'm having issue to come up with.
Appreciate any help and advice. Thanks!

A: You can use CASE statement
INSERT INTO Input
    SELECT  EmpID,
            CASE WHEN C.[Consulting-A] > 0 THEN CT.[Consulting-A] ELSE 0 END +
            CASE WHEN C.[Consulting-B] > 0 THEN CT.[Consulting-B] ELSE 0 END +
            CASE WHEN C.[Consulting-C] > 0 THEN CT.[Consulting-C] ELSE 0 END AS f
    FROM Condition AS C
    INNER JOIN Data AS CT ON C.EmpID = CT.EmpID


text:
Q: Gnuplot heatmap XYZ Hey guys I'm trying to do a real heat map like in    A true heat map in R, but in GNUPLOT.
My file is like
3 1 2
3 4 3
3 5 5

4 1 7
4 1 2
4 4 3
4 5 2

5 1 3
5 1 2
5 4 3

.
..
....

and I've tried with
plot "file" using 1:2:3 with image
splot "file" using 1:2:3 p3md
etc..
Also I follow this example http://gnuplot.sourceforge.net/demo/heatmaps.html, but nothing.
Can someone shed some light here please?
Thanks

A: set pm3d interpolate 2,2
splot "file"

You can adjust level of interpolation by changing the number or even set it as 0 to tell gnuplot to "guess" it. It is not well documented what interpolation method that gnuplot is using, so be careful.
set pm3d interpolate 0,0
splot "file"

Here's the result without interpolation:

Here's the result with interpolation 2,2:

Here's the result with interpolation 0,0:

A: Use the pm3d option:
set pm3d
splot "file"

redpajama_set_name: RedPajamaStackExchange


text:
Q: One vs. many domain user accounts in a server farm We are in a migration process of a group of related computers (Intranet servers, SQL, application servers of one application) to a new domain. In the past we used one domain user account for every computer (web1, web2, appserver1, appserver2, sql1, sqlbackup ...) to access central Windows resources like network shares. Every computer also has a local user account with the same name.
I am not sure if this is necessary, or if it would be easier to configure and maintain to use one domain user account.
Are there key advantages / disadvantages of having one single user account vs. dedicated accounts per computer for this group of background servers? If I am not wrong, one advantage besides easier administration of the user account could be that moving installed applications and services around between the computers does not require a check of the access rights anymore. (Except where IP addresses or ports are used)

A: I might be misreading what you're asking here, but if you have one domain, then your domain administrator account will have admin rights on all of the attached systems.
The only advantage to creating multiple, separate accounts is for partitioning of responsibilities and control. One separate admin account for each server might make sense if each server had its own administrator and you wanted to ensure they didn't overstep their responsibilities.
As for local users, it's wise to maintain separate accounts on each member server that you can use should your domain spontaneously explode, but I wouldn't say there's any need to use them for day-to-day administration.


text:
Q: How do I deal with connection strings in a Click-Once application? I'm thinking of building a Click-Once application, and am trying to wrap my head around how to handle the whole connection string issue. The problem is the following:
I want to use EF to get data directly from each client, thus requiring each client to have a connection string configured (this is not the issue). How do I deal with clients that are not on the same domain as the SQL Server being queried? In other words, if I tried to run my app from home as opposed to from work, what should my connection string look like? Would I need to configure my SQL Server differently to allow this scenario?
Thanks in advance!

A: This issue goes beyond ClickOnce, it's a general networking issue.
The first question is: Can you reach the SQL Server at all from home?
Most likely the answer is "no" if the SQL Server is on an internal company network.  You would need to set up a VPN in order to reach the server.  If you set up a VPN, then you should be able to use the same connection string from home as long as you fully-qualify the server names, i.e. SqlServer.mycompany.local as opposed to just SqlServer.  You would likely connect to the VPN using domain credentials, so you would be able to use the same connection strings.
But an even better way would be to use a wrapper such as WCF Data Services.  This will expose the data through a Web Service (WCF) and gives you a lot of functionality - you can write Linq against it and everything.  In the long run, this is probably going to be easier to work with if you expect the application to be used remotely.
In our case, we actually have business services - a fairly large API that provides business logic over Web Services as opposed to just wrapping database tables (call it an SOA if you like).  In the super-long term, this is the best option because it abstracts a logical API as opposed to a database, but if you're looking for a quick fix, WCF Data Services might be the way to go.

A: How are you planning to authenticate the home users?  Within a domain you can check the user accounts permissions, using integrated authentication so the connection string itself does not contain credentials.  For users outside of a domain I don't think this is possible.
I would think you need to wrap your database behind a webservice, with the webservice supporting a non-domain based authentication scheme.  Remote users access that not the database.

A: Use SQL authentication.  That will work across domains.

A: Although SQL auth would work, you'd need a different user/password combo set up for each user of your application on the SQL server. Not an ideal or easy to maintain situation.
Your best bet is to not connect to the database at all. Instead, build a secure web service that your application calls to obtain its data. That web service can then be secured via Windows or username/password auth (which can be validated against the AD domain).

A: If the SQL Server is routeable on the same hostname regardless of where the client is (i.e. your home, client's offices) - I'm guessing you've got some sort of VPN or DMZ set up so your SQL server is accessible outside of your office building - then you can leave the connection string in your application fine and use SQL authentication (which is username/password vs Windows authentication.)
If your SQL server requires a different connection string (e.g. at work it's accessed at sql.internal.domain.com, outside of work at sql.external.domain.com) then you're going to need some sort of selection mechanism where the user can choose which connection to use before logging in - have all possible connection strings in your application.
You could also do funky things like using the IP address to determine which connection string to use (e.g. if the current PCs IP address is in the range 172.40.10.1 - 172.40.10.254) then connect to sql.internal.domain.com, otherwise sql.external.domain.com.  Of course this is more difficult to maintain though.
EDIT:
As others have suggested, a web service may also pay in dividends here.


text:
Q: An efficient way to implement a ecommerce Cart using Spring and MongoDb I am learning Spring and I am trying to find an efficient way to implement a Cart for an ecommerce.
My requirements are that I must use MongoDb.  Also I understand that a Cart must be linked to only one User (reasonable, right?) and it encompasses a list of itens.  My difficulty is to find out the better way to do that.
My first thought was create a Cart like a relational db, but Mongo is not relational.
In a relational way I would create:

*

*a table for item

*a table for user;

*a table for cart with a fk to user id;

*a table for items inside the cart with a fk to item and a fk to cart id;

But I must get rid off the relational addiction when dealing with MongoDb.
So my actual attempt is:
package br.com.daniel.domain;

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

import org.springframework.data.annotation.Id;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Getter;
import lombok.Setter;
@Document(collection = "cartitem")
public class Cart implements Serializable, Comparable<Cart>{
    /**
     *
     */
    private static final long serialVersionUID = 4126573094618706732L;
    @Id
    @Getter
    @Setter
    @JsonProperty
    private String id;

    @Getter
    @Setter
    @JsonProperty
    List<CartItem> itens;
    @Override
    public int compareTo(Cart o) {
        // TODO Auto-generated method stub
        return 0;
    }
}

The CartItem is described below.
package br.com.daniel.domain;

import java.io.Serializable;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@Document(collection = "cartitem")
public class CartItem implements Serializable, Comparable<CartItem >{
    /**
     *
     */
    private static final long serialVersionUID = -1131052187929548122L;

    @Id
    @Getter
    @Setter
    @DBRef
    private Item item;

    @Getter
    @Setter
    @JsonProperty
    private Integer quantity;

    @Override
    public int compareTo(CartItem o) {
        return o.getItem().compareTo(o.getItem());
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((item == null) ? 0 : item.hashCode());
        result = prime * result + ((quantity == null) ? 0 : quantity.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof CartItem )) {
            return false;
        }
        CartItem other = (CartItem ) obj;
        if (item == null) {
            if (other.item != null) {
                return false;
            }
        } else if (!item.equals(other.item)) {
            return false;
        }
        if (quantidade == null) {
            if (other.quantity != null) {
                return false;
            }
        } else if (!quantidade.equals(other.quantity)) {
            return false;
        }
        return true;
    }
}

My doubts are:

*

*Is this the bes tway to implement?

*Are the annotations @Document correct for the sake of my e-commerce cart project?


text:
Q: Object destructuring to a named object I'm trying to destructure an object using the following code.
const searchdata = {
    org,
    packageName,
    description,
    keywords
} = this.state;

but I get the following error.
Uncaught ReferenceError: org is not defined

What am I doing wrong here? could we destruture and object into another named object?
added a sample of the state object
this.state = {
    searchKey: '',
    onValueChange: false,
    org: '',
    packageName: '',
    description: '',
    keywords: '',
};

A: You can do it by way of elimination using object rest:

const state = {
  searchKey: '',
  onValueChange: false,
  org: '',
  packageName: '',
  description: '',
  keywords: '',
};

const {
  searchKey,
  onValueChange,
  ...searchdata
} = state;

console.log(searchdata);


text:
Q: How to combine short dragging and long press I have a UILongPressGestureRecognizer with minimumPressDuration to 0.5. I need it for fast dragging. Now I also want to detect when a user makes a long press without moving the fingers for more than few seconds. How to do it?

A: Take a look at UIGestureRecognizerDelegate Protocol Reference.
Your UIView will have to adopt this protocol and implement - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer method. If you have only this two recognizers attached you can simply return YES.
Don't forget to set your UIView as a delegate of both UIGestureRecognizers.


text:
Q: jQuery get all attributes as string variation I've got some simple html a bit like this
balrbalr

I'd like to be able to get the full contents of  as a string.
I know you can use .html to get the inner html, however if I use
var string = $('a').html();

If would return, balrblabrlabr
If I do string = $('a').parent.html();
I'd get ALL of the 's inside the parent.
how would I go about just getting the full html content of itself?

A: You can use native javascript outerHTML property of DOM elements:
var string = $('a')[0].outerHTML;

Live DEMO

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

MDN

If you wish to get the outerHTML of multiple elements, you can use jQuery map function, like in this example:
var str = $('#foo a').map(function() {
    return this.outerHTML;
}).get();

Live DEMO

A: Set your element's id to "a" and just use this function
    function msg() {
        var attrib="";
        var el =document.getElementById('a');
        for (var i = 0; i < el.attributes.length; i++) {
            attrib = attrib + ' ' + el.attributes.item(i).nodeName + ' = "' + el.attributes.item(i).nodeValue + '"';
        }
        alert(attrib);
    }


text:
Q: How to show boxes properly? (Algorithm, UI) I am currently trying to generate a View with React Typescript where I can show all Appointments of a day (similar to outlook calendar). But I am facing an issue. When Appointments are overlapping how can I determine the with and position? So I guess that I probably need an algorithm accomplish this issue.
Here an example how it could be structured:

Every box stands for an Appointment
The classes of the Object looks like this:
class AppointmentStructured {
  appointment: Appointment
  width?: number
  left?: number
}

class Appointment {
start: Date
end: Date
subject:string
duration: number
}

I am looking for a solution where I can determine the width (max. 1 = 100%) of the specific appointment and additionally I need the position. The easiest would be to how far it is from the left (max. 1). When there are more than 2 appointments starting at the same time, the appointments are ordered by the appointment with the longest duration.
Example the third box from the image would be:

*

*width: 0.333

*left: 0.666

Out of this data I can use CSS to design them.
The generated CSS then would look more or less like this:
 position: absolute;
 width: calc(100% * 0.33333);
 top: 20rem; //doesn't matter for the algorithm
 left: calc(100% * 0.66666)

--Edit
This is how far i came. It starts with the method generateAppointmentTile([])
export interface AppointmentStructured {
    appointment: Appointment
    width: string | number;
    left: string | number
}

export const generateAppointmentTile = (appointments: Appointment[]): AppointmentStructured[] => {
    var appointmentsStructured = initAppointmentStructured(appointments);
    var response: AppointmentStructured[] = [];

    for (var i = 0; i < appointmentsStructured.length; ++i) {
        var width = 1;

        var previous = getPreviousOverlapping(appointmentsStructured, i);
        var previousWidth = previous
            .map((item: AppointmentStructured): number => item.width as number)
            .reduce((a: number, b: number): number => a + b, 0)

        var forward = getForwardOverlapping(appointmentsStructured, i);
        var forwardOverlays = appointmentOverlays(forward);

        var previousHasOverlayWithForward = false;
        previous.forEach((structured: AppointmentStructured) => checkAppointmentOverlaySingle(structured, forward) !== 0 ? previousHasOverlayWithForward = true :  null);

        width = (width - previousWidth) / (!previousHasOverlayWithForward && forwardOverlays !== 0 ? forwardOverlays : 1);
        appointmentsStructured[i].width = width;
        response.push(appointmentsStructured[i]);
    }

    response.forEach((value: AppointmentStructured): void => {
        value.width = `calc((100% - 8rem) * ${value.width})`;
    });

    return response
}
const appointmentOverlays = (reading: AppointmentStructured[]): number => {
    var highestNumber = 0;

    reading.forEach((structured: AppointmentStructured): void => {
        var start = checkAppointmentOverlaySingle(structured, reading) + 1;
        highestNumber = start > highestNumber ? start : highestNumber;
    });

    return highestNumber;
}

const checkAppointmentOverlaySingle = (structured: AppointmentStructured, reading: AppointmentStructured[]): number => {
    var start = 0;

    reading.forEach((item: AppointmentStructured): void => {
        if (item.appointment.id !== structured.appointment.id) {
            if ((structured.appointment.start <= item.appointment.start && structured.appointment.end >= item.appointment.start)
                || (structured.appointment.start >= item.appointment.start && structured.appointment.start <= item.appointment.end)) {
                start += 1;
            }
        }
    });

    return start;
}

const getPreviousOverlapping = (appointmentsStructured: AppointmentStructured[], index: number): AppointmentStructured[] => {
    var response: AppointmentStructured[] = [];

    for (var i = index - 1; i >= 0; --i) {
        if (appointmentsStructured[index].appointment.start >= appointmentsStructured[i].appointment.start
            && appointmentsStructured[index].appointment.start <= appointmentsStructured[i].appointment.end) {
            response.push(appointmentsStructured[i]);
        }
    }
    return response;
}

const getForwardOverlapping = (appointmentsStructured: AppointmentStructured[], index: number): AppointmentStructured[] => {
    var response: AppointmentStructured[] = [];

    for (var i = index; i < appointmentsStructured.length; ++i) {
        if (appointmentsStructured[index].appointment.start >= appointmentsStructured[i].appointment.start
            && appointmentsStructured[index].appointment.start <= appointmentsStructured[i].appointment.end) {
            response.push(appointmentsStructured[i]);
        }
    }
    return response;
}

const initAppointmentStructured = (appointments: Appointment[]): AppointmentStructured[] => {
    var appointmentsStructured: AppointmentStructured[] = appointments
        .sort((a: Appointment, b: Appointment): number => a.start.getTime() - b.start.getTime())
        .map((appointment: Appointment): AppointmentStructured => ({ appointment, width: 100, left: 0 }));
    var response: AppointmentStructured[] = [];

    // sort in a intelligent way
    for (var i = 0; i < appointmentsStructured.length; ++i) {
        var duration = appointmentsStructured[i].appointment.end.getTime() - appointmentsStructured[i].appointment.start.getTime();
        var sameStartAppointments = findAppointmentWithSameStart(appointmentsStructured[i], appointmentsStructured);
        var hasLongerAppointment: boolean = false;
        sameStartAppointments.forEach((structured: AppointmentStructured) => (structured.appointment.end.getTime() - structured.appointment.start.getTime()) > duration ? hasLongerAppointment = true : null);

        if (!hasLongerAppointment) {
            response.push(appointmentsStructured[i]);
            appointmentsStructured.splice(i, 1);
            i = -1;
        }
    }

    return response.sort((a: AppointmentStructured, b: AppointmentStructured): number => a.appointment.start.getTime() - b.appointment.start.getTime());
}

const findAppointmentWithSameStart = (structured: AppointmentStructured, all: AppointmentStructured[]): AppointmentStructured[] => {
    var response: AppointmentStructured[] = [];
    all.forEach((appointmentStructured: AppointmentStructured) => appointmentStructured.appointment.start === structured.appointment.start
        && appointmentStructured.appointment.id !== structured.appointment.id ? response.push(appointmentStructured) : null)
    return response;
}

Even some pseudo code would help me a lot.

A: This solution is based on this answer: Visualization of calendar events. Algorithm to layout events with maximum width
I've just ported the script from C# to JS and extracted some steps.

*

*Group all your intervals/appointments into distinct groups, where one group does not influence another.

*For each group, fill columns from left to right (with each appointment getting the same width). Just use as many columns as you need.

*Stretch each appointment maximally.

*Make the actual boxes from that and render them.

This procedure is not perfect. Sometimes you will have a thin box on the left and the box to the right got stretched all the way. This happens mainly when the left box has a long "overlap chain" to the bottom, which does not really happen in practice.

/*
interface Interval {
  start: number;
  end: number;
}
*/

// Just for demonstration purposes.
function generateIntervals({ count, maxStart, maxEnd, minLength, maxLength, segments }) {
  return Array.from(Array(count), () => randomInterval())

  function randomInterval() {
    const start = randomInt(0, maxStart * segments) / segments
    const length = randomInt(minLength * segments, maxLength * segments) / segments
    return {
      start,
      end: Math.min(start + length, maxEnd),
      text: "Here could be your advertising :)"
    }
  }

  function randomInt(start, end) {
    return Math.floor(Math.random() * (end - start) + start)
  }
}

function isOverlapping(interval1, interval2) {
  const start = Math.max(interval1.start, interval2.start)
  const end = Math.min(interval1.end, interval2.end)
  return start < end
}

// Sorts by start ascending.
function sortIntervalsByStart(intervals) {
  return intervals
    .slice()
    .sort(({ start: s1 }, { start: s2 }) => s1 - s2)
}

// Split intervals into groups, which are independent of another.
function groupIntervals(intervals) {
  const groups = []
  let latestIntervalEnd = -Infinity
  for (const interval of sortIntervalsByStart(intervals)) {
    const { start, end } = interval
    // There is no overlap to previous intervals. Create a new group.
    if (start >= latestIntervalEnd) {
      groups.push([])
    }
    groups[groups.length - 1].push(interval)
    latestIntervalEnd = Math.max(latestIntervalEnd, end)
  }
  return groups
}

// Fill columns with equal width from left to right.
function putIntervalsIntoColumns(intervals) {
  const columns = []
  for (const interval of intervals) {
    let columnIndex = findFreeColumn(interval)
    columns[columnIndex] = (columns[columnIndex] || []).concat([interval])
  }
  return columns

  function findFreeColumn(interval) {
    let columnIndex = 0
    while (
      columns?.[columnIndex]
        ?.some(otherInterval => isOverlapping(interval, otherInterval))
    ) {
      columnIndex++
    }
    return columnIndex
  }
}

// Expand columns maximally.
function makeBoxes(columns, containingInterval) {
  const boxes = []
  for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {
    for (const interval of columns[columnIndex]) {
      const columnSpan = findColumnSpan(columnIndex, interval)
      const box = {
        ...interval,
        top: (interval.start - containingInterval.start) / (containingInterval.end - containingInterval.start),
        height: (interval.end - interval.start) / (containingInterval.end - containingInterval.start),
        left: columnIndex / columns.length,
        width: columnSpan / columns.length
      }
      boxes.push(box)
    }
  }
  return boxes

  function findColumnSpan(columnIndex, interval) {
    let columnSpan = 1
    while (
      columns
        ?.[columnIndex + columnSpan]
        ?.every(otherInterval => !isOverlapping(interval, otherInterval))
    ) {
      columnSpan++
    }
    return columnSpan
  }
}

function computeBoxes(intervals, containingInterval) {
  return groupIntervals(intervals)
    .map(intervals => putIntervalsIntoColumns(intervals))
    .flatMap(columns => makeBoxes(columns, containingInterval))
}

function renderBoxes(boxes) {
  const calendar = document.querySelector("#calendar")

  for (const { top, left, width, height, text = "" } of boxes) {
    const el = document.createElement("div")
    el.style.position = "absolute"
    el.style.top = `${top * 100}%`
    el.style.left = `${left * 100}%`
    el.style.width = `${width * 100}%`
    el.style.height = `${height * 100}%`
    el.textContent = text
    calendar.appendChild(el)
  }
}

const hours = 24
const intervals = generateIntervals({
  count: 20,
  maxStart: 22,
  maxEnd: hours,
  maxLength: 4,
  minLength: 1,
  segments: 2,
})
const boxes = computeBoxes(intervals, { start: 0, end: hours })
renderBoxes(boxes)
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

#calendar {
  height: 100vh;
  width: 100vw;
  min-height: 800px;
  position: relative;
}

#calendar > * {
  border: 1px solid black;
  background-color: #b89d9d;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  overflow-y: auto;
}


text:
Q: Example on Banach-Mazur distance Suppose two normed vector spaces $X,Y$ are isomorphic, and we define the Banach-Mazur distance between $X,Y$ as $$ d(X,Y)=\inf \{ \|T\|\|T^{-1}\|:T\in GL(X,Y) \} ,$$ where $GL(X,Y)$ is the space of all linear isomorphisms.

Is there a simple example of two infinite dimensional normed spaces that are isomorphic and we know exactly the B-M distance ( except $c_0,c$ )?

Where $c$ is the set of convergent sequences and
$c_0$ the set of sequences converging to $0$


text:
Q: Android Alarm manager not firing when device is in sleep mode I'm trying to create a reminder app for tablets.
My problem is that if the tablet is in sleep mode the alarm isn't getting called.
i tried a lot off project on github none of them wase working when my tablet wase in sleep mode.
My code is the following:
The code to set the alarm:
    Intent intent = new Intent(getApplicationContext(),RingAlarmReceiver.class);
    Intent intent = new Intent("kidsplaylist.info.waketest.MyWakefulReceiver");

    PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 30);

        alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent);

The code of the receiver:
public class MyWakefulReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    WakeLocker.acquire(context);
    // Start the service, keeping the device awake while the service is
    // launching. This is the Intent to deliver to the service.
    Intent service = new Intent(context, MyIntentService.class);
    startWakefulService(context, service);
    }
}

The code for the service that is supposed to ring the alarm:
public class MyIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
public MyIntentService() {
    super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    // Do the work that requires your app to keep the CPU running.
    String song = Settings.System.DEFAULT_RINGTONE_URI.toString();

    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(song));
        mediaPlayer.prepare();
        mediaPlayer.setLooping(false);
        mediaPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    MyWakefulReceiver.completeWakefulIntent(intent);
    }
}

Can anyone with experience in such thick advice me how to fix it
Thank's a lot
Avi
P.B: When the device is connected to the charger or when the screen is on it works OK
The problem is when the device screen is off.

A: Note that on Android 6.0+, Doze mode and app standby will affect AlarmManager events.
Beyond that, using an IntentService to directly play media will not work well. Once onHandleIntent() returns, the IntentService is destroyed, and your process will typically be terminated shortly thereafter.
I strongly recommend that you raise a Notification that uses this media as a ringtone. That would eliminate the need for the service entirely (you could raise the Notification in onReceive(), since that should be fairly quick to execute). It gives the user more control over whether the music plays (via Notification controls on Android 5.0+), and it gives the user a straightforward way to shut it up (swipe away the Notification).
If you insist upon playing the media yourself, you will need to use a regular Service and manage your own WakeLock, so that you can keep all that outstanding while the media is playing. Use an OnCompletionListener to stopSelf() the service and release() the WakeLock when the media is done.


text:
Q: force element to use 100% of available space between fixed width elements? I've got a div being used as a container for 3 other divs. These are all lined up horizontally, using float:left. I need the left and right divs to keep their same fixed width of 40px. I want the middle div to expand dynamically - using only CSS if possible.
Here is a JSFiddle I'm experimenting with: http://jsfiddle.net/xJB9n/
If you update the width of my .middle CSS class to 620px, this is the result I'm looking for, where the middle div is expanded as much as it can, while keeping itself horizontally aligned with the other two divs.
No matter the width of container I want the middle div to always expand to 100% of the area that's left, and setting:
width: 100%;

does not do the trick. Does anyone know of a way to accomplish this?

A: If you can change the markup, this may work:

With the following CSS:
.middle {
    height: 100%;
    margin: 0 40px;
}

.left {
    width: 40px;
    float: left;
}

.right {
    width: 40px;
    float: right;
}

See this fiddle.

Alternatively you can use absolute positioning, though this can be a pain in IE7 and below. This does allow you to keep DOM order though.

With this (relevant) CSS:
.container { position: relative; }

.left  { position: absolute; left: 0;  top: 0; }
.right { position: absolute; right: 0; top: 0; }

.middle { margin: 0 40px; }

See this fiddle for a demo.

A: Don't know if you can use flexbox, but the following works on Chrome, Firefox, and Safari.
.container
{
    height: 100px;
    width: 700px;
    border: 1px solid black;
    display: box;
    display: -moz-box;
    display: -webkit-box;
}

.left, .right
{
    height: 100%;
    width: 40px;
    background-color: red;
    -moz-box-flex: none;
    -webkit-box-flex: none;
    box-flex: none;
}

.middle
{
    background-color: blue;
    height: 100%;
    -moz-box-flex: 1;
    -webkit-box-flex: 1;
    box-flex: 1;
}

You can see the fiddle http://jsfiddle.net/sx2Sg/

A: From your structure.
2 options:

*

*display:table

*display:flex
display:table works fine for all browsers, including IE8.
Display:flex is still growing and is not yet mature and many browser has difficulties with it .
I propose then only display:table;
http://jsfiddle.net/xJB9n/1/
Don't mistake, it's only CSS, you have no
 in your markup.

A: In addtion to the css of @Jeroen you need to add one more thing:
html, body {
    height: 100%;
}

.middle {
    height: 100%;
    margin: 0 40px;
}

.left {
    width: 40px;
    float: left;
}

.right {
    width: 40px;
    float: right;
}

The thing I added is to actually set the height to 100%. Without the parent elements' height set 100% you can't apply height 100% to child elements.
See this fiddle for demo.


text:
Q: JS - Thin number of points based on density Say I have an array as follows (each small array is [x, y]):
var myPoints = [[25, 28], [26, 26], [70, 40], [50, 50], [300, 300], [285, 350], [1000, 1000]];

Let's say I need to thin the array down to 4 points. (this is a small example, my acutal array has thousands of points) How could I go about thinning the array based on density so more points are removed from areas with points closer together and less points are removed from areas with lower density?
In this case (reducing the above array from 8 to 4 items) I would expect the returned array to look something like the following:
var thinnedPoints = [[25, 28], [70, 40], [300, 300], [1000, 1000]];

My idea on how to approach this would be to generate a dictionary that maps the point to it's minimum distance to another point (e.g. a point close to another point would have a small minimum distance) then sort the dictionary based on ascending minimum distance, then remove every n'tn item of the dictionary.
The problem with this approach is I don't know how to efficiently generate the distance to closest other point value for each point.
Is there an efficient way to generate those values or maybe is there another way to approach this density based thinning problem?
Thanks!

A: It seems you want to solve either a P-center problem or a P-median problem.
From Approximability Results for the p-Center Problem by Stefan Buettcher,

The p-Center problem, also known as the Min-Max Multicenter problem
  or the Facility Location problem, is a famous problem from operations
  research. Informally, it is the problem of placing fire stations in a
  city so that the maximum time to reach any point in the city is
  minimized.

From Methods for Solving the p-Median Problem: An Annotated Bibliography by J. Reese,

The p-median problem is simply stated as: Given a graph or a network
  G = (V, E), find Vp ⊆ V such that |Vp| = p, where p may either
  be variable or fixed [...], and that the sum of the shortest distances
  from the vertices in {V\Vp} to their nearest vertex in Vp is
  minimized.

Both problems are NP-complete in general, so there is no (known) way to solve them in polynomial time. But there are various heuristics you could try.

A: A very simple and efficent solution that works especially well on large sets is to just pick the points randomly. This implicitly removes less points from regions containing less points than elsewhere - which seems to be just what you want, if you only want to scale the density linearly. It should yield the same results as your approach, without needing to calculate any distances.
If the data is not ordered in any way (i.e. already random), you can also drop every second point or just the first or second half.
If you want to tweak the density distribution non-linearly, you could divide the set into multiple regions (e.g. squares) small enough so that the density is roughly uniform in each of them, and then drop every n-th of the points per region. If you choose the region size appropriately, this approach might also deliver better (and more consisten) results than the purely random one on smaller data sets.

A: You can use for..of loop, for loop, .map(), Math.min(), .filter().
Loop through each element of array, assign x, y to separate array variables; subtract the difference between each element in x or y arrays; map original array, begin by removing first or second element of matched pair where the two elements have the least numeric difference between any other number in array; that is, the two numbers are separated by the least amount of digits. Continue removing elements, as distance between numbers increases, until n, here, 3, elements are removed from original array.
For example, mapping x can return either
  [[25, 28], [70, 40], [300, 300], [1000, 1000]];

or
  [[26,26], [50,50], [285,350], [1000,1000]]

as the range between the numbers is the same each in direction
  [1, 1, 20, 20, 15, 15, 700]

var myPoints = [
  [25, 28],
  [26, 26],
  [70, 40],
  [50, 50],
  [300, 300],
  [285, 350],
  [1000, 1000]
];

var [x, y] = [
  [],
  []
];

var [xx, yy] = [
  [],
  []
 ];

for (let z of myPoints) {
  [x, y] = [
    [...x, z[0]],
    [...y, z[1]]
  ];
}

var stop = 3;

for (var i = 0; i < x.length; i++) {
  var prop = x[i];
  if (typeof xx[i] !== "object") {
    xx[i] = {
      index: i,
      diff: [],
      value: prop
    };
  }

  for (var len = 0; len < x.length; len++) {
    var key = x[len];
    xx[i].diff.push(
      prop > key
      ? prop - key
      : key > prop ? key - prop : Infinity
    )
  }
}

var range = xx.map(prop => Math.min.apply(Math, prop.diff));
var temp = range.slice(0);

for (var i = 0; i < stop; i++) {
  var curr = Math.min.apply(Math, temp);
  var index = temp.indexOf(curr);
  temp[index] = Infinity;
  var pair = Math.min.apply(Math, temp);
  var next = temp.indexOf(pair);
  temp[next] = Infinity;
  x[next] = void 0;
};

var res = myPoints.map((prop, index) =>
            x[index] === undefined ? null : prop).filter(Boolean);

console.log(res);

usage as a function

var myPoints = [
  [25, 28],
  [26, 26],
  [70, 40],
  [50, 50],
  [300, 300],
  [285, 350],
  [1000, 1000]
];

var filter = (arr, xy, n) => {

  var [x, y] = [
    [],
    []
  ];

  var [xx, yy] = [
    [],
    []
  ];

  for (let z of arr) {
    [x, y] = [
      [...x, z[0]],
      [...y, z[1]]
    ];
  }

  var XY = {
    "x": [x, xx],
    "y": [y, yy]
  };

  var item = XY[xy];
  var stop = n;
  for (var i = 0; i < item[0].length; i++) {
    var prop = item[0][i];
    if (!item[1][i]) {
      item[1][i] = {
        index: i,
        diff: [],
        value: prop
      };
    }

    for (var len = 0; len < item[0].length; len++) {
      var key = item[0][len];
      item[1][i].diff.push(
        prop > key ? prop - key : key > prop ? key - prop : Infinity
      )
    }
  }

  var range = item[1].map(prop => Math.min.apply(Math, prop.diff));
  var temp = range.slice(0);

  for (var i = 0; i < stop; i++) {
    var curr = Math.min.apply(Math, temp);
    var index = temp.indexOf(curr);
    temp[index] = Infinity;
    var pair = Math.min.apply(Math, temp);
    var next = temp.indexOf(pair);
    temp[next] = Infinity;
    item[0][next] = void 0;
  };

  return arr.map((prop, index) =>
    item[0][index] === undefined ? null : prop).filter(Boolean);
}

console.log(filter(myPoints, "x", 3));


text:
Q: .Net C# WinForm DataGridView - TextBox Cell: what's the best way to update/change from a numeric user input to a specific culture currency? A. BACKGROUND OF THE QUESTION
I am trying to have a cell in a datagridview to accept a numeric only user input, which I've handled on the Grid's EditingControlShowing event and the textbox cell's KeyPress event. Now, after the user hits enter or leaves the focus from that cell, I would like to update the cell's value to have a decimal separator and the specific culture currency. The following is the flow that I'm trying to explain:

*

*numeric user input on a datagridview cell -> done (NOTE: cell's ValueType == int || double already).

*on cell's leave focus, update the cell value to have decimal separator and specific currency symbol from a culture, to display. (The reason to have a specific culture so that if the application is installed on a different machine with different culture, it will stay on that specific culture).

*on cell's enter focus or editing, i would like to strip all of that separators and currency symbol and go back to the numeric only user input value.
B. THE QUESTIONS

*

*First of all, is there a way to implement this without using the CellFormatting event? (I would like to prefer to avoid using this event because this event is called so often and I don't want to put burden on the performance already).

*I already use the following:
NumberFormatInfo numberFormat = CultureInfo.CreateSpecificCulture("de-DE").NumberFormat;
double d = double.Parse(<value>, numberFormat);
string test = d.ToString(numberFormat);

But, it doesn't really updates the value, what do I miss here?

*what's the best way to implement the behavior, for example, is the cellValueChanged event and CellEnter event will be the best events to handle the above behavior? or CellValidated and CellEnter events will be best events?

Basically, I'm confused on which event is the best event to handle the behavior (without being called so often such as CellFormatting event which is called every time the grid is painted or basically every time you touch the grid), and how to enforce the NumberFormatInfo to that string value.
Thanks!
EDIT (15/09/2016): I actually can update the value to what I want, by doing this:
string test = d.ToString("c2", numberFormat);

I thought the numberFormat itself is sufficient to applying the format because it has the information, but I actually have to explicitly specifying the format such as "c2" from above example, and it acts like a "command" which take the information from a "dictionary" which in this case the "numberFormat" (the definition).

A: So, this is how it works for me:

*

*I added DataGridViewColumn programmatically, so when I create those columns, I setup these properties:
DataGridViewTextBox column = new DataGridViewTextBoxColumn();
...
column.ValueType = typeof(decimal);
column.DefaultCellStyle.Format = "c2";
column.DefaultCellStyle.FormatProvider = CultureInfo.CreateSpecificCulture("de-DE").NumberFormat;

*Handle on the DataGridView EditingControlShowing event, to remove the Currency Symbol and to only shows the number only during editing the cell's value:
public void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
 ...
 if(decimal.TryParse(grid.EditingControl.Text, NumberStyles.Currency, CultureInfo.CreateSpecificCulture("de-DE").NumberFormat, out decimalValue))
 {
  grid.EditingControl.Text = decimalValue.ToString("#", CultureInfo.CreateSpecificCulture("de-DE").NumberFormat);
 }
 ...
}

*Handle on the `CellValidating' event, to make sure the user input value is in proper format (or in numeric only):
public void Grid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
 ...
  //No need to check/validate the new row
  if (gridSender.Rows[e.RowIndex].IsNewRow)
  {
   return;
  }
  ...
  if(!decimal.TryParse(value, NumberStyles.Currency, CultureInfo.CreateSpecificCulture("de-DE").NumberFormat, out result))
  {
   e.Cancel = true;
  }
  ...
 }

NOTE: if you do step #1 above (i.e. "c2" and specifying the FormatProvider), then it will automatically shows the Currency Symbol and the decimal points, every time the user leave focus of the cell of that column. So, the only thing needs to do, is stripping the currency symbol and how to show the value in numeric only by doing step #2. Step #3, is just another validation to make sure the input is numeric.
Example Flow:

*

*users click on the cell and in edit more, it will display 1000

*user click on another cell or focus away, it will display $1.000,00

*user click on the cell again and in editing, it will display 1000
The above solutions works good enough for me.

A: Why is having a culture currency symbol such a big deal for you Jay??? Also why are decimal points such a big deal??? Can the program work without these and achieve the same goal??? Would it not be better to determine the culture symbol of the currency at the outset in the program and possibly use it as a variable and append it later to the string?


text:
Q: ModSecurity SecRule based on original browser url, not internal rewrite (index.php, app.php, etc.) I'm working on a Symfony 2 site, and am trying to create a ModSecurity rule to match a particular browser URL.  IE example.com/results
Symfony 2 internally rewrites all requests to app.php using rules in .htaccess, so when I check REQUEST_URI in the ModSecurity rule, it is set to app.php.  I have tried any other server parameter that appears relevant, but all are either app.php or blank.
Is there any way to create a ModSecurity rule in a config file that is based on the URL requested by the browser, rather than on the result of an internal rewrite?
The same issue appears to exist with CMS's like wordpress: everything is rewritten to index.php, so I can't find any way to apply modsec rules to a specific route.  (I figured since WP is so common I might be able to find an answer by searching for the same problem there.)

A: It looks like I can use the server variable THE_REQUEST, as per this answer: https://stackoverflow.com/a/27968463/160565

A:
It looks like I can use the server variable THE_REQUEST, as per this answer: https://stackoverflow.com/a/27968463/160565
:
I'm using mod_rewrite to dump THE_REQUEST into an environment variable just above the mod_security rules, then matching on that.

As noted, THE_REQUEST is an Apache server variable used by mod_rewrite, not a mod_security variable. The directly equivalent variable in mod_security is REQUEST_LINE, ie. the first line of the request. This takes the form of a string like:
GET /foo/bar HTTP/1.1

THE_REQUEST (mod_rewrite) variable does not change when the URL is rewritten, whereas REQUEST_URI (mod_rewrite) does.
However, I'm a bit surprised that the REQUEST_URI (mod_security) variable is returning the rewritten URL (maybe this is to do with the ordering of directives or using mod_security embedded?), instead of the originally requested URL, unless you are actually using the REQUEST_URI (mod_rewrite) variable (assigning this to an env var?) in your mod_security rule?

just above the mod_security rules...

The mod_security rules should probably be at the top of your file, if not already, before any mod_rewrite directives. (Although whether the order really matters I'm not sure.)
Note that the REQUEST_URI (mod_security) variable is not the same as the REQUEST_URI (mod_rewrite) variable, despite being named the same. Notably, REQUEST_URI (mod_security) contains the query string, whereas REQUEST_URI (mod_rewrite) does not.
Reference:

*

*https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-%28v2.x%29#REQUEST_LINE

UPDATE:

... the REQUEST_URI (mod_security) variable is returning the rewritten URL

You may be running the mod_security rule too late in the request, ie. in the wrong phase? To process the requested URL you should be comparing against REQUEST_URI in either phase 1 or 2 (the request). Later phases (ie. 3 - 5) will process against the response which may explain why you are seeing the rewritten URL and not the requested URL.
The phase is set in the action argument or SetDefaultAction directive. For example:
SecDefaultAction "log,pass,phase:2,id:4"
SecRule REQUEST_URI "attack" "phase:1,id:52,t:none,t:urlDecode,t:lowercase,t:normalizePath"

The five phases are:

*

*Request headers (REQUEST_HEADERS)

*Request body (REQUEST_BODY)

*Response headers (RESPONSE_HEADERS)

*Response body (RESPONSE_BODY)

*Logging (LOGGING)

Starting in ModSecurity version v2.7 there are aliases for some phase numbers:
2 - request
4 - response
5 - logging
Example:
SecRule REQUEST_HEADERS:User-Agent "Test" "phase:request,log,deny,id:127"

Reference:

*

*https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v2.x)#Processing_Phases

*https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v2.x)#phase

*https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v2.x)#REQUEST_URI


text:
Q: How to Mutate a Dichotomous Variable Based on The Yearly Mean of Another Variable in R? I am wondering how users on here would go about creating a new dichotomous variable in a dataframe based on whether a value in another variable falls above or below that variable's yearly average. I have tried checking for similar answers, but while I have uncovered the recommendation to use the aggregate function to generate the means on groups in a dataframe, that does not fully address my needs in this case.
Specifically I have a spatially lagged variable (already constructed), and I want to make a dichotomous variable that captures whether a state (id = COW) falls above or below the yearly average in my spatially lagged variable.
This is not the actual data I am working with, but a simplified version that should convey the structure of the data. Needless to say there are many other covariates and states in the actual dataframe. The Year variable is comprised of discrete intervals comprising all years from 1967-2018 (inclusive). In terms of additional information, the number of states is not equal across all years, as I have removed state entries prior to their formal entrance into (eg. South Sudan entering after 1967), or after their formal exit from the international state system (eg. Czechoslovakia):
COW     Year        SL_UN_ICCPR
2       1967        0
20      1967        0
31      1967        0
40      1967        0
...
2       1968        0
20      1968        1.2
31      1968        1.5
...
2       1980        4.6
20      1980        3.7
31      1980        3.0
...
900     2018        5.10
910     2018        2.6
920     2018        1.5

I want to produce output like this:
COW     Year        SL_UN_ICCPR     Dichotomous
2       1967        0                      0
20      1967        0                      0
31      1967        0                      0
40      1967        0                      0
...
2       1968        0                      0
20      1968        1.2                    0
31      1968        1.5                    1 #(assuming yearly mean = 1.4)
...
2       1980        4.6                    1
20      1980        3.7                    1
31      1980        3.0                    0  #(assuming yearly mean = 3.1)
...
40      2018        5.10                   1
42      2018        2.6                    0 #(assuming yearly mean = 3.2)
51      2018        1.5                    0

I've tried grouping the data by Year with group_by but the following code is not producing the desired result:
Data <- group_by(Data, Year)
Data <- mutate(Data, Spatial_Dummy_ICCPR = ifelse(SL_UN_ICCPR > mean(SL_UN_ICCPR) , 1, 0))

This produces a dichotomous variable without the desired grouping by year, instead mutating based on the overall variable mean. Can anyone give me some direction on where I am going wrong?

A: You need to first create the average by year, then ungroup and finally create your dummy. Something like this should work:
library(tidyverse)
Data %>%
group_by(Year)%>%
mutate(avg_year = mean(SL_UN_ICCPR))%>%
ungroup()%>%
mutate(Spatial_Dummy_ICCPR = ifelse(SL_UN_ICCPR > avg_year , 1, 0))

A: You could use base R's ave to create a variable with yearly means on which you apply the ifelse, conveniently in a within.
d <- within(d, {
  SL_UN_ICCPR.mean=ave(SL_UN_ICCPR, Year, FUN=mean)
  Spatial_Dummy_ICCPR=ifelse(SL_UN_ICCPR > SL_UN_ICCPR.mean, 1, 0)
})
#    COW Year SL_UN_ICCPR Spatial_Dummy_ICCPR SL_UN_ICCPR.mean
# 1    2 1967         0.0                   0         0.000000
# 2   20 1967         0.0                   0         0.000000
# 3   31 1967         0.0                   0         0.000000
# 4   40 1967         0.0                   0         0.000000
# 5    2 1968         0.0                   0         0.900000
# 6   20 1968         1.2                   1         0.900000
# 7   31 1968         1.5                   1         0.900000
# 8    2 1980         4.6                   1         3.766667
# 9   20 1980         3.7                   0         3.766667
# 10  31 1980         3.0                   0         3.766667
# 11 900 2018         5.1                   1         3.066667
# 12 910 2018         2.6                   0         3.066667
# 13 920 2018         1.5                   0         3.066667

Data
d <- structure(list(COW = c(2L, 20L, 31L, 40L, 2L, 20L, 31L, 2L, 20L,
31L, 900L, 910L, 920L), Year = c(1967L, 1967L, 1967L, 1967L,
1968L, 1968L, 1968L, 1980L, 1980L, 1980L, 2018L, 2018L, 2018L
), SL_UN_ICCPR = c(0, 0, 0, 0, 0, 1.2, 1.5, 4.6, 3.7, 3, 5.1,
2.6, 1.5)), row.names = c(NA, -13L), class = "data.frame")


text:
Q: Question about how all related objects are used in trigger I am new to Saleforce coding but I have some prior development experience in some other Programming language as well. I am trying to learn triggers by myself now.
Can some one help me to understand the below code especially how the List (contactList) and temporary contact variable (myCon) are related.
trigger UpdateContactAddr on Account (before update) {
    for(Account acc: Trigger.new){
        List<Contact> ContactList = [Select Id from Contact where Contact.Id = :acc.Id];
        for(Contact myCon: contactList){
            myCon.MailingCountry = acc.BillingCountry;
        }
        update ContactList;
    }
}

*

*Because my doubt is that we are getting full list of all Contacts from an Account in  list variable.

*Inside loop - Then for each record in <contactList> its assigned to myCon temporary variable one by one and move  Account variable acc in it

*Then finally outside the loop updating the List -  ContactList directly

Can you please help me to understand, how ContactList is updated directly as the actual value is just moved to myCon only and no assignment happened to ContactList and the piece of code works

A: Iterating over a list like this:
for(Contact myCon: contactList){
    // myCon represents each record in a list
}

is same as:
for(Integer count = 0; count < contactList.size(). count++){
    // contactList[count] - now this represent each record
}

Its a short hand of iterating over a list.
Now will try to explain the code:
trigger UpdateContactAddr on Account (before update) {

    // iterate over all the updated records
    for(Account acc: Trigger.new){

        // query all Contacts where Account Id matches current Account record from list
        List<Contact> ContactList = [Select Id from Contact where AccountId = :acc.Id];

        // iterate over all contacts of current parent
        for(Contact myCon: contactList){

            // myCon represents contact record from list
            // you are modifying Mailing country on Contact with Account's Billing country
            // this would update be in your Contact list
            myCon.MailingCountry = acc.BillingCountry;
        }

        // now at this point you are performing update operation
        // this would save all changes to Mailing country to Contacts
        update ContactList;
    }
}

You have SOQL and DML inside a for loop, which is a bad practice. Suggest you to learn from awesome Trailhead site. Refer this module for triggers.


text:
Q: Should Internal error (500) be part of Swagger API documentation? As far as I checked on many swagger files of Amazon/Google and more, That error code (or generally error codes of 5xx family) is not shown as a part of the swagger files. Is their  a reason for that?
I am asking because one of our microservices API returns 500 when it fails to communicate to other service (for instance) and we are wondering if that error code should be part of our swagger files.

A: I think API documentation should only contain expected errors such as 4xx ones. But 5xx are unexpected errors and should not be documented.

A: Generally clients/consumers can't do much upon getting the 5xx errors, since those are purely server side errors. So it need not to be part of your API specification.
If you think, based on the error which the API throws, client/consumer should do something (For example retry or try another site or so.), then Yes.


text:
Q: Laravel: eloquent select * vs select column In my Laravel API everyone and everywhere written select *, even when it does not need to collect all the column data.
Is it better to use eloquent select instead, specifying exactly what's needed?

A: There are several ways of doing this:
To select only specific fields you can do something like:
ModelName::all('column1', 'column2', 'column3');

Or using get:
ModelName::get(['id', 'date']);

For Models with relationships:
$model->relation()->only(['column1', 'column2']);

If you need to eager load while selecting specific columns with relationship:
$data = Model::with(array('relation' => function($query)
{
    $query->select('name');

}))->get();

You can read more at collections


text:
Q: Dynamic SASS variables from a server side language I have a database table that contains a list of colour variables (example HEX colour code). My styles are compiled using Gulp and SASS.
When my Django app creates/updates a row in the database i need to build a new stylesheet based on the colours.
Somehow i need to get the colours from my server side app into a build process.
Record with colours added -> Gulp runs -> New colour variables are used within the stylesheet generation.

Any ideas how this could be done?
Thanks,

A: I solved this problem in a less than ideal way..
There is a module called gulp-preprocess which take a context array and replaces vars before the sass process runs..
For example:
SASS File
$body-background: '/* @echo body-background */';

body {
  background: $body-background;
}

GULP
var data = {
    '1': {
        'body-background': '#f00',
    },
    '2': {
        'body-background': '#ffffff',
    }
}

gulp.task('scss', function () {

    for (var partner_id in data) {
        if (!data.hasOwnProperty(partner_id)) continue;
        var partner_data = data[partner_id]

        gulp.src('./static/scss/*.scss')
            .pipe($.sourcemaps.init())
            .pipe($.preprocess({context: partner_data}))
            .pipe($.sass({
                    errLogToConsole: true,
                    style: 'compact'
                })
                .on('error', function (err) {
                    console.log('Error:', err);
                    this.emit('end');
                }))
            .pipe($.autoprefixer({cascade: false}))
            .pipe($.cssnano())
            .pipe($.sourcemaps.write('./maps'))
            .pipe(gulp.dest('./static/css/'+ partner_id))
    }
});

A: I came across this service https://www.grooveui.com, that lets you create multiple themes from your SASS files.
The only catch is you have to host your SASS files with them. Then you can create new themes and set variable values. I guess they are using database to store variables and generating multiple SASS files.
Could be worth a try.


text:
Q: How to receive broadcasts in ServiceTestCase? I'm stuck with this issue.
Here is the code of my service:
public class APIService extends IntentService {

    public static final String MY_SERVICE = "com.approject.myproject.APIService";
    private HttpClient httpClient = null;
    private ArrayList<AbbrRecord> results = null;

/*Constructor*/
public APIService(){
    super("APIService");
}

/*Process created.*/
/*Intialize HttpClient.*/
@Override
public void onCreate(){
    super.onCreate();
    httpClient = new DefaultHttpClient();
}

/*HandleIntent from Activities*/
@Override
public void onHandleIntent(Intent i){
    results = null;
    HttpGet getMethod = new HttpGet("http://www.someurl.com" +    i.getStringExtra("search_request")); //getData().toString()
    try{
        InputStream instream = null;
        HttpResponse response = httpClient.execute(getMethod);
        HttpEntity entity = response.getEntity();
        if(entity != null){
            instream = entity.getContent();
        }
        InputSource input_source = new InputSource(instream);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try{
            SAXParser parser = factory.newSAXParser();
            XMLReader xml_reader = parser.getXMLReader();
            DataParser content_handler = new DataParser();
            xml_reader.setContentHandler(content_handler);
            xml_reader.setErrorHandler(content_handler);
            xml_reader.parse(input_source);
            results = content_handler.pullDataOut();
        }catch(ParserConfigurationException e){
            e.printStackTrace();
        }catch(SAXException e){
            e.printStackTrace();
        }
    } catch(ClientProtocolException e){
        e.printStackTrace();
    } catch(IOException e){
        e.printStackTrace();
    }
    if(results == null){
        if( i.getIntExtra("sender", -1) == 0){
            Intent it = new Intent("DATA_WAS_NOT_RETRIEVED");
            sendBroadcast(it);
            Log.d(getClass().getSimpleName(), "DATA_WAS_NOT_RETRIEVED BROADCAST WAS SENT FOR MAIN");
        } else {
            Intent it = new Intent("DATA_WAS_NOT_RETRIEVED_RESULTS");
            sendBroadcast(it);
        }
    } else {
        if(i.getIntExtra("sender", -1) == 0){
            Intent it = new Intent("RETRIEVE_DATA_MAIN");
            it.putExtra("search_results", results);
            sendBroadcast(it);
            Log.d(getClass().getSimpleName(), "DATA_RETRIEVED BROADCAST WAS SENT FOR MAIN");
        } else {
            Intent it = new Intent("RETRIEVE_DATA_RESULTS");
            it.putExtra("search_results", results);
            sendBroadcast(it);
        }
    }
    Log.d(getClass().getSimpleName(), "Intent was handled.");
}

@Override
public void onDestroy(){
    super.onDestroy();
    Log.d( getClass().getSimpleName(), "APIService is destroyed");
}
}

APIServiceTest.java
public class APIServiceTest extends ServiceTestCase<APIService>{

private BroadcastReceiver receiver1 = null;
private BroadcastReceiver receiver2 = null;
private ArrayList<AbbrRecord> results = null;

public APIServiceTest(){
    super(APIService.class);
}

@Override
protected void setUp() throws Exception{
    super.setUp();
    receiver1 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent){
            ArrayList<AbbrRecord> results = (ArrayList)intent.getSerializableExtra("search_results");
        }
    };
    receiver2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ArrayList<AbbrRecord> results = (ArrayList)intent.getSerializableExtra("search_results");
        }
    };
    IntentFilter filter1 = new IntentFilter();
    filter1.addAction("RETRIEVE_DATA_MAIN");
    getSystemContext().registerReceiver(receiver1, filter1);
    IntentFilter filter2 = new IntentFilter();
    filter2.addAction("DATA_WAS_NOT_RETRIEVED");
    getSystemContext().registerReceiver(receiver2, filter2);
}

public void testMakeRequest() throws InterruptedException{
    Intent i = new Intent();
    i.putExtra("search_request", "asap");
    i.putExtra("sender", 0);
    i.setClassName("com.approject.myproject", "com.approject.myproject.APIService");
    getSystemContext().startService(i);
    assertFalse(results == null);
}

@Override
protected void tearDown() throws Exception{
    super.tearDown();
    if(receiver1 != null && receiver2 != null){
        getSystemContext().unregisterReceiver(receiver1);
        getSystemContext().unregisterReceiver(receiver2);
    }
}
}

I already tried using MockApplication, MockContext classes.
Command line output:
com.approject.APIServiceTest:
Failure in testMakeRequest:

junit.framework.AssertionFailedError

at com.approject.myproject.APIServiceTest.testMakeRequest(APIServiceTest.java:71)

at java.lang.reflect.Method.invokeNative(Native Method)

at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)

at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)

at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)

at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

..

Test results for InstrumentationTestRunner=.F..

Time: 10.239
FAILURES!!!

Tests run: 3,  Failures: 1,  Errors: 0

Log:
02-07 19:54:13.358: DEBUG/AndroidRuntime(239): >>>>>>>>>>>>>> AndroidRuntime   START<<<<<<<<<<<<<<
02-07 19:54:13.358: DEBUG/AndroidRuntime(239): CheckJNI is ON
02-07 19:54:13.568: DEBUG/AndroidRuntime(239): --- registering native functions ---
02-07 19:54:13.888: DEBUG/ddm-heap(239): Got feature list request
02-07 19:54:14.208: DEBUG/ActivityManager(59): Uninstalling process    com.approject.myproject
02-07 19:54:14.238: INFO/ActivityManager(59): Start proc com.approject.myproject for  added application com.approject.myproject: pid=245 uid=10029 gids={3003, 1015}
02-07 19:54:14.368: DEBUG/ddm-heap(245): Got feature list request
02-07 19:54:14.588: INFO/TestRunner(245): started: testMakeRequest(com.approject.myproject.APIServiceTest)
02-07 19:54:15.778: DEBUG/dalvikvm(245): GC freed 3273 objects / 241584 bytes in 83ms
02-07 19:54:17.398: DEBUG/APIService(245): DATA_RETRIEVED BROADCAST WAS SENT FOR MAIN
02-07 19:54:17.398: DEBUG/APIService(245): Intent was handled.
02-07 19:54:17.518: DEBUG/dalvikvm(245): GC freed 5615 objects / 327224 bytes in 62ms
02-07 19:54:17.888: DEBUG/APIService(245): APIService is destroyed
02-07 19:54:24.650: INFO/TestRunner(245): failed: testMakeRequest(com.approject.myproject.APIServiceTest)
02-07 19:54:24.650: INFO/TestRunner(245): ----- begin exception -----
02-07 19:54:24.679: INFO/TestRunner(245): junit.framework.AssertionFailedError
02-07 19:54:24.679: INFO/TestRunner(245):     at  junit.framework.Assert.fail(Assert.java:47)
02-07 19:54:24.679: INFO/TestRunner(245):     at junit.framework.Assert.assertTrue(Assert.java:20)
02-07 19:54:24.679: INFO/TestRunner(245):     at junit.framework.Assert.assertFalse(Assert.java:34)
02-07 19:54:24.679: INFO/TestRunner(245):     at junit.framework.Assert.assertFalse(Assert.java:41)
02-07 19:54:24.679: INFO/TestRunner(245):     at com.approject.myproject.APIServiceTest.testMakeRequest(APIServiceTest.java:71)...
02-07 19:54:24.689: INFO/TestRunner(245): ----- end exception -----
02-07 19:54:24.729: INFO/TestRunner(245): finished: testMakeRequest(com.approject.myproject.APIServiceTest)
02-07 19:54:24.749: INFO/TestRunner(245): started: testServiceTestCaseSetUpProperly(com.approject.myproject.APIServiceTest)
02-07 19:54:24.799: INFO/TestRunner(245): finished: testServiceTestCaseSetUpProperly(com.approject.myproject.APIServiceTest)
02-07 19:54:24.799: INFO/TestRunner(245): passed: testServiceTestCaseSetUpProperly(com.approject.myproject.APIServiceTest)
02-07 19:54:24.809: INFO/TestRunner(245): started: testAndroidTestCaseSetupProperly(com.approject.myproject.APIServiceTest)
02-07 19:54:24.829: INFO/TestRunner(245): finished: testAndroidTestCaseSetupProperly(com.approject.myproject.APIServiceTest)
02-07 19:54:24.829: INFO/TestRunner(245): passed: testAndroidTestCaseSetupProperly(com.approject.myproject.APIServiceTest)
02-07 19:54:24.859: DEBUG/AndroidRuntime(239): Shutting down VM
02-07 19:54:24.859: DEBUG/dalvikvm(239): DestroyJavaVM waiting for non-daemon threads to exit
02-07 19:54:24.869: DEBUG/ActivityManager(59): Uninstalling process com.approject.myproject

Thank you for your time.


text:
Q: Difference between List, List>, List, List, and List What are the differences between List, List<?>, List<T>, List<E>, and List<Object>?
1. List
List: is a raw type, therefore not typesafe. It will only generate a runtime error when the casting is bad. We want a compile time error when the cast is bad. Not recommended to use.
2. List<?>
List<?> is an unbounded wildcard. But I'm not sure what it's for? I can print a List<?> without issue:
public static void test(List<?> list){
    System.out.println(list);   // Works
}

Why can't I add items to a List<?>?
public static void test(List<?> list){
    list.add(new Long(2));     // Error
    list.add("2");             // Error
    System.out.println(list);
}

3. List<T>
public static void test(List<T> list){   // T cannot be resolved
    System.out.println(list);
}

I don't understand this syntax. I saw something like this, and it works:
public <T> T[] toArray(T[] a){
    return a;
}

Sometimes, I see <T>, or <E>, or <U>, <T,E>. Are they all the same or do they represent something different?
4. List<Object>
This gives the error "The method test(List<Object>) is not applicable for the argument List<String>":
public static void test(List<Object> list){
    System.out.println(list);
}

If I try this then I got "Cannot cast from List<String> to List<Object>":
test((List<Object>) names);

I am confused. String is a subclass of Object, so why isn't List<String> a subclass of List<Object>?

A: 1) Correct
2) You can think of that one as "read only" list, where you don't care about the type of the items.Could e.g. be used by a method that is returning the length of the list.
3) T, E and U are the same, but people tend to use e.g. T for type, E for Element, V for value and K for key. The method that compiles says that it took an array of a certain type, and returns an array of the same type.
4) You can't mix oranges and apples. You would be able to add an Object to your String list if you could pass a string list to a method that expects object lists. (And not all objects are strings)

A: In your third point, "T" cannot be resolved because its not declared, usually when you declare a generic class you can use "T" as the name of the bound type parameter, many online examples including oracle's tutorials use "T" as the name of the type parameter, say for example, you declare a class like:
public class FooHandler<T>
{
   public void operateOnFoo(T foo) { /*some foo handling code here*/}

}

you are saying that FooHandler's operateOnFoo method expects a variable of type "T" which is declared on the class declaration itself, with this in mind, you can later add another method like
public void operateOnFoos(List<T> foos)

in all the cases either T, E or U there all identifiers of the type parameter, you can even have more than one type parameter which uses the syntax
public class MyClass<Atype,AnotherType> {}

in your forth ponint although efectively Sting is a sub type of Object, in generics classes there is no such relation, List<String> is not a sub type of List<Object> they are two diferent types from the compiler point of view, this is best explained in this blog entry

A: I would advise reading Java puzzlers. It explains inheritance, generics, abstractions, and wildcards in declarations quite well.
http://www.javapuzzlers.com/

A: Let us talk about them in the context of Java history ;

*

*List:

List  means it can include any Object. List was in the release before Java 5.0; Java 5.0 introduced List, for backward compatibility.
List list=new  ArrayList();
list.add(anyObject);

*List<?>:

? means unknown Object not any Object; the wildcard ? introduction is for solving the problem built by Generic Type; see wildcards;
but this also causes another problem:
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error

*List< T> List< E>
Means generic Declaration at the premise of none T or E type in your project Lib.

*List< Object> means  generic parameterization.

A: Theory
String[] can be cast to Object[]
but
List<String> cannot be cast to List<Object>.
Practice
For lists it is more subtle than that, because at compile time the type of a List parameter passed to a method is not checked.  The method definition might as well say List<?> - from the compiler's point of view it is equivalent.  This is why the OP's example #2 gives runtime errors not compile errors.
If you handle a List<Object> parameter passed to a method carefully so you don't force a type check on any element of the list, then you can have your method defined using List<Object> but in fact accept a List<String> parameter from the calling code.
A.  So this code will not give compile or runtime errors and will actually (and maybe surprisingly?) work:
public static void main(String[] args) {
    List argsList = new ArrayList<String>();
    argsList.addAll(Arrays.asList(args));
    test(argsList);  // The object passed here is a List<String>
}

public static void test(List<Object> set) {
    List<Object> params = new ArrayList<>();  // This is a List<Object>
    params.addAll(set);       // Each String in set can be added to List<Object>
    params.add(new Long(2));  // A Long can be added to List<Object>
    System.out.println(params);
}

B.  This code will give a runtime error:
public static void main(String[] args) {
    List argsList = new ArrayList<String>();
    argsList.addAll(Arrays.asList(args));
    test1(argsList);
    test2(argsList);
}

public static void test1(List<Object> set) {
    List<Object> params = set;  // Surprise!  Runtime error
}

public static void test2(List<Object> set) {
    set.add(new Long(2));       // Also a runtime error
}

C.  This code will give a runtime error (java.lang.ArrayStoreException: java.util.Collections$UnmodifiableRandomAccessList Object[]):
public static void main(String[] args) {
    test(args);
}

public static void test(Object[] set) {
    Object[] params = set;    // This is OK even at runtime
    params[0] = new Long(2);  // Surprise!  Runtime error
}

In B, the parameter set is not a typed List at compile time: the compiler sees it as List<?>.  There is a runtime error because at runtime, set becomes the actual object passed from main(), and that is a List<String>.  A List<String> cannot be cast to List<Object>.
In C, the parameter set requires an Object[].  There is no compile error and no runtime error when it is called with a String[] object as the parameter.  That's because String[] casts to Object[].  But the actual object received by test() remains a String[], it didn't change.  So the params object also becomes a String[].  And element 0 of a String[] cannot be assigned to a Long!
(Hopefully I have everything right here, if my reasoning is wrong I'm sure the community will tell me.  UPDATED: I have updated the code in example A so that it actually compiles, while still showing the point made.)

A: Problem 2 is OK, because " System.out.println(set);" means "System.out.println(set.toString());" set is an instance of List, so complier will call List.toString();
public static void test(List<?> set){
set.add(new Long(2)); //--> Error
set.add("2");    //--> Error
System.out.println(set);
}
Element ? will not promise Long and String, so complier will  not accept Long and String Object

public static void test(List<String> set){
set.add(new Long(2)); //--> Error
set.add("2");    //--> Work
System.out.println(set);
}
Element String promise it a String, so complier will accept String Object

Problem 3: these symbols are same, but you can give them differet specification. For example:
public <T extends Integer,E extends String> void p(T t, E e) {}

Problem 4: Collection does not allow type parameter covariance. But array does allow covariance.

A: For the last part:
Although String is a subset of Object, but List<String> is not inherited from List<Object>.

A: The notation List<?> means "a list of something (but I'm not saying what)". Since the code in test works for any kind of object in the list, this works as a formal method parameter.
Using a type parameter (like in your point 3), requires that the type parameter be declared. The Java syntax for that is to put <T> in front of the function. This is exactly analogous to declaring formal parameter names to a method before using the names in the method body.
Regarding List<Object> not accepting a List<String>, that makes sense because a String is not Object; it is a subclass of Object. The fix is to declare public static void test(List<? extends Object> set) .... But then the extends Object is redundant, because every class directly or indirectly extends Object.

A: The reason you cannot cast List<String> to List<Object> is that it would allow you to violate the constraints of the List<String>.
Think about the following scenario: If I have a List<String>, it is supposed to only contain objects of type String. (Which is a final class)
If I can cast that to a List<Object>, then that allows me to add Object to that list, thus violating the original contract of List<String>.
Thus, in general, if class C inherits from class P, you cannot say that GenericType<C> also inherits from GenericType<P>.
N.B. I already commented on this in a previous answer but wanted to expand on it.

A: You're right: String is a subset of Object. Since String is more "precise" than Object, you should cast it to use it as an argument for System.out.println().


text:
Q: IE10 - Hebrew text reversed - how to fix? I am facing issue with Hebrew language in IE10 and Firefox. Some part of the text gets reversed as mentioned below:
(79 הכול 1 - 50) מתוך
The number 79 should be after הכול with a closing bracket. Its working fine in IE11.
Tried the steps given in IE10 - RTL reversed - how to fix? however its not working.


text:
Q: Beautiful Soup - inserting before extracted portion of parse tree I'm trying to extract information from a large webpage using Beautiful Soup 4.  The information I want is contained within one particular div, which I can extract without problem:
passage = soup.find("div", class_="desired_div")

I then want to add tags before the extracted part of the tree - e.g. I want to wrap the extracted div with another div - in preparation for outputing the extracted info as another html file.
With BS4, how do I insert tags before the extracted portion of the parse tree, or wrap the extracted portion of the parse tree? BS4 seems to only allow me to operate on the children of the extracted div (as per the documentation), but I want to insert before or wrap the extracted div.

A: BeautifulSoup is intended to extract the content out of a HTML file. It is not intended to build HTML elements. There is however another library Karrigell that can be used to achieve what you are trying to do.
Related answers on StackOverflow:

*

*python html generator

*Generating HTML documents in python
EDIT: BeautifulSoup 4.2.1 supports creating new tags and adding them into the HTML. BeautifulSoup.new_tag() creates a new HTML tag and insert_before() and insert_after() allow you add them before or after certain elements.

A: In case anyone else is looking for a solution, here's what I ended up doing.
First, find the div of interest:
tag = soup.find("div", class_="desired_div")

Next, wrap another 'placeholder' div around the div of interest
newtag = soup.new_tag("div")
newtag['class'] = "placeholder"
tag.wrap(newtag)

THEN extract the placeholder div:
passage = soup.find("div", class_="placeholder").extract()

The div of interest is now a child of the extracted portion of the parse tree, and so ready for adding tags before or wrapping tags around.
I'm certainly open to a better solution, but this does seem to work.


text:
Q: Reindex monthly indices into daily indices in Elasticsearch I have some monthly indices like monthly-2021-01, monthly-2021-02 containing documents with a date field.
I would like to break those monthly indices into daily ones
so that documents from the 1st of January in monthly-2021-01 are then stored in daily-2021-01-1.
I tried with the _reindex API but found no way of adding a condition for the reindexed documents.

A: Can be done with
{
        "source": {
            "index": "index-src",
            "query": {
                "bool": {
                    "must": {
                        "range": {"date": {"gte": "start-date", "lt": "end-date"}},
                    }
                }
            },
        },
        "dest": {
            "index": "index-dest"
        }
    }

Then do this for each mont/date relation


text:
Q: Can i run a facebook application hosted on localhost Is it possible to run a facebook hosted on localhost?Will other users throughout the world will be able to use that app or the firewall will be blocking facebook from fetching content from my computer when users request for it?

A: Firewalls don't even get a chance to intercept it.
"localhost" is on a non-routable network by definition of IPv4. I can not reach your home computer by name reliably and "localhost" will always resolve to the local host.
There are some tricks that you can use to make your home machine visible to the outside world, but they are not reliable and I really don't want to use a service that went down because your Angry Birds game crashed your machine.

A: In your app's basic settings (https://developers.facebook.com/apps) under Settings->Basic->Select how your app integrates with Facebook...
Use "Site URL:" and "Mobile Site URL:" to hold your production and development URLs. Both sites will be allowed to authenticate. I'm just using Facebook for authentication so I don't need any of the mobile site redirection features. I usually change the "Mobile Site URL:" to my "localhost:12345" site while I'm testing the authentication, and then set it back to normal when I'm done.


text:
Q: How to add data in JavaScript and bind it to jQuery grid I have a form whose value get stored in the database on click of submit button.
Also there are 4 fields whose data is to be displayed into the struts2-jquery-grid. I first used a temporary table to save values and display those values in the grid. But this approach isn't correct as the values remain in the table even if the user doesn't click on submit.
So is there a way to temporary store the data of 4 fields into the array and display in the grid and then when user submits the data the values from the array(grid) are stored into the database.

A: Temporary table is not solution as you have mentioned in the post, but you can use a session map to save your array before you display it in the grid. When you submit a form the values from the session could be retrieved back to the action and a session map could be cleared. To use a session map with the action you should implement SessionAware or get the session from the action context. See this answer for using a session in JSP.


text:
Q: How can I set binary back to zero after checkbox is checked to false? I have have useState hook where I have array of 0's as follows const [binary, setBinary] = useState([0, 0, 0, 0, 0, 0, 0, 0]);
Then I have function called isToggled where I set the toggle to true and variable called bin that gets the binary value which is then sliced and concat and then set with the hook. I have so far it working a way that all the 0's will turn to 1's but won't go to zero when the checkbox is unchecked.

Then in the input fields onChange it is used as follows
<input type="checkbox" onChange={(e, b) => isToggled(0, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(1, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(2, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(3, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(4, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(5, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(6, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(7, b)} />

And in the text input field
<input
   name="binary"
   type="text"
   value={binary}
   onChange={binary.join("")}
/>

Whole code is as follows.
import React, { useState } from "react";
import "./App.css";

function Binary() {
  const [binary, setBinary] = useState([0, 0, 0, 0, 0, 0, 0, 0]);
  const [toggle, setToggle] = useState(false);
  const [decimal, setDecimal] = useState(0);
  const isToggled = (form) => {
    setToggle(true);
    let bin = binary
      .slice(0, form)
      .concat([toggle ? 1 : 0])
      .concat(binary.slice(form + 1));
    setBinary(bin);
  };
  const showDecimal = (e) => {
    setDecimal("" + parseInt(binary.join(""), 2));
    e.preventDefault();
  };
  return (

        <form className={"form"}>

            <input type="checkbox" onChange={(e, b) => isToggled(0, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(1, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(2, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(3, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(4, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(5, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(6, b)} />
            <input type="checkbox" onChange={(e, b) => isToggled(7, b)} />

            <input
              name="binary"
              type="text"
              value={binary}
              onChange={binary.join("")}
            />

            <button onClick={showDecimal}>Convert</button>

            <input type="text" value={decimal} />

        </form>

  );
}

export default Binary;

A: If you insist on this structure, I refactored your code a bit. I got rid of the "toggle" variable because you can just use the event from the input field. This means, that your new toggle is going to be the 'checked' state on the input itself which is either true or false. I tested it and it works.
import React, { useState } from "react";

function Binary() {
    const [binary, setBinary] = useState([0, 0, 0, 0, 0, 0, 0, 0]);
    const [decimal, setDecimal] = useState(0);
    const isToggled = (position, value) => {
        let bin = binary
            .slice(0, position)
            .concat([value ? 1 : 0])
            .concat(binary.slice(position + 1));
        console.log(bin)
        setBinary(bin);
    };
    const showDecimal = (e) => {
        setDecimal("" + parseInt(binary.join(""), 2));
        e.preventDefault();
    };
    return (

                <form className={"form"}>

                        <input type="checkbox" onChange={(e => isToggled(0, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(1, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(2, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(3, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(4, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(5, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(6, e.target.checked))} />
                        <input type="checkbox" onChange={(e => isToggled(7, e.target.checked))} />

                        <input
                            name="binary"
                            type="text"
                            value={binary}
                            readOnly
                        />

                        <button onClick={showDecimal}>Convert</button>

                        <input type="text" value={decimal} readOnly />

                </form>

    );
}

export default Binary;

A: First of all,
        <input type="checkbox" onChange={(e, b) => isToggled(0, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(1, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(2, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(3, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(4, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(5, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(6, b)} />
        <input type="checkbox" onChange={(e, b) => isToggled(7, b)} />

this is a very bad design. Try rendering like this:
{binary.map((bin,index) => <input key={index} type="checkbox" onChange={(e, b) => isToggled(index, b)} />)}

Since your rendered element does not depend on your binary state, your update doesn't reflect on the component, since the state changes but there is nothing different with the rendered jsx element
Note: Giving key={index} has some problems in some cases, which you can read more here


text:
Q: How to upload and convert XLSX file to JSON using ember.js I am trying to allow the user to upload an XLSX file to be converted to a JSON or CSV file to be parsed through on the back-end.  I am using node.js, and tried several packages including the read-excel-file
(https://github.com/catamphetamine/read-excel-file/blob/master/README.md)
readXlsxFile(file).then(function(data) {
let jsondata = JSON.parse(data);
-do something with jsondata-
});

A: The usual place to look for add-ons would be Ember Observer but the options available seem have a status of Work In Progress - they might be a useful place to look though to get some inspiration for how to proceed.
There are plenty of options on npm. You can import one of those into your project using the new add-on ember-auto-import or, if you'd rather do the hard work yourself, the Ember guides provide some guidance on manually importing.

A: You can use js-xlsx. Add it as bower dependecy and add its imports to your ember-cli-build file as:
app.import('bower_components/js-xlsx/dist/jszip.js');
app.import('bower_components/js-xlsx/dist/xlsx.min.js');

Handle it as the documentation's parsing-workbooks section shows. (handleFile function is explaining it well.)


text:
Q: Blocking a game on XP with the hosts file In the Windows XP hosts file (C:\windows\drivers\etc\hosts) replaces the mnemonic format with an ip address locally before talking to the dns.  Previously, I have used the four slots for hosts and keywords in a linksys router wrt54gs; which is very limiting. The segment below has been designed to block the game Adventure Quest with hosts collected from Fiddler2.

*

*How can this segment be consolidated and/or is there a better way to block this game?

*Does the host "battleon.com" differ from the host "www.battleon.com"?

*Can hosts reference a subdirectory "dragonfable.battleon.com/game/"?

*Can hosts reference a specific page?

*Is there a better way, have I errored, and any suggestions?

# BattleOn (Adventure Quest);

127.0.0.1 battleon.com
127.0.0.1 www.battleon.com
127.0.0.1 battleon.com/aq-play.asp # ? specific asp page
127.0.0.1 aq.battleon.com
127.0.0.1 banners.battleon.com
127.0.0.1 dragonfable.battleon.com
127.0.0.1 dragonfable.battleon.com/game/ # ? subdirectory
127.0.0.1 guardian.battleon.com
127.0.0.1 media.battleon.com
127.0.0.1 forums.battleon.com
127.0.0.1 forums1.battleon.com
127.0.0.1 forums2.battleon.com
127.0.0.1 video.battleon.com
127.0.0.1 adlegend.com
127.0.0.1 ad.adlegend.com
127.0.0.1 cpmstar.com
127.0.0.1 cdn.cpmstar.com
127.0.0.1 server.cpmstar.com
127.0.0.1 scorecardresearch.com
127.0.0.1 beacon.scorecardresearch.com
127.0.0.1 quantserve.com
127.0.0.1 edge.quantserve.com
127.0.0.1 pixel.quantserve.com

A:

*

*How can this segment be consolidated and/or is there a better way to block this game?

Without using third party software, not really. The advantage of this method is that the hosts files can most probably be copied over to a completely different operating system.

*

*Does the host "battleon.com" differ from the host "www.battleon.com"?

I think so. They are two different domains.

*

*Can hosts reference a subdirectory "dragonfable.battleon.com/game/"?

*Can hosts reference a specific page?

No. The .hosts file is meant to be a local 'replacement' for DNS systems. They will only look up the domain name, hence you can only block domains using a .hosts file, not paths.

*

*Is there a better way, have I errored, and any suggestions?

As I mentioned before, .hosts files are native and the same to pretty much any modern operating system. You could opt for some third part filtering software, but they can be expensive and possibly a bit too confusing.

A:
Does the host "battleon.com" differ from the host "www.battleon.com"?

No.

Can hosts reference a subdirectory "dragonfable.battleon.com/game/"?

No.

Can hosts reference a specific page?

No.
All you can do here is block the computer from being able to contact specific hosts. Not directories or pages on a particular website. In order to do that you will need to use your router, or specialized blocking hardware or software.

A: have a look at trusty old Proxomitron, still one of the finest and most efficient web filters.
at Sidki's page you'll find a well maintained up-to-date configuration file.

A:
Can hosts reference a subdirectory
  "dragonfable.battleon.com/game/"?
   Can hosts reference a specific page?
  Is there a better way, have I errored,
  and any suggestions?

No only domains. You want to block at the router level for that ability.

A: Blocking a web site, or domain this way works...  But it's all or nothing.
And second, anyone that has any technical ability will check the host file.  I hope this user isn't an Administrator, or have SuperUser rights...
The host file is easy to modify, and even easier to fix from this kind of damage....


text:
Q: Flutter :type '_InternalLinkedHashMap' is not a subtype of type 'String' I am trying to user Dio Client for making API calls. While I receive the response It throws an error

'_InternalLinkedHashMap' is not a subtype of type 'String'

Trying to resolve it but I can't. Below is the code

  Future<dynamic> get(
      String uri, {
        Map<String, dynamic> queryParameters,
        Options options,
        CancelToken cancelToken,
        ProgressCallback onReceiveProgress,
      }) async {
    try {
      final Response response = await _dio.get(
        uri,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onReceiveProgress: onReceiveProgress,
      );
      return response.data;
    } catch (e) {
      print(e.toString());
      throw e;
    }
  }
}

Post Api Call
Future<News> getPosts() async {
    try {
      final res = await _dioClient.get(Endpoints.getPosts);
      return News.fromJson(res);
    } catch (e) {
      print(e.toString());
      throw e;
    }
  }

Model class uses built_value
abstract class News implements Built<News, NewsBuilder> {
  News._();

  factory News([updates(NewsBuilder b)]) = _$News;

  @BuiltValueField(wireName: 'status')
  String get status;
  @BuiltValueField(wireName: 'totalResults')
  int get totalResults;
  @BuiltValueField(wireName: 'articles')
  BuiltList<Articles> get articles;
  String toJson() {
    return json.encode(serializers.serializeWith(News.serializer, this));
  }

  static News fromJson(String jsonString) {

    return serializers.deserializeWith(
        News.serializer, json.decode(jsonString));
  }

  static Serializer<News> get serializer => _$newsSerializer;
}

Serializer class
@SerializersFor([
  News,
  Articles,
  Source,
])
final Serializers serializers = (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

help me how to solve it

A: You need to change 2 things
1) use jsonSerializers instead of default serializers in your built_value.
2 )use response.toString() instead of data in dio. Here a working example from me, just copy the parts you need.
Built Value Model
abstract class TravelRequest implements Built<TravelRequest, TravelRequestBuilder> {
  TravelRequest._();

  factory TravelRequest([updates(TravelRequestBuilder b)]) = _$TravelRequest;

  @nullable
  @BuiltValueField(wireName: 'id')
  int get id;

  @nullable
  @BuiltValueField(wireName: 'country_from')
  String get countryFrom;

  @nullable
  @BuiltValueField(wireName: 'traveler_name')
  String get travelerName;

  @nullable
  @BuiltValueField(wireName: 'traveler_email')
  String get travelerEmail;

  @nullable
  @BuiltValueField(wireName: 'description')
  String get description;

  String toJson() {
    return json.encode(jsonSerializers.serializeWith(TravelRequest.serializer, this));
  }

  static TravelRequest fromJson(String jsonString) {
    return jsonSerializers.deserializeWith(TravelRequest.serializer, json.decode(jsonString));
  }

  static Serializer<TravelRequest> get serializer => _$travelRequestSerializer;
}

How to use with Dio
  Future createTravelRequest(TravelRequest travelRequest) {
return _apiProvider.dio.post(rootPath, data: travelRequest.toJson()).then((response) {
  travelRequests.add(TravelRequest.fromJson(response.toString()));
});
  }


text:
Q: Is it possible to make a .png (or other) image that does NOT have rectangular dimensions? This might be a dumb question, but is it possible to make a .png file that isn't square?
If so, how can one do this in Gimp?
Ideally I'd like one in the shape of an X.

A: All image formats (even vector) must maintain a rectangular border specifying the size of the image.
However, one can use the transparent properties of PNG images to simulate the appearance of a non-square image.

Just create your image/shape, ensure the background is transparent, and save the file in the PNG format.  Make sure you include the alpha channel so there is a transparent background saved with the image.