text:
Q: Indentation sensitive parser using Parslet in Ruby? I am attempting to parse a simple indentation sensitive syntax using the Parslet library within Ruby.
The following is an example of the syntax I am attempting to parse:
level0child0
level0child1
  level1child0
  level1child1
    level2child0
  level1child2

The resulting tree would look like so:
[
  {
    :identifier => "level0child0",
    :children => []
  },
  {
    :identifier => "level0child1",
    :children => [
      {
        :identifier => "level1child0",
        :children => []
      },
      {
        :identifier => "level1child1",
        :children => [
          {
            :identifier => "level2child0",
            :children => []
          }
        ]
      },
      {
        :identifier => "level1child2",
        :children => []
      },
    ]
  }
]

The parser that I have now can parse nesting level 0 and 1 nodes, but cannot parse past that:
require 'parslet'

class IndentationSensitiveParser < Parslet::Parser

  rule(:indent) { str('  ') }
  rule(:newline) { str("\n") }
  rule(:identifier) { match['A-Za-z0-9'].repeat.as(:identifier) }

  rule(:node) { identifier >> newline >> (indent >> identifier >> newline.maybe).repeat.as(:children) }

  rule(:document) { node.repeat }

  root :document

end

require 'ap'
require 'pp'

begin
  input = DATA.read

  puts '', '----- input ----------------------------------------------------------------------', ''
  ap input

  tree = IndentationSensitiveParser.new.parse(input)

  puts '', '----- tree -----------------------------------------------------------------------', ''
  ap tree

rescue IndentationSensitiveParser::ParseFailed => failure
  puts '', '----- error ----------------------------------------------------------------------', ''
  puts failure.cause.ascii_tree
end

__END__
user
  name
  age
recipe
  name
foo
bar

It's clear that I need a dynamic counter that expects 3 indentation nodes to match a identifier on the nesting level 3.
How can I implement an indentation sensitive syntax parser using Parslet in this way? Is it possible?

A: There are a few approaches.

*

*Parse the document by recognising each line as a collection of indents and an identifier, then apply a transformation afterwards to reconstruct the hierarchy based on the number of indents.

*Use captures to store the current indent and expect the next node to include that indent plus more to match as a child (I didn't dig into this approach much as the next one occurred to me)

*Rules are just methods. So you can define 'node' as a method, which means you can pass parameters! (as follows)
This lets you define node(depth) in terms of node(depth+1). The problem with this approach, however, is that the node method doesn't match a string, it generates a parser. So a recursive call will never finish.
This is why dynamic exists. It returns a parser that isn't resolved until the point it tries to match it, allowing you to now recurse without problems.
See the following code:
require 'parslet'

class IndentationSensitiveParser < Parslet::Parser

  def indent(depth)
    str('  '*depth)
  end

  rule(:newline) { str("\n") }

  rule(:identifier) { match['A-Za-z0-9'].repeat(1).as(:identifier) }

  def node(depth)
    indent(depth) >>
    identifier >>
    newline.maybe >>
    (dynamic{|s,c| node(depth+1).repeat(0)}).as(:children)
  end

  rule(:document) { node(0).repeat }

  root :document
end

This is my favoured solution.

A: I don't like the idea of weaving knowledge of the indentation process through the whole grammar. I would rather just have INDENT and DEDENT tokens produced that other rules could use similarly to just matching "{" and "}" characters. So the following is my solution. It is a class IndentParser that any parser can extend to get nl, indent, and decent tokens generated.
require 'parslet'

# Atoms returned from a dynamic that aren't meant to match anything.
class AlwaysMatch < Parslet::Atoms::Base
  def try(source, context, consume_all)
    succ("")
  end
end
class NeverMatch < Parslet::Atoms::Base
  attr_accessor :msg
  def initialize(msg = "ignore")
    self.msg = msg
  end
  def try(source, context, consume_all)
    context.err(self, source, msg)
  end
end
class ErrorMatch < Parslet::Atoms::Base
  attr_accessor :msg
  def initialize(msg)
    self.msg = msg
  end
  def try(source, context, consume_all)
    context.err(self, source, msg)
  end
end

class IndentParser < Parslet::Parser

  ##
  # Indentation handling: when matching a newline we check the following indentation. If
  # that indicates an indent token or detent tokens (1+) then we stick these in a class
  # variable and the high-priority indent/dedent rules will match as long as these
  # remain. The nl rule consumes the indentation itself.

  rule(:indent)  { dynamic {|s,c|
    if @indent.nil?
      NeverMatch.new("Not an indent")
    else
      @indent = nil
      AlwaysMatch.new
    end
  }}
  rule(:dedent)  { dynamic {|s,c|
    if @dedents.nil? or @dedents.length == 0
      NeverMatch.new("Not a dedent")
    else
      @dedents.pop
      AlwaysMatch.new
    end
  }}

  def checkIndentation(source, ctx)
    # See if next line starts with indentation. If so, consume it and then process
    # whether it is an indent or some number of dedents.
    indent = ""
    while source.matches?(Regexp.new("[ \t]"))
      indent += source.consume(1).to_s #returns a Slice
    end

    if @indentStack.nil?
      @indentStack = [""]
    end

    currentInd = @indentStack[-1]
    return AlwaysMatch.new if currentInd == indent #no change, just match nl

    if indent.start_with?(currentInd)
      # Getting deeper
      @indentStack << indent
      @indent = indent #tells the indent rule to match one
      return AlwaysMatch.new
    else
      # Either some number of de-dents or an error

      # Find first match starting from back
      count = 0
      @indentStack.reverse.each do |level|
        break if indent == level #found it,

        if level.start_with?(indent)
          # New indent is prefix, so we de-dented this level.
          count += 1
          next
        end

        # Not a match, not a valid prefix. So an error!
        return ErrorMatch.new("Mismatched indentation level")
      end

      @dedents = [] if @dedents.nil?
      count.times { @dedents << @indentStack.pop }
      return AlwaysMatch.new
    end
  end
  rule(:nl)         { anynl >> dynamic {|source, ctx| checkIndentation(source,ctx) }}

  rule(:unixnl)     { str("\n") }
  rule(:macnl)      { str("\r") }
  rule(:winnl)      { str("\r\n") }
  rule(:anynl)      { unixnl | macnl | winnl }

end

I'm sure a lot can be improved, but this is what I've come up with so far.
Example usage:
class MyParser < IndentParser
  rule(:colon)      { str(':') >> space? }

  rule(:space)      { match(' \t').repeat(1) }
  rule(:space?)     { space.maybe }

  rule(:number)     { match['0-9'].repeat(1).as(:num) >> space? }
  rule(:identifier) { match['a-zA-Z'] >> match["a-zA-Z0-9"].repeat(0) }

  rule(:block)      { colon >> nl >> indent >> stmt.repeat.as(:stmts) >> dedent }
  rule(:stmt)       { identifier.as(:id) >> nl | number.as(:num) >> nl | testblock }
  rule(:testblock)  { identifier.as(:name) >> block }

  rule(:prgm)       { testblock >> nl.repeat }
  root :prgm
end


text:
Q: datagrid property window not showing the row related things(means rowcommand,rowdatabound...)Why? Iam using vb 2005,sqlserver 2005,vb.net web application
in my datagrid properties window not showing the rowcommand..
I need create row command/..
Why its not showing?

A: The designer sometimes misses it, don't know why but you can manually type it in.
ASP.Net:
<asp:GridView OnRowCommand="ProductsGridView_RowCommand" />

CODE BEHIND:
Sub ProductsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS MSK User/Password Authentication/Authorization i want to be able to authenticate/authorize clients to produce/consume messages on certain topics. they would be part of our vpn (incl. aws). as i understand the available documentation the only option to do this is to issue client certificates and setup ACLs based on the clients DNs? Unfortunately i was not able to use my private CA (that i've created on my linux laptop) to create client certs. so the following questions arise:

*

*is it correct that i need to setup an AWS hosted CA (ACM PCA). that would result in almost twice the setup costs incl. the minimum broker configs.

*i could proxy the outer world into the msk cluster via something like "kafka rest proxy" from confluent - correct?

*am i missing something? is there an easier way built into AWS?

please enlighten me :)
thanks in advance
marcel

A: *

*Yes, I believe that's correct.  To do client authentication over TLS, you need to provide the ARN of your private CA that's set up with AWS PCM at the time the cluster is created - and you have to use the aws command-line tool (aws kafka create-cluster ...) to create the cluster.  The UI (last time I looked) didn't have anywhere to specify that ARN.

*I don't know - we bit the bullet and set up a private CA with ACM.

*Nope.  We're hoping that eventually AWS will integrate IAM so you can authenticate as an IAM user instead of a client certificate, but that's not where it stands today.  Today, it's client certificate only for authentication.

A: Support for Username and Password Security looks like what you want?  I think it's new..

A: There's AWS Cognito which you might want to try https://aws.amazon.com/cognito/


text:
Q: Warning: fsck not present, so skipping root file system My server (18.04) crashes during startup. One of the messages that is shown and which I think may be the reason for it is:
Warning: fsck not present, so skipping root file system
[      5.502634] EXT4-fs (sda2): INFO: recovery required on readonly filesystem
[      5.503676] EXT4-fs (sda2): write access will be enabled during recovery
[      5.544074] EXT4-fs (sda2): recovery complete
[      5.548989] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null)

How can I fix this?
Thanks,
Tom
Edit: Image added
Ubuntu startup before crash

A: I had the same problem and the solution described here worked perfectly for me.
umiddelb wrote:

You need to add the relevant executables:
echo \
'#!/bin/sh
. /usr/share/initramfs-tools/hook-functions
copy_exec /sbin/e2fsck /sbin
copy_exec /sbin/fsck /sbin
copy_exec /sbin/fsck.ext2 /sbin
copy_exec /sbin/fsck.ext4 /sbin
copy_exec /sbin/logsave /sbin' \
  | sudo dd of=/etc/initramfs-tools/hooks/e2fsck.sh
sudo chmod +x /etc/initramfs-tools/hooks/e2fsck.sh

before building the initrd
sudo update-initramfs -c -k ${kver}

After that, reboot and checkout the results.


