text:
Q: How does the merge sort algorithm go "up the tree"? I'm having trouble understanding how the recursive merge sort algorithm works, I understand how it theoretically works :
if there's more than one element in an array find its middle and divide the array into 2 smaller sub-arrays and so on until you have 2 arrays of 1 element that are by definition already sorted (base case) then you can merge them using a merging algorithm, then you go up the tree and so on.
I've tried to implement it in python with some print statements to follow step by step and it works but I don't really understand why it works the way it does. I'll describe you my wrong logic:
the algorithm in pseudo code with l being the low index and h the high index :
merge_sort(l,h){

if(l < h){
mid = (l+h)//2
merge_sort(l,mid)
merge_sort(mid+1,h)
merge(l,mid,h)
}

}

so for a an arr = [9,3,7,5]

*

*We call merge_sort(0,3) which is the full array, l=0 , h =3, mid = 1 [9,3,7,5]

*l < h so it calls merge_sort(0,1), l=0,h=1 , mid=0 [9,3]

*l < h so it calls merge_sort(0,0) l=0 h=0 mid =0 [9]

from here l == h so we don't fulfill the condition l < h and thus  merge_sort doesn't call itself again, for me the algorithm ends here ( which is obviously wrong ) BUT here it goes upand calls merge_sort(1,1) [3] (right side of the array)  then merge is executed.
After that it goes up again and tackles the right side of the initial array merge_sort(2,3) [7,5] and continues. ( [7] then [5] then merging )
Can someone please explain me why the algorithms continues to call himself after l == n ? I've read some explanations and watch some videos and some even argues merge(l,mid) sort the full first half [9,3]  and merge(mid+1,h) sort the second full half [7,5] which is apparently not how it's working, I'm really confused.

A: It doesn't call itself again, it returns back to it's previous step in recursion, once it finishes the current one.
Here is an example from GeeksForGeeks of a merge sort algorithm, with each step labeled numerically in a sequential order:

