text:
Q: Creating a Pinterest-like layout for Xamarin.iOS I've tried for too long to figure out how to convert This into C# and iOS. I can basically find nothing that really helps me, especially on the .net side of things an was wondering if there is a kind soul that maybe has an example of an solution or is willing to maybe provide the code for such a solution.
Also, how would one use this solution with images that are being downloaded from a web request?
I've tried creating something similar which kinda works, problem is I can only simulate the different cell sizes, I can't figure out how to accually calculate the image size or how to even get the image information into my PrepareLayout() method in the Layout-class.
https://pastebin.com/jEXThW0X
public partial class CustomViewCell : UICollectionViewCell
{

    public CustomViewCell (IntPtr handle) : base (handle)
    {
    }
    public static readonly NSString Key = new NSString("ViewCell");
    public static readonly UINib Nib;

    public string ItemId { get; private set; }

    static CustomViewCell()
    {
        Nib = UINib.FromName("ViewCell", NSBundle.MainBundle);

    }

    public static CustomViewCell Create()
    {
        var cell = (CustomViewCell) Nib.Instantiate(null, null)[0];

        return cell;
    }

    public void Bind(ContentObjectViewModel model)
    {
        var imageUrl = $"myUrl/{image}";

        InvokeOnMainThread(() =>
        {
            ItemImageView.Image = ImageHelper.FromUrl(imageUrl);
            ItemId = model.Id.ToString();
        });

    }

    public async Task<UIImage> DownloadImageAsync(string imageUrl)
    {
        var httpClient = new HttpClient();

        Task<Byte[]> contentsTask = httpClient.GetByteArrayAsync(imageUrl);

        var contents = await contentsTask;

        return UIImage.LoadFromData(NSData.FromArray(contents));
    }
}

public class CustomDataSource : UICollectionViewSource
{
    public IEnumerable<ContentObjectViewModel> Items { get; set; }

    public override nint NumberOfSections(UICollectionView collectionView)
    {
        return 2;
    }

    public override nint GetItemsCount(UICollectionView collectionView, nint section)
    {
        var count = section == 0 ? 1 : Items?.Count() ?? 0;

        return count;
    }

    public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
    {

            var cell = collectionView.DequeueReusableCell(CustomViewCell.Key, indexPath) as CustomViewCell ?? CustomViewCell.Create();

            cell.Bind(Items.ElementAt(indexPath.Row));

            return cell;

    }

}

public partial class CollectionViewLayout : UICollectionViewFlowLayout
{
    private const int NumberOfColumns = 2;

    private readonly List<UICollectionViewLayoutAttributes> _calculatedAttributes = new List<UICollectionViewLayoutAttributes>();
    private nfloat _contentWidth = 0f;
    private nfloat _contentHeight = 0f;

    private readonly nfloat[] _columnsXOffset = new nfloat[NumberOfColumns];
    private readonly nfloat[] _columnsYOffset = new nfloat[NumberOfColumns];

    public CollectionViewLayout(IntPtr handle) : base (handle)
    {
    }

    public override void PrepareLayout()
    {
        base.PrepareLayout();
        _calculatedAttributes.Clear();

        _contentWidth = CollectionView.Frame.Width;
        var columnWidth = _contentWidth / NumberOfColumns;

        for (var i = 0; i < _columnsXOffset.Length; i++)
        {
            _columnsXOffset[i] = i * columnWidth;
        }

        for (var i = 0; i < _columnsYOffset.Length; i++)
        {
            _columnsYOffset[i] = 0;
        }

        var attribute1 = UICollectionViewLayoutAttributes.CreateForCell(NSIndexPath.FromItemSection(0, 0));
        attribute1.Frame = new CGRect(_columnsXOffset[1], 0, columnWidth, 0);
        _calculatedAttributes.Add(attribute1);

        //_columnsYOffset[1] = _buttonHeight; // Second column has a vertical offset (due to sell button height)
        var random = new Random();
        var column = 0;
        for (var i = 0; i < CollectionView.NumberOfItemsInSection(1); i++)
        {
            var cellHeight = random.Next(250, 500);
            var photoHeight = CollectionView.Frame.Height;
            var indexPath = NSIndexPath.FromItemSection(i, 1);

            var frame = new CGRect(_columnsXOffset[column], _columnsYOffset[column], columnWidth, photoHeight);
            var insetFrame = frame.Inset(0f, 0f);

            var attribute = UICollectionViewLayoutAttributes.CreateForCell(indexPath);

            attribute.Frame = insetFrame;

            _calculatedAttributes.Add(attribute);

            _contentHeight = NMath.Max(_contentHeight, frame.GetMaxY());
            _columnsYOffset[column] = _columnsYOffset[column] + photoHeight;

            column = column >= (NumberOfColumns - 1) ? 0 : ++column;
        }
    }

    public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
    {
        var attributes = new List<UICollectionViewLayoutAttributes>();

        foreach (var attr in _calculatedAttributes)
        {
            var intersection = CGRect.Intersect(attr.Frame, rect);

            if (intersection != CGRect.Empty)
            {
                attributes.Add(attr);
            }
        }

        return attributes.ToArray();
    }

    public override CGSize CollectionViewContentSize => new CGSize(_contentWidth, _contentHeight);

}

  public partial class TabProfileController : UIViewController
{
    private CustomDataSource _customDataSource;
    private readonly ContentServiceClient _contentServiceClient = new ContentServiceClient();
    private string _userId = "userid";
    bool useRefreshControl = false;
    UIRefreshControl RefreshControl;

    public TabProfileController(IntPtr handle) : base(handle)
    {
    }

    public override async void ViewDidLoad()
    {
        base.ViewDidLoad();

        AddRefreshControl();
        ProfileItemsCollectionView.Add(RefreshControl);

        imageViewProfilePicture.Image = UIImage.FromBundle("profilepic");
        imageViewProfilePicture.Layer.CornerRadius = imageViewProfilePicture.Frame.Size.Width / 2;
        imageViewProfilePicture.ClipsToBounds = true;

        //await LoadSaleItems();
        await InitializeCollectionView();

    }

    private async void HandleValueChanged(object sender, EventArgs e)
    {
        await RefreshAsync();
    }

    async Task RefreshAsync()
    {
        // only activate the refresh control if the feature is available

            RefreshControl.BeginRefreshing();
        _customDataSource.Items = await _contentServiceClient.GetItemsForUser(_userId.ToString());
        ProfileItemsCollectionView.ReloadData();
            RefreshControl.EndRefreshing();

    }

    // This method will add the UIRefreshControl to the table view if
    // it is available, ie, we are running on iOS 6+
    void AddRefreshControl()
    {

        // the refresh control is available, let's add it
        RefreshControl = new UIRefreshControl();
        RefreshControl.ValueChanged += async (sender, e) =>
        {

            await RefreshAsync();
        };
        useRefreshControl = true;

    }

