text:
Q: Swift: ScrollView not scrolling (how to set the constraints)? I am trying to set up a scroll view with auto layout in my storyboard and populate it with a couple of buttons in code, but the scroll view doesn't scroll and I don't understand how to set up the constraints to make scrolling available?
Especially how to set the constraints to the content view (what's that?).
In storyboard the scroll view is placed at the bottom of the screen (20 pix to the safe area) and from leading to trailing. It has a size of 375x80.
Now in code this is how the scroll view is populated with buttons and how it is set up:
override func viewDidLoad() {
    super.viewDidLoad()

    var xCoord: CGFloat = 5
    var yCoord: CGFloat = 5
    let buttonWidth: CGFloat = 70
    let buttonHeight: CGFloat = 70
    let gapBetweenButtons: CGFloat = 5

    var itemCount = 0

    for i in 0..<CIFilterNames.count {
        itemCount = 1

        // Button properties
        let filterButton = UIButton(type: .custom)
        filterButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
        filterButton.tag = itemCount
        filterButton.addTarget(self, action: #selector(ViewController.filterButtonTapped(sender:)), for: .touchUpInside)
        filterButton.layer.cornerRadius = 6
        filterButton.clipsToBounds = true

        //Code for filters will be added here

        let ciContext = CIContext(options: nil)
        let coreImage = CIImage(image: originalImage.image!)
        let filter = CIFilter(name: "\(CIFilterNames[i])")
        filter!.setDefaults()
        filter?.setValue(coreImage, forKey: kCIInputImageKey)
        let filteredImageDate = filter!.value(forKey: kCIOutputImageKey) as! CIImage
        let filteredImageRef = ciContext.createCGImage(filteredImageDate, from: filteredImageDate.extent)
        let imageForButton = UIImage(cgImage: filteredImageRef!)

        // Asign filtered image to the button
        filterButton.setBackgroundImage(imageForButton, for: .normal)

        // Add buttons in the scrollView
        xCoord += buttonWidth + gapBetweenButtons
        filterScrollView.addSubview(filterButton)

    }

    filterScrollView.contentSize = CGSize(width: buttonWidth * CGFloat(itemCount + 2), height: yCoord)
    filterScrollView.isScrollEnabled = true

}

Depending on the device size 4 or 5 buttons are shown, but not more and scrolling is not possible.
What can be done to make scrolling possible?

A: Reason is in itemCount , you're settings it to itemCount + 2 will be 3 as itemCount is 1 from the for loop so , set it to equal array size
   filterScrollView.contentSize = CGSize(width: buttonWidth * CIFilterNames.count  , height: yCoord)

A: You will be much better off using auto-layout over calculating sizes - gives much more flexibility for future changes.
Here is an example you can run in a Playground page. I used the "count" as the button labels, since I don't have your images. If you add images, you can un-comment the appropriate lines and remove the .setTitle and .backgroundColor lines:
import UIKit
import PlaygroundSupport
import CoreImage

class TestViewController : UIViewController {

    var CIFilterNames = [
        "CIPhotoEffectChrome",
        "CIPhotoEffectFade",
        "CIPhotoEffectInstant",
        "CIPhotoEffectNoir",
        "CIPhotoEffectProcess",
        "CIPhotoEffectTonal",
        "CIPhotoEffectTransfer",
        "CISepiaTone"
    ]

    let buttonWidth: CGFloat = 70
    let buttonHeight: CGFloat = 70
    let gapBetweenButtons: CGFloat = 5

    override func viewDidLoad() {
        super.viewDidLoad()

        // create a UIScrollView
        let filterScrollView = UIScrollView()

        // we will set the auto-layout constraints
        filterScrollView.translatesAutoresizingMaskIntoConstraints = false

        // set background color so we can see the scrollView when the images are scrolled
        filterScrollView.backgroundColor = .orange

        // add the scrollView to the view
        view.addSubview(filterScrollView)

        // pin scrollView 20-pts from bottom/leading/trailing
        filterScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0).isActive = true
        filterScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0).isActive = true
        filterScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0).isActive = true

        // scrollView height is 80
        filterScrollView.heightAnchor.constraint(equalToConstant: 80).isActive = true

        // create a UIStackView
        let stackView = UIStackView()

        stackView.spacing = gapBetweenButtons

        // we will set the auto-layout constraints
        stackView.translatesAutoresizingMaskIntoConstraints = false

        // add the stackView to the scrollView
        filterScrollView.addSubview(stackView)

        // with auto-layout, scroll views use the content's constraints to
        // determine the contentSize,
        // so pin the stackView to top/bottom/leading/trailing of the scrollView
        // with padding to match the gapBetweenButtons
        stackView.leadingAnchor.constraint(equalTo: filterScrollView.leadingAnchor, constant: gapBetweenButtons).isActive = true
        stackView.topAnchor.constraint(equalTo: filterScrollView.topAnchor, constant: gapBetweenButtons).isActive = true
        stackView.trailingAnchor.constraint(equalTo: filterScrollView.trailingAnchor, constant: -gapBetweenButtons).isActive = true
        stackView.bottomAnchor.constraint(equalTo: filterScrollView.bottomAnchor, constant: -gapBetweenButtons).isActive = true

        // loop through the images
        for i in 0..<CIFilterNames.count {

            // create a new UIButton
            let filterButton = UIButton(type: .custom)
            filterButton.tag = i

            // we will set the auto-layout constraints, and allow the stackView
            // to handle the placement
            filterButton.translatesAutoresizingMaskIntoConstraints = false

            // set the width and height constraints
            filterButton.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
            filterButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true

            filterButton.layer.cornerRadius = 6
            filterButton.clipsToBounds = true

            filterButton.addTarget(self, action: #selector(filterButtonTapped(_:)), for: .touchUpInside)

            // this example doesn't have your images, so
            // set button title and background color
            filterButton.setTitle("\(i)", for: .normal)
            filterButton.backgroundColor = .blue

//          //Code for filters will be added here
//
//          let ciContext = CIContext(options: nil)
//          let coreImage = CIImage(image: originalImage.image!)
//          let filter = CIFilter(name: "\(CIFilterNames[i])")
//          filter!.setDefaults()
//          filter?.setValue(coreImage, forKey: kCIInputImageKey)
//          let filteredImageDate = filter!.value(forKey: kCIOutputImageKey) as! CIImage
//          let filteredImageRef = ciContext.createCGImage(filteredImageDate, from: filteredImageDate.extent)
//          let imageForButton = UIImage(cgImage: filteredImageRef!)
//
//          // Asign filtered image to the button
//          filterButton.setBackgroundImage(imageForButton, for: .normal)

            // add the image view to the stackView
            stackView.addArrangedSubview(filterButton)

        }

    }

    func filterButtonTapped(_ sender: Any?) -> Void {
        if let b = sender as? UIButton {
            print("Tapped:", b.tag)
        }
    }

}

let vc = TestViewController()
vc.view.backgroundColor = .red
PlaygroundPage.current.liveView = vc


text:
Q: Spring Web Sockets - Get access to web socket session in controller I am working on a spring web socket app and I am looking to find a way to get hold of the spring web socket session decorator at my controller.
By looking at the spring code I saw that WebSocketSessions by default are decorated with ConcurrentWebSocketSessionDecorator in SubProtocolWebSocketHandler:decorateSession()
Here is how my code looks like
@Controller
public class MyController {

   @MessageMapping("/endpoint")
    public void method(Request request) {
        //logic
        // This is where I want to have access to ConcurrentWebSocketSessionDecorator
    }
}

Is it possible to get access to the decorator in my controller ?
Thanks
Nikos

redpajama_set_name: RedPajamaStackExchange


text:
Q: drop-down menu and check-boxes in r I have a dataframe that has different columns. The first one is the year, the rest are different brands. I would like to plot a graph showing how those different brands performed throughout the years in terms of profits. This graph should have a dropdown menu that allows you to choose which company you would like to see, that is a dropdown checkbox with all the brands. The checkbox should also allow you to see all of them at the same time, or just some.
#Here is my go at it.

library(plotly)
x <- seq(-2 * pi, 2 * pi, length.out = 1000)
df <- data.frame(x, y1 = sin(x), y2 = cos(x), y3=cos(2*x), y4=sin(3*x))

p <- plot_ly(df, x = ~x) %>%
  add_lines(y = ~y1, name = "Sin") %>%
  add_lines(y = ~y2, name = "Cos", visible = F) %>%
  layout(
    title = "Drop down menus - Styling",
    xaxis = list(domain = c(0.1, 1)),
    yaxis = list(title = "y"),
    updatemenus = list(

      list(
        y = 0.7,
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(TRUE, FALSE)),
               label = "Sinx"),

          list(method = "restyle",
               args = list("visible", list(FALSE, TRUE)),
               label = "Cosx")))
    )
  )
p

In the example above, I was able to create a drop-down menu but it is not close to what I want. Also, I couldn't grasp the answer given in this question since it uses so much html (I suck at html). Any help is greatly appreciated.

A: The question you linked uses shiny, but you do not seem to be using shiny.
Here is a non-shiny approach that is pretty close to what you want. It uses crosstalk::SharedData and crosstalk::filter_select() on long format data to give you a drop-down type input permitting multiple selections.
library(crosstalk)
library(dplyr)
library(plotly)
library(tidyr)

data_wide <- tibble(x = seq(-2 * pi, 2 * pi, length.out = 1000),
                    y0 = 0,
                    y1 = sin(x),
                    y2 = cos(x),
                    y3 = cos(2 * x),
                    y4 = sin(3 * x))

data_long <- data_wide %>%
  gather("series", "y", -x) %>%
  mutate(series = case_when(series == "y0" ~ "0",
                            series == "y1" ~ "sin(x)",
                            series == "y2" ~ "cos(x)",
                            series == "y3" ~ "cos(2x)",
                            series == "y4" ~ "sin(3x)"))

data_shared <- SharedData$new(data_long, key = ~series)

p <- data_shared %>%
  plot_ly(x = ~x, y = ~y, color = ~series) %>%
  add_lines()

bscols(widths = c(3, NA),
       filter_select(id = "fsid",
                     label = "Series",
                     sharedData = data_shared,
                     group = ~series),
       p)

If you are not aware, clicking series in the legend of a plotly plot will toggle visibility of that series. So you may not need a drop-down menu at all and could instead just do something like:
library(plotly)

x <- seq(-2 * pi, 2 * pi, length.out = 1000)
df <- data.frame(x, y = 0, y1 = sin(x), y2 = cos(x), y3 = cos(2 * x), y4 = sin(3 * x))