A: You can understand a recursive algorithm by trusting it. Have a look at the annotation below (! starts a comment):
merge_sort(l,h) {

if (l < h) {
    mid = (l+h)//2
    merge_sort(l,mid) ! If merge_sort does its job, the array is now sorted from l to mid
    merge_sort(mid+1,h) ! If merge_sort does its job, the array is now sorted from mid+1 to h
    merge(l,mid,h) ! If merge does its job, the array is now sorted from l to h
}
else { ! If l==h, the array is already sorted from l to h
}

Now you can see that if we call the function with some values of l and h, it will return a sorted array, by calling itself on parts of the array, each time returning them sorted. The whole construction works because the size of the subarrays goes decreasing across the levels of calls, and always reaches 1, causing an immediate return to the calling level.


text:
Q: How to do Javadoc on Java enums that have extra attributes? One topic that I can't seem to find information on is how to do Javadoc for enums that have an extra parameter.  For example in the classic Coins example how can the 1,5,10,25 values be associated with penny, nickle, dime, quarter (other that keying each in by hand)?
 enum Coin {
     PENNY(1),
     NICKEL(5),
     DIME(10),
     QUARTER(25);

   private final int denomValue;

   Coin(int denomValue) {
       this.denomValue = denomValue;
   }

   int denomValue() {
      return denomValue;
   }

   int toDenomination(int numPennies) {
      return numPennies / denomValue;
   }
}

A typical use case is documenting error mnemonics and int error codes.

A: Won't this work for you or am I misunderstanding the question?
/**
 * blah blah
 */
enum Coin {
    /**
     * Penny - 1 cent, blah blah
     */
    PENNY(1),

    /**
     * Nickel - 5 cents, blah blah
     */
    NICKEL(5),
    ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: pandas.dataframe.from_records not working on numpy array Let's create a numpy array and a list
import pandas as pd
import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
l = ["a", "b", "c"]

This works:
> pd.DataFrame.from_records(m, index=l)

   0  1  2
a  1  2  3
b  4  5  6
c  7  8  9

This works:
> pd.DataFrame.from_records(m, columns=l)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

but this does not:
pd.DataFrame.from_records(m, index=l, columns=l)
Empty DataFrame
Columns: []
Index: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

This slight bug does not occur if we don't call from_records method. But I need it to avoid the Dataframe from copying the data.


text:
Q: Youtube downloader that can use the youtube.com/user/userxxxx url I am trying to find a youtube downloader that allows to put in the url youtube.com/user/userxxx, then presents me with a list of all the videos of userxxx so that I can select the videos I am interested in and download them. This allows me for example to easily download lots of videos from a specific channel, instead of having to copy/paste individual links like it is done in many downloaders.
Up till now I have been using the dvdvideosoft.com free youtube downloader and it works well. However, with their latest version of the downloader, they have started to use the opencandy adware stuff when installing the software. I do not like this opencandy stuf at all, as it happens during install time when the app has admin rights. Also see this article http://kb.eset.com/esetkb/index?page=content&id=SOLN2677.
I have been looking at many downloaders yesterday (eg xVideoservicethief, freemake video downloader, imtoo download youtube video, zillatube, cliparchiver, xilisoft online video downloader, ashampoo clipfinder,..etc) but none seem to offer this functionality. The only one that indicated it supported it, was the biennesoft youtube downloader. However, when I tried it out, it did not work at all.
Does anyone know of an alternative downloader that has such a feature?

A: I read your question and decided I could use a piece of software like that too. So I started looking around and here is what I found.
Look at this and see if there is a windows version.
Internet Download Manager is the software I currently use, it just inserts a link into the browser. It doesn't really answer your question but I find it useful.
I'll let you know if I find anything else.


text:
Q: How do you type a line containing a single dot (.) in ed? \.  doesn't work.  a single dot (.) ends the command and cant be recognized.
Please don't tell me; use sed or echo . >> file.   Is there a way to do it with ed ?

A: Maybe type "dot space" (or some other character) then dot then edit the line to remove the trailing character
touch afile
ed -s afile <<END
a
foo
.x
bar
.
-1s/x//
wq
END

then
$ cat -A afile
foo$
.$
bar$


text:
Q: Ensuring an event loaded by jquery .load only fires once I have a page that looks like this:
  <form id="NoteForm" >
        <input type="submit">
    </form>
    <script>

        $(document).on("submit", "#NoteForm", function (e) {

            console.log("Submitted");
            e.preventDefault();

            $.ajax({

                url : 'Forms/Data.cfm',

                type : 'POST',

                data: $(this).serialize(),

                success : function(data)
                {
                    $('#Status').html(data);
                },

            });
        });

    </script>

It's loaded by
$('#ActivePage').load('NotePage.cfm);

When I submit the NoteForm after it has loaded, it triggers once for every time I have loaded it into ActivePage. How can I ensure it only fires one time?

A: Calling $(document).off('submit'); before .load() fixed this issue.


text:
Q: Google charts api after ajax call I've got a problem with the visualization of data with google's charts api after an ajax call.
First I made an ajax call and fetched a json object. After that I want to extract some data out of the json and draw a gauge chart. Getting the json and extracting the data works fine, but when I try to load the chart, the body gets removed and I get a blank/white screen. Does anyone knows what I am doing wrong? I also tried to hard code values for the chart instead of taking the json values (but kept the ajax call before loading the chart), but it didn't work neither.
function loadStats(){
    var http = getRequestObject();
    var city = "berlin";
    http.open("GET", "getTwitterSentiments.php?city="+city, true);
    http.onreadystatechange=function() {
        getStatistic(http)
    };
    http.send(null);
}

function getStatistic(request) {
    if ((request.readyState == 4) && (request.status == 200)) {
        var data = request.responseText;
        var JSONStats = eval("(" + data + ")");
        loadGauge(JSONStats.sentiment_index);
    }

function loadGauge(sentiment){
    google.load('visualization', '1', {packages:['gauge']});
    google.setOnLoadCallback(drawGauge);
    function drawGauge() {
        var data = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Test', sentiment]
        ]);

        var options = {
            width: 100,
            height: 100,
            redFrom: 0,
            redTo: 45,
            yellowFrom: 45,
            yellowTo: 55,
            greenFrom: 55,
            greenTo: 100,
            minorTicks: 10
        };

        var chart = new google.visualization.Gauge(document.getElementById('testgchart'));
        chart.draw(data, options);
    }
}

A: Try using the callback feature of google.load() function.
For instance, for your code, try the following:
function loadGauge(sentiment){
    google.load('visualization', '1.0', {'packages':['gauge'], 'callback': drawGauge});

}

function drawGauge(){
...
chart.draw(data, options);
}

For more information, check the 'Dynamic loading' section of Google Loader Developer Guide:
https://developers.google.com/loader/#Dynamic
If i understand correctly, calling loadGauge() multiple times will not cause multiple trips to Google servers to load the required APIs, but just once.

A: I guess your element testgchart is not load in the DOM yet, your code should work.
I made an example from your code :
<!DOCTYPE html>

    <meta charset="utf-8">

But it doesn't work if you delete this line  and replace the body tag with . Your probably doing something similar.
If your sure the element testgchart is present then put a log in loadGauge and tell me if it really get called by getStatistic.


text:
Q: How can I convert string to int/Integer if the string contains word? Basicly I want to convert string word to int like from xml but now from a raw file.
I can do this from xml:
final int[] colorArray = getResources().getIntArray(R.array.colors_int);

And I have this in the xml file:
<integer-array name="colors_int">
            <item>@color/red</item>
            <item>@color/yellow</item>
            <item>@color/blue</item>
   </integer-array>

By this I can easily set colors on my objects:
view.setBackgroundColor(colorArray[i]);

BUT now I have a raw file which contains a colors name dividing them by whitespace: "blue red yellow"
How can I read these into an int array/Integer arraylist, so I can color objects easily?
I tried this:
input_file_int.add( Integer.parseInt(line));

but it didnt work because the string isnt an int.
 java.lang.NumberFormatException: Invalid int: "blue"

With string arraylist, it works perfectly but I cant use strings to color objects.
How could I do this?
EDIT:
I have this example raw file:
black
gray
silver
maroon
red
olive

My colors.xml:
<?xml version="1.0" encoding="utf-8"?>
    <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <!--16 basic color -->
        <color name="black">#000000</color>
        <color name="gray">#808080</color>
        <color name="silver">#C0C0C0</color>
        <color name="white">#FFFFFF</color>
        <color name="maroon">#800000</color>
    </resources>

And thats how I initialized the Integer ArrayList:
ArrayList<Integer> input_file_int= new ArrayList<Integer>();

A: You could create a Map of the colors:
Map<String, Integer> colors = new HashMap<String, Integer>();
colors.put("blue", 0xff00ff00);

input_file_int.add(colors.get("blue"));

EDIT:
If you're trying to do a lookup of the colors listed on your xml, you can do so like so:
Resources resources = getResources();
int colorId =  resources.getIdentifier(line, "color", "com.mypackage.myapplication");
int color = resources.getColor(colorId);
input_file_int.add(color);

A: // Your arraylist
ArrayList<Integer> input_file_int = new ArrayList<Integer>();

// Read raw file
Scanner scanner = new Scanner(getResources().openRawResource(
        R.raw.colors));
try {
    while (scanner.hasNext()) {
        switch (scanner.next()) {
        // include case of your all 16 (or any number of) colors of your
        // colors.xml file
        case "black":
            input_file_int.add(Integer.parseInt(getResources()
                    .getString(R.color.black).substring(3), 16));
            break;
        case "gray":
            input_file_int.add(Integer.parseInt(getResources()
                    .getString(R.color.gray).substring(3), 16));
            break;
        case "silver":
            input_file_int.add(Integer.parseInt(getResources()
                    .getString(R.color.silver).substring(3), 16));
            break;
        // and keep going on
        default:
            break;
        }
    }
} catch (Exception e) {
    Log.e(getTitle().toString(), e.getMessage());
} finally {
    scanner.close();
}
// Now, Arraylist contains true Integer value of colors
// Be aware you can't directly use it.
// Use it like this...

view.setBackgroundColor(0xff000000 + input_file_int.get(2));
// Silver in this case


text:
Q: remove the duplicate tr based on class (only if consecutive tr have the same class) There are two tr with the same class "redline" one after the other (that appears consecutively), I want to remove one 'tr' in that.
This is the HTML example

bla

bla

bla

bla

bla

bla

bla

bla

A: Consider using + selector in CSS.
https://www.w3schools.com/cssref/css_selectors.asp
Here is the example:

const dups = document.querySelectorAll('.redline + .redline')
dups.forEach((dup) => {dup.remove()})

    bla

    bla dulplicate

    bla

    bla

    bla

    bla

    bla dulplicate

    bla

A:

document.querySelectorAll("#test .redline").forEach(function(element){
    if(document.querySelectorAll("#test .redline").length > 1)
        element.remove()
});

bla

bla

bla

bla

bla

bla

bla

bla


text:
Q: How make a list of images responsive inside a flexbox container using all available height I want to create a list of images that will fill the whole height of the side panel of my app. But I want the images to be responsive too. I was able to make the images responsive, the problem is that the side panel won't shrink for the resized images width.
Here a example in CodePen so you can play with the container height: https://codepen.io/guilhermeaiolfi/pen/bGvBdpG

html, body {
    height: 100%;
    margin: 0;
}

.app .left-side {

}

.app .right-side {
    margin: 10px;
}

.app {
    display: flex;
    flex: 1;
    height: 100%;
    flex-direction: row;
}
.zoom__images {
    border: 1px solid black;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.zoom__images > * {
    flex: 1 0 0;
    min-height: 0;
    display: flex;

}

.zoom__images img {
    max-height: 100%;
    margin-left: auto;
    margin-right: auto;
}

  content

The images size (both height and width) are being properly handled when the .left-side height changes, but the left-panel width is always 400px wide when it should be the size of the images inside it.
Thanks.

A: i think you want like this
html, body {
  height: 100%;
  margin: 0;
}

.app {
  display: flex;
}

.left-side {
  background:red;
  flex: 1;
}

.left-side .zoom__images div img{
  width: 100%;
}

.right-side {
  flex: 1
}


text:
Q: Weird result when convert Hex to String How to can i convert hex value to string ? i get this weird result by using the following method.
for example :
String result = DB_record.convertHexToString(PASSWORD);
// c53255317bb11707d0f614696b3ce6f221d0e2f2 hex value;
System.err.println("result==="+result);

Java
 public String convertHexToString(String hex){

  StringBuilder sb = new StringBuilder();
  StringBuilder temp = new StringBuilder();
  for( int i=0; i<hex.length()-1; i+=2 ){

      //grab the hex in pairs
      String output = hex.substring(i, (i + 2));
      //convert hex to decimal
      int decimal = Integer.parseInt(output, 16);
      //convert the decimal to character
      sb.append((char)decimal);

      temp.append(decimal);
  }

  return sb.toString();
 }

output

A: Problem lays here
    sb.append((char)decimal);
this is not a correct way, how to convert int to String.
try this
sb.append(Integer.toString(decimal));

A:  byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
      String result= new String(bytes, encoding);


text:
Q: Windows 7 On Domain Access Ubuntu Shared Folder Had the samba setup done and when W7 access using \ip_address\share it prompts but only allow domain name login.
How should i go about it without dropping out W7 from domain?

A: yeah managed to resolve after found this article http://blink4blog.blogspot.com/2012/02/fedora-16-post-installation-guide-mount.html although is for Fedora but it works for Ubuntu as well.


text:
Q: ¿Porqué no funciona la función alert()?

$(function() {
    $('#depnac').on('change', onSelecDepChange);
});

function onSelecDepChange() {
  var id_dep = $(this).val():
  alert(id_dep);
}

      Departamento de
          Nacimiento:

        <select class="form-control" id="depnac" name="dep_nac_asp">
          @foreach($departamentos as $departamento)
          <option value="{{$departamento->id_dep}}">{{$departamento-
           >nom_dep}}</option>
          @endforeach
        </select>

      Municipio de
          Nacimiento:

        <select class="form-control" id="munnac" name="mun_nac_asp">
          @foreach($municipios as $municipio)
          <option value="{{$municipio->id_mun}}">{{$municipio-
            >nom_mun}}</option>
          @endforeach
        </select>

A: Intenta cambiando los ":" por un ";".
$(function() {
    $('#depnac').on('change', onSelecDepChange);
});

function onSelecDepChange() {
    var id_dep = $(this).val();
    alert(id_dep);
}

Saludos y recuerda aceptar respuesta sí te funcionó.

A: Corregí el ":" por ";" y agregue la referencia a jquery

$(function() {
    $('#depnac').on('change', onSelecDepChange);
});

function onSelecDepChange() {
    var id_dep = $(this).val();
    alert(id_dep);
}

<select id="depnac">
<option value='1'>prueba</option>
<option value='2'>prueba</option>
</select>


text:
Q: Creating an observer-able variable in Swift for MVVM pattern I'm trying to observe a variable for it's change. The below code works, but when I set the initial value of isValid the observer is fired. Then after the my callAPI() the variable isValid is set again. So part of my logic code is being checked prematurely.
What is the correct way to implement an observer of so that on initial load, the initial setting of the value isn't fired?
Am I doing this all wrong? Is there a better way?
The ViewController
class SomeViewController: UIViewController {

    private let viewModel = SignInViewModel()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // I want to watch this variable, but when it is initialized, it's already false and fires off the bad() func
        viewModel.isValid.bind {[weak self] isValid in
            if(isValid){
                self?.good()
            }  else {
                self?.bad()
            }
        }

        viewModel.callAPI()

    }

    private func bad(){
        print("VALID --")
    }

    private func bad(){
        print("-- NOT VALID")
    }
}

My ViewModel
public class SomeViewModel {

    lazy var isValid = Observer(false)

    func callAPI(){
        // Do something on the background and set the boolean
        isValid.value = //result
    }
}

The Observer
final class Observer<T> {
    typealias Listener = (T) -> Void

    var listener: Listener?
    var value: T {
        didSet {
            listener?(value)
        }
    }

    init(_ value: T) {
        self.value = value
    }

    func bind(listener: Listener?) {
        self.listener = listener
        listener?(value)
    }
}

A: You can avoid the initial fire of your listener by modifying Observer to something like this:
final class Observer<T> {
    typealias Listener = (T) -> Void

    var listener: Listener?
    var value: T {
        didSet {
            listener?(value)
        }
    }

    init(_ value: T) {
        self.value = value
    }

    func bind(listener: Listener?) {
        self.listener = listener
    }

    func bindAndFire(listener: Listener?) {
        self.listener = listener
        listener?(value)
    }
}

calling bind(listener:) function will only add the new listener without immediately calling it, while calling bindAndFire(listener:) will also fire the listener for the initial value.
Or you can use a Bool parameter in bind(listener:) function to determine whether you want or you don't want to fire the listener for the initial value:
func bind(fire: Bool = false, listener: Listener?) {
    self.listener = listener
    if fire {
        listener?(value)
    }
}


text:
Q: Fastest way to generate long strings in JavaScript (performance) There are lot of random string questions on stack exchange, but they do not help me with my problem.
I need to generate a lot of random (no need to be true random) long strings (256 chars) in JavaScript as fastest as possible. It doesn't need to be one-line function, performance is the only thing that matters. Can someone help me with this?


text:
Q: Clubs whose intersections are multiples of six (Oddtown variant) This is a question about generalizing the famous "Clubs in Oddtown" problem. The original setup is that a town has $n$ people, and $m$ clubs each consisting of a subset of the population. Each club has an odd number of members, while any two distinct clubs have an even number of members in common. Given this, you the goal is to prove $m\le n$. You can prove this using linear algebra over $\mathbb F_2$.
One might ask if the results still hold if we replace $2$ with another number $d$. That is, if we have a town with $n$ people and $m$ clubs such that the number of people in any club is not a multiple of $d$, while the number of people in common to any two clubs is a multiple of $d$, what it is the greatest possible value of $m$ in terms of $n$? When $d=p$ for any prime $p$, you can prove $m\le n$ using the same argument but with $\mathbb F_p$-linear algebra. You can also prove that $m\le n$ when $d=p^k$ is any prime power, see Generalize Oddtown.
This leads me to ask, can we also prove that $m\le n$ for all other $d$? For concreteness, I am asking about $d=6$ (I like to call this variant "Clubs in Sioux City"). That is,

Question: There is a town with $n$ people and $m$ clubs consisting of subsets of the population. Any club has a number of members which is not a multiple of $6$, while the number of members in common to any two clubs is a multiple of $6$. Can we conclude that $m\le n$?

I know that you can prove $m\le 2n$, by combining the $d=2$ and $d=3$ results (proving this result is what was asked at that question I linked before). But from playing with small cases, it does not seem like it is possible to create a setup with $m>n$, though I also cannot prove this. Does anyone know how to prove that $m\le n$, or how to construct a set of $n+1$ clubs satisfying the requirements?


text:
Q: How to make a JLabel change once based on time I've ben researching how to use swing timers for 2 days now and am trying to figure out how to change the image I have at the center of my JFrame. As of now my program runs properly, but the image does not change the way I want it to. This class was just used as a test so it might not have proper java syntax.
    package hauntedHouseAdventure;

import java.awt.BorderLayout;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;

    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.Timer;

public class timertest {
    static JFrame sceneOne = new JFrame();
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

    ImageIcon image = new ImageIcon(
            "/Users/computerscience2/Desktop/dark-forest-night-image.jpg");
    JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(imageLabel, BorderLayout.NORTH);
    sceneOne.add(panel);
    sceneOne.setResizable(false);
    imageLabel.setVisible(true);
    sceneOne.pack();

    JButton leave=new JButton("Leave");
    JButton stay= new JButton ("Stay");
    leave.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            sceneOne.setVisible(false);
        }
    });
    stay.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent f)
        {
            //Execute when button is pressed
           sceneOne.setVisible(false);
        }
    });

    panel.add(leave, BorderLayout.EAST);
    panel.add(stay, BorderLayout.WEST);

    JLabel label1 = new JLabel("Test");

    label1.setText(" It was approximately 11:30 pm. The night sky was black not a single star piercing through the darkness"
            + "except the thick and powerful moonlight."
            + "
"
            + "You are alone leaving a costume party at a friend's place."
            + "It was rather boring and you decided to leave early."
            + "A stutter is heard and your"
            + "
"
            + "car begins to shake"
            + "Your headlights and car lights crack. The engine is left dead silent."
            + "You are left in a total silence"
            + "and baked in merely the moonlight."
            + "
"
            + "There is a mere second of silence till a harsh chill ripes through the"
            + "car like a bullet through paper. You are left dumbfounded. What do you do?");
    label1.setHorizontalAlignment(JLabel.CENTER);
    label1.setVerticalAlignment(JLabel.BOTTOM);
    label1.setVisible(true);
    label1.setOpaque(false);

  panel.add(label1);

  final ActionListener updater = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent event) {

          ImageIcon image = new ImageIcon(
                  "/Users/computerscience2/Desktop/image-slider-5.jpg");
          JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(imageLabel, BorderLayout.NORTH);
          sceneOne.add(panel);

          }
  };

  Timer timer = new Timer(1000, updater);

  timer.start();

  sceneOne.setSize(2000,1000);
    sceneOne.setTitle("The Car");
    sceneOne.setVisible(true);
    sceneOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    sceneOne.setLocation(250, 200);
}

}