text:
Q: Java problem with parallel 2d arrays and arrays I was wondering if there is a more efficient way to get each row from the jagged array instead of listing each position of the word. The problem is when the user puts in the name of the family, it displays the corresponding list of siblings (parallel arrays, that stores and retrieves the names) afterwards it prompts the user again for the number then it shows the children who are born first, second, etc.
Here is what I have so far:
import java.util.*;
public class siblings{
    public static void main (String [] argrs){
        String [] family =  { "Potter", "Weasley", "Grangley",
                "Dubmbledore", "Black", "Patil", "Creevey"};
        String [] [] siblings = {
                {"harry"},
                {"bill", "charlie", "percry", "fred", "george", "ron", "ginny"},
                {"hermione"},
                {"Ablus","aberforth", "arrianna"},
                {"Sirius", "regulus"},
                {"padma", "pavarti"},
                {"colin", "dennnis"}};

        Scanner kb = new Scanner (System.in);
        System.out.println("Enter a family name: ");
        String input = kb.next().toLowerCase();

        switch (input) {
            case "black" :
            System.out.println(
                siblings[4][0]+" "+ siblings[4][1]);

            break;
            case "potter":
            System.out.println(
                siblings[0][0]);

            break;
            case "weasley":
            System.out.println(
                siblings[1][0]);

        }

        System.out.println("Enter number between 1-7");
        int input2 = kb.nextInt();

        switch (input2) {
            case 1:
            System.out.println("the names of the 1st born child:");
            System.out.println(
                siblings[0][0]
                +", "
                +siblings [1][0]
                +", "
                +siblings [2][0]
                +", "
                +siblings [3][0]
                +", "
                +siblings [4][0]
                +", "
                +siblings [5][0]
                +", "
                +siblings [6][0]
            );

            break;
            case 2 :
            System.out.println("the names of the 2nd born child:");
            System.out.println(
                siblings [1][1]
                +", "
                +siblings [3][1]
                +", "
                +siblings [4][1]
                +", "
                +siblings [5][1]
                +", "
                +siblings [6][1]
            );

            break;
            case 3 :
            System.out.println("the names of the 3nd born child:");
            System.out.println(
                siblings [1][2]
                +", "
                +siblings [3][2]
            );
            break;

            case 4:
            System.out.println("the names of the 4th born child:");
            System.out.println(
                siblings [1][3]
            );
            break;

            case 5:
            System.out.println("the names of the 4th born child:");
            System.out.println(
                siblings [1][4]
            );
            break;

            case 6:
            System.out.println("the names of the 4th born child:");
            System.out.println(
                siblings [1][5]
            );
            break;

            case 7:
            System.out.println("the names of the 4th born child:");
            System.out.println(
                siblings [1][6]
            );
        }
    }
}

A: You can see my example, start from here and look for generic ways in programming, your approach is too hard-coded, you need to learn loops(while, for), control structures (if, else). Also, see code conventions, you write a bit awkward for java: https://howtodoinjava.com/java/basics/java-naming-conventions/
import java.util.Scanner;

//Note, class name must start from capital letter
//See code conventions: https://howtodoinjava.com/java/basics/java-naming-conventions/
public class Siblings {

public static void main (String [] argrs){
    String [] family =  { "Potter", "Weasley", "Grangley", "Dubmbledore", "Black", "Patil", "Creevey"};
    String [] [] siblings = {
            {"harry"},
            {"bill", "charlie", "percry", "fred", "george", "ron", "ginny"},
            {"hermione"},
            {"Ablus","aberforth", "arrianna"},
            {"Sirius", "regulus"},
            {"padma", "pavarti"},
            {"colin", "dennnis"}};

    Scanner kb = new Scanner (System.in);
    System.out.println("Enter a family name selecting one of those: ");
    System.out.println("");
    for(String name: family){
        System.out.print(name);
        System.out.print(" ");
    }

    String input = kb.next();//note I did not convert to lower case here

    int i = 0;
    String mySiblings[]  = null;
    for(String member: family){
        if(input.equalsIgnoreCase(member)){//note how I ignore the case,, when checking
            mySiblings = siblings[i];
            break;
        }
        i++;
    }

    System.out.println("Siblings of "+input + " are:");

    for(String sibling: mySiblings){
        System.out.print(sibling);
        System.out.print(" ");
    }

    //Continue your code here

}

}


text:
Q: How to select all .csv files within a folder and then import them through VBA coding I am new to VBA and I'm trying to automate a procedure that imports 4 .csv files in a specific folder to the SQL database.
I have a code in which I have 4 command buttons and in each 4, I am picking the files and then importing them to SQL. However, I wanted to know if there is a way in which I can have just 1 command button that picks all the .csv files from that specific folder and then imports them to SQL. Assume the folder name is Database in the following path: Y:\Data\Database
I have the following import button code that converts the local path to SQL server path and all other sorts of functions to import the data to SQL server. (fName1...fName4 are the TextBox values for the 4 file paths currently being picked by the user)
Private Sub ImportButton_Click()
Dim fName1 As String
Dim fName2 As String
Dim fName3 As String
Dim fName4 As String
Dim perc As Single

Dim index As Integer
Dim subStr As String
Dim sqlStr As String
sqlStr = "E:\Analytics\"

'Convert the local path to SQL server path
fName1 = TextBox1.Value
index = InStr(1, fName1, "\")
subStr = Left(fName1, index)
fName1 = Replace(fName1, subStr, sqlStr, , 1)

fName2 = TextBox2.Value
index = InStr(1, fName2, "\")
subStr = Left(fName2, index)
fName2 = Replace(fName2, subStr, sqlStr, , 1)

fName3 = TextBox3.Value
index = InStr(1, fName3, "\")
subStr = Left(fName3, index)
fName3 = Replace(fName3, subStr, sqlStr, , 1)

fName4 = TextBox4.Value
index = InStr(1, fName4, "\")
subStr = Left(fName4, index)
fName4 = Replace(fName4, subStr, sqlStr, , 1)

'Modify the text captions for test purpose
TextBox1.Value = fName1
TextBox2.Value = fName2
TextBox3.Value = fName3
TextBox4.Value = fName4

Dim cnPubs As ADODB.Connection
Dim cmd As ADODB.Command

' Create a connection object.
Set cnPubs = New ADODB.Connection

' Provide the connection string.
Dim strConn As String

'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"

'Connect to the Pubs database on server hcdcd-actstat01 .
strConn = strConn & "DATA SOURCE=hcdcd-actstat01;INITIAL CATALOG=Analytics;"

'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"

'Now open the connection.
cnPubs.Open strConn

Set cmd = New ADODB.Command
cmd.ActiveConnection = cnPubs
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "dbo.Proc_CapitalAllocation_Step1"
cmd.CommandTimeout = 1200 'Seconds

''cmd.Parameters.Append cmd.CreateParameter_(fName1, fName2, fName3, fName4)
Call cmd.Execute(Parameters:=Array(fName1, fName2, fName3, fName4), Options:=adCmdStoredProc)

End Sub

Any help would be appreciated.
Thank you so much.

A: This will help you loop through the .csv files in a folder.
Option Explicit

Sub LoopThroughFiles()

    Dim strFile As String, strPath As String

    strPath = "E:\Analytics\"
    strFile = Dir(strPath & "*.csv")

    While strFile <> ""

        '-> code upload the file to SQL Database

        strFile = Dir

    Wend

End Sub

If you need more refinement, like you only want certain .csv files in the folder, add a statement after While strFile <> "" to weed out any files you don't want. Something like:
If InStr(1, strFile, "myName") > 0 Then
   '-> code to upload the file to SQL database
End If

A: I use the
SearchFile = Dir(SearchFolder & "*.csv")

line to successfully select only .csv files the first time through the code but as I loop through all the files in the folder using
SearchFile = Dir

in each loop, it selects other file types and I haven't found a way to force that line of code to select only .csv. So my fix was to add an IF statement right after to check it
     SearchFile = Dir
CheckFile:
     If Right(SearchFile, 3) <> "csv" Then
         SearchFile = Dir
         GoTo CheckFile
     End If

this way, if there is other file types in the folder it just skips over them. I use that format because of other code in my sub but it could be re-written as
CheckFile:
     SearchFile = Dir
     If Right(SearchFile, 3) <> "csv" Then
         GoTo CheckFile
     End If


text:
Q: ASP.NET send multipart/form-data to Power Automate I'm trying to send multipart/form-data to a Power Automate "When a HTTP response is received" trigger action (webhook).
I generate a RestSharp request in Postman like this...
        var client = new RestClient("https://prod-122.westeurope.logic.azure.com:443/workflows/********************************/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=***********************");
        client.Timeout = -1;
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "multipart/form-data");
        request.AddFile("file", @"C:\Temp\MyFile.pdf");
        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);

Using Postman to send the above works fine, the Power Automate action is triggered, as can be seen in the Power Automate log.
Using ASP.NET web form to send seems to fail i.e there is no record of it in the Power Automate log.
Without a proxy I get an error in the response "The remote server returned an error: (407) Proxy Authentication Required."
With a proxy I get an error in the response "The underlying connection was closed: An unexpected error occurred on a send"
Any ideas?

A: The unexpected error was protocol related.  Inserting the following line before the RestClient is instantiated resovled the issue.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;


text:
Q: SAS set missing value to 0 with array, while columns contain mixed data types I am reading this post about setting all missing values of a dataset to 0.
However, it seems that it only apply to datasets with numeric data types only. What if I have data with character and numeric data types at the same time? I cannot declare an array like array a(*) _numeric_; or array a(*) _character_;, and it seems that using ALL is not acceptable in arrays. What is the appropriate ways to get around it then?

A: If you want BOTH numeric and character variables to be set to 0 / "0" you have to run two arrays - eg as follows:
array __missnums _numeric_;
do over __missnums;
  if __missnums=. then __missnums=0;
end;
array __misschars _character_;
do over __misschars;
  if __misschars="" then __misschars="0";
end;

It makes no difference if your dataset contains variables of both types, the _numeric_ and _character_ keywords only apply to the numeric / character vars accordingly.


text:
Q: Process.WaitForExit() doesn't wait for log creation when trying to get log from DxDiag So i am using c# (.net 4.0) version and trying to run DxDiag to get the log.
I tried to use anwer in this question: Getting output from DxDiag in C#
But it looks like prc.WaitForExit() quits immediatelly and when trying to read log file it is empty (because it is made after 4-5 seconds).
I was using psi.UseShellExecute = true and false and both results was the same.
Also if I checked:
Process[] pname = Process.GetProcessesByName("dxdiag");

The pname process id was different than id from prc.Start().
It looks like process (dxdiag) is starting, immediately closing and another one is starting and doing the log file.
Anybody knows why this is happening?


text:
Q: Applying validation class ng-valid delayed for one step after real state change I have two input controls in reactive form on the page (see sample).
Here is main template part:
<form [formGroup]="loginForm" novalidate>
  <ion-list>
    <ion-item>
      <ion-label>PIN code</ion-label>
      <ion-input type="text" formControlName="pinVisible" ></ion-input>
      </ion-item>
    <ion-item>
      <ion-label>hidden control</ion-label>
      <ion-input type="number" formControlName="pin" #pin></ion-input>
    </ion-item>
  </ion-list>
</form>

Both should be valid when content only 4 chars long. When I edit "hidden control" it fills other control ("PIN code") with new masked value with following code:
this.loginForm = this.fb.group({
  pinVisible: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(4)]],
  pin: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(4)]]
});
this.pinVisibleControl = this.loginForm.get('pinVisible');
let pinControl = this.loginForm.get('pin');
pinControl.valueChanges.subscribe((value: string) => {
  console.log(value);
  this.pinVisibleControl.setValue(new Array(value.length).fill('*').join(''));
  this.pinVisibleControl.markAsTouched({ onlySelf: true });
  console.log(`PIN visible status: ${this.pinVisibleControl.status}`);
});