    private async Task InitializeCollectionView()
    {
        var nib = UINib.FromName(CustomViewCell.Key, null);
        ProfileItemsCollectionView.RegisterNibForCell(nib, CustomViewCell.Key);

        _customDataSource = new CustomDataSource();

        var items = await _contentServiceClient.GetItemsForUser(_userId.ToString());
        _customDataSource.Items = items;
        ProfileItemsCollectionView.Source = _customDataSource;
        ProfileItemsCollectionView.ReloadData();

    }

A: So after a lot of research and some trial and error I've finally managed to understand delegates and how to use them in conjuction with Xamarin.iOS.
Basically what i had to do was to add the following to my Layout class:
public delegate CGSize CollectionViewDelegateFlowLayout(UICollectionView collectionView, UICollectionViewFlowLayout layout, NSIndexPath indexPath);
    public event CollectionViewDelegateFlowLayout SizeForItem;

And then call the event ''SizeFoItem' in the loop that calculates the sizes of the cells.
Finally adding the call into my ViewController like so:
collectionViewLayout.SizeForItem += (collectionView, layout, indexPath) => {

            return new CGSize((View.Bounds.Width - 40) / 3, photoheight
        };

The variable photoHeight comes from a list of photos that gets initialized when the ViewController is constructed.


text:
Q: Creating shapes in similar fashion as with autoshape dropdown I would like to make a macro in Powerpoint that enables me to create shapes in a similar fashion as when you select the autoshapes in the autoshape overview (i.e. once you call the macro you have a possibility to click to set the coordinates and subsequently you drag and click to set the width&height). Also, I would like to give it pre-set cosmetic characteristics (e.g. certain inner margins, fill color, border style and transparancy), which will be defined in the vba code.
I am aware of .addshapes(), however, this requires coordinates and height/width as input. Moreover, I have not find any posts / documents on vba to create shapes without defined coordinates and height/width.
Anyone some ideas on how to tackle this challenge?
Many thanks in advance!
Sofar

A: Building on what John Korchok suggested, here's code that retrieves the just-drawn shape so that your code can resume and manipulate it...
Sub testAppComBars()
    Dim SHP As Shape

    Application.CommandBars.ExecuteMso ("ShapeFreeform")

    Stop

    Set SHP = Selection.ShapeRange(1)
    With SHP.Fill
        .ForeColor.RGB = RGB(192, 0, 0)
        .Transparency = 0.75
    End With
End Sub

I would hope there's a more elegant solution than using Stop to pause code execution while the user picks the shape's location (or in this case, draws a freeform polyline/polygon), but that's all I could come up with off the top of my head.

A: I was fascinated by this problem and think this might help you.
Consider that when you draw a new autoshape, you have changed the window selection, and created a new selection ShapeRange with exactly 1 item (the new shape).
So by setting a WindowSelectionChange event, you're able to apply any formatting you wish at the time of creation.
First create a class module called cPptEvents with the following:
Public WithEvents PPTEvent As Application

Private Sub PPTEvent_WindowSelectionChange(ByVal sel As Selection)
    On Error GoTo Errhandler
    Debug.Print "IN_PPTEvent_WindowSelectionChange"

    Dim oShp As Shape

    If (ActiveWindow.ViewType = ppViewNormal) Then
        With sel
            If .Type = ppSelectionShapes Then
                If .ShapeRange.Count = 1 Then
                    Set oShp = .ShapeRange(1)
                    If oShp.Type = msoAutoShape Then
                        If oShp.AutoShapeType = msoShapeOval Then
                           If oShp.Tags("new_oval") = "" Then
                                oShp.Fill.ForeColor.RGB = RGB(255, 0, 0)
                                oShp.Tags.Add "new_oval", "true"
                            End If
                        End If
                    End If
                End If
            End If
        End With

    End If

    Exit Sub

Errhandler:
    Debug.Print "Error: " & Err.Description

End Sub

This checks the selection every time it changes.  If there's an oval selected, it looks for the "new_oval" tag, which will not exist for a newly created shape.  In that case, it applies a red fill, although of course once you get to this point you can call an entirely different sub, pass along the shape, and do whatever you want formatting-wise to it.
By adding that "new_oval" tag, you ensure that the formatting will not be applied to an oval that hasn't been newly created. This allows the user to make manual changes to the formatting as needed -- otherwise you're just resetting the formatting every time the user selects an oval.
Note that for the _WindowSelectionChange event to be running in the background, you have to call this at some point:
Public MyEventClassModule As New cPptEvents

'
Public Sub StartMeUp()
   Set MyEventClassModule.PPTEvent = Application
End Sub

You can include that one line from StartMeUp above in whatever Ribbon_Onload sub is triggered by your addin, if you're making a new addin ribbon.
With this solution, you don't even have to give the end user a special button or set of tools to create the shapes that are being formatted. It happens invisibly whenever the user draws a new shape from the native PPT tools.

A: This will put your cursor in drawing mode to draw an oval. After running, you may have to click on the slide once, then the cursor will change shape and you can draw an oval:
Sub DrawOval()
  Application.CommandBars.ExecuteMso ("ShapeOval")
End Sub

Other commands to substitute for ShapeOval:
ShapeRectangle
ShapeElbowConnectorArrow
ShapeStraightConnectorArrow
Get the full list in Excel spreadsheets from Microsoft Office 2016 Help Files: Office Fluent User Interface Control Identifiers
Look for the powerpointcontrols.xlsx file and search the first column with "shape"
There are 173 shapes in the menu, so you have a lot of macros to write.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java- paintComponent most efficient way of drawing millions of squares from an array I have written a program, based off of some examples, to simulate Conway's game of life.
Each cell in the game is either alive or dead and they are stored in an array of integers int[][] this array is always at least 1000*1000, meaning that there are millions of cells.
Iterating through the array to find apply all of the different rules is fine, and is not particularly CPU intensive. However, the method used to draw these rectangles on a JFrame can lead to 90+% CPU usage on my Xeon E3 1246 V3 (I7 4770). On array sizes of 2000^2, it can lead to Windows 10 hard locking completely.
@Override
    protected void paintComponent(Graphics g) {
        liveCells = 0;
        super.paintComponent(g);
        Color gColor = g.getColor();
        if(!backgroundWork || isPaused) {
            for (int row = 0; row < grid.length; row++) {
                for (int column = 0; column < grid[row].length; column++) {
                    //Checking if the cell is alive.
                    if (grid[row][column] == 1 ) {
                        liveCells++;
                        g.setColor(Color.red);
                        g.fillRect(column * UIScale, row * UIScale, UIScale, UIScale);

                    }
                }
            }
        }

        g.setColor(gColor);
        if (isPaused) {
            g.drawString("The game is paused", 0, 30);
            g.drawString("Generation: " + generationCounter, 0, 10);
            g.drawString("Living cells: " + liveCells, 150, 10);
        } else { //If the game is running
            g.drawString("Generation: " + generationCounter++, 0, 10);
            g.drawString("Living cells: " + liveCells, 100, 10);
        }
        g.setColor(gColor);
        try {
            /* Sleep for some microseconds. */
            TimeUnit.MICROSECONDS.sleep(sleepTimer);
        } catch (InterruptedException ex) {
            System.err.println("An InterruptedException was caught: " + ex.getMessage());
        }
    }

I can see quite clearly that the drawing of the cells is the problem, in order to allow the program to run faster, I had already added a way to change the variable backgroundWork, which disables updating the grid of rectangles. Turning this on or off results in differences of up to 80% in task manager CPU utilisation.
With the current method of drawing the grid, I don't see a way to make it much faster, as all the cells are independent of each other, and generally there won't be more than 3 which are red next to each other anyway, so there is no reason to implement a way to draw multiple at the same time.
Can anyone suggest a way to speed up the current process, or a different way of drawing the squares.
Thanks for any help.

A: This method, suggested by Hovercraft Full Of Eels (Nice name by the way) is much faster than what I was using previously-
@Override
protected void paintComponent(Graphics g) {
    liveCells = 0;

    BufferedImage BI = new BufferedImage(UIDimensions, UIDimensions, BufferedImage.TYPE_INT_RGB);

    super.paintComponent(g);
    Color gColor = g.getColor();
    if(!backgroundWork || isPaused) {
        for (int row = 0; row < grid.length; row++) {
            for (int column = 0; column < grid[row].length; column++) {
                //Checking if the cell is alive.
                if (grid[row][column] == 1 ) {
                    liveCells++;
                    if(UIScale != 1) {
                        //TODO- Draw squares larger than one pixel
                    } else {
                        BI.setRGB(column, row, 16711680);
                    }

                    //The old code is commented out below

                    //g.setColor(Color.red);
                    //Drawing the colour in a 4x4 pixel square. With a window of 1000x1000, there are 250x250 organisms, hence the /4 everywhere
                    //g.fillRect(column * UIScale, row * UIScale, UIScale, UIScale);
                    //The way that this works is that it draws rectangles at the coordinates of the grid.
                    //The graphics on the screen aren't a grid themselves, they are just lots of squares
                } else {
                    BI.setRGB(column, row, 16777215);
                }
            }
        }
        g.drawImage(BI, 0, 0, null);
    }

    g.setColor(gColor);

    if (isPaused) { //If the game is paused (isPaused is true)
        g.drawString("The game is paused", 0, 30);
        g.drawString("Generation: " + generationCounter, 0, 10);
        g.drawString("Living cells: " + liveCells, 150, 10);
    } else { //If the game is running
        g.drawString("Generation: " + generationCounter++, 0, 10);
        g.drawString("Living cells: " + liveCells, 100, 10);
    }
    g.setColor(gColor);
    try {
        /* Sleep for some seconds. */
        TimeUnit.MICROSECONDS.sleep(sleepTimer);
    } catch (InterruptedException ex) {
        System.err.println("An InterruptedException was caught: " + ex.getMessage());
    }
}


text:
Q: Is it safer to load Kernel32.dll with absolute path? I have a driver code with the following line
hKernel32DLL = LoadLibrary( "Kernel32.dll" );

Now someone reviewed my code and suggested to load the DLL with full path.
I did a quick search online about loading kernel32.dll but no one really use a full path.
Can someone explain to me why I should specify the absolute path of kernel32.dll?

A: It is safer to load .DLLs with a full path. Kernel32 is already loaded because you statically linked to LoadLibrary so in your specific case it does not matter. (On all versions of Windows except 2000, CreateProcess will load Kernel32 into the process before it even starts but this does not apply to other core .DLLs like Gdi32 and User32.)
If you are worried about .DLL hijacking attacks then you can call SetDefaultDllDirectories with the LOAD_LIBRARY_SEARCH_SYSTEM32 flag, this forces all .DLLs with a relative path to load from the system directory.


text:
Q: Create map network_iface_name <--> IPv4 address I'd like to implement a bash script that creates a mapping between the network cards (or interfaces) names in my computer and their IP address (in CIDR format, if possible).
The goal is having something like an associative array, or a file looking like:
lo: "127.0.0.1/8"
eth0: "192.168.1.123/24"
br-priv: ""      # <-- No IP assigned
wlan0: "10.42.0.10/24"

I have the ifconfig and the ip commands available, but the parsing of their outputs is a bit tricky, because the IP address and the interface's name don't appear in the same line so I would have to find the interface IP address and then rollback to find the network's name, or viceversa.
Is there any other way to find my interfaces IP addresses?
I have all the interfaces names (as directory names) under /sys/class/net/
root@borrajax:~# ls /sys/class/net/
br-priv/   eth0/    lo/    mon0/   wlan0/

But I haven't been able to find their IP in those directories. Doing that would be great, because I could just walk the directory, retrieve the directory's name and then read the IP from some other file.
This is intended to run in an embedded system running OpenWRT, but a solution for a Debian based system might be suitable. My bash's version is 4.2.28, just in case.

A: Use the "-o" option of ip:
ip  -o addr  | sed -e 's/^[0-9]: \([^ ]*\).*inet \([^ \t]*\).*/\1: "\2"/;t;s/^[0-9]*: \([^ :]*\).*/\1: ""/g' | sort -r | sort -u -t: -k1,1

Output should be then in your case:
br-priv: ""
eth0: "192.168.1.123/24"
lo: "127.0.0.1/8"
wlan0: "10.42.0.10/24"

The command prints only one IPv4 per network device (it is possible to configure multiple IP addresses at the same interface).

Explanations:
The sed expression
s/^[0-9]: \([^ ]*\).*inet \([^ \t]*\).*/\1: "\2"/;

replaces 1: lo    inet 127.0.0.1/8 brd 255 [...] with lo: "127.0.0.1/8"
t;

jump to end if this could be done (=an IPv4 address was found), otherwise:
s/^[0-9]*: \([^ :]*\).*/\1: ""/

replace lines without IPv4-addresses e.g. 1: lo    inet6 ::1/128 [...] with lo: "".
All lines are automatically printed out (no -n flag).
The command sort -r sorts now the line reverse. The lines with IPv4-addresses (e.g. lo: "127.0.0.1/8") are then in all cases before the lines without (lo: "").
The command sort -u -t: -k1,1 applies unique sorting to the first field (the interface names, separator is set to :). In our example only the "lo: "127.0.0.1/8" line survive as it comes first (due to the previous sorting).


text:
Q: Antiderivative of an even function I'm faced with an issue in terms of antiderivatives of even and odd functions.
Define $f \in C[-a,a]$ where $a>0$. Let $f$ be an even function on $[-a,a]$.
We wish to show that
$$\int_{-a}^a f(x)\ dx = 2\int_{0}^{a}f(x)\ dx$$
On the whole, I understand how to manipulate integrals and their substitution to get this result. However, I am faced with another alternative proof, where we define
$$F(x)=\int_0^x f(t)\ dt.$$
for $-a \leq x \leq a$, and it is easy to show that $F(-x)=-F(x)$, and so the proof can also proceed along these lines.
However, with a different definition of $F$, i.e.
$$F(x)=\int_{-a}^x f(t)\ dt,$$
I fail to be able to obtain the result.
So my question is, why does the first definition of $F$ work, and why does the second fail?
I hope to gain more understanding of even and odd functions from this.

A: Your second attempt failed because F (in second definition) no need to be either even or odd although $f$ is an even fuction on $[-a,a]$. As an example consider the  continuous function $f:[-1,1]\rightarrow \mathbb{R}$ define by $f(x)=1$ for each $x\in [-1,1]$. Then clearly f is even.
Observe that $$ F(x)=\int_{-1}^{x}f(t)dt=\int_{-1}^{x}1dt=x+1 $$.
Therefore $F$ is neither even nor odd.


text:
Q: CountDown timer PHP/JavaScript Hi I have a JavaScript for countdown which is selecting time form MySQL and it is working fine on (Chrome, Firefox), but on (IE and Safari) it is returning "NaNd NaNh NaNm NaNs".
I have attached my code below.
<?php
$con = mysqli_connect("localhost", "root", "", "timer") or die("Error Could
not connect to the database Sir." . mysqli_error($con));

$query = mysqli_query($con, "SELECT * FROM counter WHERE id = 1") or
die(mysqli_error($con));
$row = mysqli_fetch_array($query)or die(mysqli_error($con));

?>
<div id="form<?php echo $row['id'];?>" style="color:green" class="form-
group">

Please check if i am missing something again. thank you for all the replies.

A: Check carefully ' single quotes here, Use double quotes for first parameter as second param.
createCountDown("form<?php echo $row['id'];?>", "<?php echo $row['time_to_expire'] ;?>")

Here is working example

function createCountDown(elementId, date)
    {
    // Set the date we're counting down to
    var countDownDate = new Date(date).getTime();
    //console.log(countDownDate.getTime());
    // Update the count down every 1 second
    var x = setInterval(function()
    {

      // Get todays date and time

      var now = new Date().getTime();

      // Find the distance between now an the count down date
      var distance = (countDownDate) - (now);

      //Hint on converting from object to the string.
      //var distance = Date.parse(countDownDate) - Date.parse(now);

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 *
      60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Display the result in the element with id="demo"
      document.getElementById(elementId).innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";

      // If the count down is finished, write some text
      if (distance < 0)
      {
        clearInterval(x);
        document.getElementById(elementId).innerHTML = "ORDER EXPIRED";
      }
      }, 1000);
      }
      createCountDown('form1', "08-09-2017 12:10:00Z");
      createCountDown('form2', "08-09-2018 12:10:00Z");

A: EDIT
Internet Explorer and Safari aren't tolerant on malformed dates.
The date passed from PHP to JavaScript Date() : 2017-09-30 00:00:00 was "malformed".
It came from PHP Date("Y-m-d H:i:s"); which is VERY commonly used...
The fix on JavaScript side is: date = date.replace(" ","T");
It also could be fixed on PHP side with: $date = Date("Y-m-d\TH:i:s");
Or if the date comes form a database:
$date = str_replace(" ","T",$row['time_to_expire']);
createCountDown("form<?php echo $row['id'];?>", "<?php $date;?>")

The resulting date string is then 2017-09-30T00:00:00, which is ISO 8601 compliant.
The issue was abvout ONE character!
I'll remember that one.
;)

A: Use moment.js and try below code for timer
    var eventTime = moment("target time").unix(),
                currentTime = moment().unix(),
                diffTime = eventTime - currentTime,
                duration = moment.duration(diffTime * 1000, "milliseconds"),
                interval = 1000;

            if (diffTime > 0) {
                var timer = setInterval(function () {
                    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
                    var h = moment.duration(duration).hours(),
                        m = moment.duration(duration).minutes(),
                        s = moment.duration(duration).seconds();

                    // show how many hours, minutes and seconds are left
                    var temp = '
' + h + ' hr

'
                        + m + ' min

' + s +
                        ' sec
';
                    $(elementId).html(temp);

                   if ((h == 0 && m == 0 && s == 0) || (s < 0)) {
                      clearInterval(timer);

                }, interval);
            }
       }


text:
Q: How many bits of storage would be required if we are in a simulation? The answers here didn't really address what I was looking for (How many bits are needed to simulate the universe?), so...
If we are in a simulation, can we presume the simulation only needs to be perfect at the levels at which we consciously observe it, and it can therefore become more and more 'fuzzy' as we 'zoom out' (ie, we don't need to simulate all the atoms on the moon etc)? If so, in order to make the simulation just good enough to pass all our tests, only a fraction of the bit space for simulating the whole universe would be needed, and there must be plenty of opportunities for data compression too.
In other words, to create a simulation of the universe as "we observe it", how much storage is likely to be required?


text:
Q: "requestAnimationFrame" method is not working "requestAnimationFrame" method is not working in the following example. Console doesn't show any error messsage. Then what is the error in this code?
html:

         <canvas id="canvas" width="1024" height="1024"></canvas>

javascript:
 var canvas = document.getElementById('canvas');
 var ctx = canvas.getContext('2d');
 var chop1 = new Image();
 chop1.src = "img/chopper.png";
 var chopperX = 0;
 var chopperY = 0;
 var ascent = 20;

 function fly()
 {
    chopperY += ascent;
    ctx.drawImage(chop1, chopperX, chopperY, 30, 80);
    requestAnimationFrame(fly);

 }

 window.onload = function() {
    init()
 };

 function init()
 {
    chop1.src = "img/chopper.png";
    ctx.drawImage(chop1, 0, 0, 30, 80);
    fly()
 }
 ;

A: You probably want to scale the animation using the timestamp that's passed to the callback given to requestAnimationFrame. Use something like this:
var ascent = 20;
var limit = 5000;
var start = null;

function fly(timestamp) {
    if (start === null) {
        start = timestamp;
    }
    var progress = timestamp - start;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(chop1, 0, Math.min(progress / ascent, canvas.height),
                  chop1.width, chop1.height);
    if (progress < limit) {
        requestAnimationFrame(fly);
    }
}

requestAnimationFrame(fly);

You can modify ascent and limit to increase/decrease the animation's speed and final position to taste.
As others have mentioned, be sure to use the correct requestAnimationFrame:
window.requestAnimationFrame = window.requestAnimationFrame ||
                               window.mozRequestAnimationFrame ||
                               window.webkitRequestAnimationFrame ||
                               window.msRequestAnimationFrame;

More information:

*

*https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

A: You need to call your draw() from within the fly() here is how I got it working with comments to explain.  You'll need to change your image's src to what it is in your own project since I didn't have your image.
Edit:
Added a way to draw image based on image size and made image turn around at edges of canvas. And here is a fiddle to show it in action:
Canvas Animation
JavaScript
/**
 * Namespace to set up your animation
 * @namespace
 */
var anim = (function() {
   var exports = {};

   // Make sure we use the right "requestAnimationFrame"
   // For the right browser
   window.requestAnimationFrame =
           window.requestAnimationFrame ||
           window.mozRequestAnimationFrame ||
           window.webkitRequestAnimationFrame ||
           window.msRequestAnimationFrame;

   // Keep some variables for the namespace
   var canvas = null, // The Canvas element to draw to
           ctx = null, // The context of the canvas
           chop1 = null, // The image that will get drawn
           chopperX = 0, // The X position of the image
           chopperY = 0, // The Y position of the image
           ascent = 20;    // How much to increment height by per anim

   /**
    * The function to get called by, and to perpetuate
    * the requestAnimationFrame() function
    * @returns {undefined}
    */
   function fly() {
      // Increment the height of the image
      chopperY += ascent;
      // Switch directions at bottom of canvas
      if (chopperY > 1000) {
         ascent = -ascent;
      }
      if (chopperY < 0) {
         ascent = -ascent;
      }
      // Clear the canvas so the animation looks good
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      // Draw the image to the canvas
      ctx.drawImage(chop1, chopperX, chopperY, chop1.width, chop1.height);
      // Get ready to draw again on the next animation frame
      requestAnimationFrame(fly);
   }

   /**
    * Function to start the animation process
    * @param {Canvas DOM Element} canvasElement The canvas to draw on
    * @returns {undefined}
    */
   exports.go = function(canvasElement) {
      // Set the canvas we draw to
      canvas = canvasElement;
      // Get a context to draw to
      ctx = canvas.getContext("2d");
      // Create the image we want to draw
      chop1 = new Image();
      // Set the image's source
      chop1.src = "../../img/dice.png";
      // Start the animation process
      window.requestAnimationFrame(fly);
   };

   // Let our functions get called from our namespace
   return exports;
}());

/**
 * Function that gives the canvas element to the namespace to animate
 * @returns {undefined}
 */
function init() {
   anim.go(document.getElementById("canvas"));
}

/**
 * Function to start the initialization on a window load
 * @returns {undefined}
 */
window.onload = init;
//init();

HTML

         <canvas id="canvas" width="1024" height="1024"></canvas>


text:
Q: Workflow when connecting to spring AspectJ project colleagues.
I connect aspects, native ajc compiler. Idea used: Intelleje IDEA
Technologies on the project:
Maven
Spring boot
Lombok

Problem: Trying to run aspectj for java 16 with integrated stack of the above technologies. + framework for automating the assembly of projects to build in jar with working aspects
I tried:
1. plugin for automated project building "org.codehaus.mojo" works only with Java 1.8, I cannot use later versions. As I understand it, the plugin is outdated.

2. Including aspectjrt in project dependencies and assigning aspectjtools and aspectjweawer to the project facet

3. Various manipulations with installing the Java version in ide

Results:
1. Works but target is not achieved (java before 8)
2. Does not work
3. Does not work

Spent time studying the material: 2-3 weeks, shoveled a bunch of articles and Internet resources. Also read the book casually AspectJ in action
I am attaching a pom file with a working plugin:
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>MyAopWithoutSpring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--    <parent>-->
    <!--        <groupId>com.baeldung</groupId>-->
    <!--        <artifactId>parent-boot-2</artifactId>-->
    <!--        <version>0.0.1-SNAPSHOT</version>-->
    <!--        <relativePath>../parent-boot-2</relativePath>-->
    <!--    </parent>-->
    <!--    <parent>-->
    <!--        -->
    <!--    </parent>-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>${aspectj-plugin.version}</version>
                <configuration>
                    <complianceLevel>${java.version}</complianceLevel>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <showWeaveInfo>true</showWeaveInfo>
                    <verbose>true</verbose>
                    <Xlint>ignore</Xlint>
                    <encoding>UTF-8</encoding>
                    <excludes>
                        <exclude>**/pointcutadvice/**</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>10</source>
                    <target>10</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <aspectj-plugin.version>1.11</aspectj-plugin.version>
        <java.version>1.8</java.version>
    </properties>

</project> ```

To be honest, I am already ready to despair, I do not understand the sequence of actions at all in order for it to somehow work on the technology stack that is necessary. I will be glad to any advice and tips from more experienced colleagues

A: *

*Version 1.14.0 of the MojoHaus AspectJ Maven Plugin supports Java 16.

*Version 1.13.1 of the AspectJ.dev AspectJ Maven Plugin has additional features, supports Java 16 and 17 and can be configured to support future Java and AspectJ versions greater than 17 too.

*Both plugins already have a dependency on the AspectJ compiler contained in aspectjtools, which you can up- or downgrade, if you need a specific version.

*You do need to add aspectjrt when using compile-time weaving, because running AspectJ-enabled programs needs a small AspectJ runtime.

*IntelliJ IDEA has plugins for "AspectJ" (marketplace, author JetBrains) and "AOP Pointcut Language" (bundled). You can install both in order to get support for the AspectJ syntax and also for AspectJ Maven Plugin (both variants mentioned above).

*When combining Lombok and AspectJ, please be aware of possible problems, because they both fork the Eclipse Java Compiler in different ways. The problems can be solved by either weaving delomboked source code or by first applying Lombok with javac and then adding an additional AspectJ binary weaving build step. See here and here


text:
Q: Syntax Coloring for Studio Code Server YAML file type in Home Assistant Add-on not working? My understanding is the editor add-on should be configured by default for YAML syntax, but mine shows no coloring.  How do I enable colored syntax?
I tried other plugins such as Prettier but no effect.
I've Googled as well but no luck.
Thanks.


text:
Q: Crash when using indexPath.row in a modalViewController I've a problem with indexPath.row, when I try to access this variable my app crashes and I get no errors on the console :(
the code is this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    NSLog(@"%@", indexPath); //works fine
    NSLog(@"%@", indexPath.row); //crash
}

and I'm using it inside a ModalViewController.

A: You have to use
NSLog(@"%d", indexPath.row);

instead of
NSLog(@"%@", indexPath.row);

This is because, indexpath.row is an integer and you have to use the %d .


text:
Q: PYTHON: How to make sure biggest number ALWAYS divide the smallest number Quick question:
Was wondering how to make sure ; when doing a division calculation so that the LARGEST NUMBER will always divide the SMALLEST number.
my friend told me it's like:
abs(Number1/Number2)

Is the code above correct?
Or is there another method to make sure it wiill work. :)

A: If I understood your question correctly min(a, b)/max(a, b) should be ok.
EDITED: max(a, b)/min(a, b) does same thing oposite way

A: If you want to avoid duplicating the variable names and creating new variables
from operator import div
result = div(*sorted((Number1, Number2), reverse=True))

eg.
>>> div(*sorted((10, 5), reverse=True))
2

>>> div(*sorted((5, 10), reverse=True))
2

Usually it's going to be better to do something like this
small, big = sorted((Number1, Number2))
result = big / small


text:
Q: Search a query in multiple sql server table i have many tables that contains same column i want to search for a value and return all the line for example
Tab1

col1 col2 col3

val1   val2  val3

val7   val8  val9

Tab2
col1 col2 col3

val4   val2  val5

i want the sql syntax that return if i search in my java code for val2 the two lines
Tab1

col1   col2  col3

val1   val2  val3

and
Tab2

col1   col2  col3

val4   val2  val5

thank you

A: You can try doing a UNION between two queries each of which selects the records you want:
SELECT col1, col2, col3, 'Tab1' AS table_name
FROM Tab1
WHERE col2 = 'val2'
UNION ALL
SELECT col1, col2, col3, 'Tab2'
FROM Tab2
WHERE col2 = 'val2'

If you want to search for val2 in any column, then you can use this:
SELECT col1, col2, col3, 'Tab1' AS table_name
FROM Tab1
WHERE col1 = 'val2' OR col2 = 'val2' OR col3 = 'val2'
UNION ALL
SELECT col1, col2, col3, 'Tab2'
FROM Tab2
WHERE col1 = 'val2' OR col2 = 'val2' OR col3 = 'val2'

A: you also can try sp_MSforeachtable and temporary table.
    CREATE TABLE #tt(col1 INT,col2 INT,col3 int)
    INSERT INTO #tt
    EXEC sp_MSforeachtable 'select  * from ? where col1=''1'' and OBJECT_ID(''?'') in (OBJECT_ID(''table1''),OBJECT_ID(''table1''),OBJECT_ID(''table1'')) '
    SELECT * FROM #tt


text:
Q: What is the best way for fetching data and for passing to another Activity?
Most the app so far I had created, I fetch the data from Network and store it in a singleton class to share data between Activities, when I'm done with those data, I usually clear those setting it to NULL, its work perfectly well

My Question is which approach is better ??

*

*Use parcelable

*Writing in database and Query for it

*Singleton classes

When exactly we need to use Loaders ?? Why we can't share the data through Loaders ??
If question is repeated ... Please ignore ??

A: Answer to first part

*

*Parcelable:
The best way to pass data between Activitys or Fragments is by using Parcelable objects. It is said to be more optimised than Serializable. There are couple of libraries/plugins which can help you create Parcelable objects. Lately I was referred to Parceler, created by John Carl. However, I personally use Android Parcelable code generator by Michal Charmas, plugin for IntelliJ IDEA and Android Studio.

*DataBase or SharedPreferences:
Using DataBase or SharedPreferences to pass data between Activitys or Fragments sounds weird, and since they are not designed to be used this way, it will only create a mess.

*Singletons:
Read this very informative post Singletons are Pathological Liars.
Conclusion:
I recommend Parcelable or if you want to be real lazy then go for Serializable (it's not terrible but it's not great either, according to most).
Don't mess up your code by using singletons, DataBases, static fields, etc. They will come back and haunt you.
Answer to second part:

When exactly we need to use Loaders

Loaders, which will be AsyncTaskLoader when you use, are basically used for situations where we want to retrieve data from the server (via web API), or doing something in background. It is similar to using Thread or AsyncTask but is very powerful as it isn't destroyed on screen rotation, unlike those two.
You should read How to Use Loaders in Android and Alex Lockwood's posts on Loaders (this is a series of 4 posts. Very detailed and great).

A: It all depends on the way you want to use the data.If you want to use the data in future, as in after the application is killed and re launched you should save it in a database.
I would prefer parcelable over a singleton as I don't have to bother about clear the data.
According to the Documentation we generally use loaders to load data asynchronously and to monitor a the data source for change. To my understanding you aren't doing either of them, hence loaders are not required in this case.

A: 1.Database: If you are going to use the network data in future or you are going to do some query operation to perform filtration according to requirement,it is preferable to go with db.
2.Singleton Class: Most of the developer use this because it is more efficient,the values can be changed and retrieve easily with the help of getters and setters.

A: Here is a very cool way of passing data to another activity I read this somewhere else on Stackoverflow and always use it now. It may not fit your use-case but it sounds like it will.
For example, say you want to pass a parcelable "DataModel" from ActivityA to ActivityB.
Inside ActivityB create a public static method called 'start' like this.
private static final String DATAMODEL_KEY = "datamodel_key";

public static void start(Context context, DataModel dataModel) {
        Intent intent = new Intent(context, ActivityB.class);
        intent.putExtra(DATAMODEL_KEY, dataModel);
        context.startActivity(intent);
    }

To start ActivityB simply call the 'start' method above like this
ActivityB.start(this, datamodel);

Use 'this' if called from an activity, or 'getActivity()' from with a fragment.
This will contain the code for starting ActivityB inside ActivityB, like the private static final DATAMODEL_KEY field and such. To answer your question though, go with option 1 and use parcelables and try out the code I posted above to help with starting the Activity with the data.


text:
Q: git repo with svn external/submodule I have been searching for a long time now.
And cannot really find a good enough answer for my problem.
We now use SVN for our projects. These projects share 3 libraries which are also SVN repos.
We include them into our projects via SVN externals.
We are looking into GIT now and I am searching for a solution to use these libraries and keep them synced between GIT and SVN.
I tried using submodules, but they only support GIT repos, not SVN.
Then I created a new GIT repo for our library and used that as a submodule in our GIT project. Then I added a svn remote to the submodule, which allowed me to fetch from svn and commit to svn.
But then I ran into the problem where the new GIT library and SVN library went out of sync. someone committed to SVN and i comitted to GIT and all hell broke loose. I cannot get them synced anymore. Merging and more stuff failed all over the place.
so the solution I came up with is not what I want.
It generated more problems than solutions for us.
So, my question: What is the best solution to keep data synced?
Some relatively older projects need to keep the reference to their GIT or SVN revision(submodules do exactly what we want).
It is o.k. for us, for now, to keep de libraries in SVN only.
Can someone explain to me how this should/can be handled?
Thank you


text:
Q: Is it possible to create button by reading a saved file in Tkinter I have a button which will toggle the frame to be visible or hidden and the frame contains a few buttons inside.
I have a saved file where I'll store the name of the buttons I would like to display.
Is there any possible way where I could use the saved file to create the buttons to be displayed (in the case of multiple files)
At the moment I could only pre-create the buttons

A: So based on what you described and the sample text file you provided, here is a (not the best) working solution for you. Must read the comments in code snippet to understand what I did.
To summarize though, just read the file, save the data in a variable (may be list, dict or whatever). Then use those variables to create widgets.
If I missed some point in the question or I misunderstood the question, do let me know.
try:
    import tkinter as tk  # for python 3.x
except ImportError:
    import Tkinter as tk  # for python 2.x

# a function to create buttons. Optional if you don't plan to
# give these buttons a command (I'm sure you will but it's up to you)
def createButton(buttonName):
    tk.Button(root, text=buttonName).pack()

# reading the file content
with open('test.txt') as file:
    buttonNames = file.read().split()

root = tk.Tk()
root.geometry('200x200')

# Looping through the names that were in the file
for buttonName in buttonNames:
    createButton(buttonName)

root.mainloop()

a sample image of program for the text file you provided ::


text:
Q: On matrices in linear forms with vanishing determinant This is a cross-post from my original question at math.se. I decided to post here because it seems more difficult than I originally thought.
Let $R=\mathbb C[x_1,\ldots,x_r]$ be a polynomial ring. Assume that $f_{ij}\in R$ are homogeneous linear polynomials for $1\le i,j\le n$. If $\det(f_{ij})=0$, I can consider this equation over $K:=\mathrm{Frac}(R)$ and get $\lambda_1,\ldots,\lambda_n\in K$, not all zero, with the property that
$$ \forall i:\quad \sum_{j=1}^n \lambda_j\cdot f_{ij} = 0 $$
Now, I can clear denominators and assume $\lambda_j\in R$. Since the $f_{ij}$ are homogeneous, I can also assume that the $\lambda_j$ are homogeneous and of minimal degree with the above property. Unfortunately, the $\lambda_j$ do not have to be constant (which is my desire), made visible by the simple counterexample
$$\begin{pmatrix} x&y\\x&y\end{pmatrix} .$$
However, note that it is true for the transpose. So we similarly choose homogeneous $\mu_1,\ldots,\mu_n\in R$ which are not all zero and of minimal degree with
$$ \forall j:\quad \sum_{i=1}^n \mu_i\cdot f_{ij} = 0$$
Question: Is it true that if the $\lambda_j$ are not all constant, then all the $\mu_i$ are constant?
I think the answer is affirmative, so my search for better counterexamples might have been half-hearted. However, so far, I cannot give a proof either. Searching the literature has yielded almost nothing, maybe I am looking in the wrong places. Your help is greatly appreciated!

A: The simplest counterexample is the following bivariate one:
$$
\begin{bmatrix}
0 & x & y\\ x & 0 & 0\\ y & 0 & 0
\end{bmatrix},
$$
with left and right kernel spanned by $v=\begin{bmatrix}0 \\ -y \\ x\end{bmatrix}$.
See also my comment for a literature pointer on how to construct bivariate examples with arbitrary kernel structure.

A: The answer is negative. Your problem amounts to the following one:
given a linear subspace $V$ of $M_n(\mathbb{C})$ consisting entirely of singular matrices,
is it true that either all the matrices of $V$ vanish at some common non-zero vector,
or the same holds for all the matrices of $V^T$?
For $2 \times 2$ matrices, the result is known to hold (this is a special case of Schur's theorem on vector spaces of matrices with rank at most $1$).
For greater values of $n$, the following example shows that your conjecture fails:
one takes the space $V$ of all $n \times n$ matrices of the form
$\begin{bmatrix}
? & [?]_{1 \times (n-1)} \\
[?]_{(n-1) \times 1} & [0]_{(n-1) \times (n-1)}
\end{bmatrix}$. Obviously, all these matrices have rank at most $2$ and hence they are singular if $n>2$. On the other hand, no non-zero vector is annilated by all the matrices in $V$,
and the same holds for $V^T$ as $V^T=V$.

A: Typically there is no (nontrivial) "constant" solution of either $A\vec{\lambda}=\vec{0}$ or $A^\dagger\vec{\mu}=\vec{0}$.  For instance, consider the following $6\times 6$ matrix,
$$ A= \left[ \begin{array}{rrrrrr}
y & -x &  0 &  0 &  0 &  0 \\
z &  0 &  0 & -x &  0 &  0 \\
0 &  y & -x &  0 &  0 &  0 \\
0 &  z &  0 & -y &  0 &  0 \\
0 &  0 &  0 &  0 &  z & -y \\
0 &  0 &  z &  0 & -y &  0
\end{array} \right]. $$
One nontrivial "nullvector" is
$$ \vec{\lambda} = \left[ \begin{array}{r}
x^2 \\ xy \\ y^2 \\ xz \\ yz \\ z^2
\end{array} \right]. $$
Thus, $\text{det}(A)$ is zero.  However, there is no nontrivial constant solution of $A\vec{\lambda} = \vec{0}$, nor of $A^\dagger \vec{\mu} = \vec{0}$.


text:
Q: Create a subquery in a view SQL- ORACLE I am setting up a database view.
I have a table PERSON and a RELATION_COMPANY related by the person_id. I amb trying to obtain the min date from the relation_company for each person_id.
I need to use a subquery?
This is what I have tried so far.
CREATE OR REPLACE VIEW PEOPLE_ADDRESS
select
    p.id as ADDRESS_CODE,
    case p.type_
        when 1 then 'JURIDICAL'
        when 0 then 'NATURAL'
    end PERSON_TYPE,
    (select min(start_date) from relation_company where relation_company.person_id = p.id) as INITIAL_dATE
    P.ID as PERSON_CODE,
    p.ADDRESS_NAME as ADDRESS,
    p.POSTAL_CODE as POSTAL_CODE,
    case P.COUNTRY_ID
        when 68 then 'NO'
        else 'YES'
    end FOREIGN_INDICATOR

from
    PERSON p join relation_company r on relation_company = p.id ;

That's my person table:
ID TYPE_ ADDRESS_NAME          NAME             OTHER COLUMNS
1   0    AVENUE SMITH, 19      MICHAEL SCOTT     ....
2   1    OXFORD STREET , 119   COMPANY A          ....
3   1    CHESTHAM ROAD, 7      COMPANY B          ....

That's the RELATION_COMPANY table:
ID      PERSON_ID       START_DATE
1           1           2016-12-12 00:00:00
2           1           1981-07-09 00:00:00
3           2           1991-10-10 00:00:00
4           2           1981-03-09 00:00:00
5           3           1984-07-05 00:00:00
6           3           1981-08-11 00:00:00
7           3           1987-07-09 00:00:00
8           3           2011-07-09 00:00:00

select min(START_DATE) from RELATION_COMPANY group by PERSON_ID;

The result should be:
ADDRESS_CODE  PERSON_TYPE    INITIAL_dATE                 other columns
1             NATURAL        1981-07-09 00:00:00             ....
2            JURIDICAL      1981-03-09 00:00:00               ....
3             JURIDICAL     1981-08-11 00:00:00

I want to get the min(start_date) for each person_id and print it to the view to the column INITIAL_dATE.
I am having trouble to create that query.

A: You Already have the solution, this query are missing the "person_id" column in your SELECT statement.
Change this query
select min(START_DATE) from RELATION_COMPANY group by PERSON_ID;

To this.
select min(START_DATE),PERSON_ID from RELATION_COMPANY group by PERSON_ID;

Hope this helps.

A: You don't need a subquery for your solution.
Only add a group-clause to your query.
like this one:
select
p.id as PERSON_ID,
case p.type_
    when '1' then 'JURIDICAL'
    when '0' then 'NATURAL'
end PERSON_TYPE,
min(start_date) as INITIAL_dATE,
p.ADDRESS_NAME as ADDRESS,
p.POSTAL_CODE as POSTAL_CODE,
case P.COUNTRY_ID
    when 68 then 'NO'
    else 'YES'
end FOREIGN_INDICATOR
from PERSON p join relation_company r on r.person_id = p.id
group by p.id, type_, ADDRESS_NAME, POSTAL_CODE, P.COUNTRY_ID;


text:
Q: Access Here XYZ Studio Map GeoJSON via API? I'm wondering if there's a way to build a map in Here XYZ Studio but then get said map's GeoJSON via one of the Here APIs.

A: HERE Maps API for Javascript can render your XYZ Studio spaces directly:
// Assumption: the platform is instantiated
var service = platform.getXYZService({
      token: 'authentication_token_goes_here'
    }),
    provider = new H.service.xyz.Provider(service, 'space_id_goes_here');
map.addLayer(new H.map.layer.TileLayer(provider));

doc: https://developer.here.com/documentation/maps/3.1.14.0/api_reference/H.service.xyz.Provider.html

It also can render geojson features:
var reader = new H.data.geojson.Reader('/path/to/geojson/file.json');
reader.parse();
// Assumption: map already exists
map.addLayer(reader.getLayer());

doc: https://developer.here.com/documentation/maps/3.1.14.0/api_reference/H.data.geojson.Reader.html

Here is simple jsfiddle example of loading geojson features (country shapes):
https://jsfiddle.net/vhwfg8t4/


text:
Q: How to remove linux from a dual boot (Mint/Windows 10) NOT FROM A PARTITION but from 2 different disks? Can I do the same as we do if the two systems are in the same HDD in 2 partitions or there is something else I should consider?

A: delete the partition while in windows, reboot and do a fixmbr afterwards with a windows live CD/flashdrive

A: For safety, first update the bootloader, and make sure than you can still boot into the windows partition without getting the choice.  Be very sure you know which disk/partition is used by which OS (if you delete the wrong partitions you might never be able to boot into anything).
Then just boot into windows and delete the two Linux partitions (hopefully Microsoft will warn you if you try to delete the wrong one).  That will leave you downgraded to "only windows".  The extra disk doesn't make a difference - it's just like having C: and D: drives in windows.
Of course, you could do it the other way around, and delete the windows partitions ;)


text:
Q: What's the best way to leave a backdoor in ASP.NET Identity app? I'm a developer of a company's internal client system and there are some situations I have to login into the system using a user account to check for a bug or something. Since passwords are encrypted I can't just look up them in the DB and get the access.
The best thing I invented is to use a query parameter flag like ?heyThisIsAdmin=soJustLetMeInWithoutAnyPasswords which allows me to enter any password and log in.
But I quite understand the security concerns. Could you advise me some ways of achieving what I want but more robust and safe?

A: As you said, the solution you propose is not safe at all as any person reading the code or knowing the secret would use the magic query string to use this super power as well.
A better solution could be to create yourself an account on the client platform, but with a special flag on it allowing you to impersonate user accounts (or just see what they see). Such mechanism would require some development of course.
Please note that even with this solution the trick could only be done once your are already logged in. To increase security you could also require a 2nd factor for your authentication (email, SMS, TOTP...)
You need to see what you're trying to achieve here as a feature of your app, not a backdoor. You should be able to explain how it works to anyone without exposing your app. Because the strength of it is in:

*

*your password

*your second factor if any

*the fact that you have THE flag set on your account

A: ASP has the ability to handle this through impersonsation. You'll need to implement methods to both set and disable imperonsation.
The way I implemented this was to only decorate the SetImpersonation action with [Authorize] attributes to only allow the Admin user role to impersonate users.
Here's an example for MVC:
To set the impersonation
  [Authorize(Roles = (AccountController.Permissions.SUPER_USER))]
    public ActionResult ImpersonateUser(string userName)
    {
        string originalUsername = LoggedInUser.Email;

        ApplicationUser impersonatedUser = UserManager.FindByNameAsync(userName).Result;

        var impersonatedIdentity = UserManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie).Result;
        impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));
        impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);

        return RedirectToAction("Index", "Home");
    }

And to revert the impersonation (this action needs to be accessible by the imperonsated user)
public ActionResult RevertImpersonationAsync()
    {
        if (!HttpContext.User.IsImpersonating())
        {
            // we could throw an exception here, but it might be more prudent to just silently fail, keeps this feature quiet from snoopers

            //throw new Exception("Unable to remove impersonation because there is no impersonation");

            return RedirectToAction("Index", "Home");
        }

        var originalUsername = HttpContext.User.GetOriginalUsername();

        var originalUser = UserManager.FindByNameAsync(originalUsername).Result;

        var impersonatedIdentity = UserManager.CreateIdentityAsync(originalUser, DefaultAuthenticationTypes.ApplicationCookie).Result;

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);
        return RedirectToAction("Index", "Home");
    }


text:
Q: Characteristic function of $X+X^2$ if $X$ is a standard Gaussian random variable Can anyone please tell me how I can find the characteristic function of the random variable given by the sum $X+X^2$ where $X$ is a standard Gaussian random variable?
Many thanks!

A: In a comment I indicated how the answer can be found from knowledge of the Non-central chi-squared distribution.  Here I will sketch how to find it from the definition.
Let $X$ be a random variable.  Recall that the characteristic function of any random variable $g(X)$ is, by definition, a function of a real variable $t$ given by
$$\phi_{g(X)}(t) = E\left[e^{ig(X)t}\right]$$
where $i^2=-1$ is a Complex imaginary unit.
For a standard Gaussian (Normal) random variable, this expectation is the integral against the Normal density $$f(x)\mathrm{d}x = \frac{1}{\sqrt{2\pi}} e^{-x^2/2}\mathrm{d}x,$$
so with $g(x) = x+x^2$ we find
$$\eqalign{\phi_{X+X^2}(t) &= \frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}} e^{i(x+x^2)t}e^{-x^2/2}\mathrm{d}x = \frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}} e^{-(x^2 -2i(x+x^2)t)/2}\mathrm{d}x.\tag{1}
}$$
Evaluate this integral by completing the square
$$x^2 - 2i(x+x^2)t = (1-2it)\left(x^2 -\frac{2ixt}{1-2it}\right) = (1-2it)\left(x -\frac{it}{1-2it} \right)^2 + \frac{t^2}{1-2it}.$$
This puts the exponent in integral $(1)$ into the form
$$-\frac{1}{2\sigma^2}((x-\lambda)^2) + \gamma$$
where $\sigma^2 = 1/(1-2it),$ $\lambda = it/(1-2it),$ and $\gamma = -t^2/(2(1-2it)).$  Because
$$1 = \frac{1}{\sqrt{2\pi\sigma^2}}\int e^{-u^2/(2\sigma^2)} \mathrm{d}u,$$ upon the change of variable $u=x-\lambda,$ $(1)$ becomes
$$\eqalign{\phi_{X+X^2}(t) &= e^{\gamma}\frac{1}{\sqrt{2\pi}}\int_{-\infty-\lambda}^{\infty-\lambda} e^{-u^2/(2\sigma^2)}\mathrm{d}u \\&= e^\gamma \sqrt{\sigma^2}\frac{1}{\sqrt{2\pi\sigma^2}}\int_{-\infty-\lambda}^{\infty-\lambda} e^{-u^2/(2\sigma^2)}\mathrm{d}u \\
&= e^\gamma \sqrt{\sigma^2} \\&=\frac{e^{-t^2/(2(1-2it))}}{\sqrt{1-2it}}.
}$$

As a quick check, I simulated 10,000 realizations of $X$ and estimated $\phi_{X+X^2}(t)$ for a range of values of $t$ by averaging their realizations.  This figure graphs the real and imaginary parts of $\phi_{X+X^2}$ in red and overplots the simulated estimates: the agreement is excellent.

This is the R code to do these calculations:
x <- rnorm(4e4)
t <- seq(-1e2, 1e2, length.out=201)
z <- sapply(t, function(t) mean(exp((x + x^2) * (1i * t))))
phi <- function(t) exp(-t^2 / (2*(1-2i * t))) / sqrt(1 - 2i * t)
par(mfrow=c(1,2))
for (s in list("Re", "Im")) {
  f=eval(parse(text=s))
  curve(f(phi(t)), xname="t", xlim=range(t), col="Red", lwd=2, n=501, ylab="",
        main=substitute(f(phi[X+X^2]), list(f=s)))
  points(t, f(z), pch=16, cex=1/2)
}
par(mfrow=c(1,1))


text:
Q: How to keep track of users (connections) in a WebSocket Chat application I'm using the em-websocket (Ruby EventMachine) gem to serve up a WebSocket chat application. I was able to get a demo app working pretty easy (based on this gist). Now I would like to go a little more advanced. Currently, the only functionality is to post a message to the chatroom, but it is not show who sent the message (because I don't know how to keep track of this information).
I'm assuming the way to do this is to send JSON back and forth with some sort of ID, but where does this ID come from? Is there some sort of reusable ID that is unique to each connection that identifies the user?
Sorry if this is a dumb question, I am new to working with WebSockets.

A: I have written a basic chat app using em-websocket.  You can see the code here:
https://github.com/DavidEGrayson/websocket-chat/blob/master/rws1/server.rb
The em-websocket gem creates a web socket object to represent each connection.  I made my own Client class which holds a user name and a reference to the websocket object.
Feel free to ask me questions about that code.


text:
Q: How to link between django views components Actually, I am pretty new in Django. I have created three views in my views.py.
This is my following code in views.py :
from django.shortcuts import render
import pymongo
from .models import *
from .serializers import *
from .forms import *
from .codes.scraping import scrap

def home_view(request):
    context = {}
    context ['form'] = Scraping()
    return render(request,'home.html',context)

def loading_view(request):
    return render(request,'loading.html')

def datatable_view(request):
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db= client["aliexpress_db"]
    col = db["segment"]
    products = col.find()
    context = {'products' : products}
    return render(request,'datatable.html', context)

My question is that I want to get a method in order to get the home_view first then my loading_view while the scraping is processing then my datatable_view.
I don't know how to link between these views. I am completely beginner. Any help would be great.

A: this is not a job for Django. I think what you want to do is possible through these steps:

*

*place your loading gif/vector animation in your home_view

*when the user submits the form show this animation using some javascript code until you get a response from datatable_view and change the page

*pass the results to the template of datatable_view to render them.

alternatively, you can use an AJAX Call to receive the results in the home view.
checking out this answer would also help.


text:
Q: How to parse MongoDB int32 in node.js I am using MongoDB for a discord bot I am working on, and I want to retrieve a user's balance. My current code is
function findBalance(id){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("DiscordDB"); var query = { uuid: id }; dbo.collection("players").find(query).toArray(function(err, result) { if (err) throw err; console.log(result.balance); db.close(); }); }); }. When I call the function it returns undefined... any thoughts?

A: Note the db.collection("players").find(query).toArray() returns an array of documents - these are available as result array. Your code console.log(result.balance) returned undefined - as you are looking for a property called balance in the array. You could do that on an object (or document) which has a property with that name - not on the array.
Retrieve an individual property from an array of objects - do the following to print each document's balance property value:
result.forEach(doc => console.log(doc.balance));

Here is your function's code in a slightly different way:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
    if (err) throw err;
    console.log("Connected successfully to server");
    const db = client.db("DiscordDB");
    const id = "some value"; // input value

    findBalance(db, id, function(result) {
        console.log(JSON.stringify(result));
        result.forEach(doc => console.log(doc.balance));
        console.log("Closing connection.");
        client.close();
    });
});

const findBalance = function(db, id, callback) {
    const query = { uuid: id };
    db.collection("players")
        .find(query)
        .toArray(function(err, result) {
            if (err) throw err;
            console.log("Query ran okay");
        callback(result);
    });
};


text:
Q: MySQL return items with joined tables I'm working on a project where I have to look for every area that's free on a specific moment but I'm kinda confused on how to do it.
I've got 2 tables. Area and Reservation.
Area has:
id,
name
Reservation has:
id,
area_id,
start_date,
end_date
What I want to return are all Areas that don't have a Reservations on a specific date. Any idea how to do that?

A: Query:
$date = '2016-2-2';
SELECT a.name
FROM area AS a,
     reservation AS r
WHERE (r.start_date <> '$date' OR r.end_date <> '$date')

Assuming that your date format is Y-m-d in your database.

A: Try using this query:
SELECT a.name
FROM area AS a
LEFT JOIN reservation AS r ON r.area_id = a.id
AND :myDate between r.start_date AND r.end_date
WHERE r.id IS NULL


text:
Q: How do I get the color of a color-picker on button click? Background:
I am trying to get the current value of a color picker when I click my onSubmit button. The color picker is in a separate component.
Problem:
When I change the color via the color picker, I am getting an error message that says: TypeError: _this.props.setSelectedColor is not a function
Component that has Color Picker Inside of It:
function myFunctionA(props) {

  const [selectedColor, setSelectedColor] = useState(null)

  const handleSubmit = useCallback(() => {
    console.log(selectedColor);
  });

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <MyColorPicker setSelectedColor/>
      </Form>
    </>
  )
}

Color Picker Code:
class MyBlockPicker extends React.Component {
  state = {
    background: this.props.background,
  };

  handleChangeComplete = (color) => {
    console.log(color);
    this.setState({ background: color.hex });
    this.props.setSelectedColor(color.hex)
  };

  render() {
    return (
      <BlockPicker
        color={this.state.background}
        onChangeComplete={this.handleChangeComplete}
      />
    );
  }
}

export default MyBlockPicker;

Any ideas on how to fix?

A: If you want to pass a function down to a child you need to do it like this:
<MyColorPicker setSelectedColor={setSelectedColor} />


text:
Q: Unable to satisfy all prerequisites for setup I made setup project for C# application from Visual Studio 2008. My motive of creating this setup is that I just want to give exe file to client and at clients place this setup should install all prerequisites for running the setup smoothly like .net framework sql server express edition etc. So for that I selected all the prerequisites by right clicking the setup project and double clicking the Prerequisites button. But when I am running this setup on other PC. The setup file is not running because of two error:

1) Unable to satisfy all prerequisites for setup setup cannot continue
  until all system components have been successfully install.
Details:
Prerequisite check for system component SQL Server 2005 Express
  Edition SP2(x86) failed with following error message. "This version of
  SQL Server 2005 Express edition is not supported for the current
  processor architecture"
2) Communication port doesn't exist.

Now what should I include in my setup project. I don't want to give all this headache to the client.
These are the prerequisites I selected

A: The error message is telling you that the SQL version isn't supported on the current processor architecture. That implies that you are trying to install it on a 64-bit system, and it's not supported. The communication port issue might be a downstream result of the first error, so I'd ignore it until you've addressed the SQL issue.
You are using really old tools that may not be supported any more. You could be more up-to-date by using the free Visual Studio 2015 Community Edition, and after installing that you can add the installer project add-on to build your setup, which will have more recent versions of prerequisites.
http://www.microsoft.com/en-us/download/details.aspx?id=48146
https://visualstudiogallery.msdn.microsoft.com/f1cc3f3e-c300-40a7-8797-c509fb8933b9/view/Discussions/4


text:
Q: How to remove branding feature I have a SharePoint site that is using custom branding. I no longer want my SharePoint site branded, so I deactivated the feature, but the branding is still applied.
Is there a job I need to run to refresh something or other? How do I get vanilla SharePoint back?

A: It depends whether the feature developer added clean up code in the FeatureDeactivating event.
By the sounds of it the answer is no so you will need to manually reverse the changes the feature made. Obviously having access to the code would make this much easier.
At a basic level you may need to change the theme, master page, stylesheet(s) or more likely a combination of these items.

A: Have you tried ((Site Settings --> Look and Feel --> Masterpage )) to apply default seattle or oslo masterpage theme?


text:
Q: How to write/read data in NSPasteboard? How to write data (image files type like .gif, .jpg, .tiff, etc) to NSPasteboard? And how to extract data from NSPasteboard?

A: Simply as that, start here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PasteboardGuide106/Introduction/Introduction.html%23//apple_ref/doc/uid/TP40008099


text:
Q: Installing postgres via puppet doesn't refresh package list, install fails I'm on OSX 10.13.6 host running VirtualBox 5.2.16 and vagrant 2.1.2
I'm trying to set up a VM with bento/ubuntu-18.04 using two provisioners:
1) inline shell, to get puppet and the required modules on the system
apt-get install puppet
puppet module install puppetlabs-postgresql

which gives me
/etc/puppet/code/modules
└─┬ puppetlabs-postgresql (v5.7.0)
  ├── puppetlabs-apt (v4.5.1)
  ├── puppetlabs-concat (v4.2.1)
  └── puppetlabs-stdlib (v4.25.1)

2) the puppet provisioning
config.vm.provision "puppet" do |puppet|
  puppet.manifests_path = "vagrant/puppet/manifests/"
  puppet.options = ['--verbose', '--hiera_config /vagrant/vagrant/hiera.yaml']
  puppet.manifest_file  = "test.pp"
end

And, besides the files, this is my most minimalistic manifest producing the problem:
class testproject {
  class { 'postgresql::globals':
    version             => '9.6',
    manage_package_repo => true,
    encoding            => 'UTF8',
  } ->
  class { 'postgresql::server':
    package_ensure          => latest,
    ip_mask_allow_all_users => '0.0.0.0/0',
    listen_addresses        => '*',
  } ->
  postgresql::server::config_entry { 'max_parallel_workers_per_gather':
    value => '2',
  }
  class { 'postgresql::server::contrib':
    package_ensure => latest,
  }
  postgresql::server::db { 'testdb':
    user     => 'testdb',
    password => postgresql_password('testdb', 'testdb'),
    encoding => 'UTF8',
  }

  apt::source { 'elasticsearch':
    location    => 'https://artifacts.elastic.co/packages/5.x/apt',
    release     => 'stable',
    repos       => 'main',
    key         => {
      id     => '46095ACC8548582C1A2699A9D27D666CD88E42B4',
      source => '/vagrant/vagrant/puppet/keys/elasticsearch.gpg',
    },
    include => {
      src => false,
    },
  }
  package { 'elasticsearch':
    ensure  => '5.3.0',
    require => Apt::Source['elasticsearch'],
    notify  => Service['elasticsearch'],
  }
  service { 'elasticsearch':
    ensure     => running,
    enable     => true,
    hasstatus  => true,
    hasrestart => true,
    require    => Package['elasticsearch'],
  }
  file { '/etc/elasticsearch/jvm.options':
    source  => '/vagrant/vagrant/conf/etc-elasticsearch-jvm.options',
    owner   => root,
    group   => elasticsearch,
    mode    => '0660',
    require => [
      Package['elasticsearch'],
    ],
    notify  => Service['elasticsearch'],
  }
}
class { testproject: }

It installs postgres and sets up a user and it installs ElasticSearch 5.3. The issue:

*

*only install postgres => works

*only install ES => works

*install both, like in the sample => postgres fails, ES works

To me it seems that postgres does not refresh the apt-get cache and thus does not "see" the package and fails.
I've run a complete provisioning with --debug (achtung: ~1.1k lines)
=> https://gist.github.com/mfn/8656324a8dcd736d45035ea8cd0ee74a
The first error is on line 1008:
Error: /Stage[main]/Testproject/Postgresql::Server::Db[testdb]/Postgresql::Server::Role[testdb]/Postgresql_psql[CREATE ROLE testdb ENCRYPTED PASSWORD ****]: Could not evaluate: Error evaluating 'unless' clause, returned pid 14088 exit 1: 'Error: Could not execute posix command: Invalid group: postgres

Invalid group: postgres

Because none of the required postgres packages where instaled, the users weren't created, etc.
But I can see that:

*

*source list is added

*GPG key is imported

*but somehow the refresh isn't propagated to update the packages

I tried to find problems related to the missing package update and found https://tickets.puppetlabs.com/browse/MODULES-2190

apt::source does not force an 'apt-get update' and fails on first run

And indeed, I was able to get it working by:

*

*manually running apt-get update in the VM

*run provisioning again

In the end this issue links to https://github.com/puppetlabs/puppetlabs-apt#adding-new-sources-or-ppas
I tried modifying the postgres installation to depend on the update like this, but nothing changed:
  class { 'postgresql::server':
    package_ensure          => latest,
    ip_mask_allow_all_users => '0.0.0.0/0',
    listen_addresses        => '*',
    require => Class['apt::update']
  } ->

I also tried adding the example from the docs, without effect:
class testproject {
  Class['apt::update'] -> Package <| provider == 'apt' |>
  class { 'postgresql::globals':

I also wonder I'm missing more explicit resource dependencies here. The postgres part is from an older puppet installation where it worked, but I've yet to figure out if I did something wrong here. Checked with https://forge.puppet.com/puppetlabs/postgresql already a few times.

A: Seems I need an explicit dependency to not have the DB user being created before the package is installed; this changed fixed it:
  class { 'postgresql::server':
    package_ensure          => latest,
    ip_mask_allow_all_users => '0.0.0.0/0',
    listen_addresses        => '*',
  } ->
  postgresql::server::db { 'testdb':
    user     => 'testdb',
    password => postgresql_password('testdb', 'testdb'),
    encoding => 'UTF8',
  }

I.e. adding -> right there.
Was definitely not "needed" in previous versions but now it seems to be important to have this explicitly stated.


text:
Q: Calling new PostgreSQL command from Java Application issue I have defined a new command my_command in PostgreSQL. This command takes the path of ANALYZE and inside analyze.c, I have a function to do some operations if its my_command.This command takes the input arguments: table name, column name and an input string.
When I run this command from command line psql, it works as expected. But when I call the same command from a java application, all the variables that store the input arguments are NULL.
I printed the value of the input string in gram.y file where I have defined my_command.
fprintf (stderr, "I am inside gram.y %s\n",n->inp_str);
and the input string is printed correctly.
But when I print stmt->inp_str in the function standard_ProcessUtility() of utility.c for the case T_VacuumStmt, I get the value as NULL. This is as far as I could trace back from analyze.c.
I am not sure how running the command from an application can make a difference.
gram.y content gist:

MyStmt:
        my_keyword qualified_name name_list my_inp_str
            {
                VacuumStmt *n = makeNode(VacuumStmt);
                n->options = VACOPT_ANALYZE;
                n->freeze_min_age = -1;
                n->freeze_table_age = -1;
                n->relation = $2;
                n->va_cols = $3;
                n->inp_str = $4;
                fprintf (stderr, "I am inside gram.y %s\n",n->inp_str);

                $$ = (Node *)n;
            }
;

char *inp_str is added to the struct VacuumStmt in parsenodes.h
Any help is appreciated. Thanks!

A: I had mailed this question to the pgsql-hackers mailing list and I got a response that I had to add code to copy inp_str to _copyVacuumStmt().
Once this was done, the command worked from the Java application too. I have asked for the reason why it worked from command line even without adding the above code. I will update the details once I get the details.


text:
Q: Search all folders and subfolders I need to search on all folders and subfolders to find image files.
My problem is that I can not search on a network dir and with this code, it only find onde folder and not all folders and subfolders. Any help? Thank you.
What I have:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
    List<string> filesList = new List<string>();
    // Create the new DataTable to be used
    tableWithPhotos = new DataTable();
    tableWithPhotos.Columns.Add("Nome e formato do ficheiro (duplo clique para visualizar a imagem)");
    tableWithPhotos.Columns.Add("Caminho ( pode ser copiado Ctrl+C )");
    var diretorios = new List<string>() {@"C:\Users\myfolder\pictures"};
    var extensoes = new List<string>() { "*.jpg", "*.bmp", "*.png", "*.tiff", "*.gif" };
    foreach (string entryExtensions in extensoes)
    {
        foreach (string entryDirectory in diretorios)
        {
        filesList.AddRange(Directory.GetFiles(entryDirectory, entryExtensions, SearchOption.TopDirectoryOnly));
        }
    }

A: Your immediate problem is you're specifying TopDirectoryOnly for SearchOptions. It should be AllDirectories.
filesList.AddRange(Directory.GetFiles(entryDirectory, entryExtensions, SearchOption.AllDirectories));

To add to the answer, I think you can simplify the process. Creating a list of strings with one directory doesn't make sense. I'm talking about this line:
var diretorios = new List<string>() {@"C:\Users\myfolder\pictures"};

Instead, do something like this:
var topDir = @"C:\Users\myfolder\pictures";
var extensoes = new List<string>() { "*.jpg", "*.bmp", "*.png", "*.tiff", "*.gif" };
foreach (string ext in extensoes)
{
    var files = Directory.EnumerateFiles(topDir, ext, SearchOption.AllDirectories);
    // Add to list.
}

I encourage the use of EnumerateFiles() instead of GetFiles() as it's faster especially if you have a large number if files. See this answer.

A: This is what I need to do:

filesList.AddRange(Directory.EnumerateFiles(allDir, ext, SearchOption.AllDirectories));


text:
Q: Printing from Windows machines to CUPS works erratically I'm trying to construct a Linux print server to be accessed by Windows machines. The setup is as follows:

*

*Ubuntu 12.10 Desktop

*CUPS 1.6.1

*Printers shared via Samba 3.6.6

*Windows machines are running Windows 7, Windows XP

Printing from Ubuntu works fine. Installation of the shared printers in Windows also seems to work. However, I'm unable to print arbitrary documents from Windows, though some printing efforts do work. Here's what I observed so far:

*

*Printing a text file from Notepad on the shared printer doesn't work. No error messages, no document in Windows' printer status window.

*Printing from WordPad doesn't work either.

*Printing from Microsoft Word does work.

*Printing test pages works.

*Opening an image file in MS Paint and trying to print it doesn't work.

*Dragging the same image file onto the printer status window will print the file.

All of these are repeatable. What could be the issue here, preventing arbitrary printing?


text:
Q: Attaching a LED to PIC's Rx pin I need some way to know whether the microcontroller (PIC) is receiving (or transmitting)  any data. So I thought of keeping a separate LED so that it'll blink when any data transfer occur.
But I need to know how to attach this LED. Is it OK to directly attach an LED to PICs Tx (and Rx) pins? I mean will it affect the transferring data in some way (like by dropping out the voltage etc...).

A: You shouldn't attempt to connect the diode directly to the pin because it will definitely affect the operation of the pin. Instead, try using a logic level mosfet to drive the LED. Connect the MOSFET's gate pin to the Rx pin and the drain to the LED and a resistor.

Ignore the part number shown on the schematic. BS170 would be much cheaper and work fine for this purpose.

A: (At least some) PICs can't drive much current(*), but also for the RxD pin you better use a transistor to drive the LED, since you'll avoid loading the transmitter at the other end (probably a MAX3232 or similar?).

Connect the input "Q" to the TxD/RxD line. A typical general purpose transistor will have a gain of about 100, then 1 mA base current is enough to get 20 mA collector current.
For a 5 V bus and power supply:
choose \$R_B\$ = 3.9 kΩ, then the base current will be (5 V - 0.7 V)/ 3.9 kΩ = 1.1 mA. To limit the collector current to 20 mA (typical indicator LED) \$R\$ should be (5 V - 2 V)/ 20 mA = 150 Ω.
For a 3.3 V bus and power supply, use the same equations, replacing 5 V by 3.3 V, then your resistor values will be 2.2 kΩ and 47 Ω resp.

A MOSFET like AndrejaKo suggests is a good alternative, but make sure you have a logic level gate type, with a maximum gate threshold voltage somewhat below the bus voltage. (There are logic level gate FETs where that can be as high as 4 V and then you won't get enough drain current with a 3.3 V bus voltage.) The real advantage of the FET is that it needs hardly any drive current, but since we only need a mA for the BJT we won't have any problems with that either.

(*) This random PIC controller specifies a 700 mV drop at only 3 mA output current, that's a 230 Ω output resistance. A 2 V LED directly driven from a 3.3 V output will drop the output by 1 V at only 4 mA. Most indicator LEDs are specified for 20 mA.

A: No, you don't want to connect the LED via a low side switch transistor as others have shown.  In the normal case, the idle level of both lines is high, which would then result in the LED lit most of the time.  It will be very difficult to notice it occasionally getting a little dimmer.  What you want is the LED to be on only when the line is in the active state, which is low.  Here is a simple circuit:

The transistor is used in emitter follower configuration, which eliminates the need for a base resistor and also uses the minimum possible base current for the resulting LED current.  When the digital line goes low, the emitter will be at about 700 mV.  Considering a normal green LED that drops about 2.1 V, that leaves 2.2 V accross R1.  2.2V / 120Ω = 18 mA, which is just under the maximum of 20 mA the typical T1-3/4 and many other common LEDs are rated for.
This is a case where you want to maximize the LED light output, meaning to run it at its maximum current.  The line will go low for short periods, so you want to make that short time as visible as possible.  If that doesn't work, you will need some kind of pulse stretching, but try this first.
If you are using a 3.3 V supply, adjust R1 accordingly.  3.3V - 2.1V - 700mV = 500mV accross R1.  500mV / 20mA = 25Ω.  You want to leave some margin, so the standard value of 27 Ω should work fine.  3.3 V supply is about the minimum you want to use the emitter follower configuration in.


text:
Q: Map elements in two lists and add one to the other list Sorry if the title is a little confusing. I have two files, file1 and file2 both with many columns. I need to find common elements in a certain column, if they match, the whole line from file1 should be added to the matched line in file2:
e.g.:
file1.txt:
[a,b,c],
[x,e,y],
...

file2.txt:
[d,e,f],
[s,p,z],
...

Note, here just the element "e" matches, the result should (in a new file, but with all of the information in file2.txt) be:
newfile.txt:
[d,e,f],[x,e,y],
[s,p,z]

...
My idea:
output = open('file2.txt', 'w')
for f in variants:
    add = ""
    if f[0] in sources:
        add = ???
    output.write("\t".join(f) + add + "\n")
output.close()

"variants" contains the list from file1.txt, I don't really understand how to add the rest of the information from file1.txt to the matching line in file2.txt, any help please!

A: from collections import defaultdict

def parse_data(line):
    # Returns a list of values from line of text.
    return line[1:-2].split(',')

with open('newfile.txt', 'wb') as new_file, open('file1.txt', 'rb') as f1, open('file2.txt', 'rb') as f2:
    mapping = defaultdict(list)
    # Zero-based indexing.
    CERTAIN_COLUMN = 1
    for line in f1:
        # Remove new-lines and get comma-separated values.
        line = line.strip()
        columns = parse_data(line)
        mapping[columns[CERTAIN_COLUMN]].append(line)

    for line in f2:
        line = line.strip()
        columns = parse_data(line)
        for matched in mapping[columns[CERTAIN_COLUMN]]:
            new_file.write('{},{},\n'.format(matched, line))

The first loop populates the dict with search_criteria -> matched rows mapping, i.e e -> ['[x,e,y]'].
The second loop prints all entries that meet the search criteria for each line of file2.txt


text:
Q: Using "knew" and "didn't" in present tense writing The sentence is:

I wonder sometimes if he even knows what 'fun' means, but I guess he wouldn't be in Harvard if he didn't.

Or is it "... if he doesn't"?
And at the front portion, is it "if he even knew" or "if he even knows"?

A:
I wonder sometimes if he even knows what 'fun' means, but I guess he wouldn't be in Harvard if he didn't.

This use of didn't is not the past tense. It is the subjunctive mood.
The subjunctive mood expresses hypothetical or imaginary situations. Often in the subjunctive mood we use the past tense form of a verb even when discussing events that might occur in the present or near future.
For example,

I would go to the play if my favorite actor was performing

or

What would you do if you had a million dollars?

A: The way you have it now is grammatically correct. The text below is just digging a bit further into how you would use the other words you mentioned.
One example that may clear it up is this "He doesn't know how to read" means he currently does not know how to read. "He didn't know how to read" means he previously did not know how to read.
If you say "I wonder if he even knew" you're saying you wonder if he had certain knowledge at some previous time. If you say "I wonder if he even knows" you're saying you wonder if he currently has certain knowledge.
You could say "I guess he won't be in Harvard long if he doesn't".
Or lets say you were talking about whether or not he'd turned in a vital assignment, "I guess he won't be in Harvard long if he didn't". Meaning if he didn't turn in the assignment, surely sooner or later he will be expelled.
Lets say you wanted to use "if he knew". You would have to do something like this:

I wonder sometimes he even knew what 'fun' meant, but I guess he wouldn't be in Harvard if he didn't.

Forgive me if you know all this, but meant is the past tense of mean. I think you could actually still use "means" and it would be grammatically correct, but if you asked me, if you don't want to use "meant", it would still be better to say something like "I wonder sometimes if even knew what 'fun' was" or "I wonder sometimes if even knew the meaning of 'fun'"
and to use "if he doesn't" it would go something like this like this

I wonder sometimes if he even knows what fun means, but I guess he won't be in Harvard long if he doesn't"


text:
Q: Jquery animation on scroll event I have the following code and if I use it the scroll efect is not working, but if I change the duration from 500 to 50 everything is ok.
$(document).ready(function(){
    currentScrollTop = $( window ).scrollTop();
    $( window ).scroll( scrollWindow );
});
function scrollWindow(){
    var newScrollTop = $( window ).scrollTop();
    var height = $( window ).height();
    if( currentScrollTop > newScrollTop ){
        var newPosition = currentScrollTop - height;
        $( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
            currentScrollTop = $( window ).scrollTop();
        });
    }
    else if( currentScrollTop < newScrollTop ){
        var newPosition = currentScrollTop + height;
        $( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
            currentScrollTop = $( window ).scrollTop();
        });
    }
}

I have fiddle here

A: Two issues here:
1. You never update currentScrollTop.
2. You need to restrict the scroll event from being re-triggered while the page is already scrolling. You can remove the event while the animation is happening by using .off (i've modified your event handler to use .on instead of .scroll for this purpose), and then rebind it when the animation completes.

Solution: JSFiddle (I've added an adjustable input for testing, so you can change scroll speed.)
$(document).ready(function(){
    currentScrollTop = $( window ).scrollTop();
    $( window ).on("scroll", scrollWindow );
});

function scrollWindow(){

    var newScrollTop = $( window ).scrollTop();
    var height = $( window ).height();
    console.log(newScrollTop);
    if( currentScrollTop > newScrollTop ){
        var newPosition = currentScrollTop - height;

        //Remove our scroll event during animation
        $(window).off();

        $( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
            currentScrollTop = $( window ).scrollTop();

             //Rebind event after animation complete
            $( window ).on("scroll", scrollWindow );

        });
    }
    else if( currentScrollTop < newScrollTop ){

        //Remove our scroll event during animation
        $(window).off();

        var newPosition = currentScrollTop + height;
        $( "html, body" ).animate({ scrollTop: newPosition }, 500, function(){
            currentScrollTop = $( window ).scrollTop();

            //Rebind event after animation complete
            $( window ).on("scroll", scrollWindow );

        });
    }

    //Update scrollTop
    currentScrollTop = newScrollTop();

}

A: If you wait for a while on the fiddle, you can see the scrolling effect working. Actually when the duration parameter of your animate function is 500 it is relatively slower than when it is at 50. So as you move towards higher values, you are slowing down the scroll speed. You can see this doc for reference. Also you can use strings like 'slow' and 'fast' instead of 500 or 50 for your animation duration.
http://api.jquery.com/animate/#duration
Or you can use a timeout. Try this code:-
$(document).ready(function(){
currentScrollTop = $( window ).scrollTop();
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
    var newScrollTop = $( window ).scrollTop();
var height = $( window ).height();
if( currentScrollTop > newScrollTop ){
    var newPosition = currentScrollTop - height;
    $( "html, body" ).animate({ scrollTop: newPosition }, 500,
function(){
        currentScrollTop = $( window ).scrollTop();
    });
}
else if( currentScrollTop < newScrollTop ){
    var newPosition = currentScrollTop + height;
    $( "html, body" ).animate({ scrollTop: newPosition }, 500,function(){
        currentScrollTop = $( window ).scrollTop();
    });
}

}, 50);});});


text:
Q: Tableau Date function and Y0Y comparsion I have Column that is in String format such as 2018-03 and I want to convert this to Date format in tableau. Once I have convert these 4 years data I want to compare 2019 data with 2018 and 2021 data with 2020s

A: To convert to a date use the DATE function:
DATE(LEFT([DateField],5)+RIGHT([DateField],2)+"01")
Check here to see 2 different ways to do YoY - do whichever works better for your use case.

A: Assuming that 03 in your date 2018-03 corresponds to month, you can convert the string column to date column with the following calculation, where my_date is your string column
DATE(DATEPARSE("yyyy-MM", [my_date]))

See the results

Note, if however, 03 is quarter, use this calculation instead
DATE(DATEPARSE("yyyy-qq", [my_date]))


text:
Q: focus event not dying after removal of class on select tag I have a select tag with class name like below:
<select name="names" id="select" class="change-me">
  <option value="">Select Name</option>
  <option value="saikiran"> Saikiran</option>
  <option value="srikanth">Srikanth</option>
  <option value="ashok">Ashok</option>
</select>

This select tag with class name has  function like below:
$('select.change-me').on('focus',function(){
  swal("click on fake ajax btn should not bring this popup");
});

I have a some action on the page for example a button click on which i am removing class of this select tag.
$('#click').on('click',function(){
  $('#select').removeClass('change-me');
});

After removal of class name the focus event on select tag is still alive. can anyone tell me why is it happening.
i tried to put up all this in a codepen. please check it below
Check the pen here

A: You have binded the function to the select.change-me element which is not removed from that element even if the class is removed. you need to unbind it as given below.
$('#click').on('click',function(){
  $("select.change-me").unbind("focus");
  $('#select').removeClass('change-me');
});

https://codepen.io/anon/pen/wPKKdX
Note that there may be other select element with the same class having the function binded in your HTML and this code will remove them all. So i will suggest to use id while using the unbind function.

A: The change event is bound to the select element. You're removing the class, but you're no longer checking for the class so it makes no difference. You can add a check for the class within your change event to get around this, e.g.
$('select.change-me').on('focus',function(){
  if(!$(this).hasClass('change-me')) {
  swal("click on fake ajax btn should not bring this popup");
  }
});

Updated Codepen.


text:
Q: pymongo: Add field containing a dict Right now my mongo document has normal key/value pairs in it.
I want to add a field (staff) that is a dict.  I can run this code, and it doesn't complain, but the users field does not show up when I find the object.  The object shows up as if it was never added.
staff = {'foo':{'name':'Jack S.', 'title':'Pirate'}, 'bar':{'name':'Abe', 'title':'Mate'}}
ships.update(
  {'_id': 1},
  {"$set": {'staff': staff},
  upsert=False
)

My _id is definitely correct because I can find on that ID and I get the result without staff just fine.
How can I add this field to my existing collection?

A: try
ships.update(
  {'_id': 1},
  {"$set": {'staff': staff}},
  false,true
)

** you were missing closing bracket. also your staff variable doesnt seems to a correct dictionary.it looks like list of dict. please check .