text:
Q: Getting the Drive letter of USB drive inserted I have detected the insertion of USB drive in my WPF application by following suggestions in given link How do I detect when a removable disk is inserted using C#?
but I am unable to figure out the Drive letter of the detected USB drive; my Code is given below
    static ManagementEventWatcher w = null;
    static void AddInsertUSBHandler()
    {

        WqlEventQuery q;
        ManagementScope scope = new ManagementScope("root\\CIMV2");
        scope.Options.EnablePrivileges = true;

        try {

            q = new WqlEventQuery();
            q.EventClassName = "__InstanceCreationEvent";
            q.WithinInterval = new TimeSpan(0, 0, 3);
            q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
            w = new ManagementEventWatcher(scope, q);
            w.EventArrived += USBInserted;

            w.Start();
        }
        catch (Exception e) {

            Console.WriteLine(e.Message);
            if (w != null)
            {
                w.Stop();

            }
        }

    }

    static void USBInserted(object sender, EventArgs e)
    {

        Console.WriteLine("A USB device inserted");

    }

Kindly guide me if possible.

A: Hope this helps, its code based on Neeraj Dubbey's answer.
We run code in a continuous multithreaded loop that keeps checking for a change in connected USB devices. Because we keep track of previously connected devices we can compare it against a new list of devices. We can also determine if a device is removed using the same method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Usb_Test
{
    class Program
    {
        private static List<USBDeviceInfo> previousDecices = new List<USBDeviceInfo>();

        static void Main(string[] args)
        {
            Thread thread = new Thread(DeviceDetection);
            thread.Start();

            Console.Read();
        }

        static void DeviceDetection()
        {
            while (true)
            {
                List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

                ManagementObjectCollection collection;
                using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
                    collection = searcher.Get();

                foreach (var device in collection)
                {
                    devices.Add(new USBDeviceInfo(
                    (string)device.GetPropertyValue("DeviceID")
                    ));
                }

                if (previousDecices == null || !previousDecices.Any()) // So we don't detect already plugged in devices the first time.
                    previousDecices = devices;

                var insertionDevices = devices.Where(d => !previousDecices.Any(d2 => d2.DeviceID == d.DeviceID));
                if (insertionDevices != null && insertionDevices.Any())
                {
                    foreach(var value in insertionDevices)
                    {
                        Console.WriteLine("Inserted: " + value.DeviceID); // Add your own event for the insertion of devices.
                    }
                }

                var removedDevices = previousDecices.Where(d => !devices.Any(d2 => d2.DeviceID == d.DeviceID));
                if (removedDevices != null && removedDevices.Any())
                {
                    foreach (var value in removedDevices)
                    {
                        Console.WriteLine("Removed: " + value.DeviceID); // Add your own event for the removal of devices.
                    }
                }

                previousDecices = devices;
                collection.Dispose();
            }
        }
    }

    class USBDeviceInfo
    {
        public USBDeviceInfo(string deviceID)
        {
            this.DeviceID = deviceID;
        }
        public string DeviceID { get; private set; }

    }
}

However this is not a great solution, you're a lot better off listening for WM_DEVICECHANGE.

Windows will send WM_DEVICECHANGE message to all applications whenever
  some hardware change occurs, including when a flash drive (or other
  removable device) is inserted or removed. The WParam parameter of this
  message contains code which specifies exactly what event occurred. For
  our purpose only the following events are interesting:
DBT_DEVICEARRIVAL - sent after a device or piece of media has been
  inserted. Your program will receive this message when the device is
  ready for use, at about the time when Explorer displays the dialog
  which lets you choose what to do with the inserted media.
DBT_DEVICEQUERYREMOVE - sent when the system requests permission to
  remove a device or piece of media. Any application can deny this
  request and cancel the removal. This is the important event if you
  need to perform some action on the flash drive before it is removed,
  e.g. encrypt some files on it. Your program can deny this request
  which will cause Windows to display the well-known message saying that
  the device cannot be removed now.
DBT_DEVICEREMOVECOMPLETE - sent after a device has been removed. When
  your program receives this event, the device is no longer available —
  at the time when Windows display its "device has been removed" bubble
  to the user.

Here are some links that each detail an answer on how to do this in C#:
http://www.codeproject.com/Articles/18062/Detecting-USB-Drive-Removal-in-a-C-Program
http://www.codeproject.com/Articles/60579/A-USB-Library-to-Detect-USB-Devices
Both solution should work, and you can always adapt them to fit your needs.

A: Hey try this console based code afetr adding the reference of System.Management in project
namespace ConsoleApplication1
{
 using System;
 using System.Collections.Generic;
 using System.Management; // need to add System.Management to your project references.

class Program
{
static void Main(string[] args)
{
    var usbDevices = GetUSBDevices();

    foreach (var usbDevice in usbDevices)
    {
        Console.WriteLine("Device ID: {0}", usbDevice.DeviceID);

    }

    Console.Read();
}

static List<USBDeviceInfo> GetUSBDevices()
{
    List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

    ManagementObjectCollection collection;
    using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
        collection = searcher.Get();

    foreach (var device in collection)
    {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID")
        ));
    }

    collection.Dispose();
    return devices;
}
}

class USBDeviceInfo
{
public USBDeviceInfo(string deviceID)
{
    this.DeviceID = deviceID;
}
public string DeviceID { get; private set; }

}


text:
Q: What is wrong with my java code, it won't compile? Okay so I typed a java code to do a simple function. Every time I enter it won't let me compile. Where is my error in this code?
public int add(int a, int b) {
 int sum;
 sum = a + b;
}
public static void main(String[] args){
 int x = 5;
 double y = 7;
 int total = add(x,y);
 System.out.println(total);
}

A: Multiple compiler errors:

*

*The add method is declared to return an int, but it has no return statement

*The main method is static, it cannot call the non-static method add

*The 2nd argument of add must be int, but in the call you're passing a double
Possible fixes:
public static int add(int a, int b) {
    return a + b;
}

public static void main(String[] args){
    int x = 5;
    int y = 7;
    int total = add(x, y);
    System.out.println(total);
}

A: You've written the add method to take two integer arguments, but have passed it an integer and a double.

A: i think it is because your method is not "static"

A: Your method add must return an int, and to call it without an instance it should be static. Like,
public static int add(int a, int b) {
    int sum;
    sum = a + b;
    return sum;
}

or
public static int add(int a, int b) {
    int sum = a + b;
    return sum;
}

or
public static int add(int a, int b) {
    return a + b;
}

or create a new instance of the class and call add on it (after fixing the return issue).

A: At first you hae to make some class. Class could be noun, one thing from the real life. For example Sum or a Number
Like this:
public class Sum {
    public int add(int a,int b) {
        return a+b;
    }

    public Sum() {
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Sum sum = new Sum();
        System.out.println(sum.add(6, 9));

    }

}

I think you should learn more about Object Oriented Programming.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS loadbalancer + Nginx + gunicorn - how to use ssl Im trying to use docker-machine to create ec2 instances with the stack nginx+gunicorn+django. I have an internet-facing Application Load balancer with two target groups (green/blue) to prevent any downtime in new deployment (new deployments gets deployed to the unused group, and the load balancer group is changed when everything checks out)
Everything works perfect with port 80, but when I try to add a listener for port 443 with a Amazon Issued Cert for that domain, I can't get it to work. Do I need to obtain certs from inside Nginx also? Do I need Nginx to listen to port 443? Targets?
Loadbalancer:
+------------+-----------------------------+----------------+
| Listener ID|            Rules.           | SSL Certificate|
+------------+-----------------------------+----------------+
| HTTP: 80   | Default: forwarding to blue.| N/A.           |
+------------+-----------------------------+----------------+
| HTTPS: 443 | Default: forwarding to blue.|Default: (ACM). |
+------------+-----------------------------+----------------+

Targets:
+------------+--------------+--------------+--------------+---------------+
|    Name    |     Port     |   Protocol   |  Target type | Load Balancer |
+------------+--------------+--------------+--------------+---------------+
| Blue       | 80           | HTTP         | instance     | loadbalancer  |
+------------+--------------+--------------+--------------+---------------+
| Green      | 80           | HTTP         | instance     |               |
+------------+--------------+--------------+--------------+---------------+

My Nginx conf:
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
  worker_connections  1024;
}

http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
  '$status $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  /var/log/nginx/access.log  main;

  sendfile        on;
  #tcp_nopush     on;

  keepalive_timeout  65;

  upstream app {
    server django:5000;
  }

  server {
    listen 80;
    charset utf-8;

    location = /favicon.ico {
        return 204;
        access_log     off;
        log_not_found  off;
    }

    location / {
        try_files $uri @proxy_to_app;
    }

    # django app
     location @proxy_to_app {
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_pass http://app;
    }
  }
}

A: Writing my own answer if any one else encounter this problem.
The security-group used to create the Ec2 instance needs to have incoming port 443 open. If your docker-compose file does not expose port 443, it will not automatically add the port as open on the security-group. You can manual open the port in the aws console for Ec2 under network & security.


text:
Q: xdvipdfmx typecheck problem I have a very simple .tex file:
\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf{blank.pdf}
\end{document}

When I compile this with xelatex (xelatex sample.tex) I get an error:
xdvipdfmx:fatal: typecheck: Invalid object type: -1 7 (line 2167)
No output PDF file written.
Error 1 (driver return code) generating output;
blank.pdf is a simple empty PDF page. "pdfinfo blank.pdf" returns this:
Title:
Creator:        Microsoft Word: cgpdftops CUPS filter
Producer:       Acrobat Distiller 9.4.2 (Macintosh)
CreationDate:   Tue Apr 19 11:41:26 2011 Romance Daylight Time
ModDate:        Mon May 13 12:38:48 2019 Romance Daylight Time
Tagged:         no
UserProperties: no
Suspects:       no
Form:           AcroForm
JavaScript:     no
Pages:          1
Encrypted:      no
Page size:      595.22 x 842 pts (A4)
Page rot:       0
File size:      14695 bytes
Optimized:      no
PDF version:    1.6

I think this has something to do with a recent update to MikTex, as I did not notice this problem before.
I'm lost here. Maybe I should downgrade my Latex installation? How? Any ideas?
Thank you very much


text:
Q: Why use a owner window in MessageBox.Show? MessageBox.Show has forms like MessageBox.Show( ownerWindow, .... ).
What do I gain by assigning a owner window?

A: Setting the owner causes the owner to be disabled while the message box is open.
If you don't set the owner then the user can click something else or even close the owner while the message box is open, then when the message box closes and the code after the call to MessageBox.Show runs your program can be in an unknown state - or if the owner was closed you are now running code inside a window that no longer exists and any calls to methods of WinForms or WPF (or for that matter also WinAPI and any other framework) are likely to cause a crash.