The problem is the validation state classes (ng-valid particularly) are applied to "PIN code" not right after change of control value, but only in next change cycle (when I enter fifth letter). So green valid indicator on "PIN code" appears only after next change (usually when it contains 3 or 5 letters, not 4).
Any suggestion how to apply validation classes right after value change?

A: You can try calling this.loginForm.updateValueAndValidity(); instead of.markAsTouched(). Marking as dirty/touched will only take effect when you check it's validity.


text:
Q: Wordpress website scrolling not working on one page with certain browser size only I am setting up a new wordpress website, and the header gets stuck and won't scroll on the / page, but no others to my knowledge. On my Macbook Air 11 inch, the default browser screen size makes it get stuck, but other sizes work fine. Tested with Chrome and Safari.
WEBSITE LINK REMOVED - SOLVED
Please advise! Thanks so much in advance.

A: Solved! Header was switching between sticky and fixed with page length.


text:
Q: Mono Slam scale consistency When running mono Slam how is scale consistency achieved between frames? One short tutorial ran the 5point algorithm repeatedly and used a motion model for consistency of scale between frames but that is clearly not done in the general case.
I think I read something once about how the 5 point algorithm is used initially to estimate motion between first two frames then features are tracked over time using reprojection loss and 3d projection.
How is it done?


text:
Q: Amazon Cloudfront setup with own origin server Hello there and thanks for reading my question.
I am looking into Amazon Cloudfront (CF) at the moment and need to define exactly the steps to setting up CF with our own origin server before I can proceed past inputting payment details.  The basic steps I have been able to find out through Googling are:

*

*Register with CF

*Set-up a CF distribution (this is where you register your origin server)

*Update your resource references on your site

The problem I am having is with step 2.  Although Amazon describe it as a simple API call, I am still not quite sure exactly what this means and what I would have to do to perform this call.
A lot of bloggers/forum posters suggest using a third party software like CloudBerry - the problem is is that CloudBerry costs to do the CF/origin server bit and I only need to do it once (everything else after that can be handled by the AWS management console.
I have looked at loads of other similar pieces of software but have found them to either error on download or on install or not have the functionality I am looking for on the Windows version!
Now, this page describes how to setup the origin server manually (http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/) but I am still not sure exactly how this is performed.
Has anyone done this before and can offer some guidance or step on how to do this?
Many thanks in advance!
Greg

A: I had success using Fog gem. Once you establish a connection to the Amazon API, it was painless to create a distribution.
cdn = Fog::AWS::CDN.new(
  :aws_access_key_id => YOUR_ID,
  :aws_secret_access_key => YOUR_SECRET_KEY
)

cdn.post_distribution(options = YOUR_OPTIONS_HASH )

And with that you should receive a 201.
The documentation is great, too.

A: This page walks through the custom origin server in a bit more detail http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?CreatingDistributions.html. The API call you need to make is to create a new distribution which points at your custom origin server. Basically you would craft the request as described and post it to amazon's web services.
Amazon just updated their CloudFront Management console to support features that were previously only available through their API, so you should be able to configure it without using the API.
http://aws.amazon.com/about-aws/whats-new/2010/11/09/cloudfront-adds-support-for-custom-origins-and-sla/?ref_=pe_2170_19753730

A: Cloudbuddy (http://m1.mycloudbuddy.com/downloads.html) is free and you can use it to setup the Cloudfront custom origin. Windows only, unfortunately, but you only have to use it once, right?  :-D


text:
Q: ImageMagick OSX Snow Leopard bad CPU type Installing imagemagick works.
But when I try to run a command it says bad cpu type.
What is this and how do I get rid of it so that it works right?
N.b. I'm 'behind the times' and only using a core solo (if that helps)

A: It sounds like you may have a 64-bit build of imagemagick which you're trying to run on a 32-bit only CPU.  As Greg noted, running the file command on it will confirm this; it will show you something like this:
styrone$ file /usr/local/bin/imagemagick
/usr/local/bin/imagemagick: Mach-O universal binary with 2 architectures
/usr/local/bin/imagemagick (for architecture x86_64): Mach-O 64-bit executable x86_64
/usr/local/bin/imagemagick (for architecture i386): Mach-O executable i386

If you don't see a line with "(for architecture i386)", that's your problem.  You'll need to get a build that supports 32-bit Intel.


text:
Q: Problem with glOrtho: the curve disappears from the scene I have curve, a parable (y=x*x) for x in [0, 10]. I have used:
glOrtho(-10 - 3, 10 + 3, -(y(10)+ 3) * (GLfloat) h / (GLfloat) w,
                        (y(10) + 3) * (GLfloat) h / (GLfloat) w, -1, 1);

a part on top is clipped.
Moreover if I consider a parable in [8, 10] and I set:
glOrtho(-10 - 3, 10 + 3, -(y(10)+ 3) * (GLfloat) h / (GLfloat) w,
                        (y(10) + 3) * (GLfloat) h / (GLfloat) w, -1, 1);

my curve disappears from the scene. How can I modify the commands to visualize the curve?


text:
Q: I am doing asynchronous processing with scala, but it is not displayed import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
def now() = new java.util.Date();
(1 to 30).foreach(_ => Future{Thread.sleep(2000);println(now)})

I am doing asynchronous processing with scala, but it is not displayed. How can I display it in this case?
No Thread.sleep please.

A:
No Thread.sleep please.

Without any Thread.sleep at the end of your program, your code will end after the foreach terminates and the async tasks pending will be killed. Thus very likely nothing will be printed because it doesn't take 2s to iterate over 30 items.

That being said, you could explicitly wait for the async tasks instead. With something like the following:
val tasks: Seq[Future[Unit]] = (1 to 30)
  .map(_ => Future {
    Thread.sleep(2000)
    println(now)
  })
val tasksMerged = Future.sequence(tasks)
Await.result(tasksMerged, 3.seconds)

Await will wait for async task passed in parameter to complete for up to the timeout given in parameter.


text:
Q: default PUBLIC settings does anyone know of any security risks with the default PUBLIC settings for sql 2005/8?
i ran sp_helprotect and it listed out the PUBLIC grants, and now i have an auditor telling me that i have a security risk because PUBLIC has access to system information. before i start to present my case i wanted to see if anyone has any links or information they can provide that would detail how the default settings allow for a security risk.
for the record, the auditor mentioned that these setting allow for the ability to crack passwords because they can view the password hash. i have not been able to verify that the setting allow for such an ability to see that information through the sys catalog views.
thanks in advance

A: In 2000, the public role has access to a lot more than in 2005 onwards - this may be the source of the auditor's issues. User/schema separation should take care of most issues, but you should create a user with minimal permissions and see what it can see. You'll want to try:
master.sys.databases (and anything else that could give away info on what is stored in the instance)
master.dbo.syslogins (which contains the password hashes - sysxlogins on 2000)
And you also want to change all XPs in master so that the public role doesn't have execute permission on any of them. There's an article and a piece of code that will do this here.
Note that it's NOT recommended to change the public role itself in any way.
Hope this helps!
PS If you get back a NULL for the password in the syslogins table, it's because the login isn't using SQL authentication. Using Windows-only is a good way to remove this risk, but you still need to have a password for the (disabled) SA account.

A: Here is a BOL aritcle explaining how the public role affects metadata visibilty for all users:
http://msdn.microsoft.com/en-us/library/ms187113(SQL.90).aspx
There is some stuff that typically needs to be visble to everyone or things will break (sys.databases is one of the examples, even if it's not listed in this aricle - for historical reason everyone can retrieve the list of all databases on the server but you can of course revoke this permission). Things tend to get funny when you start revoking public access to some pieces of metadata.
To give you an example: things will break big-time if you revoke public permission to select from sys.databases. The proper way to do it is to REVOKE VIEW ANY DATABASE from public - then sys.databases will be "filtered" and you will only see the databases for which you have permissions. But it does not give you any real security as anyone can still enumerate all databases by doing SELECT DB_NAME(X) and supplying arbitrary values for X (that's a known loophole).
And in terms of passwords, in default configuration for SQL2005 and SQL 2008, through the public role you can only see two logins via sys.syslogins: yourself and sa. And you will not see the password hash for either one. So obtaining hashes for cracking this way is not an option. And cracking those hashes requires brute-force approach anyway so it only works for weak or dictionary passwords.
My experience with auditors is that they tend to make a fuzz about small things like public permissions but miss the big thing. YMMV.
HTH


text:
Q: What is the `Join()` method on `List().Join()` used for? I came across this
List().Join()

And was wondering
How can the Join() portion in the above line of code (on the right side of List be used ?
This looks similar to the following :
String.Join()

...but it has a more complex IntelliSense tool-tip as displayed below :

A: There is no instance or extension method in .NET for a sequence of strings that will join them together as String.Join does.  If you want such an extension method you'll have to write it yourself (which should be trivially easy, given that internally all it needs to do is call string.Join).
Enumerable.Join, which is the method you are seeing on IEnumerable<T>, is referring to a Join in the set context, like what SQL does, and is a very different kind of operation.

A: Join is a regular static method of the class String. The syntax you want to use can only be used with extension methods. If you really insist on being able to use it like that simply create your own:
public static class MyExtensions
{
    public static string Join(this IEnumerable<string> enumeration, string separator)
       => string.Join(separator, enumeration);
}

A: Do this, and now you have the syntax you want.
public static class ExtensionMethods
{
    public static string Join(this IEnumerable<string> stringarray, string separator)
    {
        return String.Join(separator, stringarray);
    }
}

A: The problem is that myList is a list of strings. The Join function is a very string specific function. Since a list doesn't make any assumptions about what is inside the list (ei you can store integers, floats, user defined classes etc...) it doesn't make any sense for a list to include a function that is so specific to only string.
This is why lists don't have a myList.Join because anything could be in that list. You'll unfortunately have to stick with String.Join() as unelegant as it is.

A: You could use IEnumerable.Aggregate like this
list.Aggregate((i, j) => i + j);

But string.join is the preffered method for performance.
Do not try to invent a custom syntax. You will lose readability by other C# devs. By the way it is possible with an extension method.


text:
Q: steganography library in C or Obj-C Does anyone know of a good steganography library I can use thats written in C or Objective-C?  It would need to be used in a Mac OS X application.

A: My provocative answer will be that you should try to implement/learn some algorithms for image hiding/unhiding yourself. Sample algorithm of 3-bit image hiding into 24-bit image is very simple and consists of about 10 Python lines or so (of course it may be a bit more with C/Obj-C). And you will get not bad quality of stego image - about 87.5% of original quality. So check my blog article about this steganography method.
This stego decoding method is done in GPU pixel shader program for fast decoding procedure.
However encoding was done with Python script which after use was deleted ;P
But i think that encoding procedure is very straightforward and can be understood from my blog article. If any questions about my stego algorithm- feel free to ask.


text:
Q: Solution Verification: Is this language context free? (Building a pushdown automaton). Here's the question:

Given $L_A$ and $L_B$ are two regular languages over the alphabet $\sum=\{1,2,3\}$, is the following $L$ language context free? Prove your answer.
$L = \{w\in L_A \mid \exists x\in L_B \text{ such that }|x|=2|w|\}$

I would really appreciate any help in correcting my mistakes in formal writing as I feel that's where my weakness is.

My answer:
Intuition: Language $L$ takes the words in $L_A$ and words if there's a word exactly double their length in $L_B$, the way I could prove $L$ is context-free is by building a pushdown automaton that accepts it using the DFA's of $L_A$ and $L_B$.
The automaton will have $2$ copies, which differ by a flag bit added to the states and delta function,  $0$ for $L_A$ and $1$ for $L_B$, when reading a word in $L_A$ we will push $2$ $A's$ into the stack,  and we stay in $0$ copy until we reach any state in $F_A$, where we have an opportunity to move to the copy of $L_B$ (setting the flag to $1$), where we will stay popping $A's$ (which will bring us to have words of double length when we see the bottom of the stack), then for every state in $F_B$, we will have an opportunity to remove the bottom of the stack  if we see it (using epsilon).

Formal answer:
Both $L_A$,$L_B$ are regular, so there exists two DFA's, $A=(Q_A,\sum,\delta_A,q_{0A},F_A)$ and $B=(Q_B,\sum,\delta_B,q_{0B},F_B)$ where $L(A)=L_A$ and $L(B)=L_B$.
Notes: $S$ is stack bottom. $P$ accepts a language when stack is empty.

I will build a pushdown automaton $P=((Q_A\times\{0\})\cup (Q_B\times\{1\}), \sum, \{S,A\},\delta, (q_{0A},0),S,\phi)$.
For every $q\in Q_A$ and $\sigma\in \sum$:
$\delta((q,0),\sigma,S)=((\delta_A(q,\sigma),0), AAS)$
$\delta((q,0),\sigma,A)=((\delta_A(q,\sigma),0), AAA)$
For every $q\in F_A$:
$\delta((q,0),\epsilon,S)=((q_{0B},1),S)$
$\delta((q,0),\epsilon,A)=((q_{0B},1),A)$
For every $q\in Q_B$:
$\delta((q,1),\sigma,A)=((\delta_B(q,\sigma),1), \epsilon)$
For every $q\in F_B$:
$\delta((q,1),\epsilon,S)=((\delta_B(q,\epsilon),1), \epsilon)$. (I'm not sure how to write this.. all I want to say is accept the language by emptying the stack, do I need to put a state?).
Any help is really appreciated, thanks in advance.

A: The language $L$ is regular. This does not depend on the size of the alphabet, and it is also be true if $L_B$ is context-free. Let $\pi: \Sigma^* \to \Bbb N$ be the length map defined by $\pi(u) = |u|$. Observe that
$$
L = L_A \cap \{ w \in \Sigma^* \mid 2|w| \in \pi(L_B)\}.
$$
Since $L_B$ is context-free, the set $S = \pi(L_B)$ is a semilinear set. I let you verify that the set
$$
  T = \{n \in \Bbb N \mid 2n \in S\}
$$
is also a semilinear set. Now,
$$
L = L_A \cap \pi^{-1}(T)
$$
and thus $L$ is regular.


text:
Q: Hotkeys that use Ctrl+Shift+Alt are not working in MPV For some reason Ctrl + Shift + Alt  and any key combination will just not trigger the preconfigured action in mpv.
Ctrl+Shift+Alt+A seek 15 exact

For example, in the above Ctrl + Shift + Alt + A is set to seek 15 seconds but in MPV nothing happens.  I've even tried to express it like this:
Ctrl+Alt+A seek 15 exact

and it still does not work. I've tried many other keys from F1-F12 to 1- 9 to A-Z. Did I overlook something here? Are Ctrl + Shift + Alt +[Key] combinations not supported in MPV?
Because of constraints and edge key cases on my system I only have three key modiefier hotkeys available for use in MPV
I have taken the liberty to crosspost this question on other forums as well.
Any help would be greatly appreciated!


text:
Q: Why is LibreOffice so slow when used in Ubuntu 16.04? The Problem
I'm using LibreOffice 5.0.6.3 in Ubuntu 16.04, and the program is considerably slower than in e.g. Windows 8.1 and Debian 8.
This shows up in particular when I change the zoom level in larger documents below 200%.
Above 200% (e.g. from 200% to 220% etc.), zooming in and out happens absolutely smooth -- the program needs no time for the change.
But e.g. from 160% to 180%, zooming causes the program to get extremely laggy: Everything freezes, and sometimes also the whole program surface turns grey/black -- sometimes for some seconds, sometimes "permanently".
This does not happen when the edited document is relativley small; that is, when there are no objects, images etc. in it, but only text, or when the document is only a few pages long.
Example
I have an extensive document (50+ pages) with many arrows, tables, and also some pictures, and the problems mentioned occur when I open it in Ubuntu 16.04. But they don't occur when I edit the same document in Debian 8 and Windows 8.1.
What I've tried already
I already changed certain properties, since I searched quite a bit for possible solutions.
For example, I turned off Java and Open CL, and provided considerably more memory for LibreOffice.
But all of this improved the situation hardly noticeably -- if at all...
...which is not really surprising, since in Windows 8.1 and Debian, LO ran smoothly without making these changes.
Question
Does anyone know whether this is an Ubuntu-specific problem, or simply why that occurs?
Could it have something to do with the fact that I'm not using the pre-installed version from Ubuntu Xenial?
(I switched to the above mentioned version, since 5.1.x seemed to be even more unstable than 5.0.5 already was. (sudden crashes after simple commands))

A: In Ubuntu 16.04, to make LibreOffice Impress 5.1.4.2 fast just remove the libreoffice-gtk package. Don't remove the libreoffice-gnome package, which is necessary for the UI to look good and be properly integrated with gnome (e.g. expected integrated open file dialog). So:
$ sudo apt-get remove libreoffice-gtk

Now copy-pasting slides is fast again, and scrolling the slides as well.

A: The problem seems to be caused by bugs related to the GTK3 builds of LibreOffice (look here and here). As fare as I found out, the only way to work around is to switch back to the GTK2 version. At first you have to be sure the related packages are installed:
sudo apt install libreoffice-gtk libreoffice-gtk2

Then you can start LibreOffice with GTK2 temporarily with:
SAL_USE_VCLPLUGIN=gtk SAL_SYNCHRONIZE=1 libreoffice

Now it should work again normally. If it does, you can remove the GTK3 package to force LibreOffice to use the GTK2 version permanently:
sudo apt purge libreoffice-gtk3

Shame on Canonical to deliver an untested version of LibreOffice!

A: To avoid slow User Interface update, a workaround is to:

*

*Remove packages: libreoffice-gnome and libreoffice-gtk and
libreoffice-gtk3.

*Restart (Close and Open) LibreOffice.

After this, LibreOffice User Interface is being updated fast. But, when (main) window is resized, sometimes it becomes messy. So, avoid any unnecessary resizes (resizings), keep (main) window in full size.
It seems to be a GTK port only issue.
Workaround was tested with LibreOffice 5.1.3.2 and Ubuntu 16.04 64 bit.
Issue was fixed in LibreOffice 5.1.4.2.

A: You can try a newer version  of libreoffice to see if that fixes the issue by downloading the .deb:
https://www.libreoffice.org/download/libreoffice-fresh/?type=deb-x86_64&version=5.1&lang=en-US

A: Upgrading to Libreoffice-5.2.1 solved the problem for me.


text: Q: How to calculate the overall entropy when continuous 2D positions are known? If I have the positions of particles in continuous 2D space, how do I calculate the entropy of the system? The particles are invariant, I just need some measure of how organised they are, but I'm not sure how to calculate that. I think I need to integrate the population density over both dimensions?


text:
Q: C calculator if else I want to make a simple C calculator only with "IF" and "IF ELSE" conditions and it don't let me choose an operator ("+, -, * or /"), just appear my last if condition.
#include <stdio.h>
int main(){
    printf("\tCalculadora\n\n");
    int num1, num2, total;
    char oper;
    printf("Introduza o primeiro numero: \n");
    scanf("%d", &num1);
    printf("Introduza o segundo numero: \n");
    scanf("%d", &num2);
    printf("Escolha a operacao que quer realizar!\n\n");
    scanf("%c", &oper);
    if(oper == '+'){
        printf("O resultado e: %d", num1+num2);
    }
    else if(oper == '-'){
        printf("O resultado e: %d", num1-num2);
    }
    else if(oper == '*'){
        printf("O resultado e: %d", num1*num2);
    }
    else{
        printf("O resultado e: %d", num1/num2);
    }
    getchar();
    getchar();
}

A: I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands.
#include <stdio.h>
#include <stdlib.h>

#define ISIZE   100      // arbitrarily large

int main(){
    double num1, num2;
    int oper;
    char inp[ISIZE+1] = "";
    printf("\tCalculadora\n\n");

    printf("Introduza o primeiro numero: ");            // 1st operand
    fgets (inp, ISIZE, stdin);
    num1 = atof (inp);

    printf("Introduza o segundo numero: ");             // 2nd operand
    fgets (inp, ISIZE, stdin);
    num2 = atof (inp);

    printf("Escolha a operacao que quer realizar! ");   // operator
    fgets (inp, ISIZE, stdin);
    oper = inp[0];

    printf ("O resultado e: %f %c %f = ", num1, oper, num2);

    switch (oper) {
        case '+': printf("%f\n", num1+num2); break;
        case '-': printf("%f\n", num1-num2); break;
        case '*': printf("%f\n", num1*num2); break;
        case '/': if (num2!=0) printf("%f\n", num1/num2);
                  else printf ("Divisão por zero!\n");
                  break;
        default:  printf("Eu não sei o que operador\n");
    }
    return 0;
}

A: This
scanf("%c", &oper);

should change to
scanf(" %c", &oper);

so you let scanf() ignore the '\n' left by previous scanf()s.

A: I was also trying to apply my knowladage of C in a simple calculator and came across you question. In order to respect your if...else request I've come up with this solution. I hope this helps.
    #include <stdio.h>
void sayHello( ) {
    printf("Hello\n"); }
// to say hello to the user
int add( int num1, int num2) {
        num1 = num1 + num2;
        return num1;
}

int minus( int num1, int num2) {
        num1 = num1 - num2;
        return num1;
}

int times( int num1, int num2) {
        num1 = num1 * num2;
        return num1;
}

int divide( int num1, int num2) {
        num1 = num1 / num2;
        return num1;
}
// This is to declare the calculations
void flush_input(){
    int ch;
while ((ch = getchar()) != '\n' && ch != EOF); }
// This is to flush the scanf values
// Kudos to Huw Collingbourne, Udemy Teacher
int main(int argc, char **argv) {
        char c;
        char f;
        int n1;
        int n2;
        int total;

        // n1 = ' ';
        // n2 = ' ';

sayHello();

do {
    c = ' ';
    printf("Insert the type of Calculation you want to make:\n");
    printf("A(d)dition, Subs(t)raction, Mu(l)tiplication, Di(v)ision: ");
        c = getchar();
if(c == 'd') {
    printf("\nInsert the first number:");
    scanf("%d", &n1);
    printf("Insert the second number:");
    scanf("%d", &n2);
    total = add( n1, n2 );
    printf("%d plus %d equals to %d\n", n1, n2, total );
    flush_input(); } else {
        if( c == 't') {
        printf("insert the base number:");
        scanf("%d", &n1);
        printf("Insert the subtracting number:");
        scanf("%d", &n2);
        total = minus( n1, n2 );
        printf("The difference between %d and %d is %d\n", n1, n2, total );
        flush_input(); } else {
            if( c == 'l') {
            printf("insert the first number:");
            scanf("%d", &n1);
            printf("Insert second number:");
            scanf("%d", &n2);
            total = times( n1, n2 );
            printf("%d times %d equals %d\n", n1, n2, total );
            flush_input(); } else {
                if( c == 'v') {
                printf("insert the first number:");
                scanf("%d", &n1);
                printf("Insert second number:");
                scanf("%d", &n2);
                total = divide( n1, n2 );
                printf("%d divided by %d equals %d\n", n1, n2, total );
                flush_input();
                } else {
        printf("I couln't understand the instruction\n Reseting program\n");
                }
            }
        }
    }
        f = ' ';
        printf("\nDo you wish to make another calculation?\n");

            printf("Choose (y)es or (n)ot: ");
            f = getchar();
            // scanf("%c", &c);
            getchar();
        } while( f != 'n' );
        printf("\nThat's all folks!\n");
    return 0;
}

A: #include <stdio.h>
#include <stdlib.h>

//declaration of function
float cal (float a, float b, char o);

int main(int argc, char *argv[])
{
//  declaration of variable
    float num1,num2;
    int inum1,inum2;
    char  o;
    //initialization of variable
    num1=0;
    num2=0;

//input
    printf("Enter 1st number\n");
    scanf("%f",&num1);
//input
printf("operator\n");
    scanf(" %c", &o);

//input
printf("Enter 2nd number\n");
    scanf(" %f", &num2);

    inum1=num1;
    inum2=num2;

        if(cal(num1,num2,o)==0)
        {
            printf("Math Error");
        }
        if(cal(num1,num2,o)==1)
        {
            printf("%d",inum1%inum2);
        }
        else
        printf("%.3f\n",cal(num1,num2,o));

    return 0;
}

//definening function

float cal (float a, float b, char o)
{

        if (o=='+')
        return a+b;

        if (o=='-')
        return a-b;
        if (o=='*')
        return a*b;
        if (o=='%')
        return 1;
        if (o=='/')
        if (b!=0)
        return a/b;
        if (b==0)
        return 0;

}


text:
Q: After removing VDAgent Spice Ubuntu won't boot As the title says, I can't boot. Instead I get a black screen with a bunch of words I do not understand.
What I have done to attempt fixing:

*

*I noticed that if I go to advanced options in the GRUB that there is Ubuntu 18.04.05 and Ubuntu 18.04.06 so, assuming I tried launching the version 5. This yielded the same result

*I went it to safe mode and updated the GRUB, repaired packages with network activated then relaunched. It was just a blank screen so i used power button to reboot, and then got the same screen.

The words I do not understand.
continued...
Please help.


text:
Q: How do I get gvfs-info to output file metadata when called from cron? I'm having a weird problem and was hoping maybe someone out there might be able to give me some insight. Kind of at a loss.
On Linux Mint using Nemo which has a tendency to crash every once in a while with the annoying side-effect of shifting a bunch of my desktop icons. I thought I'd just write a quick script that would dump the locations of all my icons to a text file once a day, and then another to reposition them back where they are supposed to be.
It works perfectly when I run it manually, but not when it runs through cron.
I have figured out that the problem comes down to gvfs-info. Basically, I use the command:
gvfs-info -a 'metadata::nemo-icon-position' /path/to/file

which will produce:
metadata::nemo-icon-position: 220,682

in the output.
gvfs-info, however, needs to communicate with the dbus-daemon to get the metadata because it's actually stored in ~/.local/share/gvfs-metadata/. It can't access the dbus-daemon when it's being spawned from cron (or sudo or ssh for that matter)—a fact I discovered here and here which proposes a possible solution.
Following that solution, I can successfully execute from the terminal:
dbus-launch --exit-with-session /path/to/myscript.sh

and it works as expected. However it still produces the same output without the metadata. I've tried a lot of permutations of where I called dbus-launch and in combinations with 'su user' to ensure it's actually running as my user, but I guess I just don't understand what's going on here very well.
Anyone have any thoughts?

A: @steeldriver's comment was exactly what I needed (Thank you!).
I lifted the below from How to change Gsettings via remote shell and it was exactly what I needed!
PID=$(pidof -s nemo)
QUERY_ENVIRON="$(tr '\0' '\n' < /proc/${PID}/environ | grep "DBUS_SESSION_BUS_ADDRESS" | cut -d "=" -f 2-)"
export DBUS_SESSION_BUS_ADDRESS="${QUERY_ENVIRON}"

I used 'nemo' because I know it would be running in my desktop environment.


text:
Q: filters in the Pending Changes view of the RTC client for Visual Studio I'm using RTC a lot and my project has quite a number of components. To see only the components that I'm interested in (the ones with changes) I select a filter in the RTC Pending Changes view. However, whenever I reopen Visual Studio my filter selection is gone. As I'm switching between quite a number of sandboxes and Visual Studio instances daily, having to set the filter again some 2 dozen times a day is getting quite tiresome. Is there any way to save the filter setting?

A: Another approach would be to use only repository workspaces with the right components in them: when you define a repo workspace, you don't have to select all components from the stream.
That way, the sandboxes can load all components from your repo workspace, without having to set any filter.


text:
Q: Modify the stack of a PLY parser Trying to modify a value already pushed to the stack of a PLY/Yacc parser. I'm using ply on python 3.
Basically I want to invert the previous two values when a token SWAP is used.
Imagine we have this stack:
1, 2, 3, 4, SWAP
I need it to reduce to:
1, 2, 4, 3
the value you write to p[0] will be pushed to the stack, but how can I push more then one value?
# this fails because it consume two values and pushes only one
# results into: `1`, `2`, `4`
def p_swap(p):
   'value : value value SWAP'
   p[0] = p[2]

# this was just a try... fails as well
def p_swap(p):
   'value : value value SWAP'
   p[0] = p[2]
   p[1] = p[1]

# this locked as a good idea since consumes only only value and modify the second in place
# it fails because the stack (negative indexes) are immutable:
# https://github.com/dabeaz/ply/blob/master/ply/yacc.py#L234
# results into: `1`, `2`, `3`, `3`
def p_swap(p):
   'value : value SWAP'
   p[0] = p[-1]
   p[-1] = p[1] # this is a NOP

p is an instance of this class
I guess it was designed to be immutable to enforce the parsing to be done a certain way (the correct way), but I'm missing it: what's the correct way to modify the stack or to design a parser?

A: It sounds like you're trying to create a stack-based language like Forth or Joy. If so, you shouldn't need a bottom-up parser, and you shouldn't be surprised that a bottom-up parser-generator doesn't work the way you want it to.
Stack-based languages are mostly simply streams of tokens. Each token has some kind of stack effect, and they are just applied in sequence; there's usually little or no syntactic structure beyond that. Consequently, the languages really aren't parsed; at best, they are tokenised.
Most stack-based languages contain some kind of nested control structures which are not strictly conformant with the above (but not all; see Postscript, for example). But even these are so simple that a real parser is unnecessary.
Of course, nothing stops you from using a generated parser to parse a trivial language. But if you do that, you should certainly not expect to be able to gain access to the parser's internal datastructures. The parser stack is used by the parser in ways which might not be fully obvious, and which certainly must not be interfered with. If you want to implement a stack-based language interpreter, you need to use your own value stack. (Or stacks; many stack-based languages have several different stacks, each with its own semantics.)


text:
Q: How to use ".endswith" within a list of strings in Python? I'm struggling with this task that i've been given in Python, and it's about modifying text from a given text file (read mode, not write). Here's a piece of my code:
file = open("fileName")
suffix_list:[]

for e in file:
    elements=e.split()
    result=elements.endswith("a")
    suffix_list.append(result)

And then I want to print the length of the list with suffixes:
print(len(suffix_list))

Instead i get this error: " 'list' object has no attribute 'endswith' "
I'm really not sure whats wrong here, can someone please help?

A: Check endswith with a string and not a list. e.split() gives a list. Iterate through this list and check endswith with each item in the list.
suffix_list = []

for e in file:
    for element in e.split():
        if element.endswith("a"):
            suffix_list.append(element)

print(len(suffix_list))

Also, a list-comprehension version:
suffix_list = []
for e in file:
    suffix_list.extend([element for element in e.split() if element.endswith('a')])

assuming, you need a flat list rather than a list of lists.

A: for e in file:
    elements=e.split()
    result=[ele for ele in elements if ele.endswith("a")]
    suffix_list.append(result)


text:
Q: How to pretty print a matrix in Octave? I want to create a pretty printed table from a matrix (or column vector).
For Matlab there are several available functions that can do this (such as printmat, array2table, and table), but for Octave I cannot find any.
So instead of:
>> a = rand(3,2)*10;
>> round(a)
ans =

    2   10
    1    3
    2    1

I would like to see:
>> a = rand(3,2)*10;
>> pretty_print(round(a))

   THIS   THAT
R1    2   10
R2    1   3
R3    2   1

How can I produce a pretty printed table from a matrix?
(Any available package to do so?)

UPDATE
After trying to follow the extremely obtuse package installation instruction from Octave Wiki, I kept getting the error pkg: failed to read package 'econometrics-1.1.1.tar.gz': Couldn't resolve host name. Apparently the windows version isn't able to use the direct installation command (as given on their Wiki). The only way I managed to get it, was by first downloading the package manually into the current working directory of Octave. (See pwd output.) Only then did the install command work.
pkg install econometrics-1.1.1.tar.gz
pkg load econometrics

A: Yes, there is a prettyprint function in the econometrics package. Once the package is installed and loaded, you can use it like this:
>> a = rand(3,2)*10;
>> prettyprint(round(a),['R1';'R2';'R3'],['THIS';'THAT'])

          THIS        THAT
R1       2.000       3.000
R2       3.000       4.000
R3      10.000       3.000


text:
Q: Display an image using EventDispatchThread vs without So I'm trying to display an image(ball) which I'll eventually control with user input. For know, the image just gets displayed over intervals using thread's sleep method.
I've made 2 classes, one that extends JPanel and the other extends JFrame.
The JPanel subclass looks like this:
 public class BallPanel extends JPanel {
    private Image ball;
    private int x,y;
    public BallPanel(){
        try {
            ball=ImageIO.read(new File("C:\\Users\\Owner\\Desktop\\ball.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        x=10;
        y=10;
        Thread thread = new Thread() {
            @Override
            public void run(){
                    loop();
        }
      };
        thread.start();
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(ball,x,y,null);
    }
    public void loop(){
        while(true){
            repaint();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

In the loop method I call the sleep method to allow repaint to be called over intervals. Then, loop() is called in the constructor.
The JFrame subclass looks like this:
    public class BallFrame extends JFrame {

    public BallFrame(){
        setVisible(true);
        setSize(800,800);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setContentPane(new BallPanel());
    }
    public static void main(String args[]){
        //SwingUtilities.invokeLater(new Runnable() {
             //   @Override
              //  public void run() {
                    new BallFrame();
               // }
    //});

}
}

Now the interesting, or perhaps confusing thing, is that when I run the code as it is shown here, with the anonymous inner class commented out, the ball doesn't always appear. Sometimes I need to re-size the frame (i.e call repaint) before the ball is shown. However, when I call it through the even dispatch thread using the anonymous inner class the ball appears every time I run the code. What is the reason for this?

A: It has little to do with starting the UI from within the EDT or not (although you should cause that can cause lots of other weird and interesting issues) and more to do with the fact that you've called setVisible before you've established the contents of the UI.
This is possibly an example of a race condition between the system trying to get the EDT up and running and the OS calls responding before it's established.
In either case you SHOULD start the UI from within the EDT and call setVisible last.
Swing can be lazy about updating the UI, this is actually a deliberate design choice as well as a good idea.  You don't always want  the UI updated after each and every change you make (like adding/removing components), so it hands over some of the control to the developer to decided when it's best to revalidate container hierarchy and request repaints
I would also avoid using a Thread to update the state of the UI as this could cause dirty paints as Swing uses a passive rendering approach (painting when it feels it's required) and consider using a Swing Timer which updated from within the EDT OR use a BufferStrategy and employ a active rendering approach, which you can then control


text:
Q: Safari error undefined is not an object I've read a few post here concerning my issue but I don't know how to apply that to my code since I don't work with an array or other object.
In Safari I get this error:
TypeError: undefined is not an object (evaluating '$('#related .expansion').data('handle').replace')

I have a function that populates a select dynamically, like so:
function expansieRubberSelect(){
  var url = $('#related .expansion').data('handle').replace('.html', '.ajax');
    $.getJSON(url, function(data){
        var select = '';
       $.each(data.variants, function (index, variant) {
          select += '<option value="'+variant.id+'" data-size="'+variant.title.replace(/\D/g,'')+'" data-price="'+variant.price.price_excl.toFixed(2)+'" data-priceincl="'+variant.price.price+'">'+variant.title+'</option>'
       });
       $("#related .expansion select").append(select);
    });
}

And then in my doc ready I call it like so:
 $(function(){
     expansieRubberSelect()
 });

I've read that missing an object is causing the problem obviously. However I don't have a clue how that would apply to my code.
Do I need to change the select to an array or something? And then call in like expansieRubberSelect(mySelect)?
Any help appreciated!

A: Thx to Utkanos' answer I managed to get it working.
The idea is to check if the element exist. However you can also test for url to exist.
function expansieRubberSelect(){
 if($('#related .expansion').length){
  var url = $('#related .expansion').data('handle').replace('.html', '.ajax');
    $.getJSON(url, function(data){
        var select = '';
       $.each(data.variants, function (index, variant) {
          select += '<option value="'+variant.id+'" data-size="'+variant.title.replace(/\D/g,'')+'" data-price="'+variant.price.price_excl.toFixed(2)+'" data-priceincl="'+variant.price.price+'">'+variant.title+'</option>'
       });
            $("#related .expansion select").append(select);
    });
 }
}


text:
Q: react-router+antD/ How to highlight a menu item when press back/forward button? I create a menu and want to highlight the item which i choose,and i did it. But when i press back/forward button,the menu item don't highlight. What should i do?
I have tried to use addEventListener but failed.
Have someone could give some advice?
class Sidebar extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            test: "home"
        }
        this.menuClickHandle = this.menuClickHandle.bind(this);
    }

    componentWillMount(){
        hashHistory.listen((event)=>{
            test1 = event.pathname.split("/");
        });
        this.setState({
            test:test1[1]
        });
    }

    menuClickHandle(item) {
        this.props.clickItem(item.key);
    }

    onCollapseChange() {
        this.props.toggle();
    }

    render() {
        var {collapse} = this.props;
        return (

                <Menu mode="inline" theme="dark" defaultSelectedKeys={[this.state.test || "home"]} onClick={this.menuClickHandle.bind(this)}>
                    <Menu.Item key="home">
                        <Link to="/home">
                            <Icon type="user"/>用户管理
                        </Link>
                    </Menu.Item>
                    <Menu.Item key="banner">
                        <Link to="/banner">
                            <Icon type="setting"/>Banner管理
                        </Link>
                    </Menu.Item>
                </Menu>

                    {collapse ? <Icon type="right"/> : <Icon type="left"/>}

        )
    }
}

A: Intercepts the current URL and then set selectedKeys(Note that it is not defaultSelectedKeys).
componentWillMount(){
        hashHistory.listen((event)=>{
            pathname = event.pathname.split("/");
            if(pathname != null){
                this.setState({
                    test:pathname[1]
                });
            }
        });
    }

A: you can set the paths of the link as keys on each Menu.Item . then selectedKeys={this.props.location.pathname}
<Menu
  theme="light"
  mode='inline'
  selectedKeys={[this.props.location.pathname,]}
>
  <Menu.Item key={item.path} style={{float:'right'}}>
    Link to={item.path}>{item.name}</Link>
  </Menu.Item>
  {menulist}
</Menu>

Item would be set active according to the current path.
i added [] and trailing comma because selectedKeys accepts array while this.props.location.pathname is a String. i just code as hobby so idont know if its acceptable.

A: I could come up with a solution using WithRouter
import React,{ Component } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { Layout, Menu, Icon } from 'antd';
import PropTypes from 'prop-types';

const { Sider } = Layout;

class SideMenu extends Component{

  static propTypes = {
    location: PropTypes.object.isRequired
  }

  render() {
    const { location } = this.props;
    return (
        <Sider
          trigger={null}
          collapsible
          collapsed={this.props.collapsed}>

          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={['/']}
            selectedKeys={[location.pathname]}>
            <Menu.Item key="/">
              <NavLink to="/">
                <Icon type="home" />
                Home
              </NavLink>
            </Menu.Item>
            <Menu.Item key="/other">
              <NavLink to="/other">
                <Icon type="mobile"/>
                Applications
              </NavLink>
            </Menu.Item>
            <Menu.Item key="/notifications">
              <NavLink to="/notifications">
                <Icon type="notification" />
                Notifications
              </NavLink>
            </Menu.Item>
          </Menu>
        </Sider>
    )
  }
}

export default withRouter(SideMenu);

A: The following answer assumes you are using hooks. I know you are not in your question, but it might be useful for other people. In addition, this solution will work if you have nested paths such as /banner/this/is/nested, and it works not only when pressing back and forward buttons but also when refreshing the current page:
import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { Layout, Menu } from 'antd'

const { Sider } = Layout

const items = [
  { key: '1', label: 'Invoices', path: '/admin/invoices' },
  { key: '2', label: 'Service Details', path: '/admin/service-details' },
  { key: '3', label: 'Service Contract Details', path: '/admin/service-contract-details' },
  { key: '4', label: 'Cost Centers', path: '/admin/cost-centers' },
  { key: '5', label: 'Clients', path: '/admin/clients' },
  { key: '6', label: 'Vendors', path: '/admin/vendors' }
]

const Sidebar = () => {
  const location = useLocation()
  const history = useHistory()
  const [selectedKey, setSelectedKey] = useState(items.find(_item => location.pathname.startsWith(_item.path)).key)

  const onClickMenu = (item) => {
    const clicked = items.find(_item => _item.key === item.key)
    history.push(clicked.path)
  }

  useEffect(() => {
    setSelectedKey(items.find(_item => location.pathname.startsWith(_item.path)).key)
  }, [location])

  return (
    <Sider style={{ backgroundColor: 'white' }}>

        Costek

      <Menu selectedKeys={[selectedKey]} mode='inline' onClick={onClickMenu}>
        {items.map((item) => (
          <Menu.Item key={item.key}>{item.label}</Menu.Item>
        ))}
      </Menu>
    </Sider>
  )
}

export default Sidebar

This is how the sidebar will look like:

A: @Nadun's solution works for paths that don't contains arguments. If you're however using arguments in your routes, like me, here's a solution that should work for any route path, including /users/:id or crazy stuff like /users/:id/whatever/:otherId. It uses react-router's matchPath API, which uses the exact same logic as the Router component.
// file with routes
export const ROUTE_KEYS = {
    ROOT: "/",
    USER_DETAIL: "/users/:id",
};

export const ROUTES = {
    ROOT: {
        component: Home,
        exact: true,
        key: ROUTE_KEYS.ROOT,
        path: ROUTE_KEYS.ROOT,
    },
    USER_DETAIL: {
        component: Users,
        key: ROUTE_KEYS.USER_DETAIL,
        path: ROUTE_KEYS.USER_DETAIL,
    },
};

.
// place within the App component
<Router>
    <Layout>
        <MyMenu />
        <Layout>
            <Layout.Content>
                {Object.values(ROUTES).map((route) => (
                    <Route {...route} />
                ))}
            </Layout.Content>
        </Layout>
    </Layout>
</Router>

.
// MyMenu component
const getMatchedKey = (location) =>
    (
        Object.values(ROUTES).find((route) =>
            matchPath(location.pathname, route)
        ) || {}
    ).path;

const MyMenu = ({ location }) => {
    return (
        <Layout.Sider>
            <AntMenu mode="inline" selectedKeys={[getMatchedKey(location)]}>
                <AntMenu.SubMenu
                    title={
                        <React.Fragment>
                            <Icon type="appstore" />
                            Home
                        </React.Fragment>
                    }
                >
                    <AntMenu.Item key={ROUTE_KEYS.ROOT}>
                        <Icon type="appstore" />

                            Some subitem

                    </AntMenu.Item>
                </AntMenu.SubMenu>
                <AntMenu.SubMenu
                    title={
                        <React.Fragment>
                            <Icon type="user" />
                            Users
                        </React.Fragment>
                    }
                >
                    <AntMenu.Item key={ROUTE_KEYS.USER_DETAIL}>
                        <Icon type="user" />

                            User detail

                    </AntMenu.Item>
                </AntMenu.SubMenu>
            </AntMenu>
        </Layout.Sider>
    );
};

export default withRouter(MyMenu);

A: I do something like this but it doesn't seem to be reactive. Like if I navigate to a new page through a button (not from the menu items), it will not update the active link until the page refreshes.
import React from 'react';
import { StyleSheet, css } from 'aphrodite'
import { browserHistory, Link } from 'react-router';
import 'antd/lib/menu/style/css';
import 'antd/lib/icon/style/css';
import 'antd/lib/row/style/css';
import 'antd/lib/col/style/css';
import 'antd/lib/message/style/css';
import { appConfig } from '../../modules/config';
import { Menu, Icon, Row, Col, message } from 'antd';

const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;

const { appName } = appConfig;

const AppNavigation = React.createClass({
  getInitialState() {
        return {
          current: this.props.pathname
        };

  },
  handleClick(e) {
    browserHistory.push(e.key);
    this.setState({ current: e.key });
    return;
  },
  render() {
    return (
    <Row className='landing-menu' type="flex" justify="space-around" align="middle"  style={{height: 55, zIndex: 1000, paddingLeft: 95, color: '#fff', backgroundColor: '#da5347', borderBottom: '1px solid #e9e9e9'}}>
        <Col span='19'>
            <Link to='/'>

            {appName}
            <Icon type="rocket" color="#fff" style={{fontWeight: 200, fontSize: 26, marginLeft: 5 }}/>

        </Link>
        </Col>
        <Col span='5'>
            <Menu onClick={this.handleClick} selectedKeys={[this.state.current]} mode="horizontal" style={{height: 54, backgroundColor: '#da5347', borderBottom: '0px solid transparent'}}>
            <Menu.Item style={{height: 54, }} key="/">Home</Menu.Item>
            <Menu.Item style={{height: 54, }} key="/signup">Signup</Menu.Item>
            <Menu.Item style={{height: 54, }} key="/login">Login</Menu.Item>
          </Menu>
        </Col>

      </Row>
    );
  },
});

export const App = React.createClass({

  propTypes: {
    children: React.PropTypes.element.isRequired,
  },
  componentWillMount(){
    if (Meteor.userId()) {
      browserHistory.push('/student/home')
    }
  },
  render() {

    return (

          <AppNavigation pathname={this.props.location.pathname}  />

             { this.props.children }

    );
  }

});

EDIT:
the below works pretty well. pass down the pathname from react-router and pop that as a prop into selectedKeys
import React from 'react';
import { StyleSheet, css } from 'aphrodite'
import { browserHistory, Link } from 'react-router';
import 'antd/lib/menu/style/css';
import 'antd/lib/icon/style/css';
import 'antd/lib/row/style/css';
import 'antd/lib/col/style/css';
import 'antd/lib/message/style/css';
import { appConfig } from '../../modules/config';
import { Menu, Icon, Row, Col, message } from 'antd';

const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;

const { appName } = appConfig;

const AppNavigation = React.createClass({
  getInitialState() {
        return {
          current: this.props.pathname
        };

  },
  handleClick(e) {
    browserHistory.push(e.key);
    this.setState({ current: e.key });
    return;
  },
  render() {
    return (
    <Row className='landing-menu' type="flex" justify="space-around" align="middle"  style={{height: 55, zIndex: 1000, paddingLeft: 95, color: '#fff', backgroundColor: '#da5347', borderBottom: '1px solid #e9e9e9'}}>
        <Col span='19'>
            <Link to='/'>

            {appName}
            <Icon type="rocket" color="#fff" style={{fontWeight: 200, fontSize: 26, marginLeft: 5 }}/>

        </Link>
        </Col>
        <Col span='5'>
            <Menu onClick={this.handleClick} selectedKeys={[this.props.pathname]} mode="horizontal" style={{height: 54, backgroundColor: '#da5347', borderBottom: '0px solid transparent'}}>
            <Menu.Item style={{height: 54, }} key="/">Home</Menu.Item>
            <Menu.Item style={{height: 54, }} key="/signup">Signup</Menu.Item>
            <Menu.Item style={{height: 54, }} key="/login">Login</Menu.Item>
          </Menu>
        </Col>

      </Row>
    );
  },
});

export const App = React.createClass({

  propTypes: {
    children: React.PropTypes.element.isRequired,
  },
  componentWillMount(){
    if (Meteor.userId()) {
      browserHistory.push('/student/home')
    }
  },
  render() {

    return (

          <AppNavigation pathname={this.props.location.pathname}  />

             { this.props.children }

    );
  }

});

A: If you are using an array and mapping over it (as in my case) to set menu Items, They must be in the same order as they appear in the Side menu otherwise, an active bar or background will not be shown.

A: Environment: React Router V5, Ant Design V4.17.0
I solved this issues by override the onClick props of Menu.Item of antd
            <Menu theme="light" mode="inline">
                {menuItems.map((item) => {
                    return (
                        <NavLink
                            to={item.navigation}
                            component={({ navigate, ...rest }) => <Menu.Item {...rest} onClick={navigate} />}
                            key={item.key}
                            activeClassName="ant-menu-item-selected"
                        >
                            {item.icons}
                            {item.name}
                        </NavLink>
                    )
                }
                )}
            </Menu>

The NavLink component will pass navigate prop to Menu.Item, we need to map it to onClick prop and click behaviour will work correctly.


text:
Q: Spring AbstractFactoryBean usage I want to implement the factory pattern to construct some objects. I'm aware to use AbstractFactoryBean, but these objects have initialization parameters provided at runtime.
In fact, I want to refactor code so that users gets created and returned by a UserFactory which implements AbstractFactoryBean:
@Service
public class AuthenticationHandler {

    @Autowired
    private UserDetailsManager userDetailsManager;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public void signUp(String email, String password) throws BadCredentialsException {
        UserDetails user = User.builder()
                .passwordEncoder(rawPassword -> bCryptPasswordEncoder.encode(rawPassword))
                .username(email)
                .password(password)
                .authorities("ROLE_USER")
                .build();
        userDetailsManager.createUser(user);
    }
}

I'm looking also to configure the factory using Java annotations. Please How to do that!
Edit: Solution
I finally implemented it as below:
@Configuration
class UserConfig {

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    UserConfig(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Bean
    public Function<String, String, UserDetails> userFactory() {
        return this::user;
    }

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @Scope(value = "prototype")
    UserDetails user(String email, String password) {
        return User.builder()
                .passwordEncoder(bCryptPasswordEncoder::encode)
                .username(email)
                .password(password)
                .authorities("ROLE_USER")
                .build();
    }
}

@FunctionalInterface
public interface Function<Email, Password, UserDetails> {
    UserDetails apply(Email email, Password password);
}

The signUp() method become now as:
@Service
public class AuthenticationHandler {

    @Autowired
    private UserDetailsManager userDetailsManager;
    @Autowired
    private Function userFactory;

    public void signUp(String email, String password) throws BadCredentialsException {
        UserDetails user = constructUser(email, password);
        userDetailsManager.createUser(user);
    }

    private UserDetails constructUser(String email, String password) {
        return (User) userFactory.apply(email, password);
    }
}


text:
Q: xpath how to print more than 1 element I'm trying to scrape product titles on the first product page of Amazon using HTMLSession and xpath.
from requests_html import HTMLSession
from bs4 import BeautifulSoup

def getTitle(url):
    session = HTMLSession()
    r = session.get(url)
    r.html.render(sleep=1)

    product = {
        'title': r.html.xpath('//*[@class="a-size-medium a-color-base a-text-normal"]').text
    }

    print(product)
    return product

getTitle('https://www.amazon.com/s?k=amazon+echo+dot&qid=1605730376&ref=sr_pg_1')

>{'title': 'Echo Dot (3rd Gen) - Smart speaker with Alexa - Charcoal'}

The product titles have the attribute of class="a-size-medium a-color-base a-text-normal", so I want to scrape all the titles of the product displayed on the same page, but the code only outputs one of them.
For ex, I would want something like:
{'title': 'Echo dot 1st gen...'}
{'title': 'Echo dot for kids...'}
{'title': 'Amazon Echo dot 3rd gen...'}

Any tip or workaround?
Thank you

A: Why XPath for simple things like this?
[x.text for x in soup.find_all(class_="a-size-medium a-color-base a-text-normal")]

One thing is this dicts don't allow dupe keys, so you can't have multiple title in dict. But you can like title1,title2:
{'title'+str(x):y.text for x,y in enumerate(soup.find_all(class_="a-size-medium a-color-base a-text-normal"))}

A: Have modified your function a bit to actually collect the titles into product list of dictionaries (which btw you don't really need). You also do not need bs4 for this.
def getTitle(url):
    session = HTMLSession()
    r = session.get(url)
    r.html.render(sleep=1)

    product=[{'title':item.text} for item in r.html.xpath('//*[@class="a-size-medium a-color-base a-text-normal"]')]
    return product

results=getTitle('https://www.amazon.com/s?k=amazon+echo+dot&qid=1605730376&ref=sr_pg_1')

Replace the product line with the below to get the list of titles (strings) instead of dictionaries containing the the title key and value.
product=[item.text for item in r.html.xpath('//*[@class="a-size-medium a-color-base a-text-normal"]')]


text:
Q: Java Runtime.getRuntime().exec I am trying to merge 2 simple programs I have made to one .jar. I packed both .jars into a new one and used Runtime.getRuntime().exec method to execute them.
Code:
public class main {
  public static void main(String[] args) {
    try {
      Runtime.getRuntime().exec("cmd /c proj1.jar");
    } catch(Exception exce){
      /*handle exception*/
      try {
        Runtime.getRuntime().exec("cmd /c proj2.jar");
      } catch(Exception exc){
        /*handle exception*/

      }
    }
  }
}

The problem is that only proj1.jar is executed and proj2.jar doesn't run. I am new to java and don't know why this happens. How do I fix this? I want both files to be executed.

A: Your problem is that your second file is ONLY executed if the first throws an exeception. You're looking for this:
public class main {
  public static void main(String[] args) {
    try {
      Runtime.getRuntime().exec("cmd /c proj1.jar");
      Runtime.getRuntime().exec("cmd /c proj2.jar");
    } catch(Exception exce){
      /*handle exception*/
    }
  }
}

Or, if you absolutely must handle the exceptions separately, this:
public class main {
  public static void main(String[] args) {
    try {
      Runtime.getRuntime().exec("cmd /c proj1.jar");
    } catch(Exception exce){
      /*handle exception*/
    }

    try {
      Runtime.getRuntime().exec("cmd /c proj2.jar");
    } catch (Exception e) {
      //handle the exception
    }
  }
}


text:
Q: Is the connection for the optocoupler on this PCB damaged?
The optocoupler slot is the six pin slot on top of the board in the picture that is empty. I was wondering if the missing rings around some of the pin holes will affect connection.

A: *

*Top left: Doesn't matter, it's a No Connection (NC) pin

*Top right: Same thing, doesn't matter

*Middle left: Looks fine

*Middle right: Looks fine

*Bottom left: Probably fine if you solder carefully

*Bottom right: This one might be a problem, you might have to use a jumper wire to connect it to the via on the right of the pin


text:
Q: Syncdb error when creating CustomUser The issue is that I create Custom User:
class CustomUser(AbstractUser):
    mobile = models.CharField(max_length=16)
    address = models.CharField(max_length=100)

And in settings.py write this:AUTH_USER_MODEL = 'login.CustomUser'
And when I run manage.py syncdb for the first time(when db doesn't contains any tables), it throws an error: django.db.utils.ProgrammingError: relation "auth_group" does not exist
But when I run manage.py syncdb when db with tables already exist, then it's okay, just create additional tables. What's wrong to run it when db doesn't contain tables?

A: Try this

*

*Create a migration directory in the directory of the app containing your custom user model.

*Create an empty __init__.py file inside the migration directory.

*Execute ./manage.py makemigrations.

*Execute ./manage.py migrate.

I think when you use a custom user model, you need to create migrations. Besides, syncdb is already deprecated and will be removed in Django 1.9 so it's better to start using the ./manage.py migrate command.

A: As the error says, Your CustomUser table has relation with auth_group table, so unless that table is created or exists, you cannot create this new table in db.
When you say 'db with tables already exist, then it's okay', did You create the tables manually or included admin app in your INSTALLED_APPS?
Because if u include admin app, it will automatically create the auth_group table, so you will not see that issue


text:
Q: Why serving static files are an issue in Python apps I don't seem to understand the issue with serving static files in Python apps, for example Django. Now I am reading a documentation of WhiteNoise and first question is why it was developed in the first place? I mean what problem it solves? Why we can't save all the static files in /static folder and copy it to hosting.

A:
I don't seem to understand the issue with serving static files in Python apps, for example Django.

As is specified in the Django documentation on managing static files:

This method is grossly inefficient and probably insecure, so it is unsuitable for production.

Indeed, Django's views to serve static files are likely not very efficient. A webserver will typically cache a certain amount of files, use compression to send these to the browser (if the browser accepts this), etc. Django's views to serve static/media files are not designed to be competitive with a webserver like apache/nginx.
Even if that is solved, it using a signle server to serve static content is not a good idea. Often Content Delivery Networks (CDNs) are used to find a server close to the client that can serve these files.
The Django documentation therefore contains articles to deploy static files on a dedicated server and how to configure this server.
The whitenoise package is simply a best effort attempt to serve these files with a Python view. Python is more designed to reduce programmer time, not processing time, so while whitenoise is efficient, very likely it can not compete with CDN.


text:
Q: How can I make settings persistant on Ubuntu on USB flash drive I have created a bootable USB on Ubuntu. I opened it and made some changes like keyboard settings, creating new text files so on. After restarting Ubuntu all settings and files are gone. Is there any solution for this? What must I do?

A: There are three types of install to a USB stick.
1) Normal is is like a LiveCD. When you reboot, any "changes" are lost.
2) With Persistence is like having a Home partition on the stick. You can save SOME stuff to the persistent partition. Not everything will be saved.
3) A full install. If your USB is big enough. All changes should be saved.


text:
Q: Proving if a^2 -b^2 is even, a-b is also even As stated in title I am having trouble proving this.  I have been trying to use a proof by contradiction where I assume A^2-B^2 is even and A - B is odd and show how that is untrue.  Unfortunately I can't seem to figure this out.
I have tried setting the even expression equal to 2x (implying even) and the odd to 2y+1 and solving.  Unfortunately I got stuck with this.
Any solution using any method would be appreciated!

A: Hint factorize A^2-B^2 = (A - B) (A + B).
This implies that if A^2-B^2 is even then (A - B) (A + B) is even. If A-B is odd then...

A: Try four possibilities: both A and B are even, A is odd and B even, B is even and A odd, and both A and B are odd.

A: A^2-B^2 = (A+B)(A-B)=(C+2B)C
where C=A-B. But C and (C+2B) have the same parity. Then, if A^2-B^2 is even, so is C

A: We just take a look at each case:

*

**If a and b are both even, then say a=2n, b=2m, then a-b is even and a²-b²=4n²-4m²=4(n²-m²) therefore a²-b² is also even (it can be divided by 4).

*If a is even and b is odd, then say a=2n, b=2m+1, then a²-b² is odd and a²-b²=4n²-4m²+4m-1=4(n²-m²+m)-1 which is and odd number.

*If a is odd and b is even then a-b is odd, then let a=2n+1, b=2m, then a²-b²=4n²-4n+4m²+1=4(n²-n+m)+1 which is an odd number.ç

*Lastly, if both are odd, then let a=2n+1, b=2m+1. a-b is an even number as 2n+1-2m-1=2(n-m) (even). a²-b² is also even, as the 1s remaining cancell each other: a²-b²=4n²-4n+1-4m²+4m-1=4(n²-m²-n+m) is an even number.

What this proves is that, in all cases where a²-b² is even (when both a and b are either odd or even), then a-b must be also even. Hope it helps :)


text:
Q: S3 Bucket non-encrypted HLS works, but CloudFront of it doesn't As the title says. S3 Bucket non-encrypted HLS works, but CloudFront of it doesn't. I have been trying to get it to work for hours without any success. I followed all the docs closely. I set up header whitelist on CloudFront as well. Please help? When playing the video I get Network error message. It plays without any problem with the S3 Bucket URL. I tried various HLS streaming test websites.

A: HLS encryption does not work with Sign URL. With HLS encryption we break the video in multiple files (.ts) so if we want our playlist file (.m3u8) can able to access all those .ts files then we need to access those .ts files through signed cookie only.


text:
Q: Dialogue System C# First thing first - I'm sorry for my poor English and I'm kinda new to this great community, so I'm really sorry if something is incorrect in my question.
In short - I've started with C# not so long ago (which means you find a lot of poor written code here) and now I'm aiming to create a dialogue system. Though I have some working sample, questions are:

*

*How to make everything not this lame and improve the code;

*Suggestions about improving performance;

*Overall advices (maybe there is some more suitable tools for doing this);

Right now I use Finite-State Machine (FSM) as a general concept, so that every state is a dialogue scene. The last one is made of NPC quote and set of Player responds.
By now everything is pretty basic. Here I have my class for Player responds.
using System;
using System.Drawing;

using System.Windows.Forms;
using System.IO;

namespace Testing
{
    public class Player_Qoute : Label
    {
        public string Next_State { get; set; }//is used to tell, where to go next after choosing particular respond
    }

It's inherited from Label and has one additional field - next stage number, which is added in function below:
private void NPC_Quote(string path, string specification, RichTextBox info)
{
    StreamReader file = new StreamReader(path);//creating StremReader to read NPC quotes from .txt
    string line = "";//Creating string variable to read from
    try
    {
        while ((line = file.ReadLine()) != null)//readinf file line-by-line until the end
        {
            if (line.Contains(specification))//if line contains specified "tag"
            {
                line = line.Remove(0, specification.Length);//removing "tag" from line
                info.Text += line + "\n";//adding NPC line to the output field
            }
        }
        file.Close();
    }
    catch (Exception)
    {
        MessageBox.Show("Problem reading file");
    }
}

This function parse through .txt file, searching for lines tagged "NPC_stage_n", where "n" - is a number of stage. This number is present at the end of every Player respond in .txt file and I put it in the "Next_Stage" field of Player_Quote objects.
The same idea is applied here, but now i dynamically create Player's responds (number of which varies from stage to stage). I'm facing some issues with appropriate placing of quotes on the GroupBox - sometimes they are missing a line or words, but I'm working on it:
void Quotes_Generation(string path, string specification, GroupBox parent)
{
    parent.Controls.Clear();//deleting previous Player qoutes
    int step = 0;//auxilary variable to separate quotes from each other by heigth
    StreamReader file = new StreamReader(path);//StreamReader to read Player responds from .txt
    string line = "";
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains(specification))
        {
            Player_Qoute quote = new Player_Qoute();//inherited from Label;
            quote.Name = "qoute_" + line.Remove(specification.Length, line.Length - specification.Length);
            quote.Location = new Point(10, 20 + step);
            quote.Size = new Size(360, 10);
            quote.Text = line.Remove(0, specification.Length);//deleting "search tag" from text
            quote.Text = quote.Text.Remove(quote.Text.Length-3, 3); //here we are deleting 3-digit number at the end of the string
            //this number will show what is the next state of the dialogue if this Player respond is chosen.
            quote.Next_State = line.Remove(0,line.Length - 3);//storing 3-digit number in Player_Quote property
            using (Graphics g = CreateGraphics())//part of code which was borrowed from StackOverFlow and wasn't properly understood by me
            {
                SizeF size = g.MeasureString(quote.Text, quote.Font, 264);
                quote.Height = (int)Math.Ceiling(size.Height);
                quote.Text = quote.Text;
            }
            quote.MouseDown += new MouseEventHandler(this.Quote_Click);//creating event for choosing this respond
            parent.Controls.Add(quote);//adding respond to GroupBox
            step += (quote.Height+3);//increasing step
            if (parent.Height < step)//enlarging GroupBox
            {
                parent.MaximumSize = new System.Drawing.Size(parent.Width, step + 50);
                parent.Size = new System.Drawing.Size(parent.Width, step + 50);
            }
        }
    }
    file.Close();
}

And here is the Quote_Click event:
private void Quote_Click(object sender, EventArgs e)
    {
        Player_Qoute current = sender as Player_Qoute;//recognizing the sender
        richTextBox1.Text +=  Player_Name + "   -  " + current.Text + "\n";//adding Player respond with Player name to RichTextBox
        NPC_Quote(Application.StartupPath + "/Readme.txt", "NPC_stage_" + current.Next_State + ":", richTextBox1);//Adding new NPC line according to chosen respond
        Quotes_Generation(Application.StartupPath + "/Readme.txt", "Player_stage_" + current.Next_State + ":", groupBox1);//refreshing responds according to previous actions
    }

I'll appreciate all the advices!


text:
Q: Wordpress - how to add a button very next to 'Add new category' in post edit view and uncheck all selected categories? I want to place a button next to the 'Add new category' button in edit post or new post page.
The purpose of this button will be to uncheck/unselect all the selected categories from that post.
If knows please let me know is it possible ??If yes then how or what specific hook/filter can be used to do it ?
I tried to find the solution but could not found anything that could really help me.
I'm expecting the right direction to make it possible if its possible to do.