plot_ly(df, type = "scatter", mode = "lines") %>%
  add_lines(x= ~x, y= ~y,  name = "0",       line=list(color="red")) %>%
  add_lines(x= ~x, y= ~y1, name = "sin(x)",  line=list(color="orange")) %>%
  add_lines(x= ~x, y= ~y2, name = "cos(x)",  line=list(color="yellow")) %>%
  add_lines(x= ~x, y= ~y3, name = "cos(2x)", line=list(color="green")) %>%
  add_lines(x= ~x, y= ~y4, name = "sin(3x)", line=list(color="blue")) %>%
  layout(title = "Choose Your Own Brands")


text:
Q: Cor 1.2.28 (Finite pullback) in Lazarsfeld's Book I meet some problem when reading Lazarsfeld's Positivity in Algebraic Geometry, Cor 1.2.28.

Corollary 1.2.28 Let $f:Y\longrightarrow X$ be a finite surjective mapping of projective schemes, and let $L$ a line bundle on $X$, if $f^*L$ is ample on $Y$, then $L$ is ample on $X$.

The proof states as below.

Proof. Let $V\subseteq X$ be an irreducible variety. Since $f$ is surjective and finite, there exists irreducible variety $W\subseteq Y$ mapping finite onto $V$: we start with $f^{-1}(V)$, one constructs $W$ by taking irreducible components and $\color{blue}{\textrm{cutting down by general hyperplanes}}.$ Then by the projection formula:

$$\int_W {c_1(f^*L)}^{\text{dim}W}=\text{deg}(W\longrightarrow V)\cdot\,\int_V{c_1(L)}^{\text{dim}(V)}$$

By applying the Nakai-Moishezon ampleness criterion, we are done.

What confuses me is the $\color{blue}{\textrm{'blue'}}$ sentence, why we need the general hyperplane cut-down procedure?
Any help would be appreciated. Thanks a lot.


text:
Q: Как выгрузить фотографию с сайта с помощью Python? Мне трудно представить как это всё делается так как первый раз работаю с парсингом или чем-то подобным. В общем суть такова - даётся url картинки и мне надо загрузить её на сайт, а потом выгрузить с этого же сайта (и страницы) в обработанном виде. Уже несколько часов ищу материалы по этой теме, но понял что легче просто спросить. Сайт - Remove.bg

A: # Requires "requests" to be installed (see python-requests.org)
import requests

response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open('Здесь пишешь путь к файлу который хочешь закачать на сайт например: C:\PyCharm\main\Penguins.jpg', 'rb')},
    data={'size': 'auto'},
    headers={'X-Api-Key': 'Здесь прописываешь API KEY свой'},
)
if response.status_code == requests.codes.ok:
    with open('no-bg.png', 'wb') as out:
        out.write(response.content)
else:
    print("Error:", response.status_code, response.text)

A:
Получение API KEY, кнопка находится сверху по ссылке которую ты оставил когда задавал вопрос


text:
Q: Record and playback input/movement accurate on games running on different frame rates I have a problem that I can't seem to figure out the solution to.
I want to record the input in a game and play the input back afterward. I save the input every frame.
But when recording and playing the input back. The framerate isn't the same. That leads to that the playback isn't played back accurately.
So my question is. How can you save a timestamp that can be accurately replayed back without the frame rate being the exact same?
Let's say you have a game that runs at 60 fps. And you record the input. But now the game runs at 30 fps. How can you playback the input so it will be the same?
I guess we can calculate the game frame time/deltatime and use that. But I am not good at math so I haven't figured out how to implement it to fit my use case.


text:
Q: OnClick redirect the user to another url I wanted to change bg color in this order: [Black,White,Red,Green,Blue]

But when I click somewhere on page, nothing happens.

A: you have to do like this
 // similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

remove ; from html

Click me!!

A: The reason why your code is not working is that div tags do not support the action onclick. In order to make the div clickable, you would need to set an ID for the div and then in javascript assign an event handler to process the click for example:

Click me!!


text:
Q: Smiley Replace within CDATA of an HTML-String i have got a simple problem :( I need to replace text smilies with the according smiley-image. ok.. thats not really complex, but now i have to replace only smilie appereances outside of HTML Tags. short examplae:
Text:
Thats a good example :/ .. with a link inside.
i want to replace ":/" with the image of this smiley...
ok, how to do that the best way?

A: I won't try to create some super script but think about it.... smilies are just about always surrounded by spaces. So str replace ' :/ ' with the smiley. You could be saying "what about a smiley at the end of a sentence(where it would be used the most)". Well just check for at least one space on either the left or the right of a potential smiley.
Using the above scripts:
$smiley_array = array(
    ":) " => "",
    " :)" => "",
    ":/ " => "",
    " :/" => "");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace($codes, $links, $str);

If you rather not have to type everything twice you can generate the array from a single smiley array.

A: Why don't you just try to use some  special chars around your smiley text like this maybe -:/-
This will make your smiley text some kind of unique and easy to recognize

A: Use preg_replace with a lookbehind assertion. Example:

$smileys = array(
  ':/' => ''
);
foreach ($smileys as $smile => $img) {
  $text = preg_replace('@(?<!<[^<>]*)' . preg_quote($smile, '@') . '@',
                       $img, $text);
}

The regex should match only smileys that are not inside angle brackets. This might be slow if you have a lot of false positives.

A: I wouldn't know about the best way, only the way I would do it.
Build an array having the smiley codes as the keys and the link as the value. The use str_replace. Pass as "needle" an array of the keys (the smiley codes) and as "replace" an array of the values.
For instance, suppose you have something like this:
$smiley_array = array(":)" => "",
    ":(" => "");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace($codes, $links, $str);

EDIT: In case this could accidentally replace other instances with smiley-links you should consider using regexes with preg_replace. Obviously preg_replace is slower than str_replace.

A: You can use regex, or the extra sloppy version of the above:
$smiley_array = array(":)" => "",
    ":(" => "");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace("://", "%%QF%%", $str);
$str = str_replace($codes, $links, $str);
$str = str_replace("%%QF%%", "://", $str);

Actually, assuming str_replace follows the array sorting...
this should work:
$smiley_array = array("://" => "%%QF%%", ":)" => "",
    ":(" => "", "%%QF%%" => "://");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace($codes, $links, $str);

A: Possible overkill (increased cpu/load), but 99.99999999% safe:
<?php
$n = new DOMDocument();
$n->loadHTML('
Thats a good example :/ .. with a link inside.
');
$x = new DOMXPath($n);
$instances = $x->query('//text()[contains(.,\':/\')]');//or use '//*[child::text()]' for all textnodes
foreach($instances as $node){
    if($node instanceof DOMText && preg_match_all('/:\//',$node->wholeText,$matches,PREG_OFFSET_CAPTURE|PREG_SET_ORDER)){
            foreach($matches[0] as $match){
                    $newnode = $node->splitText($match[1]);
                    $newnode->replaceData(0,strlen($match[0]),'');
                    $img = $n->createElement('img');
                    $img->setAttribute('src','smily.gif');
                    $img = $newnode->parentNode->insertBefore($img,$newnode);
                    //var_dump($match);
            }
    }
}
var_dump($n->saveHTML());
?>

But in reality you do not want to do this all that often, save once, show many, if you are letting users edit the html (beit in wysiwyg or elsewise, the 'return' transformation (img to text) is a whole lot lighter. Up to you to expand with different smilies (one monster regex to match them, or several smaller ones / strstr()'s for readability, and a array for smiley to src (e.g. array(':/'=>'frown.gif')) would be the way to go.


text:
Q: How to see contents of output queue of NIC in Linux and introspect frame delay I am experimenting with tc tool to implement prioritization of specific data coming from my computer and would like to see exatly how the frames are scheduled and how much time they spend in the qdisc queue before the transmission (before being dequeued). The goal is to make sure my tc configuration does what it is suposed to do.
Is there any tool that allows such introspection?


text:
Q: how to create seo urls for all views using slug rails I am creating an application on which i just want to use all my app's routes should access via seo urls using slugs. i have created a slug field in my database table. this my migration file code
  class AddSlugToClients < ActiveRecord::Migration
    def change
      add_column :clients, :slug, :string
    end
  end

I have added this code to my controller's show method
my controller's code is:
def show
    @client = Client.find_by_slug(params[:id])
end

In my app's model i have added this code
class Client < ActiveRecord::Base
  def slug
    ename.downcase.gsub(" ", "-")
  end
  validates_presence_of :slug
  def to_param
    slug
  end
end

now when i create a new client than client is created by the perfect slug. but when i click show link from the listing page to that clients then getting an error in url which looks like
clients/%23<Client::ActiveRecord_Relation:0xb59828d4>

now please help me to create a seo url for show page while clicking from index view. Current view code:
<% @client.each do |client| %>

    <%= client.ename %>
    <%= link_to 'Show', client_path(@client) %>
    <%= link_to 'Edit', edit_client_path(@client) %>

<% end %>

A: You've got two problems.
In your view code, your each block takes a client param - but in your url helpers, you're passing through @client. So, you need to remove the @.
Your code becomes:
<% @client.each do |client| %>

    <%= client.ename %>
    <%= link_to 'Show', client_path(client) %>
    <%= link_to 'Edit', edit_client_path(client) %>

<% end %>

(as an aside, since your @client variable that you call each on contains multiple records, you should rename it @clients - plural. Nothing will break if  you don't do this, but it's not good practice)
You're second issue is that in your model, since you have a slug method which generates the slug from the ename, you don't actually need to have a slug column in your database. You should remove that column. The slug isn't a value stored in the database, it's just dynamically generated by ruby from the ename, which is stored in the database.
There is one other potential issue with this approach, which is that if the ename changes, then so does the slug, and that means if there are any external web pages linking in to the old slug, they will no longer work. But that's probably not worth going into here.


text:
Q: JS & Angular: Date object is "out of date" I've seen many things in JS, but this one haunts me in my dreams. Unfortunately my environment is pretty complex. But here is what I think is important (if you miss anything please ask):

*

*We're using Angular around 1.4.3

*I a lot of directives, in this case three (written with controllerAs syntax, so no $scope or $whatever in game)

*The directives are using a shared model injected via directive like <myDirective model="base.model">
My problem is a difference between what's actually in the model and what I get when I access that model directly. Reduced to the important thing, this happens:
console.log( vm.model )
  [listing all the stuff until:]

  startDate: Fri May 13 2016 15:10:19 GMT+0200

console.log( vm.model.startDate )

  Thu May 12 2016 15:10:19 GMT+0200

Basically the date is always correct when looking at the first one ( log(vm.model)) and it's wrong when accessing the vm.model.startDate directly (I checked that, it's not ony a wrong toString output, the date is actually out of date. When now changing the date via the dateTimePicker I use the model will have the right value again and when accessing the variable directly it will be Fri May 13 2016 15:10:19 GMT+0200. To be clear: When accessing the model variable directly I always get the last valid value. The values are interpreted after a ng-change was fired. I'd guess some parallel/race condition stuff is going on, but how can I get 2 different things in 2 lines (no matter in which order by the way, object always right, direct access/toString always wrong).
Do you have any idea what's possibly going on?


text:
Q: QGraphicsItems not showing up QGraphicsScene I'm trying to build a custom widget with a QGraphicsScene inside it.
class Graphics:public QWidget{
  public:
 Graphis();
}

Graphics::Graphics(){
 QGraphicsScene* scene = new QGraphicsScene(this);

    QGridLayout* grid = new QGridLayout;

    QGraphicsView* view = new QGraphicsView(this);

    QGraphicsLineItem* y = new QGraphicsLineItem(scene->width()/2, 0, scene->width() / 2, scene->height());
    QGraphicsLineItem* x = new QGraphicsLineItem(0, scene->height() / 2, scene->width(), scene->height() / 2);
    scene->addItem(y);
    scene->addItem(x);

    grid->addWidget(view, 0, 0, 1, 1);
    setLayout(grid);

    view->setScene(scene);
    view->show();
}

But when I run the widget, only an empty scene shows up in the QGraphicsView widget inside the main widget.

A: Try it like this instead; I think one problem is that scene->width() and scene->height() are very likely both returning 0, at least on your first call to them, since sceneRect() defaults to returning a QRect big enough to fit the current contents of the scene (which is initially empty):
Graphics::Graphics(){
    QGraphicsScene* scene = new QGraphicsScene(this);
    QGridLayout* grid = new QGridLayout(this);
    QGraphicsView* view = new QGraphicsView(scene, this);

    scene->setSceneRect(0, 0, 200, 200);
    QGraphicsLineItem* y = new QGraphicsLineItem(scene->width()/2, 0, scene->width() / 2, scene->height());
    QGraphicsLineItem* x = new QGraphicsLineItem(0, scene->height() / 2, scene->width(), scene->height() / 2);
    scene->addItem(y);
    scene->addItem(x);

    grid->addWidget(view, 0, 0, 1, 1);
}


text:
Q: Sending a HTTP POST Request I am trying to send a request to get public transport information. Here's a screenshot of an example below, stating that I must send an XML request to the site, defining the method and the service reference (in the example it's StopMonitoringRequest and 020035811).

So far I have managed to connect to the service, but I have no idea what to do from here. I have so far done this...
String user = "";
String pass = "";
String url = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";

String authString = user + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

HttpURLConnection  connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestMethod("POST");
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty( "charset", "utf-8");
connection.setUseCaches(false);
connection.setDoOutput(true);

InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);

int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
    sb.append(charArray, 0, numCharsRead);
}

String result = sb.toString();
System.out.print(result);

...receiving this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Siri version="1.0" xmlns="http://www.siri.org.uk/">
<ServiceDelivery>
<ResponseTimestamp>2015-11-08T20:33:03.574Z</ResponseTimestamp>
</ServiceDelivery>
</Siri>

How do I enter the required parameters and method?

A: So what I had to do was create a HttpPost and set the xml request up as an entity, binding it to the post. Here is the code, in case anyone wants to request information via HTTP POST using XML, outputting the XML as a string:
// basic autthorization security
String url = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
String authString = "<username>:<password>";
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Basic " + authStringEnc);
StringEntity input = new StringEntity(request);
input.setContentType("text/xml");
post.setEntity(input);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String unformattedXML = EntityUtils.toString(entity);


text:
Q: Kill a running thread What happens if we forcefully kill a running thread
I have a thread namely RecordThread() which calls some complex and time consuming functions. In these functions I am using try-catch blocks, allocating and deallocation memory and using critical section variables etc.
like
  void RecordThread()
  {
    AddRecord();
    FindRecord();
    DeleteRecord();
    // ...
    ExitThread(0);
   }

After creating this thread, I am immediately killing it before the thread completes its execution. In this case what happens if the thread is forcefully killed? Do the internal functions (AddRecord, DeleteRecord) complete their execution after we killed the thread?

A: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682659%28v=vs.85%29.aspx

ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.

However the function calls will of course be completed because they're called before the ExitThread().

A: killing thread is the last resort - as Andre stated it leaves data in unknown state, you should never do that if thread works on shared object. Better choices are to notify thread to finish work by:
-using global volatile (important) variable which is changed only by main thread and tested by workers
-using signal type synchronization objects (mainly Events) also set by main thread and tested by workers

A:
After creating this thread, I am immediately killing it before the thread completes its execution.

I assume you mean you are using TerminateThread() in the following fashion:
HANDLE thread = CreateThread(...);

// ...
// short pause or other action?
// ...

TerminateThread(thread, 0); // Dangerous source of errors!
CloseHandle(thread);

If that is the case, then no, the thread executing RecordThread() will be stopped exactly where it is at the time that the other thread calls TerminateThread().  As per the notes in the TerminateThread() documentation, this exact point is somewhat random and depends on complex timing issues which are out of your control.  This implies that you can't handle proper cleanup inside a thread and thus, you should rarely, if ever, kill a thread.
The proper way to request the thread to finish is by using WaitForSingleObject() like so:
HANDLE thread = CreateThread(...);

// ...
// some other action?
// ...

// you can pass a short timeout instead and kill the thread if it hasn't
// completed when the timeout expires.
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);