A: Based on testing and this other answer, .net will automatically choose the currently focused window in the same thread as your MessageBox.Show() call. To get the correct behavior, you must ensure that you display the MessageBox from the same thread as this window and specify the window the MessageBox is logically associated with as its owner. A MessageBox only modal-ly blocks input to other Forms on the thread from which it is launched. This is probably related to how MessageBox makes itself modal (maybe it intercepts messages aimed at the current thread and only allows some messages through to windows other than itself?). The effect of modal-ly blocking input is that the user will be unable to focus these windows or any controls inside of them and attempting to do so produces the "Ding" sound. Also, if the owner is not specified, the MessageBox will automatically select the active window on the current thread. If the currently active window is from a different thread (or different application!), the MessageBox will have no owner. That means it gets its own Task Bar entry: it behaves as its own distinct window. The user can raise other windows in your application (even if the user cannot interact with them). You can get the situation where your program stops responding to user input with the user confused because the user somehow raised your application's main window after the dialog was displayed. If the owner is properly set, however, trying to raise your main window will cause the MessageBox to be raised and blinked.
To make this all work nicely with child windows, ensure that each child window has its Owner property set. This will happen automatically if you call ShowDialog() (which makes your custom Form modal (and do pass its owner parameter in the same cases where you would pass owner to MessageBox.Show())).
Now, most winforms coding consists of writing code directly into event handlers inside a Form subclass. When writing winforms event handlers, you can assume many things. First, you should never have a call to this.Invoke() as a top level statement in a GUI event handler because such handlers are always run on the same thread as the Form subclass was created on. Secondly, for many (but not all) of these handlers, you can assume that the Form has focus (and would be thus automatically chosen by MessageBox.Show() as its owner). For example, when writing code inside of a button's Click event handler (possibly called button1_Click), you can safely assume that the form is focused (because calling PerformClick() on another form's Button is bad practice). However, a Timer.Tick may happen even when your form is not focused. So, in the case of Timer.Tick, there is no need to Invoke() (just like any other winforms event handler) but there is a need to specify owner. This latter case is trickier to notice because the developer must have their application unfocused to notice that a dialog displayed in this case behaves slightly differently from when their application is focused. So, specify owner whenever you need to use Invoke() or if it is possible for the event to be triggered when the window is not focused. This guideline applies when calling MessageBox.Show() and Form.ShowDialog().
Most of what I discuss here is the result of messing around while reading the other answers.

A: A message box is a modal form, which means that its parent window is disabled until the message box is dismissed.
If a Show() overload is called that does not take an owner identifier, then a parent form is usually chosen automatically. I can't find anything in the documentation that describes how that form is chosen, but my experience is that if the message box is displayed inside the GUI thread (i.e., the main thread, or message pump thread), then the active window for that thread is chosen as the parent.
Other threads may create message boxes with no parent form. This could be a bad situation, because it could sit behind the active window, and the user will not even know it is there until they close the program. To avoid this, you could pass the handle of the application's main window to the Show method, which will disable that window for the duration of the message box.

ADDED: I've been thinking about this and now I'm not so sure. The snippet from reflector that you gave below makes me think that maybe the thread doesn't matter. (I did say that I couldn't find anything in the documentation!)
I'd have to go back and look at the code to make sure, but I think the message boxes that I used to lose behind the main form may have actually been custom message box forms, in which case my experience is faulty, and you never ever have to supply a parent form parameter.
Sorry for the confusion.
My recommendation now is to never supply this parameter unless you need something other than the active window to be the main form.

A: It turns out that window ownership is not transitive. In the case where you have form, spawning a form, spawning a MessageBox, The MessageBox.Show needs to use the ownerWindow parameter. The original form should be set as the owner window of the MessageBox.

A: Calling MessageBox.Show(frmMain,"a message","a title") adds the form TextDialog
to the application's Application.OpenForms() forms collection, along-side the frmMain Main form itself.  It remains after you close the Messagebox.
I just discovered 14 of these when I called btnOK_Click() and set a breakpoint.
When I called frmMain.Close() to close the main form, nothing happened.  frmMain will not close until all 14 of the Application.OpenForms are closed as well or else you must call Application.Exit().

A: if i'm not wrong this prevents to owner window to Focus() until the messagebox is closed.

A: Using Net Reflector, I just found this code in Messagebox.Show:
else if (owner == IntPtr.Zero)
    owner = UnsafeNativeMethods.GetActiveWindow();

So if you do not nested ownership ( window--(owns)-->window--(owns)->messageBox), leaving out the ownerWindow sets the owner you would normally choose.

A: The documentation seems to imply that the only purpose of the owner parameter is if you specify MB_HELP, the message box knows which window it should send the WM_HELP message to.
http://msdn.microsoft.com/en-us/library/ms645505%28VS.85%29.aspx

Oh, just realised the OP was about .net - I gave an answer about winapi - sorry!


text:
Q: Using bash, resolve absolute path to relative path Say I have this simple bash script:
#!/usr/bin/env bash

file="$1";

if [ -z "$file" ]; then
    echo "Must pass relative file path as the first argument.";
fi

git_root=`git rev-parse --show-toplevel`;

#  => need to resolve file from an absolute path to relative path, relative to git root

git diff HEAD:"$file" remotes/origin/dev:"$file"

If I pass an absolute path to this script, it needs to be able to handle it. What is the canonical way to do that? To check if it's an absolute file path, do we just check if the first character is "/"?

A: I am on MacOS, so I had to install coreutils:
brew install coreutils

then we can use realpath like so:
file=`realpath --relative-to="$git_root" "$file"`

or if you need something that works without having to install anything, you can use this node.js script:
#!/usr/bin/env node
'use strict';

const path = require('path');

const file = process.argv[2];
const relativeTo = process.argv[3];

if (!relativeTo) {
  console.error('must pass an absolute path as the second argument.');
  process.exit(1);
}

if (!file) {
  console.error('must pass a file as the first argument.');
  process.exit(1);
}

console.log(path.relative(relativeTo, file));


text:
Q: Removing  tag using regex I want to extract the plain text from given HTML code. I tried using regex and got
String target = val.replaceAll("<a.*", "");.
My main requirement is I want remove everything between  and   (including the Link name). While using the above code all other contents also removed.
Google This is a Google Link
Yahoo This is a Yahoo Link
Here I want to remove the values between  and .
Final output should
This is a Google Link  This is a Yahoo Link

A: Use a non-greedy quantifier (*?). For example, to remove the link entirely:
String target = val.replaceAll("<a.*?", "");

Or to replace the link with just the link tag's contents:
String target = val.replaceAll("]*>(.*?)", "This is a $1 Link");

However, I would still recommend using a proper DOM manipulation API.


text:
Q: An idea for approaching Brocard's problem ($n!+1=m^2$) When I first discovered this problem, I rewrote $n!+1=m^2$ like this:
$$n!=m^2-1$$
which can be rewritten like this:
$$n!=(m+1)(m-1)$$
From this, I've gathered the following:

*

*Because n! must contain a factor of 2 to satisfy the equation (smallest possible $n$ is $4$), $(m+1)(m-1)$ must be even; $m$ must be odd to satisfy this.

*Only one of either $(m+1)$ or $(m-1)$ can be divided by 2 to a power of more than one; the other one can be divided by 2, but to no greater power.

*Because prime factors greater than 2 can only occur once between 3 consecutive numbers, and because statement 2 implies that $(m+1)$ and $(m-1)$ have a GCF of 2, $\frac{m+1}{2}$ and $\frac{m-1}{2}$ must be coprime.

These statements hold true for all currently known solutions:
$$4!=5^2-1=4*6=6*4=(2*3)*(2^2)$$
$$5!=11^2-1=10*12=(2*5)*(2^2*3)$$
$$7!=71^2-1=70*72=(2*5*7)*(2^3*3^2)$$
So, is this information at all useful to solving/helping get around Brocard's problem?


text:
Q: JavaFX Frozen GUI When adding Button on flow panel How to add 5000 buttons or labels to flow panel without freezing GUI in JAVA FX Just like this
Why I even need so many buttons
well, I don't need that many but at least 500 - 1000. Coz I'm building an application Fonticon Tool
Slow is fine but not Freezing
It's ok if the application is slow and take a couple of seconds to show all button But I don't want it to freeze progress bar and GUI
How it works
I have an SQLite database with a couple of tables,
each table has a list of values. An object gives me ArrayList values
What I'm looking for
I'm looking for something like.
FlowPane fp = new FlowPane();

for(String fonticon_code : DatabaseTable.getlist()) //getlist() returns an array list of Strings
{
  fp.getChildren.add(new button().setGraphic(new FontIcon(fonticon_code)));

}

I also wanna be able to stop and restart Thread
What I tired
I tried Thread, Task, Platform.runLater(update);
but I'm not sure that I use them correctly

A: Here an MCVE using ControlsFX GridView.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.controlsfx.control.GridCell;
import org.controlsfx.control.GridView;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication287 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        ObservableList observableList = FXCollections.observableArrayList(Font.getFamilies());
        GridView<String> myGrid = new GridView(observableList);
        myGrid.setHorizontalCellSpacing(0);
        myGrid.setVerticalCellSpacing(0);
        myGrid.setCellFactory(gridView -> {
            return new GridCell<String>()
            {
                Button button = new Button("ABC");

                {
                    button.setPrefWidth(60);
                    button.setPrefHeight(60);
                }

                @Override
                public void updateItem(String item, boolean empty)
                {
                    if (empty || item == null) {
                        setText(null);
                        setGraphic(null);
                    }
                    else {
                        button.setFont(new Font(item, 14));
                        setGraphic(button);
                    }

                }
            };
        });

        StackPane root = new StackPane(myGrid);
        Scene scene = new Scene(root, 500, 700);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}


text:
Q: Why the "Convert class" has no definition in my IDE? I am developing a simple app for Android using the Xamarin in Visual Studio 2015. I am using c# as a language. I want to convert a string to an int. But the Convert class has no definition in my IDE. I want to write the following:
int ress = Convert.ToInt32(num1.Text)+ Convert.ToInt32(num2.Text);

Here is a picture of what I am having.
Why I am having this problem? And how to solve it?

A: You may be missing a using statement at the top of your class:
using System;

Or you can write the full class name:
System.Convert.ToIn32(num1.Text);

Or you can use:
int.Parse(num1.Text)


text:
Q: How to start web Job on azure I am starting Preprocessor job on Azure but Process went down, waiting for 60 seconds after process goes to restart pending how to start and see the output.