A: I didn't look in detail but to change the image on the label then you don't need to create a new control, you just need to change the image on the existing one.
  public void actionPerformed(ActionEvent event) {

      ImageIcon image = new ImageIcon(
              "/Users/computerscience2/Desktop/image-slider-5.jpg");
      imageLabel.setIcon(image);

  }

You will also need to make imageLabel either a member variable or final so that the actionPerformed method can see it.

A: I see two problems in your code.

*

*You are adding the new image to your panel, but not removing the old image.

*You are not telling to your frame that your components changed and he needs to redraw.

I think the best way to do this, is just changing the icon of your imageLabel. Like this:
final JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
......
final ActionListener updater = new ActionListener() {

   public void actionPerformed(ActionEvent e) {
      ImageIcon image = new ImageIcon("/Users/computerscience2/Desktop/image-slider-5.jpg");
      imageLabel.setIcon(image);
      imageLabel.updateUI(); //Tell to your frame he needs to redraw the image
   }
};


text:
Q: bootstrap navbar not active I have this navbar and I cannot set an item to active - I have no idea why. Can someone explain this to me?

payment transactions

transaction notes

slow transactions


text:
Q: In what way I can automate my home? I need to connect all of the systems in my home and make them responsive to me at any time from any location. I tried to search in google but information what I found was incomprehensible for me.

A: Have you ever heard about Home Automation? you can simply connect all of the systems in your home and turn them into a "smart home". The automation is, actually, the combining of two or more of systems which are known as subsystems.


text:
Q: Trigger to avoid similar names inserted in tables isnt working and not let me insert any row I have this trigger to avoid similar names inserted in a table. But isn't working at all and not let me insert any row (as if the condition is true everytime). I tried with IF EXISTS and happen the same. Even deleting everything in the "Actor" table (leaving with no rows) and when I insert a new one the trigger fires.
CREATE TRIGGER [dbo].[AvoidSimilarName]
ON [dbo].[Actor]
FOR INSERT
AS
BEGIN
DECLARE @Firstname varchar(25)
DECLARE @Lastname varchar(25)
SELECT @Firstname = Firstname, @Lastname = Lastname FROM INSERTED;

SELECT * FROM Actor WHERE @Firstname = Firstname AND @Lastname = Lastname

IF @@ROWCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
END
END

The thing is that when I made a same example of the select that its in the trigger, works fine. Return no rows.
DECLARE @Firstname varchar(25)
DECLARE @Lastname varchar(25)
SET @Firstname = 'Johnny'
SET @Lastname = 'Depp'
SELECT * FROM Actor WHERE @Firstname = Firstname AND @Lastname = Lastname

What am I doing wrong?

A: Not trying to help you with the trigger because i don't think is your best option.
Why not create a unique constraint on those 2 fields?
ALTER TABLE dbo.Actor ADD CONSTRAINT UQ_ACTOR_NAME UNIQUE (firstname,lastname)

A: I think your trigger always fires because, since you've inserted, you're always going to get a @@rowcount of at least 1.  Try setting it to > 1 and see.

A: While I agree with @mxix and @Vinnie that you should probably use a unique constraint for this purpose, another option is to use an INSTEAD OF trigger.  As others have mentioned, your issue right now is that the data has already been inserted so your search is always finding a match, namely the row that was just inserted.  You can use the INSTEAD OF trigger to search for the values about to be inserted, and decide if you want to insert them or not.
Note that if you go this route, you are responsible for inserting into the table if you deem the data should indeed be inserted. See this answer for some more discussion on emulating a before insert trigger.
Also, as @Sean and @marc_s mentioned, your trigger does not correctly handle multiple rows being inserted in one statement.


text:
Q: Laravel asset() method not working if I installed in sub-directory instead of absolute url
This is not finding the assets from the public directory.
I installed laravel in subdirectory like:
http://localhost/yourproject
how can I fix this?

A: Adding ASSET_URL=public to .env file helped me.

A: This work for me:
.env
ASSET_URL=http://localhost/yourproject

A: The asset() helper uses the app url.  This is defined in .env.
APP_URL=http://localhost/yourproject


text:
Q: Volume inside $x^4+y^4+z^4=1$. Let's say I'm trying to find the volume inside $x^4+y^4+z^4=1$. Can I go about defining new variables $X=x^2,Y=y^2,Z=z^2$ so that we know have a unit sphere in $X,Y,Z$. Then computing the Jacobian of this inverse transformation to be $(2x)(2y)(2z)=8xyz$. So that the Jacobian corresponding to this transformation is $\frac{1}{8xyz}$ and then I need to compute:
$$\int_{0}^{2\pi} \int_{0}^{\pi} \int_{0}^{1} \frac{1}{|8\rho^3 \sin (\phi)^2 \cos(\theta) \sin(\theta) \cos (\phi)|} \rho^2 \sin(\phi)\ \mathrm d\rho\ \mathrm d\phi\ \mathrm d\theta$$
Would that work?