A: example of Thread that works well:
definition in *.h ------------------------------------

DWORD WINAPI Th_EspectroIF(LPVOID lpData);

CThread th_espectro(Th_EspectroIF);

use in *.cc -----------------------------------

DWORD WINAPI Th_EspectroIF(LPVOID lpData)
{

//Your code...

th_espectro.Stop(true);//stop this Thread

}

call the Thread with: th_espectro.Start();


text:
Q: Actions before logout from ssh session Is it possible to bind some actions which will be executed before logout from ssh session?
I mean some config like .bashrc, etc.

A: If you enter the following into .bashrc (or /etc/profile, or .profile, or any other start-up script) on the remote machine:
function onexit { xmessage "Exiting..."; }; trap onexit EXIT

You can replace the xmessage command with anything you want: if you use /etc/profile you will need to make checks that bash is in a remote session, so as not to affect local sessions.
The answers here deal with exiting scripts, but are equally valid for the shell itself.


text:
Q: Dynamically ALTER a SQL Table based on a DataTable I am getting data from a rest feed at regular intervals and want to copy this into a SQL table. Easy enough using SQLBulk copy.
The issue i am struggling with is that the fields I get from the feed could change and i want to be able to add any new columns dynamically to the table. Any columns that no longer exist i need to leave in the table. I can simply add those into the datatable.
My question. What options do i have to do this. Is there any free 3rd party .net frameworks that will do it or how can i write this manually.
Must all be done in .NET.
Thanks

A: as you stated that you are getting data from a rest feed then u can create a simple ASP WebPages Application
Add a page in which you are going to call the "Rest Feed".
Now what format the Rest Feed is offering
mostly JSON is used
you can parse JSON to a Model Class which corresponds to the data structure of that feed
then simply insert the data using SQLConnection , SQLCommand to the underlying database
here is a sample code which you can alter
string siteContent = string.Empty;
string url = "http://www.RESTFEEDURL.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream responseStream = response.GetResponseStream())
using(StreamReader streamReader = new StreamReader(responseStream))
{
    siteContent = streamReader.ReadToEnd();
}
//NOW PARSE THE DATA AND SEND TO DATABASE HERE
//data is in siteContent

//now you want to decode the data and get all the column names
var keyArray = Ext.Object.getKeys(Ext.JSON.decode(siteContent));

//if suppose data has following format
//{"ID":"1","name":"google","IP":"69.5.33.22","active":"true"}
//{"ID":"2","name":"bing","IP":"70.5.232.33","active":"false"}
console.log(keyArray);
// ["ID","name","IP","active"]

now
foreach(var item as keyArray)
{
sql = "IF COL_LENGTH('TABLENAME', item) IS NULL alter table [TABLENAME] add [item] int default 0 NOT NULL"
//run this sql query using sql command and see the magic
}


text:
Q: How to make custom LineChart control in JavaFX? I had a custom LineChartWithMarkers control in my JavaFX project.
I've made a two year pause in my Java(FX) programming and found out that LineChartBuilder does not exist any more in Java 10.
I was able to find some docs saying it is deprecated in version 8, but not how to replace it.
How do I fix my code to work with Java 10?
This is what I had:
public class LineChartWithMarkersBuilder extends LineChartBuilder {
    private Axis<Number> xAxis ;
    private Axis<Number> yAxis ;
    private ObservableList<Series<Number,Number>> data ;

    public static LineChartWithMarkersBuilder create() {
        return new LineChartWithMarkersBuilder();
    }

    public LineChartWithMarkersBuilder xAxis(Axis<Number> xAxis) {
        this.xAxis = xAxis ;
        return this ;
    }

    public LineChartWithMarkersBuilder yAxis(Axis<Number> yAxis) {
        this.yAxis = yAxis ;
        return this ;
    }

    public LineChartWithMarkers<Number, Number> build() {
        xAxis = new NumberAxis();
        yAxis = new NumberAxis();
        return new LineChartWithMarkers<Number, Number>( xAxis, yAxis);

    }
}

and the custom LineChartWithMarkers:
public class LineChartWithMarkers<X extends Number, Y extends Number> extends LineChart<X, Y>  {

    private ObservableList<Data<Number, Number>> verticalMarkers;

    public LineChartWithMarkers(Axis<X> xAxis, Axis<Y> yAxis) {
        super(xAxis, yAxis);
        this.setCreateSymbols(false);
        verticalMarkers = FXCollections.observableArrayList(data -> new Observable[] {data.XValueProperty()});
        verticalMarkers.addListener((InvalidationListener)observable -> layoutPlotChildren());
    }
    (...)
}

which I used from .fxml like this:
...
                <LineChartWithMarkers fx:id="chartFit" createSymbols="false" layoutX="14.0" layoutY="54.0" prefHeight="499.0" prefWidth="987.0" AnchorPane.bottomAnchor="162.0" AnchorPane.leftAnchor="14.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="54.0">
                <xAxis>
                    <NumberAxis side="BOTTOM" />
                </xAxis>
                <yAxis>
                    <NumberAxis side="LEFT" />
                </yAxis>
            </LineChartWithMarkers>
...

A: All JavaFX builder classes were deprecated in Java 8 and removed in Java 9. Just remove the builder class entirely. To allow the FXMLLoader top instantiate a class without a no-argument constructor, use @NamedArg annotations on the constructor parameters:
public class LineChartWithMarkers<X extends Number, Y extends Number> extends LineChart<X, Y>  {

    private ObservableList<Data<Number, Number>> verticalMarkers;