A: That's usually a sign that you are running as a Continuous WebJob something that is meant to be a Triggered WebJob. Continuous is only for processes that have a forever loop looking for work, and that never normally terminate.


text:
Q: Sorted pairs with the least number of changes between each element A colleague came to me with a problem that I managed to answer but I don't know if my answer is right or even good...
He is creating a program to compare data in various files - in this case excel spreadsheets. He has a list of comparisons which will boil down to two files with references to cells in them. For each comparison it is necessary to open the files, do the comparison and then close the files.
Of course this can be optimised if you order the comparisons such that you can keep one file and just change the other.
So how should you sort the files to minimise the number of times you need to close and open files?
It should be noted that the idea of just having all files open is not feasible since there could be over 500 different spreadsheets being compared.
My solution was to find the table that occurs in most comparisons and process all the comparisons involving that first. Then repeat the process ignoring all the comparisons that have already been done.
I am wondering if when you process that first batch you want to do the least common ones first, ending up with the most common appearing table - this is then the table you process next (meaning still only one file change).
So can anybody either give me a better option or confirm that my idea is good (or good enough)?
Concrete example:
Here is an example list of comparisons with a note next to them showing how many files need to be unloaded and loaded each time. eg after Comparing fileA and fileB it only needs to unload FileB and load FileC to do the next compariosn. After comparing FileA and FileF it needs to unload both to load FileB and FileC.
FileA   FileB
FileA   FileC   One file change
FileA   FileD   One file change
FileA   FileE   One file change
FileA   FileF   One file change
FileB   FileC   Two file changes
FileB   FileF   One file change
FileC   FileD   Two file changes
FileC   FileE   One file change
FileD   FileF   Two file changes
FileE   FileF   One file change

In theory in this example the order of the comparisons can be rearranged to make it so that at each step you only need to unload and reload one file.
FileA   FileB
FileA   FileD   One file change
FileA   FileE   One file change
FileA   FileF   One file change
FileA   FileC   One file change
FileB   FileC   One file change
FileC   FileD   One file change
FileC   FileE   One file change
FileE   FileF   One file change
FileB   FileF   One file change
FileD   FileF   One file change

So what I want to know is what the best algorithm is to sort the file pairs to get the minimum number of total file unload/load operations.
I should note that it is not always going to be posible to get it down to one file change each time as demonstrated by the trivial pair of comparisons below:
FileA   FileB
FileC   FileD   Two file changes

A: Here's an idea:
Consider a graph where each file is a node, and each required comparison is an edge.
Now, if you find a Eulerian Path in the graph, this path will represent a sequence such that only one file replacement happens after each comparison.
If no Eulerian Path exists, then once you cannot proceed with the path, just jump to some node with an odd number of edges (and if all of them have an even number of edges, just pick any node). This approach will probably still give you the best results, but at some point(s) in the sequence, you will have to replace two files instead of one. I believe it should be easy to prove that if no Eulerian Path exists, then no sequence exists that only replaces one file at each step.


text:
Q: Web App Layout Guidelines I am transitioning from Desktop apps (WPF/Winforms) to Browser Apps and am looking for a good resource on laying out an app.  I don't mean design here, just the mechanics of the layout.
For example, "don't use tables for layout" seems to come up a lot.  I have come up with the below  as a really simple app layout that does not use tables (except for the actual data grid):

        My Site Name
        Login Link

The Order Line Items goes here

        <button>Cancel Order</button>
        <button class="floatRight" >Continue</button>
        Order Total
        Order Subtotal

Is there a better way to do this?
I have Googled the subject, but mostly finding design ("this looks good") as opposed to "this is how you do it."
Greg

A: My only suggestion for improvements would be to change the widths to percentages. When working with web apps and all of the resizing of windows and device sizes, it's better to make it responsive where you can. It just makes for better overall UX.

A: Looks fine to me.
Just wanted to add that sometimes it can be useful to use a horizontal list for the layout as well. Sometimes it can get quite messy with floats when they get nested etc.


text:
Q: HOw to pass interface making it an class object and use its methods in another project I have below situation :
I have One project "Logger"
which has class concrete class named "Log"
And this "Log" is inherited from interface "Ilog" which is refereced from project "Common" which has all interfaces
So now the solution looks like
MainSolution
-Logger(CLASS LIBRARY)
  - Log.cs

*

*Common(CLASS LIBRARY)

*

*ILog (interface)

*ICache (interface)

*Cache(CLASS LIBRARY)

*

*Cache.cs (this class is inherited by ICache from common project.

Now cache.cs also needs to use Logging and i don't want to use reference of logger project, and just use the Common project reference and achieve the logging.
Please give some  way out of it.

A: You can use IOC to resolve this problem. By using IOC, you only reference the Common class library in Cache library; but call methods on Log class.
All you need to do is to create a container; map your interfaces to your objects by using either a configuration file or by coding; and resolving your objects by means of IOC.
You may refer to this link and this link for Unity IOC.

A: "I don't want to use the project that has the code in, but I do want to use it" is rather ill-thought-out.
Just use it or reimplement ILog in the Cache class library.


text:
Q: Multiple conditions findFirst i am using phalcon framework and i want to find the correct item in my db. So i use the FindFirst function like:
$existing_entry = Files::findFirst(
        [
            'conditions'  => 'name = :name AND uuid = :uuid:',
            'bind'        => [
                'name' => $data['name'],
                'uuid' => $data['uuid']
            ]
        ]
    );

but i get no result. If i search only for name or uuid it works.
Can someone help me please?

A: Placeholders in PHQL are surrounded by :, while in PDO they are only prefixed.
Problem is in your :name placeholder, try like this:
$existing_entry = Files::findFirst([
    'conditions'  => 'name = :name: AND uuid = :uuid:',
    'bind'        => [
        'name' => $data['name'],
        'uuid' => $data['uuid']
    ]
]);

Notice the :name:.


text:
Q: In Visual Studio Code code doesn't works but after a bit it again works why? I was writing some code and every thing seemed alright. I carefully watched it run, but only to half way and then it stops, when it's time to give output from my given input.
But when I removes while loop and added do while loop it worked. After that I again used the while loop, i.e. exactly the code that was not running before, not changing anything, same to same code as before. But now it works.
I faced this problem 3-4 times.
I fixed all and even though my code was correct, sometimes it runs and sometimes it doesn't.
This wastes my time a lot. Why is this happening?
My pc is i5 7200u @ 2.5 ghz, 4 gb ram.
I notice that in Visual Studio Code the text looked like they move from its place while i am scrolling through.
my code is this
#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node *next;
};
struct node *head;

void insert(int a);
void print();

int main (){
    head = NULL;
     printf("How many numbers?\n");
      int x,n;
    scanf("%d",&x);
    for(int i=0 ;i<x ;i++){
    printf("enter no\n");
    scanf("%d",&n);
    insert(n);
    }
    print();

}

void insert(int a){
    struct node *temp=(struct node*)malloc(sizeof(struct node));
    (*temp).data=a;
    (*temp).next=head;
    head=temp;

}

void print(){
    struct node *temp=head;
/* i declearde this while i was doing do while loop*/ int i=0;
     printf("list is :");
    while(temp != NULL)  //only changed this with do while
    {                    //and again replaced this same code i am 100% sure
        printf(" %d",(*temp).data);
        temp=(*temp).next;
    }
 /* do{
printf("list is :");
printf("%d",(*temp).data);
temp=(*temp).next;
i++
}while(i<3);//just to conform that I was right I set i and looped for 3 times
//and then the code worked out and after this I tried while loop then also it
worked out fine same code that was not working before, started working
*/
    printf("\n");
}

A: Two possible answers:
A) You are mistaken in "i again made it while loop,exactly the code that was not running before" and missed a tiny but relevant difference. If you do not happen to have used a versioning system for your code, this is my bet.
B) If for any reason your are 100% sure about "i again made it while loop,exactly the code that was not running before", then you probably have undefined behaviour in your code due to a mistake you made. Without seeing your code this cannot be analysed in more detail.
Undefined behaviour (see Undefined, unspecified and implementation-defined behavior) could explain any strange behaviour, including the one you describe.
With the shown code (sadly only one version of it), I can see a vulnerability to wrong input in combination with non-initiliased variables. I.e. you do not check the return value of scanf(), hence you do not notice when scanning fails. Then you use x befor it is initialised, whatever loop you use.
Gotcha: Undefined Behaviour.


text:
Q: Cálculo tamaño salida de capa convolucional Tengo una consulta simple, cómo se llega a este resultado en una red convolucional:
entrada:
Tamaño de imagen = (32,32,3)
Capa convolucional:
model.add(Conv2D(128, (3,3), strides=(2,2), padding='same', input_shape=in_shape))
formula:
(InputSize - Kernel + 2(padding))/2 + 1
Output (según el Summary):
(16,16,128).
Podrían indicarme cómo es que sale el 16?
Gracias


text:
Q: Backpack not generating "skin-purple" class on panel I started to follow the tutorial on https://backpackforlaravel.com/docs/4.0/getting-started-basics on Laravel 6. But after running:
# STEP 1. create migration
php artisan make:migration:schema create_tags_table --model=0 --schema="name:string:unique"
php artisan migrate

# STEP 2. create crud
php artisan backpack:crud tag #use singular, not plural

...the generated web page look messed up. I tracked the problem to the class "skin-purple" not being rendered on the body element.
The body tag on the /admin/dashboard page (which looks good) is:
<body class="skin-purple sidebar-mini  pace-done" style="height: auto; min-height: 100%;">

The body tag on the /admin/tag page (the one I generated) is:
<body class="app aside-menu-fixed sidebar-lg-show   pace-done pace-done" style="height: auto; min-height: 100%;">