text:
Q: Prove any positive integer can be expressed as a combination of distinct powers of $\pm4^n$ and $\pm3^{2m-1}$ Prove that any positive integer can be expressed as a combination of distinct powers of $\pm4^n$ and $\pm3^{2m+1}$(where m,n are integers).
Like $33=4^3-4^0-3^3-3^1$


text:
Q: Certificate verify failed python urlopen windows computer Just downloaded anaconda (python 3.6) to a windows computer- now I am having trouble running some old code to scrape a website.
    import urllib.request
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    from bs4 import BeautifulSoup
    f = urllib.request.urlopen(url)
    print(f.read(300))
    soup = BeautifulSoup(f, 'lxml')

When I run this with url = 'http://fivethirtyeight.com/' everything works. When I run it with url = 'https://www.wunderground.com' or 'https://weather.com' I get this error:
    "URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)>"

On other stackoverflow questions for this issue on OSX systems they say to run "/Applications/Python\ 3.6/Install\ Certificates.command". I am on a windows computer though, and it works for some websites, so I am not sure if this applies- if it does please give me explicit instructions on where/how to run that command - thanks!


text:
Q: what can i do to make my add to cart button work? Please help me out, i'm working on an e-commerce site, I added a category page, on the index page the add to cart works but when I select a particular category, and I try to add any of the product, it doesn't add to the cart and it goes back to the index page, and untick the category, maybe someone can assist me here is my code below:
I have three files,
this is my index codes
index.php:

Products

`enter code here`

    enter code here

All Categories

Select Category

                <?php
                    $sql = "SELECT DISTINCT product_cat FROM products ORDER BY product_cat";
                    $result = $conn->query($sql);
                    while ($row=$result->fetch_assoc()){
                ?>

                            <input type="checkbox" class="form-check-input product_check" value="<?= $row['product_cat']; ?>" id="product_cat"><?= $row['product_cat']; ?>

            <?php } ?>

All Products

                <?php

                    include 'config.php';
                    $sql="SELECT * FROM products";
                    $result = $conn->query($sql);
                    while($row = $result->fetch_assoc()):
                ?>

                    <img src="../admin/product-images/<?= $row['product_image']; ?>" class="card-img-top" height="250">

<?= $row['product_name'] ?>

₦ <?= number_format($row['product_price'],2) ?>/-

                        <form action="" class="form-submit">

                            <input type="hidden" class="pid" value="<?= $row['id'] ?>">

                            <input type="hidden" class="pname" value="<?= $row['product_name'] ?>">

                            <input type="hidden" class="pprice" value="<?= $row['product_price'] ?>">

                            <input type="hidden" class="pimage" value="<?= $row['product_image'] ?>">

                            <input type="hidden" class="pcode" value="<?= $row['product_code'] ?>">

                            <button class="btn btn-success btn-block addItemBtn">  Add to Cart</button>

                            <button class="btn btn-info btn-block viewItemBtn">  View Details</button>

                        </form>

    <?php endwhile; ?>

this is my action codes
action.php:
<?php
//db connection
require 'config.php';

//display products and category products
if (isset($_POST['action'])) {
    $sql = "SELECT * FROM products WHERE product_cat !=''";

    if (isset($_POST['product_cat'])) {
        $product_cat = implode("','", $_POST['product_cat']);
        $sql .="AND product_cat IN('".$product_cat."')";
    }

    $result = $conn->query($sql);
    $output='';

    if($result->num_rows>0){
        while ($row=$result->fetch_assoc()){
            $output .= '

'.$row['product_name'].'

₦ '.number_format($row['product_price'],2).'/-

                        <form action="" class="form-submit">

                            <input type="hidden" class="pid" value="'.$row['id'].'">

                            <input type="hidden" class="pname" value="'.$row['product_name'].'">

                            <input type="hidden" class="pprice" value="'.$row['product_price'].'">

                            <input type="hidden" class="pimage" value="'.$row['product_image'].'">

                            <input type="hidden" class="pcode" value="'.$row['product_code'].'">

                            <button class="btn btn-success btn-block addItemBtn">  Add to Cart</button>

                            <button class="btn btn-info btn-block viewItemBtn">  View Details</button>

                        </form>

';
        }
    }
    else{
        $output = "
No Products Found!
";
    }
    echo $output;

    }

//add to cart codes
    if(isset($_POST['pid'])){
    $pid = $_POST['pid'];
    $pname = $_POST['pname'];
    $pprice = $_POST['pprice'];
    $pimage = $_POST['pimage'];
    $pcode = $_POST['pcode'];
    $pqty = 1;

    $stmt = $conn->prepare("SELECT product_code FROM cart WHERE product_code=?");
    $stmt->bind_param("s",$pcode);
    $stmt->execute();
    $res = $stmt->get_result();
    $r = $res->fetch_assoc();
    $code = $r['product_code'];

    if(!$code){
        $query = $conn->prepare("INSERT INTO cart (product_name,product_price,product_image,qty,total_price,product_code) VALUES (?,?,?,?,?,?)");
        $query->bind_param("sssiss",$pname,$pprice,$pimage,$pqty,$pprice,$pcode);
        $query->execute();

        echo '

        <button type="button" class="close" data-dismiss="alert">×</button>
        Item added to your cart!

';
    }
    else{
        echo '

        <button type="button" class="close" data-dismiss="alert">×</button>
        Item already added to your cart!

';
    }
}

?>

thank you


text:
Q: Difficult Integral $\int_0^{1/\sqrt{2}}\frac{\arcsin({x^2})}{\sqrt{1+x^2}(1+2x^2)}dx=$ I have a difficult integral to compute.I know the result, but need to know the method of calculation.
How prove this result? $$\int_0^{1/\sqrt{2}}\frac{\arcsin({x^2})}{\sqrt{1+x^2}(1+2x^2)}dx=\frac{\pi^2}{144}$$

A: Set $\displaystyle\,\, \cos \theta=\frac{1}{2x^2+1}.$
Then the intagral transforms into $$\frac12\int_0^{\large\frac{\pi}{3}} \sin^{-1}\left(\frac{1-\cos\theta}{2\cos\theta}\right)d\theta.$$
This type of integral is called a Coxeter integral. The user @Sangchul Lee (formerly, sos440) managed to obtain a closed-form formula for a certain family of these Coxeter integrals, by generalizing Ahmed's integral.
Here you can find his general approach, and in his paper "Coxeter's Integrals" ("Abstract. In this paper, we generalize the Ahmed's integral and exhibit some identities
involved in it.") you can found explicit computations.
Specifically, he proves there that $$I_6\equiv\int_0^{\large\frac{\pi}{3}} \cos^{-1}\left(\frac{1-\cos\theta}{2\cos\theta}\right)d\theta=\frac{11\pi^2}{72},$$
which, by recalling that whenever $x \in [0,1]:$ $\,\,\cos^{-1} x+\sin^{-1} x=\frac{\pi}{2} , \,\,\,$ gives the desired closed form of your integral.

A: $\displaystyle J=\int_0^{\tfrac{1}{\sqrt{2}}}\dfrac{\arcsin (x^2)}{\sqrt{1+x^2}
(1+2x^2)}dx$
Perform change of variable $y=x^2$, one obtains:
$\displaystyle J=\int_0^{\tfrac{1}{2}}\dfrac{\arcsin x}{2\sqrt{x(1+x)}(1+2x)}dx$
$\displaystyle J=\left[\arcsin(x)\arctan\left(\sqrt{\dfrac{x}{1+x}}\right)\right]_0^{\frac{1}{2}}-\int_0^{\tfrac{1}{2}}\dfrac{\arctan\left(\sqrt{\dfrac{x}{1+x}}\right)}{\sqrt{1-x^2}}dx$
$\displaystyle J=\dfrac{\pi^2}{36}-\int_0^{\tfrac{1}{2}}\dfrac{\arctan\left(\sqrt{\dfrac{x}{1+x}}\right)}{\sqrt{1-x^2}}dx$
Define on $[0,1]$, $\displaystyle F(a)=\int_0^{\tfrac{1}{2}}\dfrac{\arctan\left(a\sqrt{\dfrac{x}{1+x}}\right)}{\sqrt{1-x^2}}dx$
For all $a$ in $[0,1]$, $\displaystyle F'(a)=\int_0^{\tfrac{1}{2}}\dfrac{x}{\sqrt{x(1-x)}(a^2x+x+1)}dx$
For all $a$ in $[0,1]$, $F'(a)=2\left[\dfrac{\sqrt{2+a^2}\arctan\left(\dfrac{\sqrt{x}}{\sqrt{1-x}}\right)-\arctan\left(\dfrac{\sqrt{2+a^2}\sqrt{x}}{\sqrt{1-x}}\right)}{(1+a^2)\sqrt{2+a^2}}\right]_0^{\tfrac{1}{2}}$
For all $a$ in $[0,1]$, $F'(a)=\dfrac{\pi}{2}\dfrac{1}{1+a^2}-\dfrac{2\arctan\left(\sqrt{2+a^2}\right)}{(1+a^2)\sqrt{2+a^2}}$
Therefore,
$\displaystyle \int_0^{\tfrac{1}{2}}\dfrac{\arctan\left(\sqrt{\dfrac{x}{1+x}}\right)}{\sqrt{1-x^2}}dx=\int_0^1 F'(a)da=\dfrac{\pi}{2}\int_0^1\dfrac{1}{1+a^2}da-2\int_0^1\dfrac{\arctan\left(\sqrt{2+a^2}\right)}{(1+a^2)\sqrt{2+a^2}}da$
Therefore,
$\displaystyle J=\dfrac{\pi^2}{36}-\dfrac{\pi^2}{8}+2\int_0^1\dfrac{\arctan\left(\sqrt{2+a^2}\right)}{(1+a^2)\sqrt{2+a^2}}da$
The last integral is the Ahmed's integral (see How to evaluate Ahmed's integral? )
Finally,
$J=\dfrac{\pi^2}{36}-\dfrac{\pi^2}{8}+2\times \dfrac{5\pi^2}{96}=\dfrac{\pi^2}{144}$


text:
Q: Show random WooCommerce products from other categories as related products if only one product in a category By default WooCommerce adds below a single product details page related products that have the same categories and/or tags.
These products are not controlled by the shop manager – WooCommerce automatically lists random related products in this area. If there is only one product in a category nothing shows up.
Any idea how to modify the arguments array of the woocommerce_output_related_products to check if there is only one product in the current category and then show products from other categories as "related" ones?
Sample code to modify the arguments below:
function woocommerce_output_related_products(){
        $args = array(
            'posts_per_page' => 3,
            'columns' => 3,
            'orderby' => 'rand'
     );
        woocommerce_related_products( apply_filters( 'woocommerce_output_related_products_args', $args ) );
}

A: You won't be able to change this via the $args, but you can via the woocommerce_related_products hook.
It comes down to if an empty array would be displayed (so no result) we will fill the empty array with the results we chose.
Initially we obtain all categoryIDs and based on that all productIDs (except the exluded productIDs) that belong to the categoryIDs.
Then we return the number of desired results via $show_products
So you get:
function filter_woocommerce_related_products( $related_posts, $product_id, $args ) {
    // Show products
    $show_products = 4;

    // Initialize
    $taxonomy = 'product_cat';

    // When empty
    if ( empty( $related_posts ) ) {
        // Get WooCommerce product categories WP_Term objects
        $product_cats_ids = get_terms( array(
            'taxonomy'  => $taxonomy,
            'fields'    => 'ids',
        ) );

        // Get product id(s) from a certain category, by category-id
        $product_ids_from_cats_ids = get_posts( array(
            'post_type'   => 'product',
            'numberposts' => $show_products + count( $args['excluded_ids'] ),
            'post_status' => 'publish',
            'fields'      => 'ids',
            'tax_query'   => array(
                array(
                    'taxonomy' => $taxonomy,
                    'field'    => 'id',
                    'terms'    => $product_cats_ids,
                    'operator' => 'IN',
                )
            ),
            'orderby'     => 'rand',
            'exclude'     => $args['excluded_ids'],
        ));

        // Extract a slice of the array
        $related_posts = array_slice( $product_ids_from_cats_ids, 0, $show_products );
    }

    // Return
    return $related_posts;
}
add_filter( 'woocommerce_related_products', 'filter_woocommerce_related_products', 10, 3 );

Related/based on: Show cross-sells before same category on related products in WooCommerce


text:
Q: how can I see or get data from bucket in HashMap? I want to clarify for myself how HashMap works. I created a Person object with an invalid hash code.
So I created a HashMap<Person, Integer> and put in some data.
I want to see how my nodes lie in the same bucket.
How can I see it? Where can I do it?
HashMap<Person, Integer> hm = new HashMap<>();
        Person a = new Person(1);
        Person b = new Person(1);
        Person c = new Person(2);

        hm.put(a, 20);
        hm.put(b, 20);
        hm.put(c, 100);
        hm.put(b, 15);

I have read this https://stackoverflow.com/questions/28346818/how-to-get-all-element-of-a-bucket-in-hashmap but there is only information that I can see this with a debugger but I have not found a method or way how I can do this


text:
Q: rCharts hPlot groups order I've created a stacked area plot with hPlot from rCharts package. Code:
set.seed(123)
x <- data.frame(x = rep(c(1:5),3), value = rnorm(15, mean = 10)
                , group = rep(LETTERS[1:3],5))
x

library(rCharts)

a <- hPlot(x = "x", y = "value", group = 'group',
           data = x[order(x$group, decreasing = T),], type = 'area')
a$plotOptions(area = list(stacking = "normal"))
a

Now I am trying to change the order of the groups to appear but in every case it is the same order (A, B, C).
For example, I would like to get the order (C, B, A), so that the area of C appear on top of the plot. But the objective is the possibility to create a personalized order like (A,C,B).
How could I achieve it? Appreciate any help
possible solution: I've found out that the order is alphabetical, so adding a prefix to a variables will put them in order I want, i.e. a_A, b_C, c_B.

A: Add a$yAxis(reversedStacks = FALSE) to it. Please note that I used the same data to show that it works when comparing the two (as highlighted by the top point point - mouse hover).
Without the reversedStacks
rm(list = ls())
library(rCharts)
set.seed(123)
x <- data.frame(x = rep(c(1:5),3), value = rnorm(15, mean = 10), group = rep(LETTERS[1:3],5))
x <- x[order(x$group, decreasing = T),]
a <- hPlot(x = "x", y = "value", group = 'group', data = x, type = 'area')
a$plotOptions(area = list(stacking = "normal"))
#a$yAxis(reversedStacks = FALSE)
a

With the reversedStacks
a <- hPlot(x = "x", y = "value", group = 'group', data = x, type = 'area')
a$plotOptions(area = list(stacking = "normal"))
a$yAxis(reversedStacks = FALSE)
a


text:
Q: Insert into a table select * from another computer table I have two computers in local network i want to insert from one table From PC(A) to other table PC(B)here is an example:
SqlConnection con = new SqlConnection(@"Data Source=(local);Initial Catalog=Db;User ID=sa;password=xxxxx");
SqlConnection conn = new SqlConnection(@"Data Source=(local);Initial Catalog=Db;User ID=sa;password=xxxxx");

SqlCommand cmd8 = new SqlCommand("insert into [192.168.1.11].Db.dbo.MArket select * from MARKET", conn);//second market is been exist in my local database,too
                cmd8.ExecuteNonQuery();


text:
Q: Improving a longtable - Underfull \vbox and Overfull \hbox I made a table using longtable and multicolumn packages. My idea is to spread the table to \textwidth , use n number of columns with the same width and use chunk of the \textwidth for each row.
tabularx is not an option because it produces error when using \kill. More info if someone is interested enter link description here
Longtabu is also not an option because is no longer maintained.
What I am missing in the calculations for columns width ?
Is there a better way to do this report (with the same layout output) ?
Any help is welcomed :)
MWE
\documentclass[paper=a4,fontsize=18pt]{article}

   \usepackage{geometry}
    \geometry{
    % verbose,
    portrait,       % page orientation (landscape or portrait)
    a4paper,        % paper size
    tmargin=5mm,    % page top margin
    bmargin=5mm,    % page bottom margin
    lmargin=5mm,   % page left margin
    rmargin=5mm % page right maring
}

\usepackage[utf8]{inputenc}
\usepackage[defaultsans]{opensans} %font
\usepackage[T1, T2A]{fontenc}
\usepackage[english,bulgarian]{babel}
\usepackage{fancyhdr}
\usepackage{multicol}
\usepackage{longtable}
\usepackage{colortbl}
\usepackage{xcolor}
\usepackage{layouts}

\renewcommand{\familydefault}{\sfdefault}

\definecolor{greyCell}{RGB}{235,235,235}
\newcommand{\smf}{ % small font
    \fontsize{9}{11}\selectfont
}
\begin{document}

\def\arraystretch{1}%  vertical padding
\setlength{\tabcolsep}{0.8mm} % for the horizontal padding
\fontsize{10}{13}\selectfont

           \vspace{-4mm}
            \noindent

      \LTleft=0pt
      \LTright=0pt
    \begin{longtable}{@{\extracolsep{\fill}}*{20}{p{0.5\textwidth}} @{}}
    \hline
    \multicolumn{20}{|p{\dimexpr 1\textwidth-2\tabcolsep}|}{ \centering \textbf{ Платежна бележка } }\\ % header
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf Период } & % ---------------- row 1
    \multicolumn{2}{p{\dimexpr 0.1\textwidth-2\tabcolsep}}{  } &
    \multicolumn{6}{p{\dimexpr 0.3\textwidth-2\tabcolsep}}{ \smf 2020.07 } &
    \multicolumn{3}{p{\dimexpr 0.15\textwidth-2\tabcolsep}}{ \smf Календар } &
    \multicolumn{7}{p{\dimexpr 0.35\textwidth-2\tabcolsep}|}{ \smf 5 Пет дневна работна седмица } \\
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf За лице } & % ---------------- row 2
    \multicolumn{2}{p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf\raggedleft\arraybackslash 146 } &
    \multicolumn{6}{p{\dimexpr 0.3\textwidth-2\tabcolsep}}{ \smf Атанас Антонов Атанасов } &
    \multicolumn{3}{p{\dimexpr 0.15\textwidth-2\tabcolsep}}{ \smf Работни дни } &
    \multicolumn{7}{p{\dimexpr 0.35\textwidth-2\tabcolsep}|}{ \smf 23 } \\
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf Заето в } & % ---------------- row 3
    \multicolumn{2}{p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf\raggedleft\arraybackslash 12 } &
    \multicolumn{6}{p{\dimexpr 0.3\textwidth-2\tabcolsep}}{ \smf Поддръжка } &
    \multicolumn{3}{p{\dimexpr 0.15\textwidth-2\tabcolsep}}{ \smf Трудов стаж } &
    \multicolumn{7}{p{\dimexpr 0.35\textwidth-2\tabcolsep}|}{ \smf 24г. 1м. 4д. към 01.07.2020 } \\
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf Длъжност } & % ---------------- row 4
    \multicolumn{2}{p{\dimexpr 0.1\textwidth-2\tabcolsep}}{ \smf\raggedleft\arraybackslash 24236003 } &
    \multicolumn{6}{p{\dimexpr 0.3\textwidth-2\tabcolsep}}{ \smf Експерт, организация на труда } &
    \multicolumn{3}{p{\dimexpr 0.15\textwidth-2\tabcolsep}}{ \smf Осн. заплата } &
    \multicolumn{7}{p{\dimexpr 0.35\textwidth-2\tabcolsep}|}{ \smf 1,000.00 } \\ \hline
    \multicolumn{10}{|p{\dimexpr 0.5\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \centering \cellcolor{greyCell} \textbf{ Начисления } } &
    \multicolumn{10}{p{\dimexpr 0.5\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \centering \cellcolor{greyCell} \textbf{ Удръжки } } \\ \hline
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{шифър} } &
    \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{Наименование} } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{Сума} } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{д\%} } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{шифър} } &
    \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{Наименование} } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \centering \textit{Сума} } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \centering \textit{д\%} } \\ \hline
                                  \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright От 01.07.2020 г. ОМВ } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 1,000.00 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 0 } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 455 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Разпл. сметка Уникредит } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 777.20 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 0 } \\ \hline
                                           \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 104 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Заплата по щат } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 1,000.00 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 23 } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 485 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Разпл. сметка FiBank } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 75.00 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 0 } \\ \hline
                                           \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 111 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Допл.проф.опит и стаж } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 144.00 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 14.4 } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 490 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Банков заем } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 0.00 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 0 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 500 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Данък общ доход } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 98.63 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 10 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 501 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright ЛОВ ф.\textquotedbl{}Безработица\textquotedbl{} } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 4.58 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 0.4 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 533 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright ЛОВ ф.\textquotedbl{}Пенсии\textquotedbl{} } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 75.28 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 6.58 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 536 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright ЛОВ ф.\textquotedbl{}ОЗМ\textquotedbl{} } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 16.02 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 1.4 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 537 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright ЛОВ ф.\textquotedbl{}ДЗПО УПФ\textquotedbl{} } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 25.17 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 2.2 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 540 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Здравно осигуряване } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 36.61 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 3.2 } \\ \hline
                                       \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{  } &
                        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 560 } &
        \multicolumn{5}{|p{\dimexpr 0.25\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedright Членски внос Подкрепа } &
        \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 35.50 } &
        \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{ \smf \raggedleft 0 } \\ \hline

    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  \raggedright Всичко начисления } & % row 1 bottom
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 1,144.00 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  Всичко удръжки } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft  1,144.00 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{   }  \\  \hline
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  \raggedright Осигурителен доход } & % row 2 bottom
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 1,144.00 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  Всичко за осигуреното лице } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft  157.66 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{   }  \\  \hline
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  \raggedright Облагаем доход } & % row 3 bottom
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 1,144.00 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  Всичко за осигурителя } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft  224.44 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{   }  \\  \hline
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  \raggedright Данъчна основа } & % row 4 bottom
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft 986.34 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}}{ } &
    \multicolumn{7}{|p{\dimexpr 0.35\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf  Сума за получаване } &
    \multicolumn{2}{|p{\dimexpr 0.1\textwidth-2\tabcolsep-1\arrayrulewidth}}{ \smf \raggedleft  887.71 } &
    \multicolumn{1}{|p{\dimexpr 0.05\textwidth-2\tabcolsep-1\arrayrulewidth}|}{   }  \\  \hline
    \end{longtable}
\end{document}

Result

As David Carlisle said, this approach is overcomplicated. The table actually contains 8 columns (not 20) so I post this MWE provided by him.
\documentclass{article}

\usepackage{geometry}
\geometry{
    % verbose,
    portrait,       % page orientation (landscape or portrait)
    a4paper,        % paper size
    tmargin=5mm,    % page top margin
    bmargin=5mm,    % page bottom margin
    lmargin=5mm,   % page left margin
    rmargin=5mm % page right maring
}

% only needed with old latex installations
  \usepackage[utf8]{inputenc}
    \usepackage[defaultsans]{opensans} %font
    \usepackage[T1, T2A]{fontenc}
    \usepackage{colortbl}
    \usepackage{longtable}

\definecolor{greyCell}{RGB}{235,235,235}

\begin{document}

\setlength{\tabcolsep}{0.8mm} % for the horizontal padding
\fontsize{10}{13}\selectfont

\setlength\extrarowheight{2pt}% keep hline away from text
\small
\LTleft=0pt
\LTright=0pt
        \begin{longtable}{@{\extracolsep{\fill}}|*{8}{l|}@{}}
        \hline
        \multicolumn{8}{|c|}{\textbf{Header}}\\
        \multicolumn{4}{|l}{%
\begin{tabular}{lrl}
Label& &  2020.07\\
Label& 146 &long variable test\\
Label & 12 & variable variable variable\\
label  & 24568545 & long variable here
\end{tabular}}
&
        \multicolumn{4}{l|}{%
\begin{tabular}{ll}
Label &  long variable \\
Label & 23\\
Label& Long variable long variable  \\
Label & 1,000.12
\end{tabular}}
\\
\rowcolor{greyCell}
\multicolumn{4}{@{}|>{\columncolor{greyCell}[.8mm][2cm]}c@{}}{Label}&\multicolumn{4}{@{}c|@{}}{Label}\\
label&label&label&d\%&label&label&label&d\%\\\hline
104& long variable& 1,000.00&14.4&455&long variable&777.20&0,4\\\hline
111 & long label & 144& 14.4 & 490 & long label & 0.00 & 0\\\hline
&&&&500 &long label &98.63&10\\\hline
\multicolumn{2}{|l|}{long label}&1,44.00 &&\multicolumn{2}{|l|}{long label}&1,44.00& \\\hline
\multicolumn{2}{|l|}{long label}&1,44.00 &&\multicolumn{2}{|l|}{long label}&157.66 &\\\hline
\end{longtable}
\end{document}

Why column 5 text is pushed so far away ?
Why the inner tables (under header) don't spread for the full width of the multicolumn ?

A: Hm, I would design your table as follows:

*

*consider most of comments below your question i.e. your second MWE

*for table I would use xltabular

*in columns with numbers I would use S column type

*form the most used multicolumn cells I would define new commands \mcl and \mcll

*in editor remove group separators for thousand (their inserting left to siunitx)

\documentclass{article}
\usepackage{geometry}
\geometry{
    a4paper,    % paper size
    margin=20mm % all margins are equal
        }
%\usepackage[utf8]{inputenc}   % only needed with old latex installations
%\usepackage[defaultsans]{opensans} %font
\usepackage[T1, T2A]{fontenc}
\usepackage{longtable, xltabular}
\NewExpandableDocumentCommand\mcll{m}{\multicolumn{2}{|l|}{#1}}
\NewExpandableDocumentCommand\mcl{ m}{\multicolumn{2}{ l|}{#1}}

\usepackage[table]{xcolor}
\definecolor{greyCell}{RGB}{235,235,235}
\usepackage{siunitx}

\begin{document}

\begingroup
\sisetup{group-minimum-digits=4,
         group-separator={,}}
\setlength\extrarowheight{2pt}% keep hline away from text
\small
    \begin{xltabular}{\linewidth}{ *{2}{|S[table-format=3]
                                        |X
                                        |S[table-format=4.2]
                                        |S[table-format=2.1]}|
                                }
    \hline
\multicolumn{8}{|c|}{\textbf{Header}}   \\
\multicolumn{4}{|l}{
    \begin{tabular}{@{}lrl}
    Label   &           & 2020.07                   \\
    Label   & 146       & long variable test        \\
    Label   & 12        & variable variable variable\\
    Label   & 24568545  & long variable here
    \end{tabular}}
    &   \multicolumn{4}{l|}{
        \begin{tabular}{@{} ll}
        Label   &  long variable                \\
        Label   & 23                            \\
        Label   & Long variable long variable   \\
        Label   & 1,000.12
        \end{tabular}}          \\
    \hline
    \rowcolor{greyCell}
\multicolumn{4}{|c|}{\textbf{Label}}   & \multicolumn{4}{c|}{\textbf{Label}}\\  \hline
{label} & label         & {label}   & {d\%} & {label} & label         & {label} & {d\%} \\  \hline
104     & long variable & 1 000.00  & 14.4  & 455     & long variable & 777.20  & 0,4   \\  \hline
111     & long label    &   144.00  & 14.4  & 490     & long label    & 0.00    & 0     \\  \hline
        &               &           &       & 500     & long label    & 98.63   & 10    \\  \hline
\mcll{long label}        &   144.00  &       & \mcl{long label}
                                                      & 1 144.00      &   \\  \hline
\mcll{long label}        &   144.00  &       & \mcl{long label}
                                                      &   157.66      &   \\  \hline
    \end{xltabular}
\endgroup
\end{document}


text:
Q: Cannot connect with cassandra node.js The developers probably do not understand my problem...which lies in the fact that it throws me an error in the file node.js shows that the object is not a function and I do not know how else to set up a javascript file was correct. The error is shown on the 490: 3. What do I have to add javascript file that did not exist error. Please honest answer because I am eager to turn on SSL

var cassandra = require('cassandra-driver');
var fs = require('fs');
var assert = require('assert')
 var sslOptions = {
 key : fs.readFileSync('client-key.pem'),
 cert : fs.readFileSync('client-cert.pem'),
 ca : [fs.readFileSync('server.pem')]
};
var client = new cassandra.Client({
  contactPoints : ['127.0.0.1'],
  authProvider : new cassandra.auth.PlainTextAuthProvider('cassandra', 'cassandra'),
  sslOptions : sslOptions
 });

client.connect(function (err) {
 assert.ifError(err);
})


text:
Q: Internet Explorer not rendering html returned from JQuery ajax post I have a page with an input box whose onkeyup fires a JQuery ajax post based on what was typed (a search field)
The ajax call's posted back html is supposed to populate another div on the page.
Here is the jquery ajax post:
var o = $(me.results).empty().addClass("aj3load");

$.ajax({
  type: "POST",
  dataType: "text",
  url: me.url,
  data: "cmd="+escape(me.cmd)+"&q="+q+"&"+me.args,
  cache: false,
  complete: function() {
    $(o).removeClass("aj3load");
    me.ls = q;
  },
  success: function(msg){
    $(ajax3.results)
      .html(msg)
      .find("div")
      .click(function(){
        var crs_id = $(this).find(":hidden").val();
        $(ajax3.field).val($(this).text());
        $(ajax3.vf).val(crs_id);
        $(ajax3.results).empty().slideUp("fast");
        ajax3.ls = $(this).text();
        getEventInfo();
      });
  }
});

Here is the response from the ajax call when searching for "eve" (per Fiddler):
HTTP/1.1 200 OK
Cache-Control: private
Date: Thu, 03 Dec 2009 16:16:05 GMT
Content-Type: text/html
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Vary: Accept-Encoding
Content-Length: 882

<input type="hidden" value="1000806" />111_Demo_Event_090924

<input type="hidden" value="1000811" />123 Test Event oct 12 2009

<input type="hidden" value="1000805" />AAA_Demo_Event

<input type="hidden" value="1000103" />Developing Algebraic Thinking in Grades 3-5 - 30hr

<input type="hidden" value="1000086" />Developing Algebraic Thinking in Grades K-2 - 30hr

<input type="hidden" value="1000144" />Facilitating Oral Language Development (Grades PreK-3) - 30hr

<input type="hidden" value="1000613" />Free PBS TeacherLine Event

<input type="hidden" value="1000088" />Math in Everyday Life for Grades 6-8 - 15hr

<input type="hidden" value="1000087" />Math in Everyday Life for Grades K-5 - 15hr

<input type="hidden" value="1000163" />Using Multimedia to Develop Understanding - 30hr

Now in firefox and chrome all those divs show up fine and dandy but in IE only the first div is displayed in the container div on the page.
Any idea what is going wrong with IE here?
UPDATE:
If I put in an alert("hello world"); after I assign the $(ajax3.results).html(msg)... call IE will render the ajax posts response correctly. This isn't a solution just possibly some help in debugging. I don't want to have an alert box mid processing. Also I've identified that this problem doesn't seem to affect IE 8, only earlier versions.
Thanks

A: Your input tags are not closed.  This may be causing some weirdness in IE.

A: Ajax requests are cached by IE. Using your $.ajax disable caching. This may just be possibly another reason of the issue.

A: It's a long shot, but what are the styles on ajax3.results? Is it possible it has a fixed height with overflow:hidden? Or you could be hitting a rendering bug...do the other fields show up if you resize the browser (to trigger redraw) after the call?

A: One thing I would do is not use divs. A more appropriate element would be p. An ol would be even better.
Give this a shot.
index.html:
<!doctype html>

    <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
    <title>IE Ajax Test<title>

This is a paragraph.

This paragraph will be replaced.

<input type="button" value="Do it!" onclick="doit();" />

php.php:
<?php
print("
text

text2

text3
");
?>

A: Check your dataType parameter in your request.  You're expecting html, back, right?  Try changing that to "html".

A: You said:

call back is: function(msg){
  $("mydiv").html(msg); } – Ryan

Are you missing the # sign in front of mydiv?  Also try </input> to see if it behaves any different than <input />.

A: I had this bug too using .html() after an ajax query. Could not get it too work in IE6 nor 7 for love nor money, so I just reverted to .innerHTML. Works fine now.

A: I am too facing this weird bug. It got fixed once I changed the doctype to transitional from strict and added
  to the beggining of every ajax response.
On another occasion I realized that IE simply refused to accept  tag in the ajax response. Whenever it use to find it, it stripped off my all the tags in the response leaving only skeletal text
Death to IE.

A: I was having the issue with the missing modals on my JS created modals on my Rails app.
The only thing that worked for me was removing any fading effect, since the response body was correct. (https://github.com/twbs/bootstrap/issues/3672)
In my rails app (haml+booststrap), I replace of the div's identifier:
"#modal-window.modal.hide.fade"
per
"#modal-window.modal.hide"
It doesn't not break Chrome, Firefox, Safari and worked on Internet Explorer.


text:
Q: Non-Nil User Crashing When Unwrapped - Firebase, SwiftUI Unwrapping values the conventional way in SwiftUI views is not allowed, but you can do so within the body of, say, an HStack or a VStack. Below I am trying to unwrap a user I was certain was not nil. My LoginView lets a user create an account on Firebase Firestore, logs you in if a user enters the correct values, and shows an alert view if not.
In my HomeView.swift, the first screen after launch, I crash when trying to present the user image. However, when I unwrap the user, the user is still nil in the console. I think this is because Firebase doesn't have time to load the image before the view initializes. But I could be wrong. Help.

struct HomeProfileView: View {
    @EnvironmentObject var session: SessionStore
    @State var showDashboard = false
    var user: User?

    var body: some View {
        if user != nil {
            URLImage(URL(string: user!.profileImageUrl)!, content: {
                $0.image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .clipShape(Circle())
            })
            .frame(width: 50, height: 50)
            .background(Color(#colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)))
            .clipShape(Circle())
            .shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
            .shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
            .sheet(isPresented: $showDashboard) {
                DashboardView(showDashboard: $showDashboard)
            }
        }
    }
}

I don't think I need an optional user, here, but I do not know how to safely unwrap the user otherwise. Another version is using the session EnvironmentObject to access the currently logged user.

struct HomeProfileView: View {
    @EnvironmentObject var session: SessionStore
    @State var showDashboard = false

    var body: some View {
        if session.isLoggedIn {
            URLImage(URL(string: session.userSession!.profileImageUrl)!, content: {
                $0.image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .clipShape(Circle())
            })
            .frame(width: 50, height: 50)
            .background(Color(#colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)))
            .clipShape(Circle())
            .shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
            .shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
            .sheet(isPresented: $showDashboard) {
                DashboardView(showDashboard: $showDashboard)
            }
        }
    }
}

The session property belongs to a SessionStore class and is essentially an optional User.

import Foundation
import Combine
import Firebase

class SessionStore: ObservableObject {

    @Published var isLoggedIn: Bool = UserDefaults.standard.bool(forKey: "isLoggedIn") {
        didSet {
            UserDefaults.standard.set(self.isLoggedIn, forKey: "isLoggedIn")
        }
    }

    var userSession: User?

    var handle: AuthStateDidChangeListenerHandle?

    func listenAuthenticationState() {
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            if let user = user {
                print(user.email as Any)
                let firestoreUserId = Ref.FIRESTORE_DOCUMENT_USERID(userId: user.uid)
                firestoreUserId.getDocument { (document, error) in
                    if let dict = document?.data() {
                        guard let decodeUser = try? User.init(fromDictionary: dict) else { return }
                        self.userSession = decodeUser
                    }
                }
                self.isLoggedIn = true
            } else {
                print("User is Logged Out")
                self.isLoggedIn = false
                self.userSession = nil
            }
        })
    }
}

The logged in user is indeed logged in but I cannot access any properties.

A: Set isLoggedIn exactly at the place you set userSession, because it is done in async callback, and do this on main queue (to update UI properly)
firestoreUserId.getDocument { (document, error) in
    if let dict = document?.data() {
        guard let decodeUser = try? User.init(fromDictionary: dict) else { return }
        DispatchQueue.main.async {
           self.userSession = decodeUser
           self.isLoggedIn = true
        }
    }
}

A: I have this working. Not sure how scalable it is but I am doing a not equals nil. I also put it in a button to toggle it versus an onTapGesture.

struct HomeProfileView: View {
    @EnvironmentObject var session: SessionStore
    @State var showDashboard = false

    var body: some View {
        if session.isLoggedIn {
            if (session.userSession?.profileImageUrl) != nil {
                Button(action: { self.showDashboard.toggle() } ) {
                    URLImage(URL(string: session.userSession!.profileImageUrl)!, content: {
                        $0.image
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .clipShape(Circle())
                    })
                    .frame(width: 50, height: 50)
                    .background(Color(#colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)))
                    .clipShape(Circle())
                    .shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
                    .shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
                    .sheet(isPresented: $showDashboard) {
                        DashboardView(showDashboard: $showDashboard)
                    }
                }
            }
        }
    }
}


text:
Q: SQL Server User create script Password description Below is my create script of user
CREATE LOGIN [sa] WITH PASSWORD=N'ô/PDM643¸}''8%õ''f;âw¡ÈS'

Can you tell me this password please?

A: I would say its [ ô/PDM643¸}'8%õ'f;âw¡ÈS ].
select N'ô/PDM643¸}''8%õ''f;âw¡ÈS'

Double quotes like: '' makes just one ' at the end.
And shouldn't forget that N'somestirng' not really the same as 'somestring'.

*

*N'somestirng' - stores 2 bytes/char

*'somestirng' - stores 1 bytes/char

So if there is some special characters like in this case- it makes difference.

A: That password is a one way hash of the original password entered.  No one here is going to be able to decrypt it without generating a rainbow table based on the way it was hashed.
So, if you've lost the password then you need to login into the machine using the administrator account and change it.
If you're just trying to hack a sql server... well, I don't think anyone needs to give you more advice.


text:
Q: Dojo version compatibility I started working on a web application that currently uses version 0.4.
How would I go about upgrading to the latest version, 1.5?
I don't think it's backward compatible?
Would I make a sub-directory in the "js" dir, call it v1.5, and add new code using a new  tag that references the new version?
Then, over time, refactor the old code to use the new version?

A: There are a lot of changes from 0.4 to the current version (1.5). There used to be some porting guides available on the Dojo site, but they don't seem to be there anymore. It's definitely not backwards compatible.
I haven't played with two versions of Dojo side by side, but if they load together then the method you mentioned is your best bet - any new code using 1.5, and refactor the old code as you go.


text:
Q: All the information is getting inside only in one block of excel python Hello I am new to the web scraping. I scrap a site but after I write it into the CSV only one block is filled with all the information and I want the information to be filled in row wise it will not matter if they are in single but they must be in different row.
Here is the code:
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
from csv import writer

url = 'https://virtualhs.pwcs.edu/about/faculty'
res = requests.get(url)

soup = BeautifulSoup(res.content, 'lxml')
Title = soup.find('div', id='divContent')
if Title:
    for p in Title.select("p"):
        p.extract()
    for h2 in Title.select("h2"):
        h2.extract()
        Title =Title.text
        print(Title)
        with open('now.csv','w',encoding='utf-8', newline='') as f:
            thewriter = writer(f)
            thewriter.writerow([Title])

A: It's not clear what you are trying to scrape. Is it the teachers and the department?
If you use 'w' as your parameter, it will overwrite after each iteration. You would need to use 'a' to append after each iteration, but need to also make sure you write an initial "blank" csv to append to.
Personally, I think it's just easier to construct a dataframe, then write that to file:
import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://virtualhs.pwcs.edu/about/faculty'
res = requests.get(url)

soup = BeautifulSoup(res.content, 'html.parser')
departments = soup.find_all('h3')

rows = []
for department in departments:
    for teacher in department.find_next('ul').find_all('li'):
        row = {
            'teacher':teacher.text,
            'department':department.text}
        rows.append(row)

df = pd.DataFrame(rows)
df.to_csv('now.csv', index=False)


text:
Q: handle DispatchKeyEvent in Xamarin Forms Android platform when no control has the focus I have a Xamarin Forms project (.NET Standard 2.1) and I need to handle DispatchKeyEvent in the Android platform.  I have that working great if an Entry control has the focus but I need it to work when no control has the focus.
Based on this related post I have tried to give the Page that inherits from PageRenderer the focus.  (I realize that that post is not about a Xamarin Forms project.)
So I put the following in the PageRenderer in the Android project.
// in the PageRenderer class
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
    base.OnElementChanged(e);
    if (e.OldElement != null || Element == null)
    {           return;       }
    try
    {
        this.Focusable = true;
        this.FocusableInTouchMode = true;
        bool f = IsFocused;  // this is false here
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(@"ERROR: ", ex.Message);
    }
}

But IsFocused is always false.
NOTE: the device ( a barcode scanner) has a hardware keyboard, which is what I am using in this case.
How can I get the code to hit the DispatchKeyEvent handler when no control has the focus?

A: Based on @ToolmakerSteve 's guidance I added this.RequestFocus() to the OnElementChanged block, and now my DispatchKeyEvent event handler gets hit even if there is no Entry control on the page.
this.Focusable = true;
this.FocusableInTouchMode = true;
this.RequestFocus();
bool f = IsFocused;  // now this is true because of RequestFocus()


text:
Q: En unity ¿Como puedo aumentar una variable de tipo "int" una unica vez dentro de update? Lo que quiero hacer es detectar cuantas fichas dentro de una list<> tienen un bool activado mediante el uso de un for loop pero almomento de hacerlo este sigue aumentando constantemente.
este es mi codigo:
int ObjetosActivado;

list<GameObjects> listaDeObjetos;

void update()
{

for(i = 0;i < listaDeObjetos.count; i++)
   {
     if(listaDeObjetos[i].GetComponent<Objeto>().boolActivado == true)
         {
           objetosActivados++;
         }
   }

}

A: @ALEMAN PLAY yo le pondria otro if fuera del bucle para que no te entrara si se ha aumentado la variable.
Para un solo objeto:
int ObjetosActivado = 0;
list<GameObjects> listaDeObjetos;

void update()
{
  if(objetosActivados == 0){
    for(i = 0;i < listaDeObjetos.count; i++)
    {
      if(listaDeObjetos[i].GetComponent<Objeto>().boolActivado)
      {
          objetosActivados++;
      }
    }
  }
}

De esta manera se inicia la variable a 0 se repatea el bucle si boolactivado es true entrara en la condicion y te aumentara la variable objetosActivados. Pero no volvera a entrar en el bucle porque ya tiene valor por lo tanto siempre la tendras a 1 cuando quieras la vuelves a poner a 0 para que te vuelva a entrar.
Para varios Objetos:
List<GameObjects> listaDeObjetosActivados = new List<GameObjects>();
list<GameObjects> listaDeObjetos;

void update()
{
  if(objetosActivados == 0){
    for(i = 0;i < listaDeObjetos.count; i++)
    {
      if(listaDeObjetos[i].GetComponent<Objeto>().boolActivado)
      {
          listaDeObjetosActivados.Add(listaDeObjetos[i]);
      }
    }
  }
}

De esta manera te creas una lista vacía y en el bucle vas detectando los objetos que tienen boolActivado a true si es true lo agregas a la lista nueva. El resultado sera una lista nueva con todos los objetos que están Activados.


text:
Q: Is there a unique projection map in this case? Let $X$ be a Banach space over $\mathbb{C}$. Let $A,B$ be closed subspaces of $X$ such that $X=A\oplus B$. Assume that $||a+b||=||a||+||b||$ for each $(a,b)\in A\times B$.
Then, does there exist a unique projection $T$ on $X$ such that $im(T)=A$?

A: Usually not. Just consider $\mathbb{C} \oplus \mathbb{C}$; we have lots of projections onto the first component: anything of the form $(x,y) \mapsto (x + cy, 0)$, for $c \in \mathbb{C}$.


text:
Q: Query with jsonb operator I'd like to make this PostgreSQL query using Npgsql 3.1.7:
SELECT jdoc FROM myTable where jdoc -> 'tags' @> '[{"name": "tv"}]'

The code looks like this:
using (var dbConnection = new NpgsqlConnection("myconnection")) {
      dbConnection.Open();

      var request = dbConnection.ExecuteReader("SELECT jdoc FROM myTable where jdoc -> 'tags' @> '[{\"name\": @var1}]'"),
                new { var1 = "tv" });
}

The jsonb operator @> is seen as a parameter and I get this Exception:
{"22P02: invalid input syntax for type json"}
Token "@" is invalid.

Is there a way to use this operator with an escape mechanism or something else?


text:
Q: how to configure two ip blocks for use on a network My ISP has given me a /30 and a /27 ip block I can use. for the sake of not giving out my ips I'll use 192.168.1.192/30 and 192.169.1.224/27. I'm not using a router in my setup, I only have a switch. Right now I do not have the possibility to use a hardware router so please dont hassle me about that.
So here is what I have:

*

*On a debian server I have it set to 192.168.1.194, subnet: 255.255.255.252, gateway: 192.168.1.193, DNS 8.8.8.8

*On a centos server i have 192.169.1.226, subnet 255.255.255.224, gateway 192.168.1.194

*On my windows 7 laptop i have 192.169.1.227, subnet 255.255.255.224, gateway 192.168.1.194

I can access the internet from the first debian server however I cant access anything on any of the other machines.
I've tried setting the gateways on the centos & windows machines to either 192.168.1.194 and 192.168.1.193 but that doesn't fix the problem. Is there something obvious I'm missing with this config?
My guess is that I need to configure the debian server as a router since it has the main ip address but how do I do that? Ive already enabled ipv4 forwardign on the debian server.
Also note that the ISP uplink is a GigE fiber connection and none of my servers has a fiber nic to connect to.

A: Do either of your linux boxes have two nics?
You can use them as a hardware router quite easily.
You'll want to enable ipv4 forwarding.
Even if they don't currently have a second NIC, adding one is pretty trivial and cheap.  Beyond that, you are going to have a mess on your hands.

A: The /30 can have 1 host plus a gateway.  The other can support up to 29 hosts plus your gateway.  If your provider only gave you one gateway address they most likely expect you to use a host in the /30 block as the router for the other block.
These are 2 separate network blocks.  Hosts in the larger block have no way to talk to the gateway address in the smaller block without some sort of a router.  If your debian host has an additional interface you could use it as a router but there be aware that done improperly you could open your hosts to malicious activity.
At minimum you will need to:

*

*Setup an additional address in the larger network on the debian host.  This can be a separate NIC or a subinterface.

*Turn on ipv4.forwarding

*Configure iptables to allow the traffic to pass through the debian host.

*Use the address from the first step as the gateway for the remaining hosts.

A: I'd do something like that. Server 1 needs iptables configuration for security, and also NAT. As said by others, ipv4.forwarding must be enabled.

EDIT: As Frederik Nielsen commented, you don't need any NAT if every device of your network has its own public IP address.