    public LineChartWithMarkers(
            @NamedArg("xAxis") Axis<X> xAxis,
            @NamedArg("yAxis") Axis<Y> yAxis) {
        super(xAxis, yAxis);
        this.setCreateSymbols(false);
        verticalMarkers = FXCollections.observableArrayList(data -> new Observable[] {data.XValueProperty()});
        verticalMarkers.addListener((InvalidationListener)observable -> layoutPlotChildren());
    }
    (...)
}

A complete discussion of the @NamedArg annotation can be found in What is the purpose of @NamedArg annotation in javaFX 8?


text:
Q: How to filter data from relational table in laravel I have three table one is orders table and another is order_status table and another is status table. Purpose of order_status table is to keep a track order's events. My table has the following column.
Order table
----------------------------
id | ref_num | name | email |
-----------------------------

Order status table has
---------------------------
order_id | status_id
---------------------

My models are like this
Order model
 public function orderStatus(){
        return $this->hasMany(OrderStatus::class');
    }

Order status model
  public function detail(){
        return $this->belongsTo(Status::class,'status_id','id');
    }

    public function order(){
        return $this->belongsTo(Order::class);
    }

Now i want to get all those order which are still pending.
How can i do so ?
I tried to retrive like this but it failed
 $data['orders']= Order::with(['orderStatus' =>function($q){
                $q->with('detail')->latest()->where('status_id',2);
            }])->latest()->take(10)->get()->toArray();

This return only one after that it does not.
Can  anyone please tell me how can i sort this one ??
Thanks
PS:: one order can have multiple status such as unpaid, pending, packageging, in transit and so on but in sequence ofcouse
I added order status table image.. As u can see E7E7FF0EB7 order number has two records 1,and 2 means it was pending and then later stage got delivered.or you can say got processed. where as E02EAEA4BE has only one record of status 1.  which means it is still pending.
So i want to get only those which are still pending.Not delivered.
This kinda sound complicated, hope i able to explain properly what i am trying to do.

A: Your model relations should be changed to a proper many to many. The schemas look correct so I'd make the following changes:
// Order model
public function statuses(){
    return $this->belongsToMany(Status::class);
}

// Status model
public function orders(){
    return $this->belongsToMany(Order::class);
}

This will pivot correctly on order_status.
To get pending orders the query would be:
Order::whereHas('statuses', function ($query) {
    // assuming a 'name' column on statuses table
    $query->where('name', 'pending');
    // or using dynamic where
    // $query->whereName('pending');
})->get();

Alternatively, add a scope to Order model:
public function scopePending($query) {
    return $query->with(['statuses' => function ($query) {
        $query->where('name', 'pending');
    });
});

Usable then as: Order::pending();

A: Update
Try this to get all those order which are still pending..
$data['orders'] =  Order::has('orderStatus', '=', 2)->whereHas('orderStatus', function ($q) {
            $q->where('status_id', 2);
        })->get()->toArray();

If there is two status records related to one order and one of the status value is 1 then this query will return the order record. You may update it with your exact conditions.(If you are sure that there will be only 2 status related to a order which is still pending then you may remove the second whereHas.
$data['orders'] =  Order::has('orderStatus', '=', 2)->get()->toArray();

You may use the many to many relation as @DigitalDrifter suggested. I would also suggest that you should follow many to many relation.
If you are using the many to many relation then you may try the below query..
Order::has('statuses', '=', 2)->WhereHas('statuses', function ($query) {
    $query->where('name', 'pending');
})->get();

or
Order::has('statuses', '=', 2)->get();


text:
Q: Go back to previous activity without touching the current I have two activity (ACT 1 and ACT 2):
ACT1 contains the button "next" with the code:
case R.id.next:
            Intent intent = new Intent(this, ACT2.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            this.startActivity(intent);
            break;
        }

ACT2 contains a button "back" no code for now.
so my problem I do not know what change in the button "next" and what to put in the button "back" to:
next: Open ACT2 if it is never open else go ACT2
back: back to ACT1
PS : I will not destroy "ACT2" if I go back a "ACT1", because I do not want to lose the contents entry

A: In the onClick() method of BACK use finish() method, this destroys the current Activity and moves to the previous opened activity.

A: From your description it seems u need to come back to act1 on back of act 2 and on next of act 1 to need to go to act 2 ....just start the activity i dont think u need that flag there

A: try this as per my suggestion..try like that.
        // Write code in Next button click Event
        Intent intent = new Intent(ACT1.this, ACT2.class);
        startActivity(intent);
        finish();

        // Write code in Back button click Event
        Intent intent = new Intent(ACT2.this, ACT1.class);
        startActivity(intent);
        finish();


text:
Q: Password for GitLab I've installed GitLab per https://github.com/gitlabhq/gitlab-recipes/tree/master/install/centos.
The instructions state to add user "git"
adduser --system --shell /sbin/nologin --comment 'GitLab' --create-home --home-dir /home/git/ git

All seemed to work.  I then added a project on the GitLab server, and it gave instructions to push to it:
cd existing_git_repo
git remote add origin git@mysite.com:root/bidjunction.git
git push -u origin master

I then went to my client to push to the git server.
[Michael@devserver bidjunction]$ git push -u origin master
The authenticity of host 'mysite.com (123.456.789.01)' can't be established.
RSA key fingerprint is cd:32:3c:5a:4e:33:44:11:df:ee:3s:4b:3a:c2:a4:c2.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'mysite.com,123.456.789.01' (RSA) to the list of known hosts.
Address 123.456.789.01 maps to ve6.phpwebhosting.com, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
git@mysite.com's password:

Is there a password I should have set?  Probably not, and instructions don't address.
Reading System ask password when push project to github, it appears it might be related to SSH.
GitLab provides the following instructions to add a SSH key.  I followed them, and first added the key to my general user's home on the server.  No change.  Then tried logging on a root, and added a key to git's home.  Still none, but I am thinking that the client already has my general user's key, thus is not pulling the new git key.
EDIT.  Please confirm that I should add these keys to the GitLab server, and not my Linux client.
Any and all help would be very much appreciated.
SSH Keys

SSH key allows you to establish a secure connection between your computer and GitLab

Before generating an SSH key, check if your system already has one by running cat ~/.ssh/id_rsa.pub If your see a long string starting with ssh-rsa or ssh-dsa, you can skip the ssh-keygen step.

To generate a new SSH key just open your terminal and use code below. The ssh-keygen command prompts you for a location and filename to store the key pair and for a password. When prompted for the location and filename you can press enter to use the default. It is a best practice to use a password for an SSH key but it is not required and you can skip creating a password by pressing enter. Note that the password you choose here can't be altered or retrieved.

ssh-keygen -t rsa -C "$your_email"

Use the code below to show your public key.

cat ~/.ssh/id_rsa.pub

Copy-paste the key to the 'My SSH Keys' section under the 'SSH' tab in your user profile. Please copy the complete key starting with ssh- and ending with your username and host.

EDIT 2
Looks like I was confused, and used GitLab's server id_rsa.pub.  Guess that doesn't make any sense!  I've since corrected it, but now I get this error:
[Michael@devserver ~]$ ssh git@mysite.com
Address 123.456.789.01 maps to ve6.phpwebhosting.com, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
PTY allocation request failed on channel 0
This account is currently not available.
                                        Connection to mysite.com closed.
[Michael@devserver ~]$

A: Seems like a SELinux permission issue. Steps to follow:

*

*restorecon -R -v /home/git/.ssh

*usermod -s /bin/bash git

*Edit your home machine user's .ssh/config to something like:

Host mysite.com
  User gitlab_username
  Hostname mysite.com
  PreferredAuthentications publickey
  IdentityFile /home/user/.ssh/id_rsa

Try connecting to the gitlab server ssh -T git@mysite.com. You should see a message welcoming you.
I added it to the installation guide. I have a merge request ready with several enhancements. I will merge it when gitlab 6.8 is released.

A: I believe you need to set up your global config username and email
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com

A: Check if the git user has a no login shell as you specified.  Changing that to bash as suggested fixed my problem (usermod -s /bin/bash git).


text:
Q: How to load child collection after loading the parent with nhibernate? I have this model
Product
- int Id
- string Name
- List<ProductChannelAffectation> Affectations

ProductChannelAffectation
- Channel Channel
- Product Product
- double Price

So I want to get the 10 first product that match to some condition and their affectation in 2 queries (no N+1 problem) and if possible in 1 trip to the DB.
So I read this Answer
https://stackoverflow.com/a/7035649/277067
OR this one
https://stackoverflow.com/a/5285739/277067
But here there is 2 problem :

*

*The condition is duplicated "Where(x => x.Id == ID)" across the 2 queries, it's ok when it's simple condition but what if it's complicated conditions (involving other tables, text search...)

*There is no "Top" condition.
Lazy loading is here causing a N+1 problem.
I tried this
var products = _nhSession.QueryOver<Product>()
    .Where(...)
    .Take(10)
    .List()
    .ToList();
var idsproduct = products.Select(p => p.ID);
var affectation = _nhSession.QueryOver<ProductChannel>()
    .Where(c => c.Product.ID.IsIn(idsproduct))
    .ToList();

But there is still N+1 (for getting the affectations) before the second query is executed.
Here is how my association is declared
  <bag name="Affectations" access="property" table="Product" lazy="false">
      <key column="n_Product" />
      <one-to-many class="CTV.ProductChannel, CTV" />
    </bag>

I'm doing my declaration with activerecord.

A: Have you tried setting a batch size
 <bag name="Affectations" ... batch-size='50'>

This will stop your n+1 problem and allow you to keep lazy loading. Basically setting batch-size to 50 will reduce the amount of queries issued to the database by a factor of 50. Without it set if you had 99 rows you would issue 99 queries to the database with batch-size set you would issue 2.

A: // subquery for the ids
var idsproduct = QueryOver.Of<Product>()
    .Where(...)
    .Take(10);
var affectation = _nhSession.QueryOver<Product>()
    .WithSubquery.Where(p => p.ID).In(idsproduct))
    .Fetch(p => p.Affectations).Eager
    .ToList();


text:
Q: Task Selection Problem I am trying to distribute 15 tasks to two people. Each task can only be assigned to one person and each person has a time budget.
I want to express this problem as a linear program (ultimately in the standard linear form) so that I can write a computer program to solve it.
\begin{array}{|c|c|c|c|c|}
\hline
Workers& Task 1 & Task2 & Task3 & ... & Time budget \\ \hline
 Jack& 0.5& 0.25& 0.25 & & 9\\ \hline
 John&  0.75& 1.0 &0.75 & & 8\\ \hline
\end{array}
I can find plenty of examples how to do it without a budget constraint. Without it, it is an Assignment Problem that can be solved with The Hungarian Method.

A: Hints: Let binary decision variable $x_{i,j}$ indicate whether person $i$ is assigned task $j$. Now you need a constraint that each task gets assigned to exactly one person, as well as a time budget constraint for each person.


text:
Q: How do I bind my properties from my ExpandedHomeSlider class to SPListItemCollection? I created the Public Classes HeroImage and ExpandedHomeSlider to access a custom list that will be given to the Repeater in order to allow the modifications of the SPListItem easily. How do I bind my properties from my ExpandedHomeSlider class to SPListItemCollection? I am new to SP development. Any help is appreciated :].
public partial class HomePageHeroRotator : UserControl
{
    public SPListItem SpListItem;

    public class HeroImage
    {
        public SPListItem SpListItem;
        public string heroImageUrl
        {
            get { return SpListItem["HeroImage"].ToString(); }
        }
        public string heroImageUrl2
        {
            get { return SpListItem["HeroImageCallOut"].ToString(); }
        }
    }
    public class ExpandedHomeSlider
    {
        public SPListItem SpListItem;
        public string explanatoryText
        {
            get { return SpListItem["ExplanatoryText"].ToString(); }
        }
        public string attentionExplanatoryText2
        {
            get { return SpListItem["ExplanatoryText"].ToString(); }
        }
        public string explanatoryText2
        {
            get { return SpListItem["ExplanatoryText"].ToString(); }
        }
        public string homeSliderImageUrl
        {
            get { return SpListItem["ExpandedSliderImage"].ToString(); }
        }
        public string GreenFlyoutText
        {
            get { return SpListItem["GreenFlyoutText"].ToString(); }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Query List for all List Items
        //ASCX to render list items
        SPSite site = null;
        if (SPContext.Current != null)
        {
            site = SPContext.Current.Site;
        }
        SPList list = site.RootWeb.Lists["HomePageHero"];

        SPListItemCollection myItems = list.Items;
        IEnumerable eList = myItems.Fields as IEnumerable;

        //foreach loop

        HomePageHeroRpt.DataSource = eList;
        HomePageHeroRpt.DataBind();

}
My Schema.xml List has these fields:
        <ViewFields>
      <FieldRef Name="LinkTitle" />
      <FieldRef Name="ExplanatoryText" />
      <FieldRef Name="GreenFlyoutText" />
      <FieldRef Name="BrownFlyoutText" />
      <FieldRef Name="RedFlyoutText" />
      <FieldRef Name="OrangeFlyoutText" />
      <FieldRef Name="LightBlueFlyoutText" />
      <FieldRef Name="BlueFlyoutText" />
      <FieldRef Name="AttentionExplanatoryText" />
      <FieldRef Name="ExplanatoryText2" />
      <FieldRef Name="HeroImage" />
      <FieldRef Name="HeroImageCallOut" />
      <FieldRef Name="ExpandedSliderImage" />
    </ViewFields>

A: The first think you need to do is transform your collection of SPListItem objects into a collection of your custom objects.  Select is a LINQ method that can do this for you.  Then you can just bind that to your repeater:
HomePageHeroRpt.DataSource = list.Items.Cast<SPListItem>()
    .Select(item => new ExpandedHomeSlider(){SpListItem = item});

On a site note there is a tool called "SPMetal" that is capable of generating classes like this for you, so that you don't need to create them on your own.  (They have their fair bit of design differences, but the general goal of having a property for each field is the same.)


text:
Q: No result from DSolve I don't get any answer when I evaluate the following expression:
DSolve[{x'[t] == -0.5*y[t] + 1 + 3*(e^(-2*t)),
        y'[t] == 2*x[t] - y[t] - 4 - 4* (e^(-t)),
        y[0] == 0, x[0] == 0}, {x[t], y[t]} , t]

Did I go wrong somewhere?
I tried solving this equation set with Laplace as well, but I didn't get any answer from that either.

A: Try replacing  the .5by 1/2 and the e by E. Also, the asterisks aren't needed in Mathematica.
s = DSolve[
 {x'[t] == -1/2 y[t] + 1 + 3 E^(-2 t),
  y'[t] == 2 x[t] - y[t] - 4 - 4 E^(-t),
  y[0]  == 0,
  x[0]  == 0}, {x[t], y[t]}, t]

ParametricPlot[{x[t], y[t]} /. s, {t, 0, 10}, AxesOrigin -> {0, 0}]

A: Two problems here are e instead of E and 0.5 instead of 1/2. For a larger system it would be more reasonable to use Rationalize instead of substituting all numbers by hand. To get a wider class of solutions we could define a function being a solution of the system of differential equations, where the initial values are parametrized by x0:
ds[x0_] = Simplify @ DSolve[ Rationalize @ {x'[t] == -0.5*y[t] + 1 + 3*(E^(-2*t)),
                                            y'[t] == 2*x[t] - y[t] - 4 - 4*(E^(-t)),
                                            y[0] == 0,
                                            x[0] == x0},     {x[t], y[t]}, t]

originally x0 == 0, i.e.
ds[0]

To plot the wider class of solutions we could use ParametricPlot as in belisarius answer with Show emphasizing ds[0] solution as a red thick curve :
Show[
      ParametricPlot[{x[t], y[t]} /. Table[ds[x0], {x0, -2, 4, 0.2}],
                                                   {t, -1, 10}, Evaluated -> True],
      ParametricPlot[{x[t], y[t]} /. ds[0], {t, -1, 10},
                                             PlotStyle -> {Darker@Red, Thickness[0.007]}],
      AxesOrigin -> {0, 0}, PlotRange -> {{-1, 6}, {-4, 5}}]


text:
Q: I am getting an error while exporting to Excel I want to transfer the data from dataGridView to Excel. For this, I added the "Microsoft.Office.Interop.Excel" plug-in to my project. I wrote the necessary codes properly. But when I run the project and click the "Export to Excel" button, I get an error. What should I do?
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DuyuTekStokApp
{
    public partial class StockAll : Form
    {
        SqlConnection connect = new SqlConnection("Data Source=DESKTOP-L01MAVE;Initial Catalog='StockControl';Integrated Security=True");
        public StockAll()
        {
            InitializeComponent();
        }
        public void VerileriGoster(string Veriler)
        {
            SqlDataAdapter da = new SqlDataAdapter(Veriler, connect);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridViewAll.DataSource = ds.Tables[0];
        }
        public void changeHeader()
        {
            dataGridViewAll.Columns[0].HeaderText = "Stok Kodu";
            dataGridViewAll.Columns[1].HeaderText = "Stok Cinsi";
            dataGridViewAll.Columns[2].HeaderText = "Barkod Numarası";
            dataGridViewAll.Columns[3].HeaderText = "Birimi";
            dataGridViewAll.Columns[4].HeaderText = "Grubu";
            dataGridViewAll.Columns[5].HeaderText = "Tarih";
            dataGridViewAll.Columns[6].HeaderText = "Açıklama";
            dataGridViewAll.Columns[7].HeaderText = "Sınıfı";
            dataGridViewAll.Columns[8].HeaderText = "Değişim Tarihi";
            dataGridViewAll.Columns[9].HeaderText = "Adeti";
            dataGridViewAll.Columns[10].HeaderText = "Kritik Miktar";
            dataGridViewAll.Columns[11].HeaderText = "Resim";
        }
        private void StockAll_Load(object sender, EventArgs e)
        {
            connect.Open();
            SqlCommand cmd1 = new SqlCommand("SELECT COUNT(*) FROM StockCard", connect);
            SqlDataReader dr1 = cmd1.ExecuteReader();
            while (dr1.Read())
            {
                labelToplam.Text = dr1[0].ToString();
            }
            connect.Close();

            connect.Open();
            SqlCommand cmd2 = new SqlCommand("SELECT SUM(StokAdet) FROM StockCard", connect);
            SqlDataReader dr2 = cmd2.ExecuteReader();
            while (dr2.Read())
            {
                labelGenel.Text = dr2[0].ToString();
            }
            connect.Close();

            VerileriGoster("SELECT StokKodu, StokCinsi, StokBarkod, StokBirim, StokGrup, StokTarih, StokAciklama, StokSinif, StokSonTarih, StokAdet, StokKritik, StokResim FROM StockCard ORDER BY StokKodu ASC");
            //VerileriGoster(@"SELECT dbo.StockCard.StokKodu, dbo.StockCard.StokBarkod, dbo.StockCard.StokBirim, dbo.StockCard.StokGrup, dbo.StockCard.StokTarih, dbo.StockCard.StokResim, dbo.StockMove.MoveAdet, dbo.StockMove.MoveMevcut, dbo.StockMove.MoveSinif, dbo.StockMove.MoveTarih
            //                     FROM  dbo.StockMove INNER JOIN
            //                  dbo.StockCard ON dbo.StockMove.StokID = dbo.StockCard.StokID ORDER BY StokKodu ASC ");
            changeHeader();
        }

        private void dataGridViewAll_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int secilen = dataGridViewAll.SelectedCells[0].RowIndex;
            labelUrun.Text = dataGridViewAll.Rows[secilen].Cells[9].Value?.ToString();
            labelKrit.Text = dataGridViewAll.Rows[secilen].Cells[10].Value.ToString();
            byte[] bytes = (byte[])dataGridViewAll.Rows[secilen].Cells[11].Value;
            MemoryStream ms = new MemoryStream(bytes);
            pictureBoxResim.Image = Image.FromStream(ms);
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            worksheet = workbook.Sheets["Sheet1"];
            worksheet = workbook.ActiveSheet;
            worksheet.Name = "Stok Bilgisi";

            for (int i = 1; i < dataGridViewAll.Columns.Count + 1; i++)
            {
                worksheet.Cells[i, 1] = dataGridViewAll.Columns[i - 1].HeaderText;
            }

            for (int i = 0; i < dataGridViewAll.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridViewAll.Columns.Count; i++)
                {
                    worksheet.Cells[i + 2, j + 1] = dataGridViewAll.Rows[i].Cells[j].Value.ToString();
                }
            }

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "StokBilgisi";
            saveFileDialog.DefaultExt = ".xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                workbook.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            app.Quit();

        }
    }
}

This is the error message I get:
System.InvalidCastException
  HResult = 0x80004002
  Message = COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' could not be assigned to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with the IID '{000208D5-0000-0000-C000-000000000046}' failed with the following error: Error loading type library / DLL. (HRESULT returned exception: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).
  Source = mscorlib
  StackTrace:
   at System.StubHelpers.StubHelpers.GetCOMIPFromRCW (Object objSrc, IntPtr pCPCMD, IntPtr & ppTarget, Boolean & pfNeedsRelease)
   at Microsoft.Office.Interop.Excel.ApplicationClass.get_Workbooks ()
   at SenseTekStokApp.StockAll.btnExcel_Click (Object sender, EventArgs e) in D: \ yNs \ VisualTutorials \ SenseTekStokApp \ SenseTekStokApp \ StockAll.cs: line 84
   at System.Windows.Forms.Control.OnClick (EventArgs e)
   at System.Windows.Forms.Button.OnClick (EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp (MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp (Message & m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc (Message & m)
   at System.Windows.Forms.ButtonBase.WndProc (Message & m)
   at System.Windows.Forms.Button.WndProc (Message & m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage (Message & m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc (Message & m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback (IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW (MSG & msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop (IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner (Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop (Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run (Form mainForm)
   at SenseTekStokApp.Program.Main () in D: \ yNs \ VisualTutorials \ SenseTekStokApp \ SenseTekStokApp \ Program.cs: line 19

A: In essence, to use EPPlus (per comments) to save your grid to an excel file:

private void btnExcel_Click(object sender, EventArgs e)
{
  var saveFileDialog = new SaveFileDialog();
  saveFileDialog.FileName = "StokBilgisi";
  saveFileDialog.DefaultExt = ".xlsx";
  if (saveFileDialog.ShowDialog() == DialogResult.OK)
  {

    using (ExcelPackage pck = new ExcelPackage(new FileInfo(saveFileDialog.FileName)))
    {
      ExcelWorksheet ws = pck.Workbook.Worksheets.Add("StokBilgisi");
      ws.Cells["A1"].LoadFromDataTable(dataGridViewAll.DataSource as DataTable, true);
      pck.Save();
    }
  }

This is the code from the linked question/answer, adjusted for your context by insertion of dataGridViewAll.DataSource as DataTable to retrieve the datatable you bound to the grid when you called dataGridViewAll.DataSource = ds.Tables[0]; in VerileriGoster, plus some other fluff like selecting the filename to save with a SaveFileDialog

A: You can try the following steps to convert datagirdview to excel.
First, please install nuget-package Microsoft.Office.Interop.Excel.
Second, please using it in the code.
using Excel=Microsoft.Office.Interop.Excel;

Third, I suggest that you can convert datagirdview to datatable first then you can convert datatable to excel.
private void button1_Click(object sender, EventArgs e)
        {
            DataTable table = (DataTable)dataGridView1.DataSource;
            ExportToExcel(table);
        }

 public void ExportToExcel(DataTable tbl )
        {
            try
            {
                if (tbl == null || tbl.Columns.Count == 0)
                    throw new Exception("ExportToExcel: Null or empty input table!\n");

                // load excel, and create a new workbook
                var excelApp = new Excel.Application();
                var workbook=excelApp.Workbooks.Add();

                // single worksheet
                Excel._Worksheet workSheet = excelApp.ActiveSheet;

                // column headings
                for (var i = 0; i < tbl.Columns.Count; i++)
                {
                    workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
                }

                // rows
                for (var i = 0; i < tbl.Rows.Count; i++)
                {
                    // to do: format datetime values before printing
                    for (var j = 0; j < tbl.Columns.Count; j++)
                    {
                        workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
                    }
                }

                try
                {
                    var saveFileDialog = new SaveFileDialog();
                    saveFileDialog.FileName = "StokBilgisi";
                    saveFileDialog.DefaultExt = ".xlsx";
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        workbook.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    }
                    excelApp.Quit();
                    Console.WriteLine("Excel file saved!");
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                    + ex.Message);
                }

            }
            catch (Exception ex)
            {
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }


text:
Q: switch to new window after clicking on the hyperlink using selenium Can anyone help me how to switch to new window after clicking on a hyperlink using selenium while doing automation . I have tried the following code but my test case is failing :
public void openView(){

        final WebElement visa=driver.findElement(By.id("pageContainer"));
        timeOut(10000);
        final List<WebElement> images=visa.findElements(By.className("nametag"));
        String handlewindow = driver.getWindowHandle();
        for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
        }
        images.get(0).findElement(By.className("info")).findElement(By.tagName("a")).click();;

A: This what we're using (Java):
public void switchToLatestPopupWindow()
{
    Iterator<String> handleIterator = this.driver.getWindowHandles().iterator();
    while (handleIterator.hasNext())
    {
        String handle = handleIterator.next();
        if (!handleIterator.hasNext())
        {
            this.driver.switchTo().window(handle);
        }
    }
}

public void resetToMainWindow()
{
    Iterator<String> handleIterator = this.driver.getWindowHandles().iterator();
    String parentHandle = null;
    while (handleIterator.hasNext())
    {
        String handle = handleIterator.next();
        if (parentHandle == null)
        {
            parentHandle = handle;
        } else if (!parentHandle.equals(handle))
        {
            this.driver.switchTo().window(handle);
            this.driver.close();
        }
    }
    this.driver.switchTo().window(parentHandle);
}

A: Assuming that the last line of code:
images.get(0).findElement(By.className("info")).findElement(By.tagName("a")).click()

opens a new window, you are fetching the window handle of the parent window itself before the child window opens after click().
Secondly, here is the code for switching to a child window:
String handlewindow = driver.getWindowHandles().toArray()[1];
driver.switchTo().window(handlewindow);

The explanation is that driver.getWindowHandles() returns a Set of all open windows handles. Convert the Set to array and fetch the element at index 1 as child window is at 1, parent window is at 0.

A: Use this code picked up from another thread on Stackoverflow ...
WebElement link = driver.findElement(By.linkText("<your link text>"));
Actions newwin = new Actions(driver);
newwin.keyDown(Keys.CONTROL).click(link).keyUp(Keys.CONTROL).build().perform();

I checked this and it opens the link in a new tab. Then use this code to switch to the new tab ...
String handlewindow = driver.getWindowHandles().toArray()[1];
driver.switchTo().window(handlewindow);

A: In the for loop we need to check if the current window handle is not equal to the one which is fetched by the loop
String handlewindow = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
    if (! handlewindow.equals (winHandle))
        driver.switchTo().window(winHandle);
}

A:     Actions ac  = Actions(driverObj);
    String parentHandle = driverObj.getWindowHandle();
    WebElement we = driverObj.findElement(By.xpath("here is your xpath"));
    ac.keyDown(Keys.CONTROL).click(we).keyUp(Keys.CONTROL).build().perform();
    String currentHandle ="";
    Set<String> win  = ts.getDriver().getWindowHandles();

    Iterator<String> it =  win.iterator();
    if(win.size() > 1){
        while(it.hasNext()){
            String handle = it.next();
            if (!handle.equalsIgnoreCase(parentHandle)){
                ts.getDriver().switchTo().window(handle);
                currentHandle = handle;
            }
        }
    }
    else{
        System.out.println("Unable to switch");
    }

Using above code you can open any link in new tab..

A: For switching between tabs you can use this methods:
    public void switchToNextTab() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(1));
    }

    public void switchToPreviousTab() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(0));
    }


text:
Q: Try-Expect block not working I am a novice at programming.
The basic idea is, when user inputs data, the code should check the data. If the data is not numerical. Instead of showing valueerror, it should show "Please enter only numbers!" message.
    number1 = int(input("Enter "))
    try:
        temp = number1/1
    except ValueError:
        msg = "Please enter only numbers!"
        print(msg)

But the code is not working as intended and showing this
Error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
number1 = int(input("Enter "))
ValueError: invalid literal for int() with base 10: 'aa'

Please let me know where I'm going wrong?

A: try catches error only inside its scope, the line which threw the error in your code is not in try block, do this:
try:
    number1 = int(input("Enter "))
    temp = number1/1
except ValueError:
    msg = "Please enter only numbers!"
    print(msg)


text:
Q: Badges earned today. vs. UTC time On Stack Overflow clicking on the dropdown by my name, it says I've earned a nice question badge today. it also says the UTC time is 16:15.
Clicking on the badge it says 19 hours ago, next to the question.
I was quite confused until I figured that it's when the question was posted, rather than when I got the badge.
Should this be changed to show when I got the badge instead of when I posted the question that received the badge?


text:
Q: Node.js + Puppeteer on Docker, No usable sandbox i'm building a node.js LTS application.
I followed puppeteer documentation, so my Dockerfile has this content:
FROM node:12.18.0

WORKDIR /home/node/app
ADD package*.json ./

# Install latest chrome dev package and fonts to support major charsets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others)
# Note: this installs the necessary libs to make the bundled version of Chromium that Puppeteer
# installs, work.
RUN apt-get update \
    && apt-get install -y wget gnupg \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
    && apt-get update \
    && apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf \
      --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

# Install node modules
RUN npm i

# Add user so we don't need --no-sandbox.
RUN groupadd -r -f audio \
    && groupadd -r -f video \
    && usermod -a -G audio,video node \
    && mkdir -p /home/node/Downloads \
    && chown -R node:node /home/node

USER node

CMD ["google-chrome-unstable"]

Application builds and runs well, but as soon as i try to start browser with await puppeteer.launch(); i get this error:
pdf    | Error: Failed to launch the browser process!
pdf    | [0612/133635.958777:FATAL:zygote_host_impl_linux.cc(116)] No usable sandbox! Update your kernel or see https://chromium.googlesource.com/chromium/src/+/master/docs/linux/suid_sandbox_development.md for more information on developing with the SUID sandbox. If you want to live dangerously and need an immediate workaround, you can try using --no-sandbox.
pdf    | #0 0x5638d5faa399 base::debug::CollectStackTrace()
pdf    | #1 0x5638d5f0b2a3 base::debug::StackTrace::StackTrace()
pdf    | #2 0x5638d5f1cc95 logging::LogMessage::~LogMessage()
pdf    | #3 0x5638d77f940e service_manager::ZygoteHostImpl::Init()
pdf    | #4 0x5638d5ad5060 content::ContentMainRunnerImpl::Initialize()
pdf    | #5 0x5638d5b365e7 service_manager::Main()
pdf    | #6 0x5638d5ad3631 content::ContentMain()
pdf    | #7 0x5638d5b3580d headless::(anonymous namespace)::RunContentMain()
pdf    | #8 0x5638d5b3550c headless::HeadlessShellMain()
pdf    | #9 0x5638d35295a7 ChromeMain
pdf    | #10 0x7fc01f0492e1 __libc_start_main
pdf    | #11 0x5638d35293ea _start
pdf    |
pdf    | Received signal 6
pdf    | #0 0x5638d5faa399 base::debug::CollectStackTrace()
pdf    | #1 0x5638d5f0b2a3 base::debug::StackTrace::StackTrace()
pdf    | #2 0x5638d5fa9f35 base::debug::(anonymous namespace)::StackDumpSignalHandler()
pdf    | #3 0x7fc0255f30e0 (/lib/x86_64-linux-gnu/libpthread-2.24.so+0x110df)
pdf    | #4 0x7fc01f05bfff gsignal
pdf    | #5 0x7fc01f05d42a abort
pdf    | #6 0x5638d5fa8e95 base::debug::BreakDebugger()
pdf    | #7 0x5638d5f1d132 logging::LogMessage::~LogMessage()
pdf    | #8 0x5638d77f940e service_manager::ZygoteHostImpl::Init()
pdf    | #9 0x5638d5ad5060 content::ContentMainRunnerImpl::Initialize()
pdf    | #10 0x5638d5b365e7 service_manager::Main()
pdf    | #11 0x5638d5ad3631 content::ContentMain()
pdf    | #12 0x5638d5b3580d headless::(anonymous namespace)::RunContentMain()
pdf    | #13 0x5638d5b3550c headless::HeadlessShellMain()
pdf    | #14 0x5638d35295a7 ChromeMain
pdf    | #15 0x7fc01f0492e1 __libc_start_main
pdf    | #16 0x5638d35293ea _start
pdf    |   r8: 0000000000000000  r9: 00007ffcd14664d0 r10: 0000000000000008 r11: 0000000000000246
pdf    |  r12: 00007ffcd1467788 r13: 00007ffcd1466760 r14: 00007ffcd1467790 r15: aaaaaaaaaaaaaaaa
pdf    |   di: 0000000000000002  si: 00007ffcd14664d0  bp: 00007ffcd1466710  bx: 0000000000000006
pdf    |   dx: 0000000000000000  ax: 0000000000000000  cx: 00007fc01f05bfff  sp: 00007ffcd1466548
pdf    |   ip: 00007fc01f05bfff efl: 0000000000000246 cgf: 002b000000000033 erf: 0000000000000000
pdf    |  trp: 0000000000000000 msk: 0000000000000000 cr2: 0000000000000000
pdf    | [end of stack trace]
pdf    | Calling _exit(1). Core file will not be generated.
pdf    |
pdf    |
pdf    | TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md
pdf    |
pdf    |     at onClose (/home/node/app/node_modules/puppeteer/lib/launcher/BrowserRunner.js:159:20)
pdf    |     at Interface.<anonymous> (/home/node/app/node_modules/puppeteer/lib/launcher/BrowserRunner.js:149:65)
pdf    |     at Interface.emit (events.js:327:22)
pdf    |     at Interface.close (readline.js:416:8)
pdf    |     at Socket.onend (readline.js:194:10)
pdf    |     at Socket.emit (events.js:327:22)
pdf    |     at endReadableNT (_stream_readable.js:1221:12)
pdf    |     at processTicksAndRejections (internal/process/task_queues.js:84:21)

oh yeah, container name is pdf
I tried looking at puppeteer troubleshooting page as suggested, but i didn't found any solution.
Any suggestions?

A: You should pass --no-sandbox, --disable-setuid-sandbox args when launch browser. this is my docker file and small script. it's run successfully.
You can know more about puppeteer with docker by this references.

*

*https://github.com/buildkite/docker-puppeteer

*https://github.com/alekzonder/docker-puppeteer
Dockerfile

FROM node:12.18.0

RUN  apt-get update \
     && apt-get install -y wget gnupg ca-certificates \
     && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
     && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
     && apt-get update \
     # We install Chrome to get all the OS level dependencies, but Chrome itself
     # is not actually used as it's packaged in the node puppeteer library.
     # Alternatively, we could could include the entire dep list ourselves
     # (https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md#chrome-headless-doesnt-launch-on-unix)
     # but that seems too easy to get out of date.
     && apt-get install -y google-chrome-stable \
     && rm -rf /var/lib/apt/lists/* \
     && wget --quiet https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh -O /usr/sbin/wait-for-it.sh \
     && chmod +x /usr/sbin/wait-for-it.sh

# Install Puppeteer under /node_modules so it's available system-wide
ADD package.json package-lock.json /
RUN npm install

CMD ["node", "index.js"]

index.js
const puppeteer = require('puppeteer');

(async() => {

    const browser = await puppeteer.launch({
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox'
        ]
    });

    const page = await browser.newPage();

    await page.goto('https://www.google.com/', {waitUntil: 'networkidle2'});

    browser.close();

})();

A: I finally found out how to run it with the sandbox but on my local machine only. I just had to read and apply the documentation on the official github repo:
The part I was missing was to run the image with the --cap-add=SYS_ADMIN option:
docker run --cap-add=SYS_ADMIN <YOUR_IMAGE_NAME>

However, this looks like a security flow because it seems to give your container some access to your host. And that's not necessarily what you want to do if you're reading this because you absolutely want to use the Chrome sandbox.
My final usecase is to run my container on Cloud Run, and in no way they are going to allow such a flag in my opinion. I'll edit my answer if I finally get it to work on Cloud Run with the sandbox...
EDIT: Nevermind it just works without any flag on Cloud Run! So yeah, I'll keep using the --cap-add=SYS_ADMIN flag on my development machine, which seems fine to me.

Here is my complete Dockerfile that works for me right now:
FROM node:14-slim

WORKDIR /app

RUN apt-get update \
    && apt-get install -y wget gnupg \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
    && apt-get update \
    && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \
      --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

COPY . .

RUN yarn \
    && groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \
    && mkdir -p /home/pptruser/Downloads \
    && chown -R pptruser:pptruser /home/pptruser \
    && chown -R pptruser:pptruser /app

# Run everything after as non-privileged user.
USER pptruser

CMD node src/index.js

And my src/index.js file:
const puppeteer = require('puppeteer')

const main = async () => {
  console.log('Starting browser')
  const browser = await puppeteer.launch()
  console.log('Opening a new page')
  const page = await browser.newPage()
  console.log('Navigating to google')
  await page.goto('https://www.google.fr', {
    waitUntil: 'networkidle2'
  })
  console.log('closing browser')
  await browser.close()
}

main()

A: I found a way that allows the use of chrome sandbox, thanks to usethe4ce's answer in here
Initially i needed to install chrome separately from puppeteer, i edited my Dockerfile as following:
FROM node:12.18.0

WORKDIR /home/runner/app
ADD package*.json ./

# Install latest chrome dev package and fonts to support major charsets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others)
# Note: this installs the necessary libs to make the bundled version of Chromium that Puppeteer
# installs, work.
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
    && apt-get update \
    && apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst ttf-freefont \
        --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

# Uncomment to skip the chromium download when installing puppeteer. If you do,
# you'll need to launch puppeteer with:
#     browser.launch({executablePath: 'google-chrome-unstable'})
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true

# Install node modules
RUN npm i\
    # Add user so we don't need --no-sandbox.
    # same layer as npm install to keep re-chowned files from using up several hundred MBs more space
    && groupadd -r runner && useradd -r -g runner -G audio,video runner \
    && mkdir -p /home/runner/Downloads \
    && chown -R runner:runner /home/runner \
    && chown -R runner:runner /home/runner/app/node_modules

USER runner

CMD ["google-chrome-unstable"]

Doing that, error changed from No usable sandbox to:
Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted

Then i followed usethe4ce's answer advices.
Docker by default blocks accessibility to some kernel level operations, Seccomp options allow to "unlock" some of those operations that chrome needs to create his own sandbox.
So i added this chrome.json file to my repo, and i edited my docker-compose file as following:
version: "3.8"

services:
  <service name>:
    build:
      <build options>
    init: true
    security_opt:
      - seccomp=<path to chrome.json file>
    [...]

If you are not using a docker-compose file you can run your container using the option --security-opt seccomp=path/to/chrome.json as suggested in the linked answer.
Finally launch the browser using:
await puppeteer.launch({
  executablePath: 'google-chrome-unstable'
});

Edit:
It is not suitable to use a custom installation of chrome, as its version could not be fully supported by puppeteer.
The only version guarantied to work with a specific puppeteer version is the one bundled.
So i suggest using security_opt as above, just ignore the custom installation part.

A: Even though a bad security practice --privileged flag did the trick for me.
(Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted)


text:
Q: Website is taking a long time to load style.css Everything else in my website is loading perfectly fine.
My style.css on the other hand takes around 15 seconds for me to load.
The only idea I have behind it taking this long is because I'm trying to load an external font onto the webpage that is 1.7mb. I then downloaded FontForge and went ahead and removed all the fonts except for the few letters I needed.
The size for the font is now 184KB. I refreshed my website and the style.css still takes around 15 seconds to load.
The problem is, how can I find out what is making my website take 15 seconds to load style.css
Here is my style.css regarding the fonts
@font-face {
    font-family: Gabriola;
    src: url('../fonts/gabriola.eot');
    src: url('../fonts/gabriola.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
    url('../fonts/gabriola.woff') format('woff'), /* Pretty Modern Browsers */
    url('../fonts/gabriola.ttf')  format('truetype'), /* Safari, Android, iOS */
}

And here is the folder with the fonts and sizes

A: Open your browser's dev tools, turn on monitoring for performance and network, and load your site, then look at the results for both of those two things. You can also try loading your site in https://developers.google.com/speed/pagespeed/insights/ and see what it tells you is making your site so slow.


text:
Q: Control Dielectric vs. Controlled Impedance Can you tell me what the differences are between Controlled Dielectric and Controlled Impedance.  Also what is a TDR report?
I'd appreciate it.

A: Controlled impedance implies that the the PCB is manufactured so that the impedance of traces are within a certain percentage of a specified value. Controlled Dielectric merely specifies that the dielectric constant of the PCB substrate is within a certain percentage of a specific value.
A controlled impedance board generally also has a controlled dielectric substrate, but the inverse is not necessarily true.
Advanced Circuits has a nice short overview here, and reproduced below.

Impedance is the sum of the resistance and reactance of an electrical circuit expressed in Ohms.  The resistance being the opposition to current flow present in all materials.  The reactance is the opposition to current flow resulting from the effect of the inherent capacitance and inductance of the conductor interacting with changes in voltage and current.  In DC circuits there is no reactance and the resistance of copper conductors is typically insignificant.  However in high speed AC circuits (those with sharp changes in voltage and/or current) the reactance and thus the impedance can become very significant.  This can become critical to a design's functionality because of the effects that changes in the impedance along the signals path from transmitter to receiver will have on the efficiency of power transfer as well as signal integrity.   While a circuit's speed is often expressed as the frequency of the wave form: the critical concern is the speed at which the voltage and/or current is required to change.
Controlled Delectric
The typical design considerations involved in the determination of the requirement for controlling the impedance are the strength of the signals involved, the susceptibility of the circuit to noise and signal distortion, the criticality of signal timing and the speed at which the signal's source is attempting to force a change in voltage and/or current.
The design considerations for setting the value of the impedance for the conductor is typically the output impedance of the transmitter and the input impedance of the receiver.  The impedance of other conductors (i.e. coaxial cables) in the circuit path will also need to be considered.  The acceptable range (tolerance) for the impedance will need to be determined and taken into account during the design phase as well as when specifying the PCB parameters.  In many cases merely by using software models to determine the anticipated impedance with particular dielectric materials and spacing, followed by requesting these parameters be followed when the PCB's are fabricated will suffice.  This is what we call "controlled dielectric".  For more critical applications you will need to specify "controlled impedance" and supply the actual impedance requirements for the conductors and we will fine tune the dielectrics and conductors to meet these requirements.  The impedance requirements will have to be specified based on the layer and the conductor widths.

TDR is Time Domain Reflectometry. Basically it's a measure of the reflections and spurious signals in a conductor arising from the source coupling into non-ideal impedances (e.g. the connecting wiring and termination). It's a common tool used for very high speed digital and analog work.
Therefore, a TDR report is generally either a simulation of a circuit board which tries to account from all of the coupling of a trace into nearby traces and grounds, together with the input and output buffers and terminations of two (or more) chips connected by PCB traces, or an actual text of the circuit-board after it has been manufactured.


text:
Q: Internet Slow Down in VPN We've 10mb/sec line and we're getting the speed of 900KB/Sec normally but in VPN we're getting 15 to 18 KB/Sec.
In VPN we're using the client proxy server for internet. Also when we copy some data of 50 MB from client server to our local machine we get very slow response.
Please advice how much speed I can get in VPN at my site and as you know we've 10mbps line


text:
Q: ActiveRecord: perform a validation on method call only? I'm trying to call validation on an ActiveRecord after a certain method in another Ruby file is called. Is there some way I can tie this into ActiveRecord's validation scheme, i.e.:
validate :cars_have_wheels?, on: after_cache_reset
Note: cars_have_wheels? is a method located in the ActiveRecord object, after_cache_reset is the method in the other file.
Thank you!

A: Check out this link (Ruby on Rails guides):
5 Conditional Validation
Sometimes it will make sense to validate an object only when a given predicate is satisfied. You can do that by using the :if and :unless options, which can take a symbol, a string, a Proc or an Array. You may use the :if option when you want to specify when the validation should happen. If you want to specify when the validation should not happen, then you may use the :unless option.
5.1 Using a Symbol with :if and :unless
You can associate the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
class Order < ActiveRecord::Base
 validates :card_number, presence: true, if: :paid_with_card?

 def paid_with_card?
  payment_type == "card"
 end
end


text:
Q: asp.net ffmpeg video encoding hangs I have below methods to encode videos uploaded to a web site with ffmpeg. It works fine for videos up to 8-9 MB but, if video size is larger than 8-9 MB it hangs web site. Only way to recover it is restarting iis.
When i watch the process i can see that ffmpeg encodes video and exits. Resulted video is just fine. Problem starts as soon as ffmpeg exists.
Application runs on win2003 x86 webserver iis6
Anyone got experience with encoding large files from asp.net web app using ffmpeg?
public EncodedVideo EncodeVideo(VideoFile input, string encodingCommand, string outputFile)
    {
        EncodedVideo encoded = new EncodedVideo();
        Params = string.Format("-i \"{0}\" {1} \"{2}\"", input.Path, encodingCommand, outputFile);
        //string output = RunProcess(Params);
        string output = RunProcessLargeFile(Params);
        encoded.EncodingLog = output;
        encoded.EncodedVideoPath = outputFile;

        if (File.Exists(outputFile))
        {
            encoded.Success = true;
        }
        else
        {
            encoded.Success = false;
        }
        //System.Web.HttpContext.Current.Response.Write(Params);
        return encoded;

    }

private string RunProcessLargeFile(string Parameters)
    {
        /* The below will be the right solution ....
         * The while loop which reads the stream is very improtant
         * for FFMPEG as .NET does not provide more memory to FFMPEG.
         * When converting large files, FFMPEG's out put stream gets filled...
         * And waits for .NET to allocate memory resources but is never done.
         * In order to utilize less memory, we are clearing the buffer periodically.
         **/

        ProcessStartInfo oInfo = new ProcessStartInfo(this.FFmpegPath, Parameters);
        oInfo.WorkingDirectory = Path.GetDirectoryName(this.FFmpegPath);
        oInfo.UseShellExecute = false;
        oInfo.CreateNoWindow = true;
        oInfo.RedirectStandardOutput = true;
        oInfo.RedirectStandardError = true;
        Process proc = System.Diagnostics.Process.Start(oInfo);
        StreamReader srOutput = proc.StandardError;
        System.Text.StringBuilder output = new System.Text.StringBuilder();

        StreamReader objStreamReader = proc.StandardError;
        System.Text.StringBuilder sbOutPut = new StringBuilder();

        while (!proc.WaitForExit(1000))
        {
            sbOutPut.Append(objStreamReader.ReadToEnd().ToString());
        }

        if (proc.ExitCode == 0)
        {
            proc.Close();
            if (objStreamReader != null)
            {
                objStreamReader.Close();
            }
        }
        else
        {
            proc.Close();
            if (objStreamReader != null) objStreamReader.Close();
        }

        return sbOutPut.ToString();
    }

A: Smells like a typical deadlock.
You call proc.WaitForExit before proc.StandardError.ReadToEnd method and it seems cause a deadlock.
A reference from MSDN:

A deadlock condition can result if the
  parent process calls WaitForExit
  before StandardOutput.ReadToEnd and
  the child process writes enough text
  to fill the redirected stream. The
  parent process would wait indefinitely
  for the child process to exit. The
  child process would wait indefinitely
  for the parent to read from the full
  StandardOutput stream.

So replacing your while cycle to:
string output = objStreamReader.ReadToEnd();
proc.WaitForExit();

should solve your problem.

A: i am not a asp.net person i work with php and in php.ini which is a config file i can set the max amount of megabytes i am able to upload. maybe if you check the config file to see anything about uploading and set it to the maximum.


text:
Q: Getting Canonical Coordinates in differential equations from Lie Group I've been trying to understand how Lie Groups can help solve differential equations (this 12-page pdf is the most straightforward explanation I've seen).
My understanding is that when a first-order differential equation $\frac{dy}{dx}=h(x,y)$ has a continuous "translation symmetry" $(x,y)\mapsto(x,y+\lambda)$, it becomes very easy to solve the equation using basic integration of one variable.
The problem is that most differential equations in standard $(x,y)$ coordinates don't have this nice translation symmetry, and so we need to change to a set of "canonical coordinates" $(X,Y)$ which do have the desired translation symmetry $(X,Y)\mapsto(X,Y+\lambda)$.
The main condition that these new canonical coordinates need to satisfy, is that the $Y$ coordinate should be aligned with the $\lambda$ variable ($\frac{dY}{d\lambda}=1,\frac{dX}{d\lambda}=0$), so that we get the nice translation symmetry we want:
$$\frac{dY}{d\lambda}=\frac{dY}{dx}\frac{dx}{d\lambda}+\frac{dY}{dy}\frac{dy}{d\lambda}=Y_x\xi+Y_y\eta=1$$
$$\frac{dX}{d\lambda}=\frac{dX}{dx}\frac{dx}{d\lambda}+\frac{dX}{dy}\frac{dy}{d\lambda}=X_x\xi+X_y\eta=0$$
We also require that the symmetry condition be satisfied:
$$\frac{dY}{dX}=\frac{D_xY}{D_xX}=\frac{Y_x+Y_y y'}{X_x+X_y y'}=h(X,Y)$$
Here's where I'm stuck. Basically all the terms in the above equations are unknowns, and it seems incredibly difficult to solve for the new coordinates $(X,Y)$. I've also seen the "linearized symmetry condition" below, but it still results in a difficult-to-solve equation:
$$\eta_x-\xi_y h^2 +(\eta_y -\xi_x)h - (\xi h_x + \eta h_y) = 0$$
Is there a nice, algorithmic approach for deducing a set of canonical coordinates? Or does it ultimately come down to "guess and check" with the above equation?


text:
Q: Lookup [HOST]: no such host error in Go I have this test program which will fetch url parallel, but when I increase the parallel number to about 1040, I start to get lookup www.httpbin.org: no such host error.
After some Google, I found others say that not close the response will cause the problem, but I do close that with res.Body.Close().
What's the problem here? thanks very much.
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func get(url string) ([]byte, error) {

    client := &http.Client{}
    req, _ := http.NewRequest("GET", url, nil)

    res, err := client.Do(req)

    if err != nil {
        fmt.Println(err)
        return nil, err
    }

    bytes, read_err := ioutil.ReadAll(res.Body)
    res.Body.Close()

    fmt.Println(bytes)

    return bytes, read_err
}

func main() {
    for i := 0; i < 1040; i++ {
        go get(fmt.Sprintf("http://www.httpbin.org/get?a=%d", i))
    }
}

A: well technically your process is limited (by the Kernel) to about 1000 open file descriptors. Depending on the context you might need to increase this number.
In your shell run (note the last line):
$ ulimit -a
-t: cpu time (seconds)         unlimited
-f: file size (blocks)         unlimited
-d: data seg size (kbytes)     unlimited
-s: stack size (kbytes)        8192
-c: core file size (blocks)    0
-v: address space (kb)         unlimited
-l: locked-in-memory size (kb) unlimited
-u: processes                  709
-n: file descriptors           2560

To increase (temporarly):
$ ulimit -n 5000
(no output)

Then verify the fd limit:
$ ulimit -n
5000

A: That's because you may have up to 1040 concurrent calls in your code so you may very well be in a state with 1040 body opened and none yet closed.
You need to limit the number of goroutines used.
Here's one possible solution with a limit to 100 concurrent calls max :
func getThemAll() {
    nbConcurrentGet := 100
    urls :=  make(chan string, nbConcurrentGet)
    for i := 0; i < nbConcurrentGet; i++ {
        go func (){
            for url := range urls {
                get(url)
            }
        }()
    }
    for i:=0; i<1040; i++ {
        urls <- fmt.Sprintf("http://www.httpbin.org/get?a=%d", i)
    }
}

If you call this in the main function of your program, it may stop before all tasks are finished. You can use a sync.WaitGroup to prevent it :
func main() {
    nbConcurrentGet := 100
    urls :=  make(chan string, nbConcurrentGet)
    var wg sync.WaitGroup
    for i := 0; i < nbConcurrentGet; i++ {
        go func (){
            for url := range urls {
                get(url)
                wg.Done()
            }
        }()
    }
    for i:=0; i<1040; i++ {
        wg.Add(1)
        urls <- fmt.Sprintf("http://www.httpbin.org/get?a=%d", i)
    }
    wg.Wait()
    fmt.Println("Finished")
}