If I add the skin purple class it fixes the problem.
I had some problems before with the backpack/generators version (I'm using ^2.0 now). Maybe it's related to that.

A: I started a new project from scratch and just got everything working right on the first try, even the backpack/generators version was right. So I guess it was something that was fixed during last week.


text:
Q: How do you use event.not-before argument in aws ec2 describe-instance-status? I want to get only the statuses with events in the future. I can search for [Complete] string in description field, but I want to use event.not-before filter and filter it out from the AWS side.
However, whenever I set event.not-before filter, I get no statuses back.
I tried this command, expecting the full result.
$ aws ec2 describe-instance-status --filters "Name=event.not-before,Values=2014-09-15T17:15:20.000Z"

However, I am getting nothing back.
Can someone spot what I am doing wrong here?

A: The CLI doesn't work in the way you expect. It will filter the results that match your criteria. For example:
aws ec2 describe-instance-status --filters Name=event.not-before,Values=2016-11-21T12:00:00.000Z

it will look for instances which have events with not-before equals the value specified. The above query results in an instance with:
    "Events": [
        {
            "Code": "instance-stop",
            "Description": "You're instance will be stopped",
            "NotBefore": "2016-11-21T12:00:00.000Z"
        },
        {

So, the not-before value has to match exactly.


text:
Q: Print calculation sheet (interactive form) in IE 11 with javascript I have different interactive forms and I am looking for a pure JavaScript solution to print a section of the page on click. So each page would have a button "Click to print" and it should open a new page ready for print.  I tried many solution and some of them work great except in IE11.
Some of my forms are complex but to keep it simple, here is a simple example of the code I am trying to use:

This is a sample text for printing purpose.

  First name: <input type="text" name="firstname" value="">

  Last name: <input type="text" name="lastname" value="">

  Gender:

  <input type="radio" name="gender" value="male"> Male

  <input type="radio" name="gender" value="female"> Female

  <input type="radio" name="gender" value="other"> Other

<input type='button' id='btn' value='Print' onclick='printDiv();'>

Two issues:
 1. I cannot get the value of each form item printed and
 2. This solution is not working in IE11.
Could someone help with this please?

A: *

*Filling the form doesn't modify the html markup, nor will it change the value attribute in actual markup. So you can't get the value with .innerHTML. If you want the html with the new value just set the attribute to the new value.

*To make sure the script's output actually shows up in the other window, we should use document.close() after writing the content.

You could check my demo, it can work well in IE and other broswers:

This is a sample text for printing purpose.

    First name: <input type="text" name="firstname" value="">

    Last name: <input type="text" name="lastname" value="">

    Gender:

    <input type="radio" name="gender" value="male"> Male

    <input type="radio" name="gender" value="female"> Female

    <input type="radio" name="gender" value="other"> Other

    <input type="radio" name="aa" value="a"> A

    <input type="radio" name="aa" value="b"> B

    <input type="radio" name="aa" value="c"> C

<input type='button' id='btn' value='Print' onclick='printDiv();'>


text:
Q: Yii2 Listview dynamically update dataProvider I have a Listview of which I'd like to dynamically update the dataProvider with the click of a button.
itemController.php:
  <?php
    public function actionList($category = ''){
      $this->layout = '_notags';
      $query['published'] = 1;
      if(!empty($category)){
        $category = category::findOne(['title'=>$category])->id;
        $query['category_id'] = $category;
      }

        echo "<script>console.log('$category')</script>";

      $items = new ActiveDataProvider([
                    'query' => Item::find()->where($query)->orderBy('date_created DESC'),
                    'pagination' => [
                        'pageSize' => 9
                    ],
                  ]);
      return $this->render('_fresh', [
          'newitems' => $items,
          'category' => $category
      ]);
    }
    ?>

_list.php:
<?php
use yii\widgets\ListView;
use kop\y2sp\ScrollPager;
use yii\helpers\HtmlPurifier;
use yii\widgets\Pjax;

if(empty($category))
$genre = '';

$listview = ListView::widget([
      'id' => 'freshitems',
       'dataProvider' => $newitems,
       'itemOptions' => ['class' => 'col-xs-4 featured-item-'.$category],
       'itemView' => '_item',
       'pager' => ['negativeMargin'=>250, 'delay'=>0, 'spinnerSrc'=> '/img/loading.png','triggerOffset' => 3, 'class' => ScrollPager::className(), 'item'=>'.featured-item-' . $genre, 'enabledExtensions'=> Array( ScrollPager::EXTENSION_TRIGGER, ScrollPager::EXTENSION_SPINNER, ScrollPager::EXTENSION_NONE_LEFT, ScrollPager::EXTENSION_PAGING ) ],
       //'summary' => false
  ]);

  $this->registerJsFile('@web/js/main.js');
  $this->registerJsFile('@web/js/jquery.quickfit.js');

  Pjax::begin(['id'=>'freshitems']);
      echo HtmlPurifier::process(
       $listview
     );
  Pjax::end();

?>

main.js:
$(document).ready(function() {
  $(".category-select").click("pjax:end", function() {
      $.pjax.reload({container:"#freshitems"});  //Reload GridView
  });
});

I tried using jQuery to change the div containing _list:
index.php:
    Some Category

    $this->render('_list.php', $category)

main.js:
$('.btn').click(function(){
  $('#list-container').load("item/list/" + $(this).id;
});

Doing this does change the listview, but it glitches the ScrollPager plugin (infinite scroller no longer works properly).
What would be the best way to dynamically change a Listview's dataProvider (or listView completely) in my view?

A: You could make an AJAX request to an action on your controller, from there return a rendered (preferably in a new view file, with a DataProvider it receives as a parameter) and empty the HTML then append it.
Assuming you put the ListView inside of a container with some id to make it easier.


text:
Q: What kind of loop works for outputting title and description from xml I have some code that reads xml from the web and I captured title and description from that as NodeLists:
        DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse("http://services.explorecalifornia.org/rss/tours.php");

        NodeList titleNode = doc.getElementsByTagName("title");
        NodeList summaryNode = doc.getElementsByTagName("description");

I want to loop through both of them and get output like

Title
Description
Title
Descripton

I can't get my head around if this is possible with loop as I used nested loop it loop the inner loop for each outer loop any suggestion for any other kinds of loop
Here's an example of the XML: (from http://services.explorecalifornia.org/rss/tours.php )
<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>Explore California Tours</title>
    <description>Explore Our World Your Way</description>
    <link>http://www.explorecalifornia.org</link>
    <copyright>Copyright (c) 2011 lynda.com</copyright>
    <item>
      <title>2 Days Adrift the Salton Sea</title>
      <link>http://www.explorecalifornia.org/tour.php?id=14</link>
      <description>The Salton Sea is saltier than the Pacific, an unusual feat for inland body of water. And even though its salinity has risen over the years, due in part to lack of outflows and pollution from agricultural runoff, it has attracted a small, but dedicated population. The sea itself offers recreational opportunities including boating, camping, off-roading, hiking, use of personal watercraft, photography and bird watching. The sea has been termed a "crown jewel of avian biodiversity," being a major resting stop on the Pacific Flyway, a migratory path for birds. 2 Days Adrift the Salton Sea includes two nights accommodations at the Bombay Beach Inn, boat rental at the Salton City Harbor, and a guided fishing tour.</description>
      <category>From Desert to Sea</category>
    </item>
    <item>
      <title>A Week of Wine</title>
      <link>http://www.explorecalifornia.org/tour.php?id=26</link>
      <description>Immerse yourself in the culture and lifestyle of a California winery. Spend 5 days in your private guest villa at the Stockbridge Winery, located in scenic Sonoma. You'll spend your days wandering the vineyards, touring the presses and cellars, and assisting staff in making America's favorite wine. Enjoy Tuscan-style meals served al fresco, overlooking the gorgeous countryside. Day trips include dinner in Sausalito, hiking in the redwood forests, and lunch in downtown San Francisco.</description>
      <category>Taste of California</category>
    </item>
    <!-- ...and so on... -->
  </channel>
</rss>

A: If there are the same number of titles and descriptions, and you want to output them in parallel, then a simple loop is all you need:
int i;
for (i = 0; i < titleNodes.length; ++i) {
    // output titleNodes[i] here
    // output descriptionNodes[i] here
}

More likely, though, there's a container element that has both of those in it, and you'd be better off looping through the container elements and then looking within each one for the title and description.
Edit (once you posted the XML): For instance, in this case, you probably want to loop through the item elements and then retrieve their title and description as you loop:
for (Element element : doc.getElementsByTagName("item")) {
    // Output element.getElementsByTagName("title").item(0) here
    // Output element.getElementsByTagName("description").item(0) here
}

Depending on what DOM library you're using, you might be able to use element.querySelector("title") rather than element.getElementsByTagName("title").item(0) (and similarly for document).

Note that I changed the names of the variables (made them plural, e.g. titleNodes rather than titleNode), as they are lists, not individual nodes.

A: Here you go:
NodeList itemNodes = doc.getElementsByTagName("item");
for (int i =0; i < itemNodes.getLength(); i++) {
    Element itemElement = (Element) itemNodes.item(i);
    String title = itemElement.getElementsByTagName("title").item(0).getTextContent();
    String description = itemElement.getElementsByTagName("description").item(0).getTextContent();

}

Basically, you need to get parent node for both "title" and "description". Then search within ancestors of found nodes.

A: You can do :
NodeList itemNode = doc.getElementsByTagName("item");
for (int i = 0; i < itemNode.getLength(); i++) {
  Element itemEle = (Element)itemNode.item(i);
  // You chould check if there is a title/description element, I'm skipping this for brevity
  Element titleEle = (Element)itemEle.getElementsByTagName("title").item(0);
  Element descrEle = (Element)itemEle.getElementsByTagName("description").item(0);
  // Output them, now you're sure you are in the same pair
}


text:
Q: Can I do something like this in SQL Server? declare @sum as nvarchar(20) = 'sum(Salary)'

select @sum from Employee

I want to do something like this. I need to store my sql query part in variable and use that variable in sql query. Is it possible in any way?

A: SQL Server does not support macro-substition.  It does however allow for DYNAMIC SQL.  Below is a simple example
declare @sum as nvarchar(20) = 'sum(Salary)'

Declare @SQL varchar(max) = 'select '+@Sum+' from Employee'
Exec(@SQL)

Now, to be clear, there are risks of SQL Injection. Take a peek at http://bobby-tables.com/

A: YOU CAN USE DYNAMIC QUERY

    BEGIN TRAN

    DECLARE @sum NVARCHAR(20) = 'sum(Salary)',@SQL VARCHAR(4000)
    SET @SQL=''
    SET @SQL = @SQL + 'SELECT '+@Sum+' FROM Employee'
    PRINT @SQL
    EXEC(@SQL)

    ROLLBACK TRAN

A: id 'sum(salary)' is like that then it should return a result of
declare @sum as nvarchar(20) = 'sum(Salary)'

result a literal string

sum(Salary)

but if like:
declare @sum as nvarchar(20)
 select @sum = sum(Salary),column1,..and so on from your table

then it should return a result from your function


text:
Q: Get upload status in webpy I'm making an uploader for my project, and I try to avoid any flash-based solutions (I dont like flash much and target for mobile platforms support).
The whole process seems rather simple: I have a form, nice jQuery progress bar, I can make ajax requests with timeout from a script to update progressbar status...
If I do it according to Webpy cookbook, the only thing I don't get is how to recieve any info from server: how many bytes/chunks/whatever were already written?

A: You can create ajax uploader using FormData for the modern browsers.
$.fn.uploader = function( options ) {
    var defaults = {},
        opts = $.extend( defaults, options ),
        that = $( this ),
        url = that.data( "upload_url" ),
        is_uploading = false;

    function upload( files ) {

        $.get( "/file/blank.html" );

        if ( FormData === undefined ) {
            alert( "Your browser does not support standard HTML5 Drag and Drop" );
            return;
        }

        var xhr = new XMLHttpRequest(),
            new_element = $( "

Loading

" )
                .appendTo( that ),
            xhr_upload = xhr.upload,
            form = new FormData();

        xhr_upload.addEventListener( "progress", function( e ) {
            if( e.lengthComputable ) {
                var p = Math.round( e.loaded * 100 / e.total );
                new_element.children( "span" ).text( e.loaded == e.total ? "Processing..." : p + "%" );
            }
        }, false);
        xhr_upload.addEventListener( "load", function( e ){}, false);
        xhr_upload.addEventListener( "error", function( error ) { alert( "error: " + error ); }, false);

        xhr.open( "POST", url, true );
        xhr.setRequestHeader( "X-Requested-With", "XMLHttpRequest" );

        xhr.onreadystatechange = function ( e ) {
            if ( xhr.readyState == 4 ) {
                is_uploading = false;
                if( xhr.status == 200 ) {
                    var data = $.parseJSON( e.target.responseText );
                    if ( data.status == 0 ) {
                        new_element
                            .fadeOut(function (){ $( this ).remove(); })
                            .children( "span" ).text( "Upload error!" );
                    } else {
                        that.html( data.html );
                    }
                } else {
                    new_element
                        .fadeOut(function (){ $( this ).remove(); })
                        .children( "span" ).text( "Upload error!" );
                }
            }
        };
        $.each( files, function() {
            form.append( "files", this );
        });
        is_uploading = true;
        xhr.send( form );
    }

    that.bind({
        "dragover": function( e ) {
            var dt = e.originalEvent.dataTransfer;
            if( !dt || is_uploading ) { return; };
            if( $.browser.webkit ) { dt.dropEffect = "copy"; };
            $( this ).addClass( "active" );
            return false;
        },
        "dragleave": function( e ) {
            $( this ).removeClass( "active" );
        },
        "dragenter": function( e ){ return false; },
        "drop": function( e ){
            var dt = e.originalEvent.dataTransfer;
            $( this ).removeClass( "active" );
            if( !dt || !dt.files || is_uploading ) { return; };
            upload( dt.files );
            return false;
        }
    });

    $( document ).bind({
        'dragenter': function( e ) { return false; },
        'dragleave': function( e ) { return false; },
        'dragover': function( e ) {
            var dt = e.originalEvent.dataTransfer;
            if ( !dt ) { return; }
            dt.dropEffect = "none";
            return false;
        }
    });

};

On the server side I process it like this:
def POST(self):
    i = web.webapi.rawinput()
    try:
        files = i.files
        if not isinstance(files, list):
            files = [files]
        for f in files:
            if f.filename:
                filetype, encoding = mimetypes.guess_type(f.filename)
                # do smth with f.file
    except KeyError:
        pass
    if web.ctx.env.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
        web.header("Content-Type", "application/json")
        return json.dumps(dict(status=1, html=unicode(render_partial.files(uploaded_files))))
    else:
        raise web.seeother(web.ctx.env.get("HTTP_REFERER", "/"))

Otherwise you may look into nginx upload progress module or apache2 upload progress module, uWSGI has got this feature too.


text:
Q: Running apps in background? Is it possible to keep a socket connection alive in background, to be able to push new data and alert users at all times?

A: The answer to this question is a definitive yes. If you are in the background state, then you can keep a connection open and process messages from a server.
Unfortunately the complexity here is that you don't have a lot of control over the state your application is in:

*

*foreground - The user has tapped your icon and the app is running with the UI visible.

*suspended - The user was previously running your app in the foreground, but suspended it by hitting the home button or receiving a call. Basically your app is 'freeze dried' and will remain inactive until it is resumed by the user (starting where it left off) or it is terminated by the OS (see below).

*background - The app was previously running in the foreground but has moved to the background state as a result of something the user has done. Normally your app will move to the suspended state in this case, but there are things you can do as the developer to prevent the instant 'freeze dry' and go into the background instead (see below). Your app will also be in the background state if it is woken up for a significant change event.

*terminated - Your app has been unloaded from memory and the next time it starts will be from scratch. This is what happens when you double click the home button and then tap the x next to your app icon. It moves the app from the suspended state into the terminated state. This will also happen if the OS decides it needs room for more recently running apps and your app has been suspended for a long time.

So obviously the trick here is how do I stay in the background state as a long as possible. There are a couple of ways to do this:

*

*Beg for more time - You can get up to 10 minutes of additional background processing when your app is closed if you ask for it.

*Use UIBackgroundMode - You can declare youself a voip, audio or location app by adding the corresponding UIBackgroundMode value to the pList. There are special requirements for these types of apps which you can check out here.

So these approaches are not without their own problems (getting approved on the store being one of them) and as such I tend to agree with the other answers that using push notifications is probably your best approach for notifying your users. With the notification improvements in iOS5 this is going to be the best user experience going forward.

A: You can keep a socket connection alive (or do whatever else you want) in the background for about 15 minutes after your app closes.  There are also more specialized background processing modes (specifically, audio, voip, and location) which Apple supports if your app fits into one of their supported categories.  See here.
If you want to keep sending the user notifications indefinitely, you want to use the Apple Push Notification Service.  This allows your app to continue to receive notifications when it's not running, and it conserves resources since there's only one connection to the APN service at a time.

A: You can definitely alert users with local and push notifications.
And as far as I know, you can keep a connection open only for limited time.
Look here for more details.


text:
Q: Move Flash Player in a Delphi TWebBrowser control to a background thread? I have a Delphi 6 Pro program with a TWebBrowser component that loads a web page that embeds a Cool Iris Wall.  The Cool Iris wall is an SWF object which means that when running, the execution happens inside the Adobe Flash player, an ActiveX or similar object I believe.  The problem I am having is that sometimes when the Wall is loading pictures/videos from the web, it takes a big hit on the CPU on the main UI thread.  I know that TWebBrowser moves most of its operations on to a background thread to keep the main UI thread happy, but something the Adobe Flash Player is doing is happening on the main UI thread and its causing my program much grief.  Is there a way to move the Adobe Flash Player on to a background thread?
[UPDATE - 12/7/2010] - After a marathon probing and debugging session it turns out that the problem had to do with the Cool Iris Wall's Flickr proxy.  You can interface with the Wall in two main ways: 1) You pass them special Flickr api protocol URLs and let them talk to Flickr for you, for example "api://www.flickr.com/?search=puppy" loads the Wall with the results of a Flickr keyword search for puppy.  The advantage to this approach is that they do all the work for you necessary to make the query to Flickr and build the Wall's contents.  2) You build an RSS media feed yourself containing the photo stream item data and feed it to the Wall.
I was using technique #1.  The problem is with #1 is that when their servers have trouble building the Flickr feed for you (for whatever unknown reason), their host SWF puts a heavy load on the CPU interfering with the main UI thread's operation.  I converted my entire code base to work directly with the Flickr API and create the feed myself using the second technique and the problem vanished.
-- roschler

A: You have no control over how the webbrowser manages its threading.  If you do not want the webbrowser interfering with the main thread, then don't run the webbrowser in the main thread to begin with.


text:
Q: Operator Overloading 'operator()' I am implementing Dijkstra's algorithm and I would like to use STL's 'priority_queue' to speed up the coding process, but as so often is the case with my attempts at coding in C++, my lack of understanding of the language is slowing me down. I found this example at http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/, but do not understand what the following is doing:
// constructing priority queues
#include <iostream>
#include <queue>
using namespace std;

class mycomparison
{
  bool reverse;
public:
  mycomparison(const bool& revparam=false)
    {reverse=revparam;}
  bool operator() (const int& lhs, const int&rhs) const
  {
    if (reverse) return (lhs>rhs);
    else return (lhs<rhs);
  }
};

int main ()
{
  int myints[]= {10,60,50,20};

  priority_queue<int> first;
  priority_queue<int> second (myints,myints+4);
  priority_queue< int, vector<int>, greater<int> > third (myints,myints+4);

  // using mycomparison:
  priority_queue< int, vector<int>, mycomparison > fourth;

  typedef priority_queue<int,vector<int>,mycomparison> mypq_type;
  mypq_type fifth (mycomparison());
  mypq_type sixth (mycomparison(true));

  return 0;
}

To be more specific, 'bool operator() (const int& lhs, const int&rhs) const' is what is tripping me up. The rest I am fine with. I think its overloading an operator, but 'operator()' makes no sense to me. Any help would be appreciated.

A: Essentially, operator() is "just" another operator that can be overloaded, so everything you know about operator overloading still applies - it's useful because it can be applied to an object with the same syntax that you might use to call a function, e.g.
MyClass f;
f(); // i.e. f.operator()();

That said, there's a lot that could be said about functors etc. beyond that - you might want to do a Google search for functors / function objects for more information. Here's one link:
http://en.wikipedia.org/wiki/Function_object
In the above code, priority_queue takes a comparison functor that it uses to order the things you put in the queue. The first queue (fifth) uses normal ordering; the second queue (sixth) uses reverse ordering.

A: That is the function call operator and you can use it like this:
mycomparison mycomp;  //defines an object
mycomp(1,2);  // invokes operator()(int,int)

A: bool operator () ( const int &, const int & );

This is a function, an overload of operator(), that takes two integers and returns a boolean. const means that the value cannot be changed. It stands for constant.


text:
Q: Postgres helm chart installation failed in Kubernetes I am trying to install PostgreSQL with helm chart dependencies in my Kubernetes cluster. But it failed in installation.
chart.yml
dependencies:
- name: postgresql
  version: "10.16.2"
  repository: "https://charts.bitnami.com/bitnami"

values.yml
global:
    postgresql:
      postgresqlDatabase: "postgres"
      postgresqlUsername: "postgres"
      postgresqlPassword: "password"

volumePermissions:
  enabled: true

In this method I was successfully Postgres installed in minikube


text:
Q: git merge rename conflict I have created a new branch from an existing branch:
git checkout master
git checkout -b test

then in the new branch I've renamed a file:
git mv foo.txt fooOld.txt
git mv fooNew.txt foo.txt
git commit -am "Rename file"

meanwhile someone else has edited the fooNew.txt on the master branch and pushed the changes:
git co master
echo "Some changes" >> fooNew.txt
git commit -am "Do some important changes"
git push origin master

now when I try and pull in the changes from master I get an error:
CONFLICT (modify/delete): fooNew.txt deleted in HEAD and modified in master.

how can I merge these 2 branches so that I end up with a foo.txt file containing the changes done to fooNew.txt on master?

A: Using your method, I had no problem.
$ git checkout -b test
Switched to a new branch 'test'

$ git mv foo.txt fooOld.txt

$ git mv fooNew.txt foo.txt

$ git commit -am "Rename file"
[test bf82f6d] Rename file
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename fooNew.txt => fooOld.txt (100%)

$ git checkout master
Switched to branch 'master'

$ echo "Some changes" >> fooNew.txt

$ git commit -am "Do some important changes"
[master 653c0df] Do some important changes
 1 files changed, 1 insertions(+), 0 deletions(-)

$ git checkout test
Switched to branch 'test'

$ git merge master
Auto-merging fooOld.txt
Merge made by the 'recursive' strategy.
 fooOld.txt |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)


text:
Q: How to proceed with this type of algorithm - getting list of products based on budget Working on a web store using Java EE. Lets say a car tuning shop. I sell kits and parts that users can buy to customise their car. I want an option such as a buyer just inputs his budget, and something like an algorithm that calculates a list of options that is possible to buy.
How can this task be accomplished?

A: For each product you should get information "how much user wants this product".
If you don't want to do such survey then gather information about bestsellers in shop and provide values for each product yourself.
When each product besides cost has "value for user" then you have classical 0-1 knapsack problem
I would recommend you solving it using dynamic programming described here


text:
Q: Reading a USB Bus with a Pi/Arduino I have bought some weighing scales which write data to a USB pen (http://www.amazon.co.uk/Homedic-Mibody-Analyser-Body-Scale/dp/B003X33XNM). I then plug that USB pen into my computer and download the information for analysing.
I'm trying to automate the process of getting that data from my scales to my computer and was hoping to use an Arduino or Pi to read the USB bus and send that data to my PC using MQTT or similar.
I don't own an Arduino or Pi yet so was wondering if anyone knows if this is even possible?
Many thanks.

A: A Raspberry Pi is likely to be the easiest to do this with as you won't have to worry about things like Host USB or basic filesystem support as you would with an Arduino.
The biggest problem will be what format the USB stick uses. If it is just a basic USB mass storage device then it will come down to what file format the data is stored in.
Lets assume the file is either CSV or and Excel spreadsheet it should be easy, but if it is some propriety format then it will be more tricky.
You may want to have a look on http://www.openyou.org/ to see if anybody has already worked the format out.

A: Another idea is to use a USB SD card adapter and then use a eye-if card (e.g. http://www.amazon.co.uk/gp/product/B003E47XIQ/ref=as_li_ss_tl?ie=UTF8&camp=1634&creative=19450&creativeASIN=B003E47XIQ&linkCode=as2&tag=bespl-21) as the storage.
This eye-fi card can then upload the csv file to somewhere like dropbox or I think even directly to your machine.
It's not a MQTT, Raspberry Pi or Arduino solution, but it may be simpler


text:
Q: How can I run away while engaged in a sword fight? I find myself getting locked in combat with a group of enemies and unable to run and hide easily or at all and end up button mashing my controller attempting to get my assassin to run away. It is incredibly frustrating since I have always been able to run away while engaging in combat in previous assassin's creed games.
Any advice on how to get my assassin to quickly remove himself from his combat stance and run away?

A: Depending on your system, press what ever button you use to lock on(LT/L1/F for 360/PS3/PC) to break the lock on, and sprint in the opposite direction of your enemy.  Then it's just the standard run far enough away or hide so that you become anonymous again.
I have noticed that in this game it is harder than others to escape combat.  I seem to remember just being able to press the buttons to sprint in the opposite direction to break combat and start running.


text:
Q: Can we use "it" to refer to "something"? Can we use "it" to refer to "something" in the following sentence or should we say "that thing"?

It's a disapproving yet humorous thing to say when someone does
something very strange and pointless, especially when it's elaborate.

A: That's very common.

I ate something.  It was hot and spicy.


text:
Q: Fastest way to assign values to class property in typescript class constructor Here is my class and an interface:
As you can see I have to write lines for all properties. Can we reduce the lines here?
interface requestQAttributes {
    id: number;
    uri?: string;
    groupId?: string;
    status?: string;
    tryCount?: number;
    createdDate: Date;
    startDate?: Date;
    completedDate?: Date;
    bodyType?: string;
    formData?: string;
    pageResponse?: string;
    domain?: string;
}

class RequestQ {
    id: number;
    uri?: string;
    groupId?: string;
    status?: string;
    tryCount?: number;
    createdDate: Date;
    startDate?: Date;
    completedDate?: Date;
    bodyType?: string;
    formData?: string;
    pageResponse?: string;
    domain?: string;

    constructor(requestQ: requestQAttributes) {
        this.id = requestQ.id;
        this.uri = requestQ.uri;
        this.groupId = requestQ.groupId;
        this.status = requestQ.status;
        this.tryCount = requestQ.tryCount;
        this.startDate = requestQ.startDate;
        this.completedDate = requestQ.completedDate;
        this.bodyType = requestQ.bodyType;
        this.formData = requestQ.formData;
        this.pageResponse = requestQ.pageResponse;
        this.domain = requestQ.domain;
    }
}


text:
Q: Do sites using Paypal's chained-payments API need to be approved before using them in production? It is unclear from their documentation if websites are required to go through the same approval process that other apps that use the adaptive payments API do. Does anyone know an answer to this?

A: The answer is yes you do, but the review process is not very onerous.


text:
Q: Adding a value to the column while importing a CSV file in CSV Right now I'm importing a CSV file using below code...and then updating a column(Date) with a macro variable(RunDate).
%let RunDATE = 25JAN2015;
data Import (KEEP = Date ID);
infile "&infl." delimiter = ',' MISSOVER DSD lrecl=32767 firstobs=2;
    informat Id $22. ;
    informat Date $1. ;
        format Id $22. ;
        format Date $1. ;
        input Id $ Date $;
run;

Data Import ;
Set Import(drop=Date);
    date="&Rundate"d; format date date9.;
Run;

Is it possible to achieve this in one step like updating the column(Date) with a macro variable while importing the CSV file?

A: Of course, as long as you're using a data step to read in the file (as you are). You're welcome to do any normal data step code in a step that is inputting from a file.
%let RunDATE = 25JAN2015;
data Import (KEEP = Date ID);
infile "&infl." delimiter = ',' MISSOVER DSD lrecl=32767 firstobs=2;
    informat Id $22. ;
    informat __dropme $1. ;
        format Id $22. ;
        format __dropme $1. ;
        input Id $ __dropme $;
    date="&Rundate"d; format date date9.;
    drop __dropme;
Run;


text:
Q: Prove that $Ker (\phi ) = (X^2 - Y^3, Y^2-Z^3)$ where $\phi : k[X,Y,Z] \rightarrow k[T]$ s.t. $X \mapsto t^9, \; Y \mapsto t^6, \; Z \mapsto t^4$. I want to prove that for a ring homomorphism $\phi : k[X,Y,Z] \rightarrow k[T]$ s.t. $X \mapsto t^9, \; Y \mapsto t^6, \; Z \mapsto t^4$, we have $Ker (\phi ) = (X^2 - Y^3, Y^2-Z^3)$.
My attempt:
It is easy to prove that $ I  = (X^2 - Y^3, Y^2-Z^3) \subset Ker (\phi ) $.
To prove $Ker (\phi) \subset I$,
Let $F(X,Y,Z) \in k[X,Y,Z]$ where $k$ is a field. We know that we can write $F$ around any point $(a_1,a_2,a_3) \in \mathbb{A}^3(k)$ as
$$
F = \sum \lambda_{(i)} (X-a_1)^{i_1} (Y-a_2)^{i_2}(Z-a_3)^{i_3}
$$
and if $F(a_1,a_2,a_3)=0$, then $F = \sum G_{i} (X_i-a_i) $ where $X_i$s are $X,Y,Z$.
We write $F$ around any general point $(t^9,t^6,t^4)$ as $F =  G_1(X-t^9)+G_2(Y-t^6)+G_3(Z-t^4)$. How can I show that $F $ can also be written as $F = H_1 (X^2-Y^3) + H_2 (Y^2-Z^3)$?
Edit 1 : Additional question
Is the ring homomorphism $\phi$ surjective? (so that we can comment $k[X,Y,Z]/I \cong k[T]$)?
It doesn't seem surjective as I can't see how what will be mapped to $T \in k[T]$. But as I have verified, I am wrong.

A: Let's denote $I=(X^2-Y^3,Y^2-Z^3)$. It is, indeed, true that $\operatorname{Ker}(\phi)=I$.
One way of seeing this is that reducing any power $X^n, n\ge2$, modulo $X^2-Y^3$, and after that reducing any power $Y^m, m\ge2$, modulo $Y^2-Z^3$ shows that the quotient ring $k[X,Y,Z]/I$ is a free $k[Z]$ module of rank four with basis $1,X,Y,XY$. After all, all the appearances of $X^2,Y^2$ or higher have been replaced with other monomials.
This means that $k[X,Y,Z]/I$ has a basis (as a vector space over $k$) of monomials of one of the four types $Z^i$, $XZ^i$, $YZ^i$, and $XYZ^i$, $i\in\Bbb{N}$. The homomorphism $\phi$ sends these monomials to $t^{4i}$, $t^{4i+9}$, $t^{4i+6}$
and $t^{4i+15}$ respectively. The integers $0,9,6,15$ are pairwise non-congruent modulo $4$, so the images of these basic monomials are linearly independent over $k$.
The claim follows.

We also see that the $k$-space $k[t]/\operatorname{Im}(\phi)$ is spanned by the cosets of the monomials $t,t^2,t^3,t^5,t^7,t^{11}$. Again, it is simplest to see this by looking at the exponents modulo $4$. The highest missing powers in each residue class are $t^5,t^2,t^{11}$ simply because $t^0,t^9,t^6$ and $t^{15}$ are in there. The problems of this type fall under the umbrella of numerical semigroups. The numerical semigroup generated by $4,6,9$ governs the image of $\phi$, and this is the complement. Whenever the generating set of natural numbers has no common factors, the complement will be finite.

A: I could not easily understand how "the claim follows" argument in @Jyrki solution. So, I complete the rest of the argument.
From @JyrkiLahtonen argument, we can infer the following two results.
(i) Every element in $k[X,Y,Z]/I$ is the $I$ residue of elements of form $F_1+F_2X+F_3Y+F_4XY$ for some $F_1,F_2,F_3,F_4 \in k[Z]$, and
(ii) In the above ring homomorphism $\phi : k[X,Y,Z] \rightarrow k[T] $, if we choose any function of the form $G = F_1+F_2X+F_3Y+F_4XY$ and s.t. $\phi (G)=0$, then $G=0$ and since all the members of the form $G$ are in correspondence with $k[X,Y,Z]/I$. So, the map $k[X,Y,Z]/I \hookrightarrow k[T] $ is an injection map (as kernel of the map is zero). Now, use the result that subring of any integral domain is also an integral domain and the result then follows.
More formally, in (ii), we can prove that $\psi : k[X,Y,Z]/I \rightarrow k[T]$ s.t. $F_1+F_2X+F_3Y+F_4XY +I \mapsto F_1+F_2\phi(X)+F_3\phi(Y)+F_4\phi(X)\phi(Y)$ and prove from there.


text:
Q: finds two numbers in an array with the smallest distance to each other In Java One question from a website: Implement a Java function that finds two numbers in an array with the smallest distance to each other. The function should return the index of the first number.
Here is my thoughts. But I don't know how to implement it.

*

*Step1. Get all the result of 2 element arrays from a given array.
For example {4,5,7,11} have 4*3 = 12 two element arrays.

*Step2. Calculate each the two array distance. And find out the minimum
distance.

I do viewed at least 10 google results. Seems don't have the good answer. IN real life, people would first sort it then try some way to figure it out. But let's assume the array as it is. We do not sort it.
The following code is based on one expert's answer. But unfortunately it seems not working...
import java.math.*;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;

public class TestallBasics1 {
    public static void main(String[] args) {
        int[] arr = new int[]{2,1,6,8,10,89,54};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        int difference=0;
        int n = arr.length;
        for(int i=0; i<n-1; i++){
            if(difference > (arr[i+1]-arr[i]))
            {difference = arr[i+1]-arr[i];}

        System.out.println(difference);

        }
    }
}

A: I found out the answer online. Brillant!
public int getIndexOfMinimumDistance() {
    int index = 0;
    int[] numbers = new int[]{999,0,5,8,10,89,54};

    for (int i = 1; i < numbers.length - 1; i++) {
        if ( Math.abs( numbers[index] - numbers[index + 1]) >
            Math.abs( numbers[i] - numbers[i + 1])) {
            index = i;
        }
    }

A: step1: sort the array by applying any technique or using any predefined methods.
Arrays.sort(), Collections.sort etc. which is applicable.
step2: Iterate the elements and find the difference between the current and next element, store the difference in a variable and update it when the difference is smaller than the current.
int difference=0;
for(int i=0; i<n-1; i++){
    if(difference > (arr[i+1]-arr[i])){
        difference = arr[i+1]-arr[i];
    }
}

now you will have the smallest distance in difference variable.


text:
Q: Как открыть новое окно с использованием QML? Здравствуйте.
Пишу мобильное приложение на Qt 5.4. Для описания интерфейса взял QML. Возникла следующая задача.
Есть два окна, родительское и дочернее. Соответственно, вызов дочернего окна происходит из родительского.
Требуется вызвать дочернее окно так, чтобы при нажатии кнопки "назад" на ОС Андройд приложение возвращалась к родительскому окну.
При таком вызове дочернего окна кнопка назад выходит из приложения.
var component = Qt.createComponent("ChildWnd.qml")
var window    = component.createObject(root)
window.show()

A: Посмотрите пример Touch Gallery.
У меня Window на Андроиде не работает, работает только Dialog. Но там тоже есть проблемы с размещением компонентов. StackView оказался лучшим вариантом.

A: Обычно, в таких случаях дочернему окну передают ссылку на родителя. И дети уже юзают родительские методы show и hide.
A: еще один голос за StackView. Сам перепробовал несколько вариантов, в т.ч. Popup из controls 2, но и он мне не подошёл, хотя очень даже ничего.

A: К сожалению в андроид нельзя открыть "новое" окно, оно одно. Но вы можете заново загрузить старое с другой разметкой, для этого используйте слот в c++, подключенный к qml. Там вызываете приватный слот через
QUrl url(str);
QMetaObject::invokeMethod(this, "loadnewurl", Qt::QueuedConnection, Q_ARG(QUrl, url));

Уже в этом слоте обращаетесь к QQuickView, если обратится в первом программа упадёт, ибо один поток.
Вы можете использовать мой пример на github, https://github.com/tripolskypetr/qmlloadnewmarkup


text:
Q: Managing the palette indicators in gnuplot I would like to ask if someone knows how to manage the palette indicators in gnuplot, I want it to fit with my colors(12) and not to be added automatically
my code is
 set palette model HSV
 set palette rgb 3,2,2
 set palette maxcolors 12
 set view map
 set size square
 set key off
 set title "Neural network output (fitted curve)"
 set xlabel "x"
 set ylabel "y"
 set zlabel "z"
 set xrange [  -7.6625930750000002  :   27.166801390000000      ]
 set yrange [  0.35422432799999998  :   30.163194489999999      ]
 set zrange [  -55.934824620000001  :   2.4059901000000002E-002 ]
 set grid
 set terminal png size 1200,900
 set output "output/fitted_curve.png "
 splot "output/plot_data_pl.txt " with points palette pt 7 ps 1

A: For the maximum flexibility, you should define your own palette.
Here is what I once did to obtain a plot with 7 distinct colors. Thereby, I can also define which color represents a given range of values.
set palette defined (0 "black",\
                     0.5 "black",\
                     0.5 "red",\
                     1.5 "red",\
                     1.5 "orange-red",\
                     2.5 "orange-red",\
                     2.5 "orange",\
                     3.5 "orange",\
                     3.5 "yellow",\
                     4.5 "yellow",\
                     4.5 "light-green",\
                     5.5 "light-green",\
                     5.5 "green",\
                     6.5 "green")

Hence, you actually have to define from / to which value you want a color to span.
Of course, you can use rgb definitions for your color. A list of gnuplot-defined colors is here.
For the sake of completeness, here is the entire code I used:
set view map
set pm3d

set term pngcairo crop font 'lmroman10,32' size 1152,864
set border lw 2
set palette defined (0 "black", 0.5 "black", 0.5001 "red", 1.5 "red", 1.5001 "orange-red", 2.5 "orange-red", 2.5001 "orange", 3.5 "orange", 3.5001 "yellow", 4.5 "yellow", 4.5001 "light-green", 5.5 "light-green", 5.5001 "green", 6.5 "green")
set xlab 'time step ' offset 0,1
set xtics 2500 offset 0,0.65
set ylab 'position [cell]' offset +.5,0
set cblab 'velocity [cells/(time step)]' offset -.8,0
set cbtics offset -1.2,0
set xrange[100000:110000]
set yrange[0:10000]
set cbrange[0:6.5]

set style line 1 lt 1 lc rgb "blue" lw .85 pt 6 ps .6

splot '6.csv' u (($1)):($2):($3) w p palette t '', 'data.csv' u (($1)):($2):($3*0) w l ls 1 t '',  'data2.csv' u (($1)):($2):($3*0) w l ls 1 t ''


text:
Q: SSH: Connect to Host XXXXX Port 22: Connection timed out Estou enfrentando um problema no meu Ubuntu e também no Windows em que eu não consigo acessar nenhum SSH e SFTP. Somente recebo a mensagem de:  "Connection Timed Out". Já enviei o IP para meus amigos, e todos eles conseguiram acessá-lo sem problemas, somente eu que estou com este problema.
Mensagem informada na hora do erro:
SSH: connect to host xxxxx port 22: Connection timed out

A: Galera eu consegui resolver. o problema é que meu roteador estava bloqueando as portas menore que 1200. não sei por qual motivo... eu troquei a porta do ssh para > 1200 e funcionou. no meu caso eu coloquei 1500.
Quem estiver com esse problema ai está a solução, E obrigado a quem tentou ajudar.


text:
Q: No interpreta HTML que hay dentro de los campos de la tabla Primero disculpar si el título no hace referencia muy bien a la duda que tengo. No sabría como interpretarlo mejor.
Estoy aprendiendo Symfony y me encuentro con los formularios y como traer los datos de la BBDD. Por el momento me lo trae todo bien, pero en los campos de la BBDD si se encuentra código html, este al traerlo a la vista no se muestra, es decir.. no aparecen saltos de linea, negritas, o cualquier cosa que sea con el uso de etiquetas. Directamente suelta todo el texto uno detrás de otro en linea.
El campo en la tabla de la BBDD se encuentra como longtext y ahora os pongo todo el código para ver si podéis orientarme en donde me estoy equivocando.
He creado un servicio con el siguiente código:
<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Posts;

class ListPosts
{
    public $doctrine;

    public function __construct(ManagerRegistry $doctrine){
        $this->doctrine = $doctrine;
    }

    public function listPosts(){
        $entityManager = $this->doctrine->getManager();
        $posts = $entityManager->getRepository(Posts::class)->findAll();
        return $posts;
    }

    public function listPostById($id){
        $entityManager = $this->doctrine->getManager();
        $posts = $entityManager->getRepository(Posts::class)->find($id);
        return $posts;
    }

}

El controlador:
<?php

namespace App\Controller;

use App\Entity\Posts;
use App\Form\PostType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\Persistence\ManagerRegistry;
use App\Service\ListPosts;
use Symfony\Component\HttpFoundation\Request;

class PostController extends AbstractController
{
    #[Route('/post', name: 'app_post')]
    public function index(ListPosts $list, ManagerRegistry $doctrine): Response
    {
        return $this->render('post/index.html.twig', [
            'controller_name' => 'PostController',
            'list' => $list->listPosts()
        ]);
    }

    #[Route('/post/{id}', name: 'app_post_id')]
    public function indexId(ListPosts $post, ManagerRegistry $doctrine, int $id): Response
    {
        return $this->render('post/indexById.html.twig', [
            'controller_name' => 'PostController',
            'post' => $post->listPostById($id)
        ]);
    }

}

Este es el formulario de symfony:

<?php

namespace App\Form;

use App\Entity\Posts;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('title')
            ->add('content', TextareaType::class)
            ->add('date', DateTimeType::class)
            ->add('submit', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Posts::class,
        ]);
    }
}

Y esta es la vista:
{% extends 'base.html.twig' %}

{% block title %}Hello PostController!{% endblock %}

{% block body %}

{{ post.title }}

{{ post.content }}

{% endblock %}

Como he dicho el servicio me funciona, me trae y me muestra el campo de la tabla, pero en caso de que esta alguna etiqueta html como un salto de liena, negrita, encabezados, etc... se muestra la etiqueta en vez de interpretarla. Esto me es esencial si quiero mostrar por ejemplo el contenido de un post.

A: Por defecto, Twig va a escapar el contenido antes de mostrarlo en la página.
Para evitarlo es necesario usar el filtro raw.
En tu caso sería algo así:
{{ post.content | raw }}

Puedes ver la documentación en este enlace:
https://twig.symfony.com/doc/3.x/filters/raw.html


text:
Q: How to force spring to do not zip log files, instead append date at end of log file Currently I'm using spring boot logs and I'm configuring it through property file
below are the sample logging property
spring.main.banner-mode=off
logging.level.root= INFO,ERROR,DEBUG
logging.level.org.springframework.web= ERROR
logging.level.com.concretepage= DEBUG
logging.pattern.console=
logging.file = D://logTest.log
logging.file.max-size=100MB
spring.output.ansi.enabled=ALWAYS

The problem is that log file backup format is in .gz format
like logTest.log.2019-06-14.0.gz
How do I exclude default zipping ?
I don't want to hard wire configuration in xml file and put it inside resource folder.
I can only put rolling appender configuration xml file, but I want to make logging file path in property file, So I can dynamically set it for different environment.
Is there any way to achieve this configuration?

A: As an alternative to @simon-martinelli's correct answer, if you did not wish to use a custom logback-spring.xml file, the Spring configuration parameter logging.pattern.rolling-file-name can be set in your application.properties or application.yml file.
For example, to disable the compression used, remove the .gz suffix from the default file name pattern (${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz as per https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-custom-log-configuration).
This would require the addition of the following element to the application.yml file:
logging:
  pattern:
    rolling-file-name: "${LOG_FILE}.%d{yyyy-MM-dd}.%i"

Or if you are using application.properties, it would be:
logging.pattern.rolling-file-name = ${LOG_FILE}.%d{yyyy-MM-dd}.%i

A: Create a logback-spring.xml file in src/main/resources
With this content
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>

<appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <cleanHistoryOnStart>${LOG_FILE_CLEAN_HISTORY_ON_START:-false}</cleanHistoryOnStart>
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>${LOG_FILE_MAX_SIZE:-10MB}</maxFileSize>
            <maxHistory>${LOG_FILE_MAX_HISTORY:-7}</maxHistory>
            <totalSizeCap>${LOG_FILE_TOTAL_SIZE_CAP:-0}</totalSizeCap>
        </rollingPolicy>
    </appender>

</configuration>

If the fileNamePattern don't end with gz (or any other compression format) logback will not compress the files.


text:
Q: How to regex a particular array variable from code string I am fairly new to regular expressions and struggling to extract the content of an array inside a code string with python. The output should be a list containing the elements of the particular array in the code string.
Assume this text structure (multilines included) in my code.txt file I want to regex:
Some code
var array = [
    element1,
    ...
    elementN
    ]
Some more code

My best approach so far was with following pattern:
pattern = r"var array = \[\s*(.*)"

This gave me the first element of the array using re.findall(). The only thing missing in this pattern is "do until ]".
Many thanks for any help beforehand!

A: Just define the closing bracket in your regex:
pattern = r"var array = \[\s*(.*)\s*\]"

There is a really good site, where you can test your regular expressions, which also give hints on what you are doing:

A: It's not really possible to loop inside a regular expression. The easy solution here is to first match everything between the brackets and split and strip the contents. Here is some example code.
import re

code = r"""
Some code
var array = [
    element1,
    element2,
    elementN
    ]
Some more code
"""

elements = [element.strip() for element in re.search(r"var array = \[([\s\S]*)\]", code).group(1).split(",")]

print(elements)


text:
Q: LINQ QueryProvider Select I am trying to write a simple QueryProvider for a selection and keep failing. This is my example query:
var query = from elem in MyIQueryableImplementation
            select new {Name = elem.Name};

It is followed by a foreach statement that calls:
public IEnumerator<T> GetEnumerator()
{
    return ((IEnumerable<T>)this.provider.Execute(this.expression)).GetEnumerator();
}

Which invokes (ignoring the expression tree for now):
public override object Execute(Expression expression)
{
       return Exec();
}

And then:
public static IEnumerable<object> Exec()
{
     for(int i = 0; i < 10; i++)
     {
        yield return new {Name = "TEST"};
     }
     yield break;
}

Running this, it throws the exception (in the GetEnumerator() call):
Unable to cast object of type '<Exec>d__0' to type 'System.Collections.Generic.IEnumerable`1[<>f__AnonymousType0`1[System.String]]'.

How do I fix this?

A: The IEnumerable returned from Exec is an IEnumerable<object>. It happens to return elements of a type derived from object, but its interface type is just IEnumerable<object>. That's why you can't cast it to IEnumerable1[<>f__AnonymousType01[System.String]].
You can cast it element-wise, though:
return ((IEnumerable)this.provider.Execute(this.expression)).Cast<T>().GetEnumerator();


text:
Q: WatiN File Upload I've hit a snag. I am trying to use WatiN to upload a file. I can load the upload box, but it quickly disappears. The last line of my code at the moment is:
ie.FileUpload(Find.ById("profile_file")).Click();

It loads the dialog to select a picture but disappears. Is it possible to set the path of the box automatically example, load "C:/Desktop/image.jpg"?
Also, is it possible to wait for the upload to complete before continuing?
Help is much appreciated.
Thanks.

A: This is 6 years late, but if anyone else (like me) is still having trouble with this, here's a solution.
To fill out the file dialogue, try this:
ie.FileUpload(Find.ById("profile_file")).Set("filename.txt");

This will automatically pull up the file dialogue. You'll then see text being automatically typed into the file selection textfield.
No need for any sendkeys.

A: While this won't answer your question directly, I suspect there is a DialogWatcher automatically canceling the dialog.

A: why do you need to select from the Dialog.. Try to just sent the Text:
ie.FileUpload(Find.ById("profile_file")).Text = "C:/Desktop/image.jpg";

A: As a security measure, browsers don't allow scripts to set the value of a file input. Imagine if they did, I could put a hidden file input on my page where I have a contact form, and set its value to c:\topsecretinfo.txt without the user's permission. then when the user submits the form, voilà, I'd have their top secret information.
As luck has it, I ran into this issue today and this is what I did to get around it:

*

*created a new hidden field on the page called "testupload".

*used Watin to set the value of this hidden field to the path to my test
file

*on the server side, I check for this field and if it exists,
instead of reading the posted file, I read this file from my local
machine.


text:
Q: How do you get the Owner of a Computer in AD? (with .NET Core) Trying to find who joined the computer to the domain.  But in C# (.NET Core).
This is the exact answer (the question title is not worded well):
Powershell ADSI ntSecurityDescriptor
$Computer = [ADSI](([ADSISearcher]"(name=myComputer)").FindOne().Path)
$Computer.PsBase.ObjectSecurity.Owner

Alternatively, you can do this, but you need to have the Active Directory Module installed:
(Get-ADComputer myComputer -Server some.domain.com -Properties nTSecurityDescriptor).nTSecurityDescriptor.Owner

My assumption is that this returns who joined the computer to the domain, but I don't know how this actually works.  However this seems like the data I need, but I want to do this in C#.

A: This is what I've figured out based on StephenP's answer from that Powershell ADSI ntSecurityDescriptor question
string ldapPath = "LDAP://DC=some,DC=domain,DC=com";
DirectoryEntry searchRoot = new DirectoryEntry(ldapPath);

DirectorySearcher search = new DirectorySearcher(searchRoot)
{
    SearchScope = SearchScope.Subtree,
    Filter = "(&" +
        "(objectClass=computer)" +
        "(CN=machineName)"
    ")"
};

var result = search.FindOne();

// if GetOwner doesn't return null, then it will contain the SID (call .Value)
result.GetDirectoryEntry().ObjectSecurity.GetOwner(typeof(System.Security.Principal.NTAccount));

//this will translate the SID to a domain\username format, but will throw IdentityNotMappedException if it can't translate
result.GetDirectoryEntry().ObjectSecurity.GetOwner(typeof(System.Security.Principal.SecurityIdentifier));

Hope this works in your AD environment as well...


text:
Q: Extract variables from Lua into C++ I'm working on a numerical C++ code. This C++ code has a config file with physical parameters of my system. I would like to be able to do mathematical computations and some programming in a config file. Lua seems perfect.
suppose my lua file computes variable vol and mass:
method = cube
len = 3
rho = 1.5
vol = len*len*len
mass = vol*rho

I'd like to pass vol and mass to C++ code. I also would like to pass method, which is a std::string.
I can do something like this. However, in this example, they go through elements of a table one-by-one without relying on the variables' names. I'd like C++ to extract values of variables based on their names. also the structure of the lua config code may be more complicated; I might be writing few functions to get those values.

A: I think you can make function such as GetGlobal(name), which will basically return the value of given variable. Then call this function from C++ with appriopriate parameter pushed onto the stack, and take the result from the stack.
Additionally, it might be worth protecting your code from variables with wrong type, using lua_is* functions.
I can post you the more complete solution of the code, but I didn't want you to spoil you the fun of writing it yourself ;), so let me know shall you need any additional information.


text:
Q: Unusual error when I try to sfdx force:source:convert I'm using the exact same methodology and commands I've used dozens of times, and now I'm getting an error.
VS Code, latest version; sfdx extensions, latest versions.
I want to convert my source to mdapi, then deploy to my patch org.
I create the directory: mkdir mdapioutput
Then I put in the convert command:
sfdx force:source:convert -d mdapioutput/
Instead of converting, it gives this error:
patmcclellan: /Users/patmcclellan/Documents/GitHub/protontext-repo git:(master)
-> sfdx force:source:convert -d mdapioutput/
ERROR running force:source:convert:  The "path" argument must be of type string. Received type undefined

Can't figure out what I'm doing wrong. Any ideas?
Here's the sfdx-project.json:
 {
      "packageDirectories": [
        {
          "path": "force-app",
          "default": true
        }
      ],
      "namespace": "",
      "sfdcLoginUrl": "https://login.salesforce.com",
      "sourceApiVersion": "42.0"
}

I tried specifying the path as well:
    patmcclellan: /Users/patmcclellan/Documents/GitHub/protontext-repo git:(master)
-> sfdx force:source:convert -r force-app -d mdapioutput/

ERROR running force:source:convert:  The "path" argument must be of type string. Received type undefined

A: This error can be caused if you have a -meta-xml.cls file without the corresponding source file.

A: Looks like a bug. The -r parameter should be specified for the source directory. Alternatively, make sure the sfdx-project.json file contains a default path.