text:
Q: AWS Network ELB take 4 minutes to recognise target as healthy Using AWS Network ELBs: takes at least four minutes for a registered instance to become 'healthy'. The instances and services have been running for days, I am simply de-registering and then registering on the same target group, as part of a deployment. If I use a script or use the AWS UI, CLI it makes no difference.
Healthcheck Settings are:

*

*Port: tried various, all have listening services tested via curl. 80,22,9001

*Healthy threshold: 2

*Unhealthy threshold: 2

*Timeout: 10

*Interval: 30

I can see the connection requests coming in on whatever port has been specified, the service responds appropriately and the connection is then closed. As far as I am aware this should be sufficient for the ELB to determine that the instance is healthy (once the threshold has been passed). Which should mean that my instances are up and running no more than 90 seconds past registration time. I have no idea why this should be happening, should be straight forward.
I cannot determine what would be causing such a long delay given that I have fulfilled the known criteria for my instances being healthy. They sit at the Elb.InitialHealthChecking reason for about 4 minutes. Any ideas on further tests to determine the cause of the delay?

A: I can confirm this doesn't work till September 2021. I thought I did something wrong, but, everything was okay and the process to healthy status after 4-5 minutes. :|

A: That is close to being the expected behavior of NLB.

Yes,  when you register a new target to your Network Load Balancer, it is expected to take between 90 and 180 seconds to complete the registration process. After registration is complete, the Network Load Balancer health check systems will begin to send health checks to the target. A newly registered target must pass health checks for the configured interval to enter service and receive traffic. For example, if you configure your health check for a 30 second interval, and require 3 health checks to become healthy, the minimum time a newly registered target could enter service is 90 seconds after a new target passes its first health check.
Similarly, when you deregister a target from your Network Load Balancer, it is expected to take 90-180 seconds to process the requested deregistration, after which it will no longer receive new connections. During this time the Elastic Load Balancing API will report the target in 'draining' state. The target will continue to receive new connections until the deregistration processing has completed. At the end of the configured deregistration delay, the target will not be included in the describe-target-health response for the Target Group, and will return 'unused' with reason 'Target.NotRegistered' when querying for the specific target.

Support also confirmed there is no work in progress to make it any faster than 3 minutes.

A: We hit this issue with NLBs and raised it with AWS support on March 20, 2018. Their response:

This is a known issue, where a newly registered instance remains in initial state for longer period of time and our internal team is already working on the fix for this issue. Unfortunately, at this point in time we do not have an ETA for the fix.

They confirmed that, under normal circumstances, targets should remain in the initial state until HealthyThreshold health checks pass.


text:
Q: Cloudera Certification for Hadoop developer I want to write Cloudera certification for Hadoop developer as people suggested that it is more complex compared to Hortonworks certification.
I was looking for materials for my preparation. All the materials in Cloudera site is very expensive atleast for me. Can you please let me know the books which I can use to clear this certification?

A: If you know the content well in the following books, then you should be decently prepared to attempt the exam:
Hadoop: The Definitive Guide
Hadoop Operations

A: I am also planning to write CCA Spark and Hadoop Developer Exam (CCA175) this year.
Kindly find my steps of preparation:

*

*Haddop: The Definitive Guide

*Pro Apache Hadoop

*Hands on Practice by following youtube channel by itversity
Kindly add if you find more useful references.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple "cannot find symbol" errors I'm working on a homework problem for an intermediate Java class and I can't find the source of the errors I'm getting. I'm getting 50+ "cannot find symbol" errors for width, height, grid, and seed. There were issues with the constructor earlier (I had declared variables in an if statement), and I think that's where the issue might be, but I've tinkered and Googled and I can't pin down the problem. (I'm working in a terminal, not an IDE.)
//single particle diffusion
import java.util.Random;
import java.io.PrintStream;

/*****************************/
/*****************************/
/* Start Public Class NFrostN /
/*****************************/
/*****************************/

public class NFrostN {

/*****************************/
/*****************************/
/*********Constructor*********/
/*****************************/
/*****************************/
public NFrostN(String[] args){
int width;
int height;
int density;
int seed;
if (args.length > 0){
      //makes sure no more than 4 have been entered
    if (!this.checkArgs(args))
        {
        System.err.print("There's a problem with the arguments. Make sure you haven't entered a string or more than four arguments.");
        System.exit(1);} //exit with non-0 status
this.setWidth(args);
this.setHeight(args);
this.setDensity(args);
this.setSeed(args);
                }
int[][] grid = new int[this.width][this.height];
}

public NFrostN(){
int width;
int height;
int density;
int seed;
this.setWidth();
this.setHeight();
this.setDensity();
this.setSeed();
int[][] grid = new int[this.width][this.height];
}

/*****************************/
/*****************************/
/***Create a Random Integer***/
/******Regular+overloaded*****/
/*****************************/

int createRandomInt(int seed,int size){
        int randomb = (int) this.randoma.nextInt(size);
        return randomb;
        }

int createRandomInt(){
        int randomb = (int) randoma.nextInt();
//      int randomc = (int) randomb.nextInt(randomb);
        return randomb;
        }

/*****************************/
/*****************************/
/**Verify arguments and Set***/
/*****************************/
/*****************************/

private boolean checkArgs(String[] args) {
    if(args.length > 4) //if too many arguments entered. not specified, made the call
    {return false;}
    else return true;
}
/*****************************/
/*****************************/
/**Width Setter+ Overloaded***/
/*****************************/
/*****************************/

void setWidth(String args[]){
    int tempWidth;
    if (args.length > 0){
    int tempWidth = Integer.parseInt(args[0]);
    if(tempWidth % 1 == 0 || tempWidth > 0)
                {
            this.width = tempWidth;
                }
            //error message??
               }
    else
    width = 256;
            }

void setWidth(){width = 256;}

/*****************************/
/*****************************/
/**Height Setter+ Overloaded**/
/*****************************/
/*****************************/

void setHeight(String args[]){
    if (args.length > 1 ){
        int tempHeight = Integer.parseInt(args[1]);
            if(tempHeight % 1 == 0 || tempHeight > 0)
                {
            height = tempHeight;
                }
             //error message??
               }
    else height = 256;
}

void setHeight(){height = 256;}

/*****************************/
/*****************************/
/*Density Setter+ Overloaded**/
/*****************************/
/*****************************/

void setDensity(String args[]){
    if (args.length > 2){
    int tempDensity = Integer.parseInt(args[2]);
        if(tempDensity % 1 == 0 || tempDensity > 0 || tempDensity <= 100)
                {
            density = tempDensity;
                }
            //error message???
               }
    else density = 25;
}

void setDensity(){density = 25;}

/*****************************/
/*****************************/
/***Seed Setter+ Overloaded***/
/*****************************/
/*****************************/

void setSeed(String args[]){
    int tempSeed = Integer.parseInt(args[3]);
    int myRandom = (int) this.randoma.nextInt();
    if (args.length > 3){
        if(tempSeed % 1 == 0 || tempSeed > 0 || tempSeed <= 100)
                {
            this.seed = tempSeed;
                }
             //error message ?
               }
    else seed = myRandom;
}

Random makeRand(){
Random randoma = new Random(seed);
return randoma;
}

void setSeed(){
    Random newRand = makeRand;
    int myRandom = (int) newRand.nextInt();
    seed = myRandom;
}

/*****************************/
/*****************************/
/**********Getters************/
/*****************************/
/*****************************/

int getWidth(){return width;}
int getHeight(){return height;}
int getDensity(){return density;}
int getSeed(){return seed;}
int[][] getGrid(){return grid;}

/*****************************/
/*****************************/
/*****Sum of all in array*****/
int gridSum(){
int count = 0;
for (int i = 0; i < height; i++)
    for (int j = 0; i < width; i++){
    {count += grid[height][width];}
        }
return count;
}

/*****************************/
/*****************************/
/*******Difusion Method*******/
/*****************************/
/*****************************/

boolean diffuse(){
    boolean filled = false;
    int diffusionSteps = ((this.height * this.width) * 2); //two times the size of the grid
    int steps = 0; //steps counter
    Random genRandom = new Random(seed);
    int indexA = (int) genRandom.nextInt(width);  //indexes within domain and range of grid
    int indexB = (int) genRandom.nextInt(height);

    while (steps <= diffusionSteps){
        NFrostN r = new NFrostN();
        //      int indexA = (int) r.createRandomInt(seed,size);
        //      int indexB = (int) r.createRandomInt(indexA,size);
                    if (grid[indexA][indexB] == 0) { //if empty
                        if (grid[indexA-1][indexB] != 0 || grid[indexA][indexB-1] != 0 || grid[indexA+1][indexB] != 0 || grid[indexA][indexB+1] != 0) //if sticks next to a particle...
                        {grid[indexA][indexB] = 1;
                            return true;
                        }
                    else {
                            steps += 1; //increase counter before moving and looping again
                            Random genRandomnew = new Random(seed);
                            int ofFour = genRandomnew.nextInt(4);
                            switch(ofFour)
                                {
                            case 1:
                                indexA++;
                                return true;

                            case 2:
                                indexB++;
                                return true;

                            case 3:
                                indexB++;
                                return true;

                            case 4:
                                indexA++;
                                return true;

                                 }
                        }
    }

}
}

/*****************************/
/*****************************/
/********Display Method*******/
/*****************************/
/*****************************/

private void display(){
PrintStream ps = new PrintStream(OutputStream);
System.out.println("P6"); //magic number
System.out.println(width); //which is which??
System.out.println(height); //which is which??
System.out.println(110); //max value
for (int i = 0; i < width; i++){
    for (int k = 0; k < this.height; k++){
        if (this.grid[this.width][this.height] == 1){
            byte[] rgb = {110,110,110};
            ps.write(rgb);
                        }
        else
            {byte[] rgb = {0,0,0};
            ps.write(rgb);
                }
        }

    }
ps.close();
}

/*****************************/
/*****************************/
/*************Main************/
/*****************************/
/*****************************/

public static void main(String[] args) {
NFrostN frost = new NFrostN(args);
int currentFull = frost.gridSum();
while ((currentFull/(frost.getHeight()*frost.getWidth()))*100 <= frost.getDensity())
    {  //while the percentage filled is smaller or equal to the density, diffuse
        if (frost.diffuse() == true)
        {
        System.exit(0);
        }
        if (frost.diffuse() == false)
        {
        System.err.print("Error in method difuse");
        System.exit(1);
            }
        frost.display();
        currentFull = frost.gridSum();
            }
    }

}

A: you should declare these fields as instance variables. but you have declare them as block/local variables so you can't access by this.width. also when you declare variables inside the constructor you cannot access them outside of the constructor.
like this
public class NFrostN {

        int width;
        int height;
        int density;
        int seed;

when you call this.width compiler see there is no instance/ width variable and give you cannot find symbol error

A: You should declare the variables directly under the class, and not as part of constructor definition. Use the constructor to assign values to the member variables
public class NFrostN {
int width;
int height;
int density;
int seed;

public NFrostN(String[] args){

    #use the constructor to initialize the variables

}

}


text: Q: How to remove duplicate add rows in jqgrid in Jquery My jqgrid is populated with 3 duplicate forms for adding a row to the grid. What could have caused this to repeat that row multiple times times in jquery. How to remove the duplicate row. I want to have only one add row.


text:
Q: Thymeleaf retriving data from view I have a problem with accessing to data from html form with controller. I'm getting a NullPointerException when I try to get data from html.
When I try to print username and password in html view, there is no problem, but when I try to do this in controller, the data is empty except the id that I add to object.
Controller:
@RequestMapping(value = "/kpi", method = RequestMethod.POST)
public ModelAndView showKPI(@Valid Kpi kpi,
    BindingResult bindingResult, Model model) throws Exception {

    if(bindingResult.hasErrors()) {
        System.out.println("errors in binding");
    }
    model.addAttribute("kpi", kpi);
    System.out.println(kpi.getId());
    System.out.println(kpi.getPost().getUsername()); // Here is the NullPointer
    Map<String, Kpi> map = new HashMap<String, Kpi>();

    return new ModelAndView("kpi.html");
}

@RequestMapping(value = "/logged", method = RequestMethod.POST)
public ModelAndView addNewPost(@Valid Post post,
    BindingResult bindingResult, Model model) throws Exception {

    if (bindingResult.hasErrors()) {
        return new ModelAndView("index.html");
    }

    ...
    List<Entry<String, MyValue>> map = handshake_parser.getAllSprints();

    /*Loop for printing all information about sprints*/
    for(Map.Entry<String, MyValue> entry : map) {
        System.out.println(entry.getKey() + " " + entry.getValue().getName() + " : " + entry.getValue().getStartDate() + " to " + entry.getValue().getEndDate());
        String id = entry.getKey();
    }
    model.addAttribute("list", map);
    Kpi kpi = new Kpi();
    kpi.setPost(post);
    model.addAttribute("kpi", kpi);
    return new ModelAndView("result.html");
}

result.html
<!DOCTYPE html>

<title>Spring Boot and Thymeleaf example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

List of all sprints in board:

            Name
            ID
            StarDate
            EndDate

            name
            id
            startDate
            endDate

    <form action="#" th:action="@{/kpi}" th:object="${kpi}" method="post">
        <select th:field="*{id}">
            <option th:each="entry : ${list}"
                    th:value="${entry.key}"
                    th:text="${entry.value.name}">
            </option>
        </select>

        <button type="submit">See KPI</button>
    </form>

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
  java.lang.NullPointerException: null

How can I retrieve and use data from view that had been declared previously in controller?

A: 1) You have to add @ModelAttribute annotation to the method argument:
public ModelAndView showKPI(@Valid @ModelAttribute Kpi kpi, BindingResult bindingResult, Model model) throws Exception {
    // ...
}

2) There is no input for the username in HTML page. You have to add something like:
<form action="#" th:action="@{/kpi}" th:object="${kpi}" method="post">
    <select th:field="*{id}">
        <option th:each="entry : ${list}"
                th:value="${entry.key}"
                th:text="${entry.value.name}">
        </option>
    </select>

    <input th:field="*{post.username}" th:value="${kpi.post.username}" />
    <button type="submit">See KPI</button>
</form>


text:
Q: Unity: player walks into trigger and animation plays once how do I make it that "Player walks into a trigger and an animation plays once and if the player walks into the same trigger nothing will happen" There are no videos on youtube nor other websites that I know that will explain how to do this.
Im also New to unity and am not the best when doing animations
[EDITED SCRIPT, FIXED ERRORS]
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    // You should make the name TheSecretWallScript
    // This is the general format for classes in C#
    public class Thesecretwallscript : MonoBehaviour
    {
        // needed to change this.
        [SerializeField] private Animator anim;
        // Start is called before the first frame update
        private void OnTriggerEnter(Collider other)
        {
            // Disables trigger so it doesn't trigger again
            other.enabled = false;
            // Triggers animation, "AnimTrigger" should refer to the trigger you set
            // in your animators settings
            Animator anim = GetComponent<Animator>();
            anim.SetTrigger("AnimTrigger");
        }
    }

A: You need to add a trigger for your animation in the player's Animation Controller.
You could disable the trigger once you walk into it by doing:
private void OnTriggerEnter(Collider other)
{
    // Disables trigger so it doesn't trigger again
    other.enabled = false;
    // Triggers animation, "AnimTrigger" should refer to the trigger you set
    // in your animators settings
    Animator anim = GetComponent<Animator>();
    anim.SetTrigger("AnimTrigger");
}


text:
Q: CSS:Hover's problem with text that is hidden because of overflow:hidden? In my application i have lots of divs containing text. All divs have overflow set to hidden so that the user does not see the text if the container is not large enough to contain the writing.
If the user wants to see the hidden text they are supposed to mouse over the "box". The box then expands and shows the text. Sounds simple enough, right?
Well i am having problems and the solution i tried did not work. The problem is that when the user mouses over the box, the text does indeed appears but stays really narrow and comes out of the bottom box, the sameway it would if overflow was set to visible.
below is the standard css applied to the div box:
.newevent
{
    overflow: hidden;
    z-index: 0;
}

I Tried to fix this by setting a hover trigger, when it is activated the box widens, i thought that this would then mean there would be more space to display the text, below is the hover effect:
.newevent div:hover
{
    width: 200px;
    padding: 50px;
    background-color:#D4D4D4;
    border: medium red dashed;
    overflow: visible;
    z-index: 1;
}

How do i go about "redrawing" the text when it is hovered over, so that the text can use the new widened area rather than behaving as it is still in a narrow box.

A: Here is my solution. I used the jQuery library, but this can be done with plain old javascript as well.
The javascript to handle the mouseover and mouseout events.

The styles for the different states of the divs.

The body of the HTML. I removed the content here to keep the answer concise, but you should add some text so it overflows to see the solution working.

        Insert content here...

       Insert content here....


text:
Q: Tooltip changes plot and displays plot in tooltip, but I just want the plot to change I am working in Tableau and I have a plot that updates based on hover over a tree map by adding the sheet that updates to the tooltip. However, I find it redundant to have both the updated plot and tooltip displaying, but when I disable the tooltip the plot no longer updates. Is it possible to have the plot update with hover AND disable the tooltip?

A: You should be able to set this up separately using "Actions". If you are not familiar with actions, the below link would be helpful:
https://help.tableau.com/current/pro/desktop/en-us/actions_dashboards.htm


text:
Q: Magento update: An error occurred while saving the URL rewrite After updating Magento 1.9.2.1 >> 1.9.2.2 I get stuck with the following error:
Next exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'product/2/8-1-2' for key 'UNQ_MAG_CORE_URL_REWRITE_ID_PATH_IS_SYSTEM_STORE_ID', query was: INSERT INTO `mag_core_url_rewrite` (`store_id`,`category_id`,`product_id`,`id_path`,`request_path`,`target_path`,`is_system`) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE `store_id` = VALUES(`store_id`), `category_id` = VALUES(`category_id`), `product_id` = VALUES(`product_id`), `id_path` = VALUES(`id_path`), `request_path` = VALUES(`request_path`), `target_path` = VALUES(`target_path`), `is_system` = VALUES(`is_system`)' in /home/sntruck/domains/sn-truckstyling.com/public_html/webshop/lib/Zend/Db/Statement/Pdo.php:235

How can I fix this (I don't have SSH access)

A: Truncate the core_url_rewrite table in database and re-index data again.


text:
Q: Timer stops in Windows Service I have a Windows Service and a System.Timers.Timer inside it. The timer's AutoReset property is set to false, and the code which is inside Elapsed event of the timer is wrapped in such a try..catch..finally block:
try
{
    Parallel.ForEach (...)
        {
            DoSomeAction();
        }
}
catch
{
    LogException(...);
}
finally
{
    // _timer is the System.Timers.Timer
    _timer.Start();
}

DoSomeAction() method also runs some concurrent operations through Task.Run method.
I understand that .NET's timer swallows the exceptions however since the entire code is wrapped in a try...catch...finally block I expect that once an exception is raised, the finally block restart the timer again but it does not happen. As a result we have to constantly watch this Windows service and re-start it a few times a day!
My guess is that an exception happens in one of the threads but then the try..catch block is unable to capture it?


text:
Q: Comparing numbered urls in django template "In urls.py I have:
path("viewer/<str:case>", views.viewer, name="viewer"),

This works when I go to the viewer:

Now, there is a submenu in nav bar that lists cases.
I need to know which specific page I'm on to make one of menu items active:
{% for item in cases %}

  {{ item.patient_name }}

request.get_full_path returns /viewer/47 for example and one of the item's id is 47. I've tried different combinations instead of "/viewer/{{ item.id }}", nothing works.

A: I ended up creating a custom template tag:
tags.py:
@register.simple_tag
def url_case_id(value):
    return int(value.split("/")[2])

and using it in html:
{% for item in cases %}
{% url_case_id request.get_full_path as id %}

  {{ item.name }}


text:
Q: Check condition of SimpleDate converted string in Android I'm trying to do a simple IF check of a String that I know has been formatted correctly with:
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c.getTime());

At this point formattedDate is "09/24/2015". I can confirm that this is true:
remoteViews.setTextViewText( R.id.widget_date, formattedDate);

It's showing me the correct date.  So I know it's good.
So I test it:
if (formattedDate=="09/24/2015"){
//do some stuff
}

For whatever reason, that condition is not true, and nothing happens.
I have tried everything from removing the slashes, to just changing the format around, but formattedDate never equals what that string clearly is.
Is there something I'm missing here?

A: Use .equals() to compare Strings. Like this
if (formattedDate.equals("09/24/2015")){
    //do some stuff
}

== tests for "reference equality", so whether a and b are referencing the same object
.equals(anotherObject) tests for "value equality", whether a and b are logically equal


text:
Q: How to retrieve the mongodb data before updating them? I need to write a nodejs api where I need to create and update a logo.
The create works fine, but while updating the logo with a given id, the previous logo should get deleted and update with the new logo. We can use fs.unlink to delete the logo; but while using fs.unlink, the code deleted the updated logo; how do I fix this?
If I somehow knew the previous logo's name, then I could delete it.
const data = await PRISMA.ref_types.update({
      where: { id: id },
      data: {
                business_name: business_name,
                business_logo: File_Name,
                business_type: business_type,
                address: address,
                timezone: timezone,
                currency: currency,
                ref: headerData?.ref
            },
    });

  // Update the existing image record in the database
  const existingImage = await PRISMA.ref_types.findFirst({
                    where: { id }, select: {
                        business_logo: true
                    }
                })

  // find the image
  const a = Object.entries(existingImage)
  const b = a[0][1]
  const fileName = b.split('/').pop()
  console.log("dsadsad", fileName)

  // Delete the old image file
  fs.unlinkSync('uploads/' + headerData?.ref + '/settings/' + fileName)
  let found = await PRISMA.languages.findFirst({
                    where: { ref: headerData.ref }
                })


text:
Q: Evaluating $\int_{0}^\infty e^{-x}\sin (x)\;dx$ How to calculate $\int_{0}^\infty e^{-x}\sin (x)\;dx$?
Is it by parts? But I ended up with the same integration repeated, so what shall I do?

A: $$I=\Im \left( \int_{0}^{\infty} e^{-(1+i)x} dx\right)=\Im \left(  \frac{e^{-(1+i)x}}{-1+i}||^{\infty}_0\right)=\Im \left(\frac{1}{1-i}\right)=\frac{1}{2}.$$

A: We will integration by parts twice in a row:
1)$ \text{First time } (f=\sin(x), g'=e^{-x} \Leftrightarrow f'=\cos(x), g=-e^{-x}$):
$$\int e^{-x} \sin(x) dx = -e^{-x} \sin(x) - \int -e^{-x} \cos(x)$$
2)$ \text{Second time } (f=\cos(x), g'=-e^{-x} \Leftrightarrow f'=-\sin(x), g=e^{-x}$):
$$- e^{-x} \sin(x) - \int - e^{-x} \cos(x) = - e^{-x} \sin(x) - (e^{-x} \cos(x) - \int -e^{-x} \sin(x))$$
So now we get:
$$\int e^{-x} \sin(x) dx = - e^{-x} \sin(x) - (e^{-x} \cos(x) + \int e^{-x} \sin(x))$$
$$2 \int e^{-x} \sin(x) dx = - e^{-x} \sin(x) - e^{-x} \cos(x) $$
$$ \int e^{-x} \sin(x) dx = \frac{- e^{-x} \sin(x) - e^{-x} \cos(x)}{2} $$
Now you can evaluate the integral for the final answer:
$$ \int_{0}^{\infty} e^{-x} \sin(x) dx = \frac{1}{2} $$

A: If you don't know Laplace transformation, simply using partial integration yields the same.
\begin{align*}
\int_{0}^{\infty} e^{-x} \sin(x) dx = - e^{-x} \cos(x) \mid_{0}^{\infty} - \int_{0}^{\infty} e^{-x} \cos(x) dx = [0-(-1)] - \left[ e^{-x} \sin(x) \mid_{0}^{\infty} + \int_{0}^{\infty} e^{-x} \sin(x) dx\right] = 1 - \int_{0}^{\infty} e^{-x} \sin(x) dx
\end{align*}
This is equivalent to
\begin{align*}
2 \int_{0}^{\infty} e^{-x} \sin(x) dx = 1
\end{align*}
which yields the solution
\begin{align*}
 \int_{0}^{\infty} e^{-x} \sin(x) dx = \frac{1}{2}
\end{align*}

A: One way is to complex the integral, and your answer will be Im($\int e^{(i-1)x} dx$). But if you don't know how to do that, I will explain it with integration by parts.
$$\int e^{-x} \sin x = - \sin x e^{-x} + \int e^{-x} \cos x \text{ (1)}$$
Use integration by parts on the second integral.
$$\int e^{-x} \cos x = - \cos x e^{-x} - \int \sin x e^{-x}$$
So $$\int \sin x e^{-x} = - \cos x e^{-x} - \int e^{-x} \cos x$$.
Add this to $(1)$ to get
$$2I = -e^{-x}(\sin x + \cos x) \Rightarrow I = -\frac{1}{2} e^{-x} (\sin x + \cos x)$$
You can then plug in the bounds.

A: IBP of the initial integral (integrating $e^{-x}$ and differentiating $\sin(x)$) gives you,
$$
\int_0^\infty e^{-x} \sin(x) dx = \int_0^\infty e^{-x} \cos(x) dx.
$$
Integrating the RHS by parts gives
$$
\int_0^\infty e^{-x} \cos(x) dx = 1 - \int_0^\infty e^{-x} \sin(x) dx.
$$
Plugging the second into the first gives
$$
\int_0^\infty e^{-x} \sin(x) dx = 1 - \int_0^\infty e^{-x} \sin(x) dx.
$$
Rearranging the above equation for the integral in question gives
$$
\int_0^\infty e^{-x} \sin(x) dx = \frac{1}{2}.
$$

A: Recognizing this as a Laplace transform,
$$\int_{0}^\infty e^{-x}\sin x \;dx = \left.\mathcal{L}(\sin x)\right|_{s=1} = \left. \frac{1}{1+s^2}\right|_{s=1}=\frac{1}{2}.$$
Or you could integrate by parts twice.  Either function can take the role of $u$ or $dv$ in $$\int u \, dv = uv-\int v\, du.$$
Method I:  $u=e^{-x}$ and $dv=\sin x \, dx$.
Method II:  $u=\sin x$ and $dv=e^{-x} \, dx$.
Either way works.

A: Using integration by parts we have:
$$\int_{0}^\infty e^{-x}\sin (x)\;dx=\lim_{b\to\infty}e^{-x}\sin\left(x\right)\Big|_0^b+\int_{0}^{\infty}e^{-x}\cos\left(x\right)dx$$$$=\lim_{b\to\infty}-e^{-x}\sin\left(x\right)\Big|_0^b+\left(\lim_{b\to\infty}-e^{-x}\cos\left(x\right)\Big|_0^b-\int_{0}^{\infty}e^{-x}\sin\left(x\right)dx\right)$$
So :$$\int_{0}^\infty e^{-x}\sin (x)\;dx=1/2$$


text:
Q:  jQuery .click() not working So, I created a delete "button" in a span, but for some reason I can't get the .click() to fire.  Any ideas?  I'm new to jQuery and am thinking that it's something obvious.  I tested in Chrome and Safari with no luck.
CSS:
.delete_button {
    cursor:pointer;
    color: #fff;
    border: 1px solid #FFF;
    border-radius: 15px;
    background: #AAA;
    font-size: 8px;
    line-height: 0px;
    padding: 0px 2px 0px 2px;
}

HTML/PHP:
<span class="delete_button" id="delete_<? echo $some_id; ?>">X

jQuery:
$(document).ready(function() {
    $('.delete_button').click(function() {
            var transaction_id = $(this).attr('id').replace('delete_','');
            alert("Delete transaction #" + transaction_id);
            return false;
        });
});

A: use .on()
As your span is added dynamically so it is not present at the time DOM ready or page load.
So you have to use Event Delegation
Syntax
$( elements ).on( events, selector, data, handler );

like this
$(document).on('click','.delete_button',function(){
    // code here
});

or
$('parentElementPresesntAtDOMready').on('click','.delete_button',function(){
   // code here
});

your code becomes
$(document).ready(function () {
    $(document).on('click', '.delete_button', function () {
        var transaction_id = $(this).attr('id').replace('delete_', '');
        alert("Delete transaction #" + transaction_id);
        return false;
    });
});

A: It seems like the span is dynamically created, you need to use event delegation. Bind it to the closest static parent or document
$(document).on('click','.delete_button',function(){
   /*Your code*/
});

A: There is a simpler solution for old webkit: set cursor to pointer via CSS for the span.
Tested and working on a music web app.


text:
Q: Need help understanding this Python list syntax I'm having trouble understanding what this syntax means in Python:
out = out[lengths - 1, range(len(lengths))]

Why is there a range inside a list? How does that work? For context, I'm training a machine learning model in PyTorch. lengths is a list of the lengths of the input.

A: I assume lengths is an array of integers. (probably a Numpy array)
The first index lengths - 1 will give a list of indices that is subtracted by -1.
The second index range(len(lengths)) will give a list of numbers from 0 to the size of lengths.
I don't know what the specific logic is in your code, but in general, you can give a list of indices to pick the data at specific locations.
out = np.array([[1,2,3],[4,5,6],[7,8,9]])
-> array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

first_idx = [0, 1, 2]
second_idx = [2, 1, 0]
# (0,2), (1,1), (2,0)

out[first_idx, second_idx]
-> array([3, 5, 7])


text:
Q: Publisher confirm / publisher returns / AmqpConnectException not working I'm using rabbitMqTemplate's convertAndSend method to publish a message. If I don't have rabbitMq server running, I would expect the call to throw an exception which it does not.
I have setup the connection factory like so
@Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
        connectionFactory.setUsername(rabbitProperties.getUsername());
        connectionFactory.setPassword(rabbitProperties.getPassword());
        connectionFactory.setPort(rabbitProperties.getPort());
        connectionFactory.setPublisherConfirms(true);
        connectionFactory.setPublisherReturns(true);
        return connectionFactory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        return rabbitTemplate;
    }

I send the message like this
this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
                LOGGER.debug("RabbitMq could not send the message");
});
this.rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
                LOGGER.debug("RabbitMq return callback : " + replyCode);
});
this.rabbitTemplate.convertAndSend(exchangeName, routing, deliverable, new CorrelationData(correlationId));

I want to take some action if convertAndSend does not successfully publish the message to Queue. How can I do this?
Thanks,
Sudha


text:
Q: Segmentation fault using a Native Window in Android We're trying to port a C++ application to Android. We think that using NativeActivity should be easiest, and let all OpenGL/EGL-stuff be done natively.
Right now, we're passing the ANativeWindow-pointer that we get from the android_app struct in android_native_app_glue.h through the application so that it can be used when the window is initialized. Here's a few relevant lines from this code (stripped from debug-code):
bool OpenGLWindowES::Initialize(EGLNativeWindowType wnd, EGLNativeDisplayType dsp,
                            EGLint redSize, EGLint greenSize, EGLint blueSize, EGLint             alphaSize, EGLint depthSize, bool bMultiSample)
{
    m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if(m_display == EGL_NO_DISPLAY)
    {
        return false;
    }

    EGLint iMajorVersion, iMinorVersion;
    if (!eglInitialize(m_display, &iMajorVersion, &iMinorVersion))
    {
        return false;
    }

    eglBindAPI(EGL_OPENGL_ES_API);
    bool ecc = eglChooseConfig(m_display, attribs, &m_config, 1, &iConfigs);
    if (!ecc || (iConfigs != 1))
    {
        return false;
    }

    EGLint format;
    eglGetConfigAttrib(m_display, m_config, EGL_NATIVE_VISUAL_ID, &format);
    ANativeWindow_setBuffersGeometry(wnd, 0, 0, format);
    m_windowSurface = eglCreateWindowSurface(m_display, m_config, wnd, NULL);
    //etc
}

This code proceeds with creating a context, makecurrent etc, but we don't get that far. We get a segmentation fault on eglCreateWindowSurface and since the display and config seem to be initialized correctly, this can only mean a problem with the ANativeWindow* (tyepdef'd to a EGLNativeWindowType). Error message:
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000058

We also get a segmentation fault if we call for example:
ANativeWindow_getHeight(wnd);

So the question is, what can cause a segmentation fault at this point? wnd is not null, we've checked this before, so it should be initalized somehow and should be ready to use. Did we miss something before calling this function, or can there be some problem with the pointer?
EDIT: We're currently wondering if this can have something to do with the APP_CMD_INIT_WINDOW command not being sent or received properly (we haven't implemented any command handling at all yet so we're looking into this).

A: Are you entirely sure that the window is correctly initialized?
The ANativeWindow pointer in the app struct is not automatically set when passed into the native entry point. It is provided by the main Android thread at a later point and will then be sent to the app via the callback system that app_glue has set up.
You need to handle the calls sent to the android_app yourself, in the native_activity example in the NDK they do it like this:
int ident;
int events;
struct android_poll_source* source;

// If not animating, we will block forever waiting for events.
// If animating, we loop until all events are read, then continue
// to draw the next frame of animation.
while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
        (void**)&source)) >= 0) {

    // Process this event.
    if (source != NULL) {
        source->process(state, source);
    }
    ....
}

You probably need something like this in your main rendering loop, this will allow app_glue to automatically set the window correctly when it gets it from the main thread.

A: The problem is wnd, pass the state->window from the main function: void android_main(struct android_app* state) to your bool OpenGLWindowES::Initialize(...) method as the first parameter:
void android_main(struct android_app* state) {
    Initialize(state->window /*, other arguments here... */);
}


text:
Q: How to get the key state via a scancode (not virtual keycode)? Is there anyway to get the state of a keyboard key (is it down or up) using just a scancode? I can't find any function in win32 for this. Anyone know any way to achieve this?
p.s. I need the actual state of the keyboard not the state derived from windows messages like GetKeyState returns.

A: You'll have to use the MapVirtualKey function, using MAPVK_VSC_TO_VK as the mode, and pass the output to GetKeyState or GetKeyboardState, as none of the WinAPI key functions directly use scan codes

A: Perhaps you are looking for GetAsyncKeyState. It is referenced from the GetKeyState documentation and appears to return what you desire.

A: MapVirtualKey doesn't translate a lot of keys, so I came up with this switch:
int main() {
    directinput = new DirectInput();
    directinput->init();
    while(1) {
        int ret = directinput->ReadKeyboard();
        if(!ret)
            continue;

        int keys_pressed = 0;
        for(int i = 0; i < 256; i++) {
            if((directinput->m_keyboardState[i] & 128) == 0)
                continue;
            unsigned char scancode = i;
            UINT key = MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
            //UINT key = MapVirtualKeyEx(scancode, MAPVK_VSC_TO_VK, GetKeyboardLayout(0)); // same as MapVirtualKey

            switch(scancode) {
                case 203: key = VK_LEFT; break;
                case 205: key = VK_RIGHT; break;
                case 200: key = VK_UP; break;
                case 208: key = VK_DOWN; break;
                case 211: key = VK_DELETE; break;
                case 207: key = VK_END; break;
                case 199: key = VK_HOME; break; // pos1
                case 201: key = VK_PRIOR; break; // page up
                case 209: key = VK_NEXT; break;  // page down
                case 210: key = VK_INSERT; break;
                case 184: key = VK_RMENU; break; // right alt
                case 157: key = VK_RCONTROL; break; // right control
                case 219: key = VK_LWIN; break; // left win
                case 220: key = VK_RWIN; break; // right win
                case 156: key = VK_RETURN; break; // right enter
                case 181: key = VK_DIVIDE; break; // numpad divide
                case 221: key = VK_APPS; break; // menu key
            }

            printf("keys_pressed=%d scancode=%d/0x%x key=%d char=%c hex=0x%x\n", keys_pressed, scancode, scancode, key, key, key);
            keys_pressed++;
        }

        Sleep((int)(1000.0 / 60.0));
    }
    return 0;
}


text:
Q: Why is GAS inputting a invalid range into a data validation? function DYNAMIC(){
  var s = SpreadsheetApp.getActiveSpreadsheet(), ss = s.getSheetByName("Snippet Gen"),
      dd = s.getSheetByName("dv snip"), column = 1, lastc = dd.getLastColumn(),
      lastr = dd.getLastRow(), time = ss.getRange(2,1), name = ss.getRange(4,1),
      time_v = time.getValue(), tp = dd.getRange(1,1,1,lastc),
      nm = dd.getRange(2,column,lastr,1), match = dd.getRange(1,column).getValue();

  var rule_tp = SpreadsheetApp.newDataValidation().requireValueInRange(tp,false).build();
  time.setDataValidation(rule_tp);

  for(; column < lastc; column++){
    if(match = time_v){
      var rule_nm = SpreadsheetApp.newDataValidation().requireValueInRange(nm,false).build();
      name.setDataValidation(rule_nm);
    }
  }
}

Sheet 1: Snippet Gen
Sheet 2: dv snip
The result is the correct DV in A2 but a continuous Loading… DV in A4. And then when I go into the DV panel, the range is set as 'dv snip'!$A$2:$A$8 which is an invalid range. How do I set the range correctly?

A: if(match = time_v){ is an assignment not a comparison try this instead if(match == time_v){

A: You're most probably getting an invalid range because of this method:
nm = dd.getRange(2,column,lastr,1);

Please notice that the method getRange(row, column, numRows, numColumns) takes the number of rows as the third parameter, not the index of the last row in the range.
Because of this, here you are getting a range that:

*

*Starts at row 2.

*Its number of rows equals the index of the last row.

With these settings, the last row in this range doesn't exist. Therefore, you get an invalid range.
To fix this, you would have to substract the first row index to the third parameter in the method. One option would define the parameters and the method in this way:
var firstRow = 2;
var column = 1;
var numRows = dd.getLastRow() - firstRow + 1;
var numCols = dd.getLastColumn() - column + 1;
var nm = dd.getRange(firstRow, column, numRows, numCols);

Also, as Cooper said, you should use a comparison operator, not an assignment one in here:
if(match == time_v){

Reference:

*

*getRange(row, column, numRows, numColumns)

*Comparison operator
I hope this is of any help.


text:
Q: BrainF*ck interpreter in x86 32-bit Assembly I started to write a BrainF*ck interpreter for my OS in 32-bit x86 assembly. I have already written one in C that just works and tried to implement it in assembly but the one written in assembly doesn't print any output.
I'm still new to assembly so I guess I just made some beginner mistakes. Only thing I can think of is that I messed up the addressing somewhere.
I'd be really happy if someone could point out what I'm doing wrong.
I tested the C and assembly programs with the same input:
-[--->+<]>---.+[----->+++<]>.[--->+<]>+.[--->++<]>-.++++.
It should print RexOS
I created a pastebin of my C code if that helps understand what I'm trying to accomplish:
pastebin
My assembly code is the following:
.intel_syntax noprefix

.section .data
TAPE:
    .zero 30000

.section .text
.global interpret
interpret:
    push ebp                // prologue
    mov ebp, esp

    mov edx, [ebp+8]        // getting the input string
    mov edi, offset TAPE    // a pointer to the tape
    xor ecx, ecx            // stores current char
                            // inner loop counter

loop:
    mov cl, byte ptr [edx]  // getting the current char

    inc edx                 // increase the index to the next char

    cmp cl, 0               // if we reached the end of the string
    je exit                 // return the length

    cmp cl, '>'
    je pinc                 // increment the pointer

    cmp cl, '<'
    je pdec                 // decrement the pointer

    cmp cl, '+'
    je vinc                 // increment value at index

    cmp cl, '-'
    je vdec                 // decrement value at index

    cmp cl, '.'
    je prnt                 // print the value at index

    cmp cl, ','
    je read                 // read character from stdin

    cmp cl, ']'
    je bend                 // end of bracket

    jmp loop

pinc:
    inc edi
    jmp loop

pdec:
    dec edi
    jmp loop

vinc:
    inc byte ptr [edi]
    jmp loop

vdec:
    dec byte ptr [edi]
    jmp loop

prnt:
    push edx

    push dword ptr [edi]
    call putchar
    add esp, 4

    pop edx

    jmp loop

read:
    call getchar
    mov byte ptr [edi], al

    jmp loop

bend:
    cmp byte ptr [edi], 0
    je loop

    mov ch, 1

ilst:
    cmp ch, 0
    jle loop

    dec edx                 // jump to the previous index
    mov cl, byte ptr [edx]  // getting the current char

    cmp cl, '['
    je dclp                 // decrease internal loop counter

    cmp cl, ']'
    je inlp                 // increase internal loop counter

    jmp ilst

inlp:
    inc ch
    jmp ilst

dclp:
    dec ch
    jmp ilst

exit:
    mov esp, ebp            // epilogue
    pop ebp
    ret

A: I finally solved this. All I needed to do was move the pointer incrementation to the end of the loop and save additional registers in the prologue (ebx) then restore the registers in the epilogue. Also needed to save and restore registers in the prnt and scan part.
My final working code looks like this:
.intel_syntax noprefix

.section .data
TAPE:
    .zero 30000

.section .text
.global interpret
interpret:
    push ebp                // prologue
    mov ebp, esp
    push ebx

    xor eax, eax            // loop counter
    mov ebx, offset TAPE    // a pointer to the tape
    mov edx, [ebp+8]        // getting the input string

clrt:                       // clear TAPE
    cmp eax, 30000
    je loop

    mov byte ptr [ebx+eax], 0

    inc eax

    jmp clrt

loop:
    mov cl, byte ptr [edx]  // getting the current char

    cmp cl, 0               // if we reached the end of the string
    je exit                 // return the length

    cmp cl, '>'
    je pinc                 // increment the pointer

    cmp cl, '<'
    je pdec                 // decrement the pointer

    cmp cl, '+'
    je vinc                 // increment value at index

    cmp cl, '-'
    je vdec                 // decrement value at index

    cmp cl, '.'
    je prnt                 // print the value at index

    cmp cl, ','
    je read                 // read character from stdin

    cmp cl, ']'
    je bend                 // end of bracket

ptlp:                       // postloop
    inc edx                 // increment the input pointer
    jmp loop                // continue the loop

pinc:
    inc ebx
    jmp ptlp

pdec:
    dec ebx
    jmp ptlp

vinc:
    inc byte ptr [ebx]
    jmp ptlp

vdec:
    dec byte ptr [ebx]
    jmp ptlp

prnt:
    push edx

    push dword ptr [ebx]
    call putchar
    add esp, 4

    pop edx

    jmp ptlp

read:
    push edx

    call getchar
    mov byte ptr [ebx], al

    pop edx

    jmp ptlp

bend:
    cmp byte ptr [ebx], 0
    je ptlp

    mov ch, 1

ilst:
    cmp ch, 0
    jle ptlp

    dec edx                 // jump to the previous index
    mov cl, byte ptr [edx]  // getting the current char

    cmp cl, '['
    je dclp                 // decrease internal loop counter

    cmp cl, ']'
    je inlp                 // increase internal loop counter

    jmp ilst

inlp:
    inc ch
    jmp ilst

dclp:
    dec ch
    jmp ilst

exit:
    pop ebx                 // epilogue
    mov esp, ebp
    pop ebp
    ret


text:
Q: Exact sign of determinant in Java Is there some Java math library for computation of exact sign of determinant?
This library have to support exact computation with constructive zero bounds, precision-driven approach and numerical filters for performance.
For example: When I simply use Java BigDecimal number type for computation, zero problem occurs. If result is, for example, 1.0E-101, is it zero? yes or no? Solution based on constant zero bound (like 0.0E-100) is inexact and not robust, in my opinion.
Thank you for response.
Note:
Personally, I tried  libraries JScience, Common Math, but I have not proof that this libraries use exact computation.
JScience offers Rational, but there is problem with operation inverse (0/x failed). Also JScience offers Real, but there is problem with inverse too (Exactness is lost).
It seems that Common Math use BigDecimal in inexact mode. (see BigReal). May be BigFraction is exact, but I have not proof.

A: I suggest to use BigDecimal.signum to test the sign of a BigDecimal.


text:
Q: Raise volume progressively in Android app I've got an app where Ii want to sound the alarm ringtone and raise the volume each second.
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
player = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));

After initializing AudioManager and MediaPlayer, I've got a method which is executed each second when some circumstances occur. The method is the next one:
private void sound() {
    if (!player.isPlaying()) {
        try {
            player.setLooping(true);
            player.setVolume(5,5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        player.start();
    } else {
        audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION,AudioManager.ADJUST_RAISE,0);
    }
}

As you can see, the first time the method is executed the sound begins, that works OK. But when is already started and I want to raise the volume, the adjustStreamVolume makes nothing.
Any help or advice?


text:
Q: StringUtils.isBlank() vs String.isEmpty() I ran into some code that has the following:
String foo = getvalue("foo");
if (StringUtils.isBlank(foo))
    doStuff();
else
    doOtherStuff();

This appears to be functionally equivalent to the following:
String foo = getvalue("foo");
if (foo.isEmpty())
    doStuff();
else
    doOtherStuff();

Is a difference between the two (org.apache.commons.lang3.StringUtils.isBlank and java.lang.String.isEmpty)?

A: StringUtils.isBlank also returns true for just whitespace:

isBlank(String str)
Checks if a String is whitespace, empty ("") or null.

A: The only difference between isBlank() and isEmpty() is:
StringUtils.isBlank(" ")       = true //compared string value has space and considered as blank

StringUtils.isEmpty(" ")       = false //compared string value has space and not considered as empty

A: StringUtils.isBlank(foo) will perform a null check for you. If you perform foo.isEmpty() and foo is null, you will raise a NullPointerException.

A: StringUtils.isBlank() checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.
From the linked documentation:

Checks if a String is whitespace, empty ("") or null.
 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true
 StringUtils.isBlank(" ")       = true
 StringUtils.isBlank("bob")     = false
 StringUtils.isBlank("  bob  ") = false

For comparison StringUtils.isEmpty:
 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true for null.
java.lang.String.isBlank() (since Java 11)
java.lang.String.isEmpty()

A: StringUtils isEmpty = String isEmpty checks + checks for null.
StringUtils isBlank = StringUtils isEmpty checks + checks if the text contains only whitespace character(s).
Useful links for further investigation:

*

*StringUtils isBlank documentation

*StringUtils isEmpty documentation

*String isEmpty documentation

A: StringUtils.isBlank() returns true for blanks(just whitespaces)and for null String as well. Actually it trims the Char sequences and then performs check.
StringUtils.isEmpty() returns true when there is no charsequence in the String parameter or when String parameter is null. Difference is that isEmpty() returns false if String parameter contains just whiltespaces. It considers whitespaces as a state of being non empty.

A: Instead of using third party lib, use Java 11 isBlank()
    String str1 = "";
    String str2 = "   ";
    Character ch = '\u0020';
    String str3 =ch+" "+ch;

    System.out.println(str1.isEmpty()); //true
    System.out.println(str2.isEmpty()); //false
    System.out.println(str3.isEmpty()); //false

    System.out.println(str1.isBlank()); //true
    System.out.println(str2.isBlank()); //true
    System.out.println(str3.isBlank()); //true

A: StringUtils.isBlank() will also check for null, whereas this:
String foo = getvalue("foo");
if (foo.isEmpty())

will throw a NullPointerException if foo is null.

A: public static boolean isEmpty(String ptext) {
 return ptext == null || ptext.trim().length() == 0;
}

public static boolean isBlank(String ptext) {
 return ptext == null || ptext.trim().length() == 0;
}

Both have the same code how will isBlank handle white spaces probably you meant isBlankString this has the code for handling whitespaces.
public static boolean isBlankString( String pString ) {
 int strLength;
 if( pString == null || (strLength = pString.length()) == 0)
 return true;
 for(int i=0; i < strLength; i++)
 if(!Character.isWhitespace(pString.charAt(i)))
 return false;
 return false;
}

A: The bottom line is :
isEmpty take " " as a character but isBlank not. Rest both are same.

A: The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,
StringUtils.isBlank()
 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true
 StringUtils.isBlank(" ")       = true
 StringUtils.isBlank("bob")     = false
 StringUtils.isBlank("  bob  ") = false

StringUtils.isEmpty
 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

A: Instead of using a third-party library, use Java 11 isBlank()
System.out.println("".isEmpty());                      //true
System.out.println(" ".isEmpty());                     //false
System.out.println(('\u0020'+" "+'\u0020').isEmpty()); //false

System.out.println("".isBlank());                      //true
System.out.println(" ".isBlank());                     //true
System.out.println(('\u0020'+" "+'\u0020').isBlank()); //true

If you want to use Java 8 and need isBlank function then try to use third-party library org.apache.commons.lang3.StringUtils
StringUtils.isBlank()
System.out.println(StringUtils.isBlank(null));      //true
System.out.println(StringUtils.isBlank(""));        //true
System.out.println(StringUtils.isBlank(" "));       //true
System.out.println(StringUtils.isBlank("bob"));     //false
System.out.println(StringUtils.isBlank("  bob  ")); //false

StringUtils.isEmpty
System.out.println(StringUtils.isEmpty(null));      // = true
System.out.println(StringUtils.isEmpty(""));        //= true
System.out.println(StringUtils.isEmpty(" "));       // = false
System.out.println(StringUtils.isEmpty("foo"));     // = false
System.out.println(StringUtils.isEmpty("  foo  ")); //= false

A: I am answering this because it's the top result in Google for "String isBlank() Method".
If you are using Java 11 or above, you can use the String class isBlank() method. This method does the same thing as Apache Commons StringUtils class.
I have written a small post on this method examples, read it here.

A: StringUtils.isBlank(myStr) checks if the String myStr is whitespace, empty("") or null.


text:
Q: Why don't repositories in the bnd workspace model support transitive dependencies? According to the Introduction to the bnd workspace model the repositories define and exact set of dependencies and not support transitive dependencies because they tend to make horrible OSGi systems.
Can someone provide a more detailed explanation (using concrete use cases is highly appreciated) when that is true? I guess this mainly related to the correct Import-Package list in the manifest. How transitive dependencies should be handled? Is there a way to provide all required imports?
Does that mean maven-only bundle development (with bnd-maven-plugin or maven-bundle-plugin) is more likely to be error-prone since maven does support transitive dependencies? How transitive dependencies should be handled in this case?
Thank you!

A: In OSGi bundle creation and application assembly are two very different things.
When creating bundles with maven you of course use transitive dependencies. The result oft the maven-bundle-plugin or bnd-maven-plugin is entries in the jar Manifest. They define things like imported or exported packages. This result does not contain transitive dependencies. These bundles can be used in workspace model as well as maven model.
The application assembly is a different process. There you build a so balled repository which is a list of possible bundles to install. In the workspace model you list each bundle without transitive dependencies.
In the maven based application assembly you define the repository using the dependencies of a pom. There the transitive dependencies are used.
The reason why transitive dependencies are not always good is that the dependencies of a bundle are often not the dependencies you want to use in your application. So the maven model has the potential of adding problematic bundles to the repository. These dependencies might then slow down to resolution of the actual bundles to use or even result in non working resolved bundles. Luckily you can fix this by excluding some of the transitive dependencies using the usual maven excludes.
In my personal experience transitive bundles are often very useful for application assembly as you do not have to list all dependencies by hand. The problematic cases are not quite easdy to fix. So I do not agree that transitive dependencies should not be leveraged.

A: The primary reason is that OSGi is a specification for a reusable component system. If you try to do that with transitive dependencies, you'll find you run into problems at assembly time:

*

*version conflicts – Component A uses version 1 of X, component B uses version 2 of X. These conflicts are often tapered over in transitive systems like Maven but time bombs are lurking to go off.

*environment dependencies – Some components depend on Windows, other on Linux. Very hard to reconcile these differences.

*version compatibility – Often components could be working together but their transitive dependencies make it impossible.

To address this problem, OSGi invented the service model. The service model allows a component to depend on an API. Once you depend on an API, you no longer have transitive dependencies since transitive dependencies are almost all about implementation dependencies. There is, of course, a dependency on the API, but that has become fuzzier since it is both the consumer of the API and the provider of the API depend on this. This fundamentally changes the dependency model for the better, but very few people grasp this.
I.e. in the service model, the buck stops at the service API. You compile against the API and you can write a lot of test cases against the API. However, your component should never depend on a specific implementation. The first time your component sees an implementation should be in a runtime.
Of course, this forfeits some convenience at the early stages of development. Where in a transitive model, like Maven, things are supposed to compile out of the box, in bnd you need to think about your, and your component's, dependencies ahead of time. This is inconvenient and annoys Maven users, but it is a requirement to make components reusable in very different environments. Maven tends to lock the runtime in often incompatible configurations, in OSGi you do not want the runtime to have any unnecessary restrictions to maximize the reusability of your components.
Putting this restriction on developers, no implementation dependencies, is often too much for developers used to the short term convenience of transitive dependencies. However, developers that embrace this model quickly see that it opens up a vista of possibilities later in the development cycle and reduces a significant of maintenance. Even I am sometimes tempted to skip this level of indirection but somehow, at even slight complexity, I revert because the model has so many advantages on the macro level.
I've been involved in many complex systems and in virtually all cases a lot of complexity in disappears when you kill the transitive dependency sirens.


text:
Q: Dynamic unordered list rendering from json with jQuery I am trying to build a dynamic unordered list with nested child ul list levels(actually 4+ sub levels), I am having hard time rendering the actual markup I need, so at a later stage I can make it more functional, I created at the following link jsfiddle, the html markup looks like:

            theatre_name: Americas

                location_name: USA

                    Living in USA

123 John Doe

534 John Doe

9728 John Doe

7668 John Doe

                    What to do in USA

Fishing

Skiing

Hicking

Running

                    Visiting in USA

By Car

By Air

By Boat

Walking

                location_name: Mexico

                    Living in Mexico

123 Juan Lopez

534 Juan Lopez

9728 Juan Lopez

7668 Juan Lopez

                    What to do in Mexico

Fishing

Skiing

Hicking

Running

                    Visiting in Mexico

Por Auto

Por Avion

Por Barco

Caminando

After rendering, the markup should look like the following image:

This is the json data.
{
            "user_id": "01010101",
            "user_name": "John Doe",
            "super_user": true,
            "theatre": {
                "theatre_name": "americas",
                "locations": [
                    {
                        "location_name": "USA",
                        "events": [
                            {
                                "event_name": "living in Palo Alto",
                                "people": [
                                    "123 John Doe",
                                    "534 John Doe",
                                    "9728 John Doe",
                                    "7668 John Doe"
                                ]
                            },
                            {
                                "event_name": "What to do in Palo Alto",
                                "people": [
                                    "Fishing",
                                    "Skying",
                                    "Hiking",
                                    "Running"
                                ]
                            },
                            {
                                "event_name": "Visiting in Palo Alto",
                                "people": [
                                    "By Car",
                                    "By Air",
                                    "By Boat",
                                    "Walking"
                                ]
                            }
                        ]
                    }
                ],
                "theatre_name": "Europa",
                "locations": [
                    {
                        "location_name": "Spain",
                        "events": [
                            {
                                "event_name": "living in Barcelona",
                                "people": [
                                    "123 Juan Garza",
                                    "534 Juan Garza",
                                    "9728 Juan Garza",
                                    "7668 Juan Garza"
                                ]
                            },
                            {
                                "event_name": "What to do in Barcelona",
                                "people": [
                                    "Fishing",
                                    "Skying",
                                    "Hiking",
                                    "Running"
                                ]
                            },
                            {
                                "event_name": "Visiting in Barcelona",
                                "people": [
                                    "By Car",
                                    "By Air",
                                    "By Boat",
                                    "Walking"
                                ]
                            }
                        ]
                    }
                ],
                "theatre_name": "Asia",
                "locations": [
                    {
                        "location_name": "China",
                        "events": [
                            {
                                "event_name": "living in Beijing",
                                "people": [
                                    "123 Wei Zhang",
                                    "534 Wei Zhang",
                                    "9728 Wei Zhang",
                                    "7668 Wei Zhang"
                                ]
                            },
                            {
                                "event_name": "What to do in Beijing",
                                "people": [
                                    "Fishing",
                                    "Skying",
                                    "Hiking",
                                    "Running"
                                ]
                            },
                            {
                                "event_name": "Visiting in Beijing",
                                "people": [
                                    "By Car",
                                    "By Air",
                                    "By Boat",
                                    "Walking"
                                ]
                            }
                        ]
                    }
                ]
            }
        }

This is a JavaScript I found but need some work to make it functional, how do I loop through the json objects, pull the data and generate the needed markup?
$(function(){
            $.getJSON('./JSON/latest.json', function(data) {
                var items = [];
                $.each(data, function(i, item) {
                items.push('
' + pName + '' + vTitle + '' + shortDesc + '
');
                });
                $('#latestList').append( items.join('') );
            });
        });

A: here is how you do it,
 $(document).ready(function(){
    $("body").append(list_theatre(events.theatre));
})

function list_theatre(jsonObject){
    var newUl = $("
");
    var newLi = $("
");
    $.each(jsonObject,function(index,object){
        var newLi = $("
");
        newLi.append('theatre_name: '+object.theatre_name+' ');
        newLi.append(list_locations(object.locations));
        newUl.append(newLi);
    })
    return newUl;
}

function list_locations(jsonObject){
    var newUl = $("
");
    var newLi = $("
");
    $.each(jsonObject,function(index,object){
        var newLi = $("
");
        newLi.append('location_name: '+object.location_name+'');
        newLi.append(list_events(object.events));
        newUl.append(newLi);
    })
    return newUl;
}

function list_events(jsonObject){
    var newUl = $("
");
    var newLi = $("
");
    //console.log(jsonObject);
    $.each(jsonObject,function(index,object){
        var newLi = $("
");
        newLi.append(''+object.event_name+'');
        newLi.append(list_people(object.people));
        newUl.append(newLi);
    })
    return newUl;
}

function list_people(jsonObject){
    var newUl = $("
");
    var newLi = $("
");
    $.each(jsonObject,function(index,text){
        var newLi = $("
");
        newLi.append(''+text+'');
        newUl.append(newLi);
    })
    return newUl;
}

I had to change the json a bit. Since theatre is a collection, its need be an array of json objects.
Find the complete js along with json here: http://jsfiddle.net/satyagupta/vabnyzvv/1/
Also you can minify the codes a bit by adding a bit of recursion to it.


text:
Q: How to get a SCNNode by tapping on it? I have a ARSCNView in which I have placed some SCNNodes, assigned IDs to each one of them and then stored them in an array.
Now what I'm trying to get is SCNNode when I tap it. Right now I am able to tap and change colour of the node. But I am unable to get the node with ID I set (it is 0 as I set it in stored properties), it's position is also (0,0,0). What I think is it is returning a new instance of that node.
I took this code as a reference: https://stackoverflow.com/a/46074366/6605214
Any help would be appreciated.

A: Found the solution. I was loading node from scene in wrong way.
Before:
let scene = SCNScene(named: "marker.scn")!
let node = scene.rootNode

After:
let scene = SCNScene(named: "marker.scn")!
let node = scene.rootNode.childNode(withName: "marker", recursively: true)


text:
Q: git-cherry seems like not working for disordered merges I tried to use git cherry-pick for merging some commits from master and then git-cherry to determine what commits currently merged. It works fine while I merge it in the order it's on master, but when I skip merging one of the commits it doesn't show me the next merged.
Example below:
$ git branch
* branch
  master
$ git log --oneline
46aad17 comment4
56e43b0 comment3
26370b3 comment2
6192fa4 comment1

$ git cherry -v branch master
- 5c5e979707cd6a77ef3ae79627cdd211cad86a28 comment3
- ee0386c78d9e6d21dce7a8bac8e40beef73fb993 comment4
+ 9495c94ece440d9a05c3218f88d1b72a7fd67664 unmerged # this wasn't merged
+ 235b0822f08f351264071e7b2500caa9af997fb8 comment2

The question is why comment2 shown as unmerged while it's shown merged in log?

A: Just as a preliminary note, it's a bit confusing to describe these as merges - they're just cherry-picks, i.e. commits created by applying the patch introduced by another commit onto a new parent.
git cherry looks at the patch which a commit introduces, and tests to see if there is already a similar patch that has been introduced in the upstream branch.  As documented in the git cherry man page, it decides whether two patches are the same based on whether they have the same "patch ID", which is described as:

A "patch ID" is nothing but a SHA1 of the diff associated with a patch, with whitespace and line numbers ignored. As such, it's "reasonably stable", but at the same time also reasonably unique, i.e., two patches that have the same "patch ID" are almost guaranteed to be the same thing.
IOW, you can use this thing to look for likely duplicate commits.

So, I suspect that if the commit associated with comment2 isn't detected as having already been applied that's because the patch IDs are different.  That might, for example, be because you had to resolve a conflict when cherry-picking the commit associated with comment2.  That might well mean the patches that the commits introduced ended up being different.  You can see if that is right by comparing the output of these two commands:
git show 26370b3
git show 235b082


text:
Q: How to create an array of definable size with a repeating tail. JavaScript It is necessary to create a function that would create an array with a repeating ending
I wrote such a function, but I understand that it is absolutely not optimal. Is it possible to solve the problem in another way?

const getArr = (arrayLength, patternLength, repeatedTailLength) => {
    const arr = Array.from(Array(patternLength), (_, index) => index +1 );
    const repeatedTailNumbers = arr.slice(patternLength - repeatedTailLength);
    const tailsCount = Math.floor((arrayLength - patternLength) / repeatedTailLength);
    const tailsOdd = arrayLength - (tailsCount * repeatedTailLength + patternLength);
    let result = [...arr];

    for(let i = 1; i <= tailsCount; i++) {
      result = [...result, ...repeatedTailNumbers]
    }

    for(let i = 0; i < tailsOdd; i++) {
      result.push(repeatedTailNumbers[i]);
    }

    return result;
}

console.log(getArr(27, 9, 4));

[
  1, 2, 3, 4, 5, 6, 7, 8, 9,
  6, 7, 8, 9,
  6, 7, 8, 9,
  6, 7, 8, 9,
  6, 7, 8, 9,
  6, 7
]

A: You could get the parts in advance and map the items.

const getArr = (arrayLength, patternLength, repeatedTailLength) => {
    const
        pattern = Array.from({ length: patternLength }, (_, i) => i + 1),
        tail = pattern.slice(-repeatedTailLength);

    return Array.from(
        { length: arrayLength },
        (_, i) => i < pattern.length
            ? pattern[i]
            : tail[(i - pattern.length) % tail.length]
    );
}

console.log(...getArr(26, 9, 4));

A:

var tr = (count, last, times) => {
    let total = []
    for (let i = 1; i <= count; i++) {
        if(total.length == count) return total
        if(i > last) i = i-times
        total.push(i)
    }
}
console.log(tr(26, 9, 4))


text:
Q: c++ QObject::connect converting to new Qt5 Syntax I am fairly new to QT so bear with me.  I have a server application that I must connect to a port on and get a packet of data which is basically a string of xml content.  The communication is ancient and will work fine returning data with the example from https://www.binarytides.com/winsock-socket-programming-tutorial/ however I am trying to convert this example to the new Qt5 connect syntax and am failing horribly, any help or insight is greatly appreciated.  Here is an example of the response from the service packet that is received.  I need to grab that xml into memory and operate on it.  However the syntax is beyond me.  Forgot to mention that I am trying to run this and compile on Windows 10 Visual Studio 2015 using command line: cl /EHsc test.cpp
This appears to be the magic that needs changed:
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
D:\git>test

Initialising Winsock...Initialised.
Socket created.
Connected
Data Send

Reply received

<?xml version="1.0" standalone="yes"?>
<zoneServer>
<name>SuperNova</name>
<status>up</status>
<users>
<connected>0</connected>
<cap>3000</cap>
<max>0</max>
<total>0</total>
<deleted>0</deleted>
</users>
<uptime>142751</uptime>
<timestamp>1609481513051</timestamp>
</zoneServer>

Here is my code in QT:
SOCKET s;
char *message , server_reply[2000];
int recv_size;

qDebug() << "\nInitialising Winsock...";

if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    qDebug() << "Failed.";
    exit;
}

qDebug() << "Initialised.\n";

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    qDebug() << "Could not create socket : " << WSAGetLastError();
}

qDebug() << "Socket created.\n";

server.sin_addr.s_addr = inet_addr("192.168.0.116");
server.sin_family = AF_INET;
server.sin_port = htons( 44455 );

//Connect to remote server
//try to connect...

int status = connect(s , (struct sockaddr *)&server , sizeof(server));

if(status < 0)
{
    qDebug() << "connect error";
    exit;
}

qDebug() << "Connected";

//Send some data
message = "GET / HTTP/1.1\r\n\r\n";
if( send(s , message , strlen(message) , 0) < 0)
{
    qDebug() << "Send failed";
    exit;
}
qDebug() << "Data Send\n";

//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
{
    qDebug() << "recv failed";
}

qDebug() << "Reply received\n";

//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
qDebug() << server_reply;

However in the editor I receive:
.cpp:407: error: no matching member function for call to 'connect'
After Unrelated Includes:
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif

#pragma comment(lib,"ws2_32.lib") //Winsock Library


text:
Q: changing xamarin forms pcl targets I have a xamarin forms PCL solution and now I want to add xamarin forms pcl class libraries but I am unable to add these libraries as references to my original PCL project seeing. It gives me the following error:

Unable to add reference to project. The targets of Portable Library
  project are not the same or compatible with the targets of the current
  Portable Library project.

I have tried to change the targets on the PCL projects so that they match up but I can't do it in Visual Studio 2017.
Below are the targets for the original PCL project.

Below are the targets for the project I want to reference in the original PCL project.

Can anyone please assist or advice on how to accomplish this?

A: I found the solution to my problem. Its a slight change to @user2297037's answer. I did have to change the profile in the project file. The initial Portable Class Library's profile was Profile259 and the two new Portable Class Libraries' was Profile111. Changing the initial Portable Class Library's profile seemed to work but created massive problems at build time. I then reverted the change to the initial Portable Class Library and then changed the Profile on the two new Portable Class Libraries from Profile111 to Profile259. This solved my problem.


text:
Q: How do I change each char in a string but not change punctuations in C? I have an assignment to create a program that converts each character in a string by a set number entered at the command line. Example: if the user enters 1 at the command line then enters abc, def then the program should convert the string to bcd, efg.
I've written the program but I can't figure out how to get the program to not convert the punctuation characters.
The program currently converts abc, def and prints bcdefg. It needs to print bcd, efg and include the punctuation characters without converting them.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[]) //user enter number at cmd prompt

{
    string key = argv[1]; //store user entered number
    int k = atoi(argv[1]); //only accept consecutive digits
    if (argc != 2 || k == 0)
    {
        printf("Usage: ./caesar key\n"); /*show error if user enters non-consecutive digits*/
        return 1;
    }
    string original = get_string("Plaintext: "); /* prompt user for message to spin*/

    for (int i = 0, n = strlen(original); i < n; i++)  /* get string length and loop char change*/
        if (isalnum(original[i])) /* only convert alphanumeric character*/
            printf("%c", original[i] + k); /* print and convert character by number entered at prompt*/

    printf("\n");
    return 0;
}

A: You are only outputting the characters that your are transforming (those that are in the isalnum set).  You need to also output the characters not transformed. For example:
    char cipher = original[i] ;
    if( isalnum( original[i] )
    {
        cipher += k ;
    }

    printf( "%c", cipher ) ;

However the algorithm as described remains deeply flawed in several ways, but it is not clear whether it is the assignment that is flawed (in which case that is not your problem) or if your description of the assignment is inaccurate.
A more practical solution might look like:
#include <ctype.h>

char caesar( char x, int key )
{
    const char alphabet[] = {'a','b','c','d','e','f','g','h',
                             'i','j','k','l','m','n','o','p',
                             'q','r','s','t','u','v','w','x',
                             'y','z',
                             '0','1','2','3','4','5','6','7','8','9'};

    char cipher = x  ;

    for( int i = 0;
         cipher == x && i < sizeof( alphabet );
         i++ )
    {
        if( alphabet[i] == tolower( x ) )
        {
            cipher = alphabet[(i + key) % sizeof( alphabet )] ;
            if( isupper( x ) )
            {
                cipher = toupper( cipher ) ;
            }
        }
    }

    return cipher ;
}

Then your output loop would be:
for( int i = 0; original[i] != '\0' ); i++)
{
    printf("%c", ceasar( original[i], k ) ) ;
}

A: What you're currently doing only prints the character + k if it's alpha-numeric, but not printing it otherwise.  You you really want to do is only add k if it is alpha-numeric.  With a little boolean logic and math, we can avoid the if-statement altogether.
printf("%c", original[i] + (k * !!isalnum(original[i])));

If isalnum returns true, !! will make the resulting value 1 (it can return non-zero value if true; double-negating logically will make it either 1 if true or 0 if false).  So now we add k if it's alpha-numeric, or add nothing otherwise, and print the character either way.


text:
Q: simple Solr deployment with two servers for redundancy I'm deploying the Apache Solr web app in two redundant Tomcat 6 servers,
to provide redundancy and improved availability. At this point, scalability is not a issue.
I have a load balancer that can dynamically route traffic to one server or the other or both.
I know that Solr supports master/slave configuration, but that requires manual recovery if the slave receives updates during the master outage (which it will in my use case).
I'm considering a simpler approach using the ability to reload a core:
 - only one of the two servers is receiving traffic at any time (the "active" instance), but both are running,
 - both instances share the same index data and
 - before re-routing traffic due to an outage, the now active instance is told to reload the index core(s)
Limited testing of failovers with both index reads and writes has been successful. What implications/issues am I missing?
Your thoughts and opinions welcomed.

A: The simple approach to redundancy your considering seems reasonable but you will not be able to use it for disaster recovery unless you can share the data/index to/from a different physical location using your NAS/SAN.
Here are some suggestions:-

*

*Make backups for disaster recovery and test those backups work as an index could conceivably have been corrupted as there are no checksums happening internally in SOLR/Lucene. An index could get wiped or some records could get deleted and merged away without you knowing it and backups can be useful for recovering those records/docs at a later time if you need to perform an investigation.

*Before you re-route traffic to the second instance I would run some queries to load caches and also to test and confirm the current index works before it goes online.

*Isolate the updates to one location and process and thread to ensure transactional integrity in the event of a cutover as it could be difficult to manage consistency as SOLR does not use a vector clock to synchronize updates like some databases. I personally would keep a copy of all updates in order separately from SOLR in some other store just in case a small time window needs to be repeated.
In general, my experience with SOLR has been excellent as long as you are not using cutting edge features and plugins. I have one instance that currently has 40 million docs and an uptime of well over a year with no issues. That doesn't mean you wont have issues but gives you an idea of how stable it could be.

A: I hardly know anything about Solr, so I don't know the answers to some of the questions that need to be considered with this sort of setup, but I can provide some things for consideration.  You will have to consider what sorts of failures you want to protect against and why and make your decision based on that.  There is, after all, no perfect system.
Both instances are using the same files.  If the files become corrupt or unavailable for some reason (hardware fault, software bug), the second instance is going to fail the same as the first.
On a similar note, are the files stored and accessed in such a way that they are always valid when the inactive instance reads them?  Will the inactive instance try to read the files when the active instance is writing them?  What would happen if it does?  If the active instance is interrupted while writing the index files (power failure, network outage, disk full), what will happen when the inactive instance tries to load them?  The same questions apply in reverse if the 'inactive' instance is going to be writing to the files (which isn't particularly unlikely if it wasn't designed with this use in mind; it might for example update some sort of idle statistic).
Also, reloading the indices sounds like it could be a rather time-consuming operation, and service will not be available while it is happening.
If the active instance needs to complete an orderly shutdown before the inactive instance loads the indices (perhaps due to file validity problems mentioned above), this could also be time-consuming and cause unavailability.  If the active instance can't complete an orderly shutdown, you're gonna have a bad time.


text:
Q: Laravel Not found after pulling from github hi after pulling my laravel application from github into apache (wampserver)and executing composer update everytime i try to acces to one of my route  it shows me
Not Found
The requested URL /getud/public/mat was not found on this server.
How could i fix this problem thnks


text:
Q: Open Source Contribution for a newbie programmer I am teaching programming to my nephews and I want them to improve their skills by contributing to open source projects. Now my question is, do you know any open source project that suit for a newbie programmer. What I mean is, the project does not have a large codebase, the project is very interesting and the project is written in C because I chose C language as their starting language but you can suggest other project made in other language.
My goal here are to improve their logic by reading other source codes, familiarize to the available development tools like bug tracker, version control system, etc. and open their interest in open source community.
Thanks. =)

A: This has been asked before?
Open source project: beginners [closed]

A: This is difficult to answer without knowing the level and skills of your students. Without that background information, I couldn't even tell if it is advisable at all to let them loose on any existing project.
In my opinion, before somebody is ready to contribute to any non-trivial open source effort, they should have a solid understanding of data structures and the concept of ADTs and information hiding. Ideally they would have implemented some basic ADTs on their own.
In my experience this is all too often lacking especially when the language used for instructing beginners is C since C doesn't have built-in ADTs nor a standard ADT library and developers are generally expected to be able to either write their own or select a third party library and if necessary customise it to their needs.
I have seen quite a few open source projects written in C where the only data structures used were fixed size arrays and linked lists, where every algorithm was the most naive possible, where the notion of an API was to expose structs and let everybody modify them.
A contributor who is familiar with ADTs will soon run away from such a project in horror. A contributor who is not familiar with ADTs will only learn bad habits there.
If your aim is solely to get your students to learn the use of version control and bugtracking systems, it is perhaps a better idea to assign them an exercise and make them set up a repository at one of those sites that integrate version control, online source code browsing and bugtracking, for example Github, Bitbucket, Google Code etc.
You can then examine the work they did for the assignment and if you find any mistakes you use the bugtracker to file a bug which they then have to deal with accordingly. You can then expand the assignment by filing feature requests again using the bugtracker etc.
Furthermore, sites like Github and Bitbucket have a clone-this-repository feature. This lends itself nicely to teaching collaboration as well. Depending on the skillset of your students you could either pick an existing repository for them to clone and then extend following your assignments, or you could ask them to search a repository (possibly matching certain criteria) and pick one for themselves, then again extend that following your assignments.
There is one more thing that I personally believe should be a pre-requisite for contributing to any non-trivial open source project: understanding design by contract, how to document a function contract, thinking in function contracts, having developed the discipline to never code anything without documenting a function contract first. Unfortunately, too few open source projects use design by contract. Again, a contributor familiar with this practise will soon run away from such a project in horror and one who isn't will only pick up bad habits.
However, you could turn this into an exercise by telling your students to clone an existing repository from say Github or Bitbucket and then assign them the task to fill in the missing function contract documentation. Needless to say that for such an exercise you would first have to have taught them what design by contract is and how to write function contracts.
Once your students have gained the skills I outlined above, I am sure the question of "which open source projects could we contribute to?" will become trivial to answer because at that stage your students will be able to find and choose a suitable project for themselves.
In the meantime, if you feel that your students still need some example code for both ADTs written in C and how to write function contracts, and you don't have any such examples handy, you might want to take a look at my repository at Bitbucket. It has a variety of common ADTs in C and all sources contains function contracts. Feel free to clone any of the repos in there and use them as a base for exercises:

*

*http://bitbucket.org/trijezdci
I am sure if you look around there is plenty of suitable material by other authors, too.

A: I'd recommend GitHub as they can start without really having to contact people to get a commit access to the repository, and where a wrong commit won't create problem as it will be only a "local" commit.

A: I have always found the freebsd project to be good for teaching people how to program in C.  They will get code review by commiters who will explain how to be better and they have great docs, http://www.freebsd.org/doc/en/books/developers-handbook/book.html.  You can volunteer to fix bugs: http://www.freebsd.org/cgi/query-pr-summary.cgi and they have a large list of things to do: http://www.freebsd.org/projects/ideas/ideas.html  some are simple and some are hard


text:
Q: find elements of different types in two lists with common property value, linq variant of two for each loops there are two lists

*

*Myobjects list contains all items, all have property "oid" of
ObjectID

*The list of ObjectID types is list of ALL objects to be
deleted

Problem is to find any item in Myobjects that has ObjectID in oid property.
I'm having a hard time finding equivalent of this two "for each" loops in LINQ.
This should be easy, but I'm doing it wrong. It takes 20 sec to perform this LINQ on 30 000 items, and under one sec using for-each loop. Below is working for-each loop, and my attempt to make LINQ of it (this one is slow). Linq solution is what I would like to have.
        For Each i As LengthAreaObject In myobjects
            For Each o As ObjectId In oidsToRem
                If i.oid = o Then
                    returnlist.Add(i)
                    oidsToRem.Remove(o)
                    Exit For
                End If

            Next
        Next

and LINQ attempt here
Dim rlist As List(Of LengthAreaObject) = (From i As LengthAreaObject In myobjects.AsParallel Where oidsToRem.Contains(i.oid) Select i).ToList

A: How much items have the collections?
For small collections, AsParallel will be slower because of the extra method call.

A: I have found similiar question on stackoverflow and modified it.
So the solution to speed things up is nothing more but to hash collection where the objects are you test for "contains". Otherwise, contains is slow!
Dim setToRemove = New HashSet(Of ObjectId)(oidstoRem)
   Dim returnlist As List(Of LengthAreaObject) = lengthAreaList.AsParallel.Where(Function(x) setToRemove.Contains(x.oid)).ToList


text:
Q: Vertical-align: middle in table-cell My markup is:
li
  .wrapper
    p = @album_count
  h3 Albums

The above is in Slim
My styles are:
  li
    +span-columns(3, 12)
    +nth-omega(4)
    position: relative
    color: $body-text

  h3
    text-transform: uppercase
    text-align: center

  .wrapper
    position: relative
    display: table
    display: block
    width: 100%
    height: 0
    padding-bottom: 94.6%
    +border-radius(50%)
    border: 6px solid $white
    border: remCalc(6px) solid $white
    text-align: center
    background-color: #266997
    +box-shadow(inset 3px 3px 3px #0B5486)
    +box-shadow(inset remCalc(3px) remCalc(3px) remCalc(3px) #0B5486)

    &:after
      content: ''
      position: absolute
      left: 10%
      top: 10%
      width: 80%
      height: 80%
      +border-radius(50%)
      background-color: white
      +box-shadow(3px 3px 3px #0B5486)
      +box-shadow(remCalc(3px) remCalc(3px) remCalc(3px) #0B5486)

    p
      position: absolute
      display: table-cell
      width: 100%
      height: 100%
      vertical-align: middle
      z-index: 10

Basically, I end up with the .wrapper being a specific width due the Compass Susy column it is sat in and the height becomes the same due to the 94% bottom padding. It's 94% due to the h3 underneath. This is something I will be changing but this isn't the issue here.
The problem I have is with the p, I have absolutely positioned it and set it's height and width to be 100% each so it sits on top of the circle .wrapper. That works fine. I then displays the .wrapper as a css table and the p as a css table cell and added vertical-align: middle. This should work as far as I am aware but it is not making any difference at all in this case.
Is anyone able to help?

A: You can't display as table-cell an absolutely positioned element: relationships between 'display', 'position', and 'float' (CSS2.1 REC)
EDIT: is there a typo in .wrapper? You've 2 instructions involving display and for compatibility reasons with IE6/7 I can understand why you would first display as block for every browser and then for IE8+ as table but here: .wrapper is a div (I think) and it's already block by default and it's written the other way around (table than block so it's block for everybody)


text:
Q: inserting document of collections to another collections in mongodb i have two different collection of documents in a mongodb database. in my recruits collection i have plenty of documents. and i want to add the document from recruit collections to employee collections
here is part of my code
function register(){
        $http({
            url:'/employee',
            method:'post',
            data:data // data is what i get from findById query.
        }).then(function(result){
            vm.cancel();
            vm.toast();
        },function(err){
            console.log(err);
        })

here data is what i get from findById  from recruits collections. now same data i want to store in employees collection.i tried so:
var emp = require('../models/employees.js');
 router.post('/',function(req,res){
console.log(req.body);
var register = new emp(req.body);
//console.log(register);
register.save(function(err, respond) {
    if (err) {
        throw err;
    } else {
        res.json(respond);
    }
})
});

i think its fine with the code my console shows me
MongoError: E11000 duplicate key error index: humanResource.employees.$_id_ dup
 key: { : ObjectId('57395146b4c73790056a3770') }

any one suggest me how to insert such document in another collections.

A: You error is saying that the document you are creating has a _id which already exists in employees collection.
The problem is that you are receiving recruit data and directly passing it to the employees collection along with the _id which is passed from the recruit. You should try copying the data but excluding the _id field. Mongo will automatically generate a _id for your employees collection.
something like this,
var emp = require('../models/employees.js');
router.post('/',function(req,res){
      console.log(req.body);
       delete req.body._id;
      var register = new emp(req.body);
      register.save(function(err, respond) {
if (err) {
      throw err;
} else {
     res.json(respond);
}
});


text:
Q: Убрать end padding у Chip элемента Программно создается Chip (в коде пытался избавится от конечного отступа)
fun createChip(): Chip {
    val chip = Chip(context)
    chip.text = "dsg dfgs adfa sfasfsd s"

    chip.chipBackgroundColor = Color.GREEN
    chip.setTextColor(Color.WHITE)

    chip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
    chip.chipStartPadding = 0F
    chip.chipEndPadding = 0F

    chip.closeIconStartPadding = 0F
    chip.closeIconEndPadding = 0F
    chip.closeIconSize = 0F

    chip.isCloseIconVisible = false
    chip.isCheckedIconVisible = false

    chip.setMargins(0, 0, 0, 0)
    chip.setPaddingRelative(0, 0, 0, 0)

    chip.textStartPadding = 0F
    chip.textEndPadding = 0F
    chip.includeFontPadding = false
    chip.minWidth = 0
    return chip
}

Chip - com.google.android.material.chip
вот результат (непонятно откуда там отступ в конце)

A: В моем случае проблема была в chip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
Решение подсмотрел тут https://stackoverflow.com/a/57397345/3671076