text:
Q: How could I check the number of files in a folder without counting them? Is there a way to check the number of files in a folder on MacBook, other than manually counting them?

A: *

*Set Finder to show icons

*Access view options with Cmd-J

*Enable "Show item info" option (where it says "Objektinfo einblenden" in the screenshot below)

A: Use the command:
$ ls -A | wc -l

What you're doing here is piping the output to another Unix function called wc (word count) and counting each line individually (the -l flag).  The ls -A command will list all entries including files/folders starting with a . (which are not visible from Finder usually), only excluding . and .. (which stand for the current directory and the parent directory, respectively).


text:
Q: Redirection Rule Using web.config I want to redirect
http://www.mydomain.com/rakhi-blog/index.php/2012/06/20/my-article/ to
http://www.mydomain.com/rakhi-blog/2012/06/20/my-article/
For this I use the following code:
   <configuration>
      <system.webServer>
        <defaultDocument>
          <files>
            <remove value="index.php" />
            <add value="index.php" />
          </files>
        </defaultDocument>
        <rewrite>
          <rules>
            <rule name="Main Rule" stopProcessing="true">
              <match url="(.*)" ignoreCase="true" />
              <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              </conditions>
              <action type="Rewrite" url="index.php/{R:0}" />
            </rule>
            <rule name="Rewrite Index">
              <match url="^index.php/*" />
              <action type="Redirect" url="/rakhi-blog/{R:1}" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>

But This Code is not working. Can Any one Help Me Pls.

A: try:
    <rewrite>
      <rules>
        <rule name="Rewrite Index">
          <match url="^rakhi-blog/index.php/(.+)$" />
          <action type="Redirect" url="/rakhi-blog/{R:1}" />
        </rule>
      </rules>
    </rewrite>

A: In the past, I used the instructions in the article "Using Failed Request Tracing to Trace Rewrite Rules" to find and resolve such issues.
Basically, you turn on tracing and see what and why IIS is actually redirecting (or not redirecting). You then can see whether your expectations match the actual results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to see the plots I expected in the output pane Sorry for the lack of a reproducible example, but the actual data I am working with is too specific to be shared here. I can share the data upon request, though.
My ui.R script is this:
    suppressPackageStartupMessages({
  library(shiny)
  library(shinyjs)
  library(data.table)
  library(leaflet)
  library(sf)
  library(tidyverse)
  library(RColorBrewer)
  library(plotly)
  library(ggmap)
  library(ggspatial)
  library(htmltools)
  library(crosstalk)
  library(tidyverse)
  library(leaflet.extras)
  library(geofacet)
})

shinyUI(fluidPage(
  titlePanel("Mosquito and environmental data Visualization"),
  # javascript code to enable/disable buttons
    tabsetPanel(
      tabPanel("About this App", htmlOutput("About this app")),
      tabPanel("Trapping data", fluid = TRUE,
               sidebarLayout(sidebarPanel(width = 2,
                                          selectInput("region", label = "Select Region", choices = c("Coachella Valley", "Suffolk County")),
                                          selectizeInput("year_vec", label = "Years", choices = 2001:2021, multi = TRUE),
                                          selectInput("weekfrom", label = "begin week", choices = 1:53),
                                          selectInput("weekto", label = "end week", choices = 1:53, selected = 53),
                                          selectInput("spat_var",label = "Spatial scale",choices = c("County/MVCAD","NLDAS","ECOSTRESS")),
                                          selectInput("summary_fun",label = "Parameter",choices = c("MIR","MLE","Mosq. unstd","Mosq. std","Wk. first pos.")),
                                          actionButton('go', label = 'Plot')),
                             mainPanel(plotOutput('trap_map', height = '900px', width= '1200px')))),
      tabPanel("Environmental data", fluid = TRUE,
               sidebarLayout(sidebarPanel(width = 2,
                                          selectInput("region", label = "Select Region", choices = c("Coachella Valley", "Suffolk County")),
                                          selectizeInput("year_vec", label = "Years", choices = 2001:2021, multi = TRUE),
                                          selectInput("weekfrom", label = "begin week", choices = 1:53),
                                          selectInput("weekend", label = "end week", choices = 1:53, selected = 53),
                                          selectInput("spat_var",label = "Spatial scale",choices = c("County/MVCAD","NLDAS","ECOSTRESS")),
                                          selectInput("env_var",label = "Env. Variable",choices = c("TMP","EVP")),
                                          actionButton('go', label = 'Plot')),
                             mainPanel(plotOutput('env_map', height = "900px", width = "1200px")))),
      tabPanel("Forecasts", mainPanel(plotOutput('forecast maps', height = "600px", width = "1000px")))
    )
))

and my server.R script is this:
suppressPackageStartupMessages({
  library(shiny)
  library(shinyjs)
  library(data.table)
  library(leaflet)
  library(leaflet.extras)
  library(leafsync)
  library(sf)
  library(tidyverse)
  library(RColorBrewer)
  library(plotly)
  library(ggmap)
  library(ggspatial)
  library(htmltools)
  library(htmlwidgets)
  library(crosstalk)
  library(lubridate)
  library(geofacet)
  library(yaml)
})

 {
#   ## Read Input yaml file ----
   input_args = yaml.load_file("test.yaml"); #Set path to location with the required YAML file
#   ## Get required source files ----
   source(input_args$data_script);
   source(input_args$plot_fn_script);
   source(input_args$mle_fns);
 }

###################################

shinyServer(function(input, output, session) {

  # Produce maps for mosquito trapping data

  output$trap_map <- renderText({

    isolate({
      year_vec <- input$year_vec
      weekfrom <- input$weekfrom
      weekto <- input$weekto
      spat_var <- input$spat_var
      region <- input$region
      summary_fun <- input$summary_fun
      #env_var <- input$env_var

      if (input$go == 0)
        return()
      # sprintf("The selected input variables are %s for region %s at the %s spatial scale, from week %s to week %s, for the years %s",
      #         summary_fun, region, spat_var, weekfrom, weekto, year_vec)
       trap_map(region = region, year_vec = year_vec, weekfrom = weekfrom, weekto = weekto, spat_var = spat_var, summary_fun = summary_fun)
    })})

  # Produce maps for environmental data
  output$env_map <- renderText({

   isolate({

      year_vec <- input$year_vec
      weekfrom <- input$weekfrom
      weekto <- input$weekto
      spat_var <- input$spat_var
      region <- input$region
      env_var <- input$env_var

      if (input$go == 0)
        return()
      # sprintf("The selected env. variables are %s for region %s at the %s spatial scale, from week %s to week %s, for the years %s",
      #         env_var, region, spat_var, weekfrom, weekto, year_vec)
      env_map(region = region, year_vec = year_vec,weekfrom = weekfrom, weekto = weekto, env_var = env_var)
    }) })

})

My problem is, I am unable to see any of my plots in the app, upon running the app. The functions I have in the plot_maps.R script produce the maps exactly as I want them when I run them independent of the app, but there is no output at all when I run them in the app. Where am I going wrong?
I'd appreciate any pointers in the code so far, and can also share the other functions and code if that helps.
Thanks a lot!


text:
Q: prime_factorize(1) -> ? (Pythonic error signalling) I have a prime_factorize function that returns a dictionary mapping from prime divisors to their powers. E.g., 50 = 2^1 * 5^2, so prime_factorize(50) returns {2 : 1, 5 : 2}.
Assuming this is the documented behavior, what would be the least surprising way to signal an error if called 0, 1, or a negative number? Throw ValueError? Return something that looks like correct output (e.g., prime_factorize(-5) -> {-1: 1, 5: 1})? return an empty dict?
And if you have a better format for returning a prime factorization, I'd love to hear that too.

A: In prime_factorize(n):
if n < 2 or not isinstance(n, numbers.Integral):
    raise ValueError("Number to factor can't be less than 2")
else:
    # normal behavior

That way users a.) get meaningful info about what went wrong and b.) can handle the exception in a try...except block.
I definitely wouldn't turn incorrect data or an empty dict, because that will lead to some tricky debugging the first time someone passes an improper value. Raise exceptions, that's what they're there for!

A: Not sure why you're using a dictionary here.  Wouldn't a list of 2-tuples work as well?  I.e., have  prime_factor(50) return [(2,1), ((5,2)].
Use of a dictionary presupposes that you know the key and want to look up it's value, which doesn't seem to be the case for the prime factors of an arbitrary number.

A: More to do with the concept of prime factorization than anything to do with python; factorization should raise an exception for all x < 2 or non integer.

A: Math functions in the standard library may be a good reference to take as the least surprising behaviour. Let's check math.sqrt for example: it returns a ValueError on domain error (here n < 1) and a TypeError on unexpected type (here if you send a non-integer). So I'd write.
if is not isinstance(n, numbers.Integral):
    raise TypeError("an integer is required")
elif n < 1:
    raise ValueError("number to factor can't be less than 1")
...

And I agree with Piotr Findeisen, a factorization of 1 as an empty dictionary seems perfectly sound.


text:
Q: Reading existing json and add new record I am trying to build an app that will allow users to add new entries to a local json file. I can easily write the record to a file but I cannot get it to update it. Here is the code I have at this point:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
...
public partial class frmGvhs : Form
{
    List<FacultyMember> memberList = new List<FacultyMember>();
    String filename = @"C:\Users\John\test.json";

    public frmGvhs()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        FacultyMember member = new FacultyMember();

        member.firstName = txtFirstName.Text;
        member.lastName = txtLastName.Text;
        member.email = txtEmail.Text;
        member.ext = txtExt.Text;
        member.department = cmbDepartments.Text;

        memberList.Add(member);

        String json = JsonConvert.SerializeObject(memberList.ToArray());
        System.IO.File.WriteAllText(filename, json);
    }

    private void frmGvhs_Load(object sender, EventArgs e)
    {
        if (System.IO.File.Exists(filename))
        {
            System.IO.StreamReader re = new System.IO.StreamReader(filename);
            JsonTextReader reader = new JsonTextReader(re);
            JsonSerializer se = new JsonSerializer();
            object parsedData = se.Deserialize(reader);
            String json = JsonConvert.SerializeObject(parsedData);

            Console.Write(json);
        }
    }
}

public class FacultyMember
{
    public String firstName { get; set; }
    public String lastName { get; set; }
    public String email { get; set; }
    public String ext { get; set; }
    public String department { get; set; }

    public FacultyMember()
    {

    }
}

Now when the app loads up I see the string of the existing json data. So now since its a string I cannot work with it. Do I need to loop through the object [parsedData]? I would like to basically add  the existing data to the List<FacultyMember> memberList variable.

A: Read file content and deserialize to memberList. Then add them and save again.
memberList = JsonConvert.DeserializeObject<List<FacultyMember>>(System.IO.File.ReadAllText(filename));

Example
class Program
    {
        static List<FacultyMember> memberList = new List<FacultyMember>();
        static String filename = @"C:\test.json";
        static void Main(string[] args)
        {
            Save();
            Load();
        }

        static void AddNew()
        {
            FacultyMember member = new FacultyMember();

            member.firstName = "Test";
            member.lastName = "Test";
            member.email = "test";
            member.ext = "test";
            member.department = "Test";

            memberList.Add(member);

            Save();
        }

        static void Save()
        {
            String json = JsonConvert.SerializeObject(memberList);
            System.IO.File.WriteAllText(filename, json);
        }

        static void Load()
        {
           memberList = JsonConvert.DeserializeObject<List<FacultyMember>>(System.IO.File.ReadAllText(filename));
            AddNew();
            Save();
        }
    }

A: A couple of things:

*

*You need to deserialize as the type of object you want then cast the result (in this case an array of FacultyMembers.

*When you read from the file you should surround it with a using statement so it closes.

Here is a sample:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Foo
{
    static String filename = @"C:\test.json";

    public static void Save()
    {
        FacultyMember member = new FacultyMember();

        member.firstName = Guid.NewGuid().ToString();
        member.lastName = "Bar";
        member.email = "Email";
        member.ext = "Ext";
        member.department = "Dept";

        List<FacultyMember> existing = new List<FacultyMember>();
        existing.AddRange(Load());

        existing.Add(member);

        String json = JsonConvert.SerializeObject(existing.ToArray());
        System.IO.File.WriteAllText(filename, json);
    }

    public static FacultyMember[] Load()
    {
        if (System.IO.File.Exists(filename))
        {
            using (System.IO.StreamReader re = new System.IO.StreamReader(filename))
            {
                JsonTextReader reader = new JsonTextReader(re);
                JsonSerializer se = new JsonSerializer();
                object obj = se.Deserialize(reader, typeof (FacultyMember[]));
                return (FacultyMember[]) obj;
            }
        }
        return new FacultyMember[0];
    }
}

public class FacultyMember
{
    public String firstName { get; set; }
    public String lastName { get; set; }
    public String email { get; set; }
    public String ext { get; set; }
    public String department { get; set; }

    public FacultyMember()
    {

    }
}


text:
Q: Extraer palabra random de una lista en Java Necesito extraer de un archivo txt palabras random, ya logré imprimir las palabras de forma random pero cómo podría imprimir sola una de la lista?
    try {
        archivo = new File("n.txt");
        leerArchivo = new FileReader(archivo);
        leerTxt = new BufferedReader(leerArchivo);
        String linea;
        while((linea = leerTxt.readLine()) != null) {
            lista.add(linea);
            int rand = new Random().nextInt(lista.size());
            System.out.println(lista.get(rand));

        }

    }catch (Exception e) {
        e.printStackTrace();
    }

}

}


text:
Q: shell script to batch replace specific string in .csv file I want to replace some strings in my raw csv file for further use and I search for the internet and create the script so far. But it seems they doesn't work. Hope anyone can help me
The csv file is like this and I want to delete "^M" and "# Columns: " so that I can read my file.
# Task: bending1^M
# Frequency (Hz): 20^M
# Clock (millisecond): 250^M
# Duration (seconds): 120^M
# Columns: time,avg_rss12,var_rss12,avg_rss13,var_rss13,avg_rss23,var_rss23^M

#!/usr/bin/env bash
function scandir(){
cd `dirname $0`
echo `pwd`
local cur_dir parent_dir workir
workdir=$1
cd ${workdir}

if [ ${workdir}="/" ]
then
    cur_dir=""
else
    cur_dir=$(pwd)
fi

for dirlist in $(ls ${cur_dir})
do
    if test -d ${dirlist}
    then
        cd ${dirlist}
        scandir ${cur_dir}/${dirlist}
        cd ..
    else
        vi ${cur_dir}/${dirlist} << EOF
        :%s/\r//g
        :%s/\#\ Columns:\ //g
        :wq
        EOF
    fi
done
}

A: Your whole script looks like just:
find "$workdir" -type f | xargs -n1 sed -i -e 's/\r//g; s/^# Columns://'

Notes to your script:

*

*Check your scripts for validity on https://www.shellcheck.net/

*The of << EOF here document is invalid. The closing word EOF has to start from the beginning of the line inside the script:

    vi ${cur_dir}/${dirlist} << EOF
    :%s/\r//g
    :%s/\#\ Columns:\ //g
    :wq
EOF
#^^ no spaces in front of EOF, also no spaces/tabs after EOF
# the whole line needs to be exactly 'EOF'

There cannot be any spaces, tabs in front of it. Also, I don't think vi is not the best tool to run substitutions on a file, also I don't know how it acts with tabs or spaces infront of :. You may want to try to run it without whitespace characters in front of ::
    vi ${cur_dir}/${dirlist} << EOF
:%s/\r//g
:%s/\#\ Columns:\ //g
:wq
EOF

*

*Backticks ` are deprecated, less readable and don't allow for easy nesting. Use $( ... ) command substitution instead.

*echo `pwd` is just invalid use of echo, just use pwd.

*for dirlist in $(ls parsing ls output is bad. Use find command instead, or if you have to, shell globulation, ie. for dirlist in *.

*if [ ${workdir}="/" ] is invalid. This tests if the string "${workdir}=/ is not null. Bash is space aware, it needs a space between = and operands. It should be if [ "${workdir}" = "/" ].

*Always quote your variables. Don't cd ${dirlist} do cd "${dirlist}" and so on.

A: Well posted answer are corrects, but I would recommand this syntax:
find "$1" -type f -name '*.csv' -exec sed -e 's/\r$//;s/^# Columns: //' -i~ {} +

*

*Using + instead of \; at end of find command will permit sed to work on many files at once, reducing forks and make whole job quicker.

*The ~ after -i option will rename existing files by appending tilde at end of names instead of deleting them.

*Using -type f will ensure working on files only (no symlinks, dirs, socket, fifos, devices...)

A: You can reduce the entire script to one command, and you do not have to use Vim to process the files:
find ${workdir} -name '*.csv' -exec sed -i -e 's/\r$//; /^#/d' '{}' \;

Explanation:

*

*find <dir> -name <pattern> -exec <command> \; will search <dir> for files matchingand execute` on each file.  You want to search for CSV files and do something with them (run a command on them).

*The command run on every (CSV) file that was found will be sed -i -e 's/\r$//; /^#/d'.  This means to edit the files in-place (-i) and run two transformations on them.  s/\r$// will remove the ^M from each line, and /^#/d will remove all lines that start with a #.

*'{}' is replaced with the files found by find and \; marks the end of the command run by find (see the find manual page for this).
Most of your script emulates part of the find command.  That is not a good idea.
Also, for simple text processing, it is easier and faster to use sed instead of invoking an editor such as Vim.


text:
Q: Reading data from a file to an object? Ok another question about my program that I'm writing called "Flight." In my tester I am creating an object from the Flight class called myFlight. The object has several fields (flight name, miles traveled, etc) but what I'm doing is reading the data from a file called input.txt and trying to put it into the object that I created. There are five lines of information on the file that I'm reading. For some reason I can't quite get it right, if anyone could help me fix this problem I would greatly appreciate it.
Here is the Constructor that has all the fields from my Flight class:
 public Flight(String name, int num, int miles, String origin, String destination)
  {
    Airlinename = name;
    flightnumber = num;
    numofmiles = miles;
    Origincity = origin;
    Destinationcity = destination;
  }

And the part of my program where I created the object and try to read the data from the file. I had created a blank constructor in my class too because I wasn't sure if I was supposed to put anything in the object when I created it.
Flight myFlight = new Flight();

    File myFile = new File("input.txt");
    Scanner inputFile = new Scanner(myFile);

    while (inputFile.hasNext())
    {
      myFlight = inputFile.nextLine();
    }

    inputFile.close();
  }
}

A: Just in case you use special characters, you need to modify your program so you can read them correctly.
Scanner inputFile = new Scanner(myFile, "UTF-8");

On the other hand, if the text file contains the following, possibly subsequent calls to nextInt() generate a runtime exception.
Gran España
1
1001
New York
Los Angeles

If that were the case, the reading should be different.
myFlight = new Flight(inputFile.nextLine(),
           Integer.parseInt(inputFile.nextLine()),
           Integer.parseInt(inputFile.nextLine()),
           inputFile.nextLine(),
           inputFile.nextLine());

As with any program, when adding more conditions to improve the model, it needs more and more code.
Good luck.

A: try
myFlight = new Flight(inputFile.next(), inputFile.nextInt(),
           inputFile.nextInt(), inputFile.next(), inputFile.next());

A: You can't directly assign a string line to an object, you need to parse the line into parts and assign values to variables one by one.

A: How is your input text organized? The Scanner's nextLine() method is returning a String object and definitely you cannot assign that to a type Flight. There are different methods to get the different values in the Scanner like nextInt(), nextFloat().
Basically you can try like this
Flight myFlight = new Flight();
myFlight.setFlightName(inputFile.next());
myflight.setMiles(inputFile.nextInt();

etc.
This is just a sample, you need to check the format you have in the input.txt file.


text:
Q: Paginating with Python 2.7.9 Web Crawler I am trying to code a program in Python 2.7.9 to crawl and gather the club names, addresses and phone numbers from the website http://tennishub.co.uk/
The following code gets the job done, except for it doesn't move on to the subsequent pages for each location such as
/Berkshire/1
/Berkshire/2
/Berkshire/3

..and so on.
import requests
from bs4 import BeautifulSoup

def tennis_club():
    url = 'http://tennishub.co.uk/'
    r = requests.get(url)
    soup = BeautifulSoup(r.text)
    for link in soup.select('div.countylist a'):
        href = 'http://tennishub.co.uk' + link.get('href')
        pages_data(href)

def pages_data(item_url):
    r = requests.get(item_url)
    soup = BeautifulSoup(r.text)
    g_data = soup.select('table.display-table')

    for item in g_data:
        print item.contents[1].text
        print item.contents[3].findAll('td')[1].text
        try:
            print item.contents[3].find_all('td',{'class':'telrow'})[0].text
        except:
            pass
        try:
            print item.contents[5].findAll('td',{'class':'emailrow'})[0].text
        except:
            pass
        print item_url

tennis_club()

I have tried tweaking the code to the best of my understanding but it doesn't work at all.
Can someone please advise what do I need to do so that the program goes through all the pages of a location, collects the data and move on the to next location and so on.

A: You are going to need to put another for loop into this code:
for link in soup.select('div.countylist a'):
    href = 'http://tennishub.co.uk' + link.get('href')
    # new for loop goes here #
        pages_data(href)

If you want to brute force it you just have the for loop go as many times as the area with the most clubs (Surrey), however you would double, triple, quadruple, etc. count the last clubs for many of the areas.  This is ugly but you can get away with it if you are using a database where you don't insert duplicates.  However it is unacceptable if you are writing to a file.  In that case you will need to pull the number in parenthesis after the area Berkshire (39).  To get that number you can do a get_text() on the div.countylist which would change the above to
for link in soup.select('div.countylist'):
     for endHref in link.find_all('a'):
          numClubs = endHref.next
          #need to clean up endHrefNum here to remove spaces and parens
          endHrefNum = numClubs//10 + 1  #add one because // gives the floor
          href = 'http://tennishub.co.uk' + endHref.get('href') + / + endHrefNum
          pages_data(href)

(disclaimer: I didn't run this through bs4 so there might be syntax errors (and you might need to use something other than .next, but the logic should help you)


text:
Q: Pytorch/Pytorch Lightning `state_dict()` cause ReferenceError: weakly-referenced object no longer exists I'm storing several pytorch-lightning modules in a list. Then I loop through them and do: [m.state_dict() for m in models], after this I get the ReferenceError: weakly-referenced object no longer exists. More detail:
File ...torch/distributed/_sharded_tensor/__init__.py", line 334, in state_dict_hook
    _recurse_update_dict(module, destination, prefix)
File ...torch/distributed/_sharded_tensor/__init__.py", line 357, in _recurse_update_dict
    if isinstance(attr, ShardedTensor):
ReferenceError: weakly-referenced object no longer exists

I get that weakly-referenced errors would occur when some memory is freed related to the object, but I can't see anything like that.


text:
Q: Future method not being invoked I have created a future method that will update accounts in seperate batches. The client sometimes gets a CPU timeout.
Anyway, my future method is not being invoked.
Does anyone have an idea why?
public class accountInformationList
    {
        Map<Id,accountInformation> accounts     { get; set; }
    }

public class accountInformation
{
    public String   BillingStreetNew        { get; set; }
    public String   BillingCityNew          { get; set; }
    public String   BillingCountryNew       { get; set; }
    public String   BillingPostalCodeNew    { get; set; }
    public String   BillingstateNew         { get; set; }
}

public void updateAccounts( List<Account> newAccounts )
{
    Integer startInd    = 0;
    while( newAccounts.size( ) > 0 )
    {
        accountInformationList  accountInformation  = new accountInformationList( );
        accountInformation.accounts                 = new Map<Id, accountInformation>( );

        Integer endInd                              = 0;
        Integer index                               = 0;

        for ( endInd = 0; endInd < 50; ++endInd )
        {
            index       = startInd + endInd;
            if ( index < newAccounts.size( ) )
            {
                if ( index > 50 )
                {
                    newAccounts[index].Name.addError( 'This account will be updated in a seperate batch.' );
                    accountInformation  acctInfo    = new accountInformation( );
                    acctInfo.BillingStreetNew       = newAccounts[index].BillingStreet;
                    acctInfo.BillingCityNew         = newAccounts[index].BillingCity;
                    acctInfo.BillingCountryNew      = newAccounts[index].BillingCountry;
                    acctInfo.BillingPostalCodeNew   = newAccounts[index].BillingPostalCode;
                    acctInfo.BillingStatenew        = newAccounts[index].BillingState;
                    accountInformation.accounts.put( newAccounts[index].Id, acctInfo );
                }
            } else break;
        }
        System.Debug( 'total size of the accounts: ' + accountInformation.accounts.keySet( ).size( ) );
        if ( accountInformation.accounts.keySet( ).size( ) > 0 )
        {
            String j = JSON.serialize( accountinformation );
            System.Debug( 'JSON: ' + j );
            try
            {
                tidyUpAccounts( j );
            } catch ( Exception exc )
            {

            }
        }
        if ( index >= ( newAccounts.size( ) - 1 ) )
            break;
        else startInd += endInd;
    }
}

@future public static void tidyUpAccounts( String accountString )
{
    accountInformationList  accountInfo = ( accountInformationList )JSON.deserialize( accountString, accountInformationList.class );
    List<Account> accounts              = new List<Account>( );

    accounts    = [SELECT Id, BillingStreet, BillingCity, BillingCountry, BillingPostalCode, BillingState FROM Account WHERE Id IN : accountInfo.accounts.keySet( )];

    for ( Account account : accounts )
    {
        accountInformation acc      = accountInfo.accounts.get( account.Id );
        account.BillingStreet       = acc.BillingStreetNew;
        account.BillingCity         = acc.BillingCityNew;
        account.BillingCountry      = acc.BillingCountryNew;
        account.BillingState        = acc.BillingStateNew;
        account.BillingPostalCode   = acc.BillingPostalCodeNew;
    }

    update accounts;
}


text:
Q: Keeping dirs in order with GNU Parallel I need to copy a large amount of files into their own directories. The issue I am having is keeping them in order when I copy them with GNU parallel. For example, file_1.output gets placed in dir_19.
Here is what I have so far that is working, besides the order of files.
ls *.output > copy.list
parallel "mkdir cele_{}" ::: {1..10000}
parallel -k --link "cp {} cele_{}" :::: copy.list ::: {1..10000}

Is there a way to do this without sacrificing parallel?
(Inspired by https://rbt.asia/g/thread/64890073/#64890111)

A: You can use --rpl to define your own replacement string and then use that both for mkdir and cp.
ls *.output |  parallel --rpl '{dir} s/\.output$/_dir/' 'mkdir {dir} && cp {} {dir}'


text:
Q: How to process uploaded files in ASP.NET core 2.0 We are trying to migrate our code from ASP.NET that was written some time ago to ASP.NET Core 2.0.
This piece of code stores a document in SQL Server and retrieves it.
***Original Code:***

protected void btnUpload_Click(object sender, EventArgs e)
{
    foreach (HttpPostedFile postedFile in multipleUpload.PostedFiles)
    {
        string filename = Path.GetFileName(postedFile.FileName);
        string contentType = postedFile.ContentType;
        using (Stream fs = postedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["ab"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into ftr_UploadMultiple (name,contentType,data) values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();

We did try with the following code, it only stores 0 bytes in the DB:
Any suggestions around this should be really helpful.
Our Code in ASP.NET Core 2.0
if (file.Length > 0)
{
    using (var stream = new
    FileStream(filePath, FileMode.Create))
    {
        await file.CopyToAsync(stream);
        using (BinaryReader br = new BinaryReader(stream))
        {
            byte[] bytes = br.ReadBytes((Int32)stream.Length);
            string constr = "<Connection String";
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "insert into ftr_UploadMultiple (data) values (@Data)";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Data", bytes);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

I have deliberately removed the closing }s. Also, facing an issue in Downloading already uploaded file as Response.Binarywrite() is not available in ASP.NET Core 2.0.

A: After you call CopyToAsync to copy the bytes from the upload file to the filestream, the filestream's position is at the end. When you then attempt to read from the filestream, you're only reading the null byte at the end, resulting in 0 bytes being read.
The simplest solution is to just add the following before you read:
stream.Position = 0;

However, unless you actually need to write the file to the filesystem as well, this is just extraneous work. It would be better to copy the upload file's stream to a MemoryStream and then simply use ToArray to get the bytes from that: no need for additional reader.

A: Try get bytes array from InputStream
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);

ASP.NET Core
if (file.Length > 0)
{
    using (BinaryReader br = new BinaryReader(file.InputStream))
    {
        /* ... use file.Length or file.ContentLength */

        byte[] bytes = br.ReadBytes(file.Length);

        /* ... File Processing (bytes) */
    }
}

.


text:
Q: How can I solve the mixed content error in web laravel? Hope you're doing well!
I have a website, made in laravel and I am presenting the mixed content error in some url of my page, and this is affecting my website's functionality because it blocks the ajax or js. Here you can see a video of the issue:
https://drive.google.com/open?id=1A3xPUw9KMhf_rnn-xJBhw77-d5Z7t-Zw
My website is hosted on the cloudways server if anyone knows how I could solve it, I would appreciate your help.
Thanks
Regards
      The htaccess file is this:
      <IfModule mod_rewrite.c>
          Options +FollowSymlinks
          RewriteEngine On
          RewriteCond %{SERVER_PORT} 80
          RewriteRule ^(.*)$ https://www.saludvitale.com/$1 [R,L]
          RewriteCond %{REQUEST_FILENAME} !-f
              RewriteRule ^css/(.*)$ /public/css/$1 [L]
              RewriteRule ^js/(.*)$ /public/js/$1 [L]
              RewriteRule ^img/(.*)$ /public/img/$1 [L]
              RewriteRule ^video/(.*)$ /public/video/$1 [L]
            RewriteRule ^images/(.*)$ /public/images/$1 [L]
            RewriteRule ^users/(.*)$ /public/users/$1 [L]
            RewriteRule ^banner/(.*)$ /public/banner/$1 [L]
                RewriteRule ^uploads/(.*)$ /public/uploads/$1 [L]
              RewriteRule ^plugins/(.*)$ /public/plugins/$1 [L]
              RewriteRule ^chat-images/(.*)$ /public/chat-images/$1 [L]
              RewriteRule ^fonts/(.*)$ /public/fonts/$1 [L]
              RewriteRule ^favicon.ico /public/favicon.ico [L]
              RewriteRule ^robots.txt /public/robots.txt [L]
          # Go ahead and process files.
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteRule ^(.*)$ /public/index.php [L]
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteCond %{REQUEST_URI} !^/public/
          RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
      </IfModule>

part of me AppServiceProvider

          use Illuminate\Support\ServiceProvider;
          use Auth;
          use DB;
          use DateTime;

          use Illuminate\Support\Facades\URL;

          class AppServiceProvider extends ServiceProvider
          {
              /**
               * Bootstrap any application services.
               *
               * @return void
               */
              public function boot()
              {
           URL::forceScheme('https');
                  view()->composer('*', function($view){
                      if(Auth::check()){
                          $profileData=DB::table("professional_details")
                                              ->select('FreeStatus')
                                              ->where("user_id",Auth::id())
                                              ->get()
                                              ;
          ....

A: I suggest you first set up a redirect for all http requests to go to https using .htaccess then make your APP_URL set to use https https:// webname.com check SSL Certificate then add \URL::forceScheme('https'); to the boot() method of your AppServiceProvider.
Let me know if you face any problem


text:
Q: Read and Send a file via QDataStream and QTcpSocket My problem is that the variable content is always empty.
Here is my code:
QFile file("/home/qt/Client/file.txt");
if(file.open(QIODevice::ReadOnly)){
    qDebug("File opened");
}

QDataStream fileData(&file);

QByteArray content;
QDataStream out(&content, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);

out << static_cast<quint16>(0) << "file" << "/home/qt/Client/file.txt" << fileData;

out.device()->seek(0);
out << static_cast<quint16>(content.size());

qDebug() << content.constData();

tcpSocket->write(content);

Output :
File opened

content is always empty
thanks for your help

A: content is not empty, but if you interpret it as a C-style 0-terminated string, it will appear to be empty.
When you write:
out.device()->seek(0);
out << static_cast<quint16>(content.size());

This will set the first two bytes of content to content.size() in big endian format (this is the default). So if content.size() is less than 255, the first byte of content.constData() will be 0 ('\0'). Any attempt to print constData() with a function that expects a C-style string will output nothing since your "string" starts with the "end-of-string" marker.
If you want to see the full contents of content, you should print all its chars separately and use something like hexdump to view the raw data.
Here's what I get if I do this instead of qDebug() << content.constData(); :
for (int i=0; i<content.size(); i++) {
    std::cout << content.constData()[i];
}

Output when run (the file contains just 20 'a' chars):
 $ ./qt | hexdump -C
00000000  00 40 00 00 00 05 66 69  6c 65 00 00 00 00 19 2f  |.@....file...../|
00000010  68 6f 6d 65 2f 71 74 2f  43 6c 69 65 6e 74 2f 66  |home/qt/Client/f|
00000020  69 6c 65 2e 74 78 74 00  00 00 00 14 61 61 61 61  |ile.txt.....aaaa|
00000030  61 61 61 61 61 61 61 61  61 61 61 61 61 61 61 61  |aaaaaaaaaaaaaaaa|
00000040

If I had used:
std::cout << content.constData();

There would have been no output because of that very first 0 char.
If your data is longer, and the size of content is bigger than 255, the first char will no longer be 0, but you'll print two characters of garbage and nothing else because Qt serializes QString (and most other types) by first writing its length (32bit here), then its contents. Since its in big endian notation, the first byte has a very high chance of being 0.
Annotated output:
00000000  00 40 00 00 00 05 66 69  6c 65 00 00 00 00 19 2f  |.@....file...../|
          <u16> < str len > <  str data   > < str len > <
00000010  68 6f 6d 65 2f 71 74 2f  43 6c 69 65 6e 74 2f 66  |home/qt/Client/f|
                               str data...
00000020  69 6c 65 2e 74 78 74 00  00 00 00 14 61 61 61 61  |ile.txt.....aaaa|
            str data            >  <data len > <
00000030  61 61 61 61 61 61 61 61  61 61 61 61 61 61 61 61  |aaaaaaaaaaaaaaaa|
                    data                                 >


text:
Q: Local By Flywheel - Error establishing a database connection I was working on a website for a client a week ago and I came back to make further edits, but whenever I want to access the website, it reads:

Error establishing a database connection

I checked my wp-config file and everything is untouched; I did not touch one single line of code here when setting up my new Wordpress project in Local by Flywheel.
All my other local websites work except for this one. I've provided an image of my workspace just to make it more clear.

Looking at this image, the MySQL Version is a little bit off. The version should in fact be 5.6.37, but instead it's reading an older version of MySQL.
I did try closing and reopening Local by Flywheel, but it had no effect.
Any help appreciated. Thank you!

A: Right click on the site name and click on "Reveal in Finder" in Local by      Flywheel.
Compress the folder containing all your site in a *.ZIP file (normally there must be at least the "app" and "logs" folder, sometimes "conf").
In Local by Flywheel, import the site manually in FILE / IMPORT SITE, choose the Zip of your site
Normally, it reinstalls the site and recreates the Database … for me it's work (on Windows and on Mac)

A: Are you able to compare your wp-config.php file in the broken site to a site that is using the same MySQL server?
I know you said that the file is untouched, but check again that all of the define parameters are correct.
Next I would suggest logging into your MySQL server using the credentials you have listed in the wp-config.php file and ensure you are able to access your database.


text:
Q: Parser Error: Could not create type 'xyz' in ASP.NET Generic Web Handler I have a ASP.NET Generic Web Handler (*.ashx) in my Web Application Project. It's path on the web server is /Services/PayPal/IPNListener.ashx.
IPNListener.ashx
<%@ WebHandler Language="C#"
               CodeBehind="IPNListener.ashx.cs"
               Class="Portal.Services.PayPal.IPNListener" %>

IPNListener.ashx.cs
//-----------------------------------------------------------------------------
// <copyright file="IPNListener.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Web;
using Portal.PayPal;

namespace Portal.Services.PayPal
{
    /// <summary>
    /// Summary description for IPNListener
    /// </summary>
    public class IPNListener : IHttpHandler
    {
        /// <summary>
        /// Receives the HttpWebRequest via an HttpContext and processes the request
        /// </summary>
        public void ProcessRequest(HttpContext context) {
            // I gutted this, because it still produces the same error
            context.Response.Write("Hello World!");
        }

        /// <summary>
        /// Gets a System.Boolean value that indicates whether the generic handler may be reused
        /// </summary>
        public bool IsReusable {
            get {
                return false;
            }
        }
    }
}

When I attempt to navigate to the handler, I receive the following error.
Parser Error

Description: An error occurred during the parsing of a resource required to service
             this request. Please review the following specific parse error details
             and modify your source file appropriately.

Source Error

Line 1:  <%@ WebHandler Language="C#"
                        CodeBehind="IPNListener.ashx.cs"
                        Class="Portal.Services.PayPal.IPNListener" %>

Source File: /portal/services/paypal/ipnlistener.ashx    Line: 1

Here is what I have done so far:
(1) Gutted the Handler. I gutted it to a simple Hello World handler as seen in the code I posted to eliminate the possibility of an error in my code. The handler was previously working just fine, and I'm actually not sure what has caused it to stop working.
(2) Checked Version Control. Like I said previously, the handler was working fine a day or so ago. I checked version control for the file's history to see if anything had changed, and it has not.
(3) Application Pool. I checked the application pool in IIS 7, and it is running ASP.NET v4.0 as it should be.
(4) Verified Build Actions. I verified that IPNListener.ashx's build action is set to Content, and that IPNListener.ashx.cs's build action is set to Compile.
(5) Verified DLL Integrity. I verified using IL Disassembler that the type Portal.Services.PayPal.IPNListener does exist in the compiled DLL file.
(6) Virtual Application Directory. The folder /Services/PayPal is not a virtual application, and I've never had to make it one for a Generic Handler to work, but I tried it anyway and the same error is still produced.
(7) Clean Rebuild. I have tried cleaning the solution, then rebuilding. There are no compiler errors. Then proceed to publish the web application, everything is fine.
(8) Checked Dependencies. I checked to make sure all required files, and dependencies are deployed. Everything checks out.
I really have no clue as to why this stopped working. Everything was tested and ready to go to publish everything live today for my first software product, and when I did one last test run on the payment services it was returning a 500 Internal Server Error, in which further investigation showed that it is being caused by this problem.
I'm actually really stumped. I searched through all other posts regarding ASHX handlers and this issue here on StackOverflow, as well as all over the web and found nothing useful to my specific issue here.
It might be something really simple I am overlooking, but I can't seem to put my finger on it.
(Update) 5/29/2012 10:57 PM. Going off of Ray Cheng's comment and mine, I realized that the service used to live in /PayPal/IPNListener.ashx, and was moved to /Services/PayPal/IPNListner.ashx. When the move was done, all the namespaces, and class locations were updated in the ASHX file.
Out of curiosity, I copied the handler to /PayPal/IPNListener.ashx, updated the namespaces and classes in the ASHX files, and navigated to the location, and the service works fine.
Essentially
/Services/PayPal/IPNListener.ashx

produces a 500 Internal Server Error due to Could not create type, and
/PayPal/IPNListener.ashx

works just fine. So why does having the handler one folder hierarchy up make a difference in working?

A: The problem was something simple. I have two IIS 7 servers, one for local testing, and the other live on the internet.
The local IIS server had the parent directory /Services set as an virtual application. I found that having a virtual application somewhere in the path to the generic handler causes the ASP engine to fail to create the handler type. This explains why moving the service from /PayPal/IPNHandler.ashx to /Services/PayPal/IPNHandler.ashx broke, because the former path was not a virtual application, and the latter was, breaking the handler.
Removing the virtual application for /Services resolved the problem on the test server, and it now works as expected.
There wasn't supposed to be a virtual application in that path anyway, but it was an oversight because /Services is used for more than just this handler.
The problem on the live server, turns out, was an service address to a WCF Service that is used in the handler was pointing to the test server using the localhost alias, thus being an invalid address. The live server did not have any problems with virtual application configuration or anything, it was an incorrect address.
Updating the incorrect address resolved the 500 Internal Server error. This is irrelevant as to the original issue of the handler causing a parse error, but was the second issue found and resolved before being able to have everything work.


text:
Q: Is it possible to use libraries while being lightweight and cross platform compatible? I've got a small C++ project to which I'd like to add the ability to detect existence of a folder and create one if it does not exist. The method I've dug up requires Boost Filesystem, however I'm unclear as to how to keep my project small, simple and cross-platform.
The main issue is that Filesystem requires me to link against a library object, this is obviously not cross platform. I do not want to require my users to install the Boost library themselves and it's clearly impractical to distribute Boost inside my own project.
I am considering two options:

*

*Somehow pull out only the files relevant for Filesystem from the Boost library and hopefully that's small enough to package with my project. Though I have no idea how I could identify which files are required.

*Distribute binaries only. I don't know if this is possible without greatly expanding my workflow, I currently work simply in VSCode and Terminal on macOS. What are the considerations for multi-platform distribution? Do I need a binary for each OS, 32/64bit and CPU? Are cross-platform compilations using march and mcpu reliable?
Please also let me know if I've greatly misunderstood the nature of my problem.


text:
Q: Site em PHP está fazendo download Estava tentando configurar o serverblocks (vhost) do nginx, então eu apaguei o arquivo "default" localizado em /etc/nginx/sites-enabled/default e criei um arquivo com o nome do meu site, adicionei essas linhas abaixo:
 server {
    listen   80;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name http://localhost/;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

E agora o meu site que é em PHP, testado no meu servidor, quando abro, ele faz o download! Acho que alguma linha de código que estava no arquivo "default" tinha algo de interpretar códigos PHP?
Como recuperar essa configuração?

A: Assim como o Vinícius comentou, a propriedade location fica dentro de server. Como respondido nessa questão do SOen,

*

*Altere seu código para:
server {
    listen   80;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

*Edite o /etc/php5/fpm/php.ini e definia o valor de cgi.fix_pathinfo para 0.

*Reinicie o nginx e o php5.


text:
Q: Android - project defaulting to appCompat library project's resources for layout I've added the appCompat supporting library to my project using instructions here  (adding library with resources using Eclipse).  When trying to reference a layout, it defaults to the appCompat project res/layout folder, not the one in the current project:

Is there a step I missed in designating the current project's resources as the default?  Any advice appreciated.

A: Seems to be working now.  Had to rebuild the project.


text:
Q: Bluetooth serial connection between Android and Ubuntu I'm working on an Android application and I have to make a Bluetooth serial communication between an Android device and a Computer with Ubuntu OS. I don't know what to do and how to connect them. I'm looking for good references and someone who can help me.
I made a button which navigates to the Bluetooth settings of our Android device. I don't know what else I should do.

A: *

*Pair the devices. This has nothing to do with any software, so it has to be done via the phone settings

*Once paired, look at 'Bluetooth Chat' example by Google. It has drop in code for connecting two devices. A serial connection is done via Serial Port Profile that is established over RFCOMM. The UUID for SPP is well known, again, you'll find it in the Bluetooth Chat example.


text:
Q: Linear Regression with one variable While implementing Gradient Descent Algorithm in linear regression, the prediction that my algorithm is making and the resulting regression line are coming as a wrong output. Could anyone please have a look at my implementation and help me out? Also, please guide me that how can I know what value of "learning rate" and "number of iterations" to choose in specific regression problem?
theta0 = 0                               #first parameter
theta1 = 0                               #second parameter
alpha = 0.001                             #learning rate (denoted by alpha)
num_of_iterations = 100                #total number of iterations performed by Gradient Descent
m = float(len(X))                         #total number of training examples

for i in range(num_of_iterations):
    y_predicted = theta0 + theta1 * X
    derivative_theta0 = (1/m) * sum(y_predicted - Y)
    derivative_theta1 = (1/m) * sum(X * (y_predicted - Y))
    temp0 = theta0 - alpha * derivative_theta0
    temp1 = theta1 - alpha * derivative_theta1
    theta0 = temp0
    theta1 = temp1
print(theta0, theta1)

y_predicted = theta0 + theta1 * X
plt.scatter(X,Y)
plt.plot(X, y_predicted, color = 'red')
plt.show()

Resulting regression line about which I need some help

A: Your learning rate is to high, I got it working by reducing the learning rate to alpha = 0.0001.


text:
Q: Nested array transform with array without nesting Сan someone help with the algorithm? I get an array with objects that has arrays and so on. and i want to make one array without nested elements
I can get unlimited number of nested array
const test = [
    {
    id: "1",
    title: "test1",
    description: "some text",
    child: [
        {
        id: "2",
        title: "test2",
        description: "some text2",
        child: [
          {
            id: "4",
            title: "test4",
            description: "some text4",
            child: [
              {
                id: "5",
                title: "test5",
                description: "some text5",
              }
            ]
          }
        ]
      },
      {
        id: "3",
        title: "test3",
        description: "some text3",
      }
    ]
  }
]

I should get an array with element level
Should be something like this:
const order = [
    {
    id: "1",
    title: "test1",
    description: "some text",
    url: 'test1',
    level: 1
  },
  {
    id: "2",
    title: "test2",
    description: "some text2",
    url: 'test1/test2',
    level: 2
  },
  {
    id: "4",
    title: "test4",
    description: "some text4",
    url: 'test1/test2/test4',
    level: 3
  },
  {
    id: "5",
    title: "test5",
    description: "some text5",
    url: 'test1/test2/test4/test5',
    level: 4
  },
  {
    id: "3",
    title: "test3",
    description: "some text3",
    url: 'test1/test3',
    level: 2
  }
]

Can someone help me please

A: This is a pre-order traversal that keeps track of the depth and path it took. Each time there are more children, we increase the depth and add the title of the child to the path.

const data = [{id:"1",title:"test1",description:"some text",child:[{id:"2",title:"test2",description:"some text2",child:[{id:"4",title:"test4",description:"some text4",child:[{id:"5",title:"test5",description:"some text5"}]}]},{id:"3",title:"test3",description:"some text3"}]}];

function flatten(root, acc = [], depth = 1, path = []) {
    acc.push({
        id: root.id,
        title: root.title,
        description: root.description,
        url: path.concat(root.title).join("/"),
        level: depth,
    });

    if (root.child)
        root.child.forEach((c) => flatten(c, acc, depth + 1, path.concat(root.title)));

    return acc;
}

console.log(data.flatMap((e) => flatten(e)));

This function is meant for a single node, and since you have an array of them, I have used flatMap in case you add more nodes to data.

A: let's write a simple function for this
function simplify (arr) {
let returnArr = [];

const recursive = (array, level) => {

    array.forEach((item, index) => {
       let arrayObj = {level: level};

       Object.keys(item).forEach((key, index) => {
          if(!Array.isArray(item[key])){
             arrayObj[key] = item[key];
          }else{
             recursive(item[key], level + 1)
          }
       })

       returnArr.push(arrayObj)
    })
 }
recursive(arr, 1)

return returnArr
}

this should do the trick, let me know if it worked for you   :)

A: You could take a recusive approach with Array#flatMap.

const
    flat = (array = [], level = 1, u = '') => array.flatMap(({ child = [], ...item }) => {
        const url = u + (u && '/') + item.title;
        return [{ ...item, level, url }, ...flat(child, level + 1, url)]
    }),
    data = [{ id: "1", title: "test1", description: "some text", child: [{ id: "2", title: "test2", description: "some text2", child: [{ id: "4", title: "test4", description: "some text4", child: [{ id: "5", title: "test5", description: "some text5" }] }] }, { id: "3", title: "test3", description: "some text3" }] }],
    result = flat(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You'll want to recursively go through your object and iterate each child until your full array is built up.
Additionally, you'll need to keep track of several things along the way: the level (depth), the url, and your final return array. Often times for recursive functions, you have a "private" function that does the real work, and a small function that exposes a reduced API. In JS, you can use an IIFE to create a closure so this private method can't be accessed.
Here is my solution:

const flattenObj = (() => {
  const _flattenObj = (obj, result, level, url) => {
    level++;

    // Only add a `/` if we have some length to our URL
    let currentUrl = url ? `${url}/${obj.title}` : obj.title;

    const newObj = {
      id: obj.id,
      title: obj.title,
      description: obj.description,
      url: currentUrl,
      level,
    };

    // Add the new object to our return array, which maintains the same reference
    result.push(newObj);

    if (obj.child) {
      // Recursively iterate the children if they exist
      for (let child of obj.child) {
        _flattenObj(child, result, level, currentUrl);
      }
    }

    // Finally, return our full array
    return result;
  };

  // The real function we'll be calling, which initializes the extra arguments
  return obj => {
    return _flattenObj(obj, [], 0, '');
  };
})();

console.log(
  flattenObj({
    id: '1',
    title: 'test1',
    description: 'some text',
    child: [
      {
        id: '2',
        title: 'test2',
        description: 'some text2',
        child: [
          {
            id: '4',
            title: 'test4',
            description: 'some text4',
            child: [
              {
                id: '5',
                title: 'test5',
                description: 'some text5',
              },
            ],
          },
        ],
      },
      {
        id: '3',
        title: 'test3',
        description: 'some text3',
      },
    ],
  })
);


text:
Q: Generic traversal of tree structure I'm trying to write my tree (well, it's binary trie) traversal more generic, because the way it is now I have very similar code repeated.
I'm walking the tree in lexicographical inorder.
The example of functions I think can be abstracted by universal tree traversal are (in pseudocode):
items(node*, key, list&) {
    if(node->value)
        list.push({node->value, key})
    if(node->left)
        items(node->value, key + "0")
    if(node->right)
        items(node->value, key + "1")
}

draw(node*, id, ostream&) {
    drawNode(node, id)
    if (node->left)
        drawLine(node, node->left, "0", ostream&)
        draw(node->left, ++id, ostream&)
    if (node->right)
        drawLine(node, node->right, "1", ostream&)
        draw(node->right, ++id, ostream&)

I'm not asking for functioning code, just a push in the right direction. Should it be done with templates taking functions as arguments? What about more complicated cases, where the traversal is not simply conditioned by existence of single left/right node (the merging of two trie seems too like a candidate for this abstraction).

A: The generic abstraction of traversal is a suitable form of iterator. Once the traversal has become a linear sequence of positions you'd formulate it using one of the conventional iterators, most likely modeling BidirectionalIterator. When generalizing traversal of trees (or more general, graphs) you may have iteration operations moving in different directions.

A: Necroposting, but still probably worth it if anyone lands on this question.
Generic tree traversal was studies by theorists of the functional programming and they eventually produced several usable libraries for haskell. I will point at recursion-schemes and syb (scrap your borderplate) libraries. Both come with a paper describing the approach taken.
Syb relies on a form of runtime reflection and uses quite a bit of type casts/coercion, but recursion-schemes were ported to several languages including kotling and scala, so they are compatible with imperative languages.
By no means those works represent pinnacle of what can be done with recursive traversal of tree-like datastructures, but they see some use and the ideas are well-tested.


text:
Q: Limit a stream and find out if there are pending elements I have the following code that I want to translate to Java 8 streams:
public ReleaseResult releaseReources() {
    List<String> releasedNames = new ArrayList<>();

    Stream<SomeResource> stream = this.someResources();

    Iterator<SomeResource> it = stream.iterator();
    while (it.hasNext() && releasedNames.size() < MAX_TO_RELEASE) {
        SomeResource resource = it.next();
        if (!resource.isTaken()) {
            resource.release();
            releasedNames.add(resource.getName());
        }
    }

    return new ReleaseResult(releasedNames, it.hasNext(), MAX_TO_RELEASE);
}

Method someResources() returns a Stream<SomeResource> and ReleaseResult class is as follows:
public class ReleaseResult {

    private int releasedCount;

    private List<String> releasedNames;

    private boolean hasMoreItems;

    private int releaseLimit;

    public ReleaseResult(List<String> releasedNames,
        boolean hasMoreItems, int releaseLimit) {

        this.releasedNames = releasedNames;
        this.releasedCount = releasedNames.size();
        this.hasMoreItems = hasMoreItems;
        this.releaseLimit = releaseLimit;
    }

    // getters & setters
}

My attempt so far:
public ReleaseResult releaseReources() {

    List<String> releasedNames = this.someResources()
        .filter(resource -> !resource.isTaken())
        .limit(MAX_TO_RELEASE)
        .peek(SomeResource::release)
        .map(SomeResource::getName)
        .collect(Collectors.toList());

    return new ReleasedResult(releasedNames, ???, MAX_TO_RELEASE);
}

The problem is that I can't find a way to know if there are pending resources to process. I've thought of using releasedNames.size() == MAX_TO_RELEASE, but this doesn't take into account the case where the stream of resources has exactly MAX_TO_RELEASE elements.
Is there a way to do the same with Java 8 streams?
Note: I'm not looking for answers like "you don't have to do everything with streams" or "using loops and iterators is fine". I'm OK if using an iterator and a loop is the only way or just the best way. It's just that I'd like to know if there's a non-murky way to do the same.

A: Since you don't wanna hear that you don't need streams for everything and loops and iterators are fine, let's demonstrate it by showing a clean solution, not relying on peek:
public ReleaseResult releaseReources() {
    return this.someResources()
        .filter(resource -> !resource.isTaken())
        .limit(MAX_TO_RELEASE+1)
        .collect(
            () -> new ReleaseResult(new ArrayList<>(), false, MAX_TO_RELEASE),
            (result, resource) -> {
                List<String> names = result.getReleasedNames();
                if(names.size() == MAX_TO_RELEASE) result.setHasMoreItems(true);
                else {
                    resource.release();
                    names.add(resource.getName());
                }
            },
            (r1, r2) -> {
                List<String> names = r1.getReleasedNames();
                names.addAll(r2.getReleasedNames());
                if(names.size() > MAX_TO_RELEASE) {
                    r1.setHasMoreItems(true);
                    names.remove(MAX_TO_RELEASE);
                }
            }
        );
}

This assumes that // getters & setters includes getters and setters for all non-final fields of your ReleaseResult. And that getReleasedNames() returns the list by reference. Otherwise you would have to rewrite it to provide a specialized Collector having special non-public access to ReleaseResult (implementing another builder type or temporary storage would be an unnecessary complication, it looks like ReleaseResult is already designed exactly for that use case).
We could conclude that for any nontrivial loop code that doesn't fit into the stream's intrinsic operations, you can find a collector solution that basically does the same as the loop in its accumulator function, but suffers from the requirement of always having to provide a combiner function. Ok, in this case we can prepend a filter(…).limit(…) so it's not that bad…
I just noticed, if you ever dare to use that with a parallel stream, you need a way to reverse the effect of releasing the last element in the combiner in case the combined size exceeds MAX_TO_RELEASE. Generally, limits and parallel processing never play well.

A: The only thing I can think of is
List<SomeResource> list = someResources();  // A List, rather than a Stream, is required
List<Integer> indices = IntStream.range(0, list.size())
                                 .filter(i -> !list.get(i).isTaken())
                                 .limit(MAX_TO_RELEASE)
                                 .collect(Collectors.toList());
List<String> names = indices.stream()
                            .map(list::get)
                            .peek(SomeResource::release)
                            .map(SomeResource::getName)
                            .collect(Collectors.toList());

Then (I think) there are unprocessed elements if
names.size() == MAX_TO_RELEASE
    && (indices.isEmpty() || indices.get(indices.size() - 1) < list.size() - 1)

A: I don't think there's a nice way to do this. I've found a hack that does it lazily. What you can do is convert the Stream to an Iterator, convert the Iterator back to another Stream, do the Stream operations, then finally test the Iterator for a next element!
Iterator<SomeResource> it = this.someResource().iterator();
List<String> list = StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED), false)
                                 .filter(resource -> !resource.isTaken())
                                 .limit(MAX_TO_RELEASE)
                                 .peek(SomeResource::release)
                                 .map(SomeResource::getName)
                                 .collect(Collectors.toList());
return new ReleaseResult(list, it.hasNext(), MAX_TO_RELEASE);


text:
Q: Batch File multiple tokens multiple variables I am trying to read two different fields per line of a file and assign those fields to two different variables so that I can work with both of the variables together in a for loop.
Right now I have
for /f "tokens=6 delims=:. " %%a in ('type %1% ^| findstr /R /V "Test"') do (
echo %%a
)

for /f "tokens=12 delims=:. " %%b in ('type %1% ^| findstr /R /V "Test"') do (
echo %%b
)

Is there anyway to combine them into something like
for /f "tokens=6,12 delims=:. " %%a %%b in ('type %1% ^| findstr /R /V "Test"') do (
echo %%a
echo %%b
)

Because right now this statement does not work.

A: This should work:
for /f "tokens=6,12 delims=:. " %%a in ('type "%~1" ^| findstr /R /V "Test"') do (
  echo %%a
  echo %%b
)

which could be simplified to
for /f "tokens=6,12 delims=:. " %%a in ('findstr /V "Test" "%~1"') do (
  echo %%a
  echo %%b
)

since findstr can read from files just fine, and you're not using a regular expression anyway.


text:
Q: How to format json in wicket dataview using javascript I am trying to display a json data in Wicket DataView. If i want to display the json with indentation, how i can achieve this using java script?
I could find many sources to pretty format the json but they  are using java script. How we can call a function to javascript from inside dataview populateItem method to format the json as described in the link  http://jsfiddle.net/unLSJ/
Html

      Name
      Value

My Java:
    dataView = new ListView<DataForTable>("notificationDetails",dataForTableList)
{
  private static final long serialVersionUID = 1L;

  @Override
  protected void populateItem(final ListItem<DataForTable> item)
  {
    item.setDefaultModel(new CompoundPropertyModel<DataForTable>(item.getModel()));
    item.add(new Label("name"));
    item.add(new Label("value"));
  }
};

I have also tried to use Jackson object mapper to format the json before adding to Label, but it does not help. The wicket page displays like this
mapper.defaultPrettyPrintingWriter().writeValueAsString(value);

The wicket page displays like this
 {\r\n \"action\" : \"add\",\r\n \"schedule\"...

Can you please help to resolve the issue?

A: You should use MultilineLabel instead of Label so \n is replaced with
. You can also replace \t with   or any other space character. In this case use MultilineLabel#setEscapeModelStrings(false).


text:
Q: Why the need for quotes in the change of extension bash commands? It seems to work fine without quotes I want to change extension of .pdf file to .zip
both commands given below  gave me results
for i in *.pdf; do mv $i ${i%.pdf}.zip;  done

or
for i in *.pdf; do mv "$i" "${i%.pdf}.zip";  done

What is purpose " " in this command


text:
Q: pandas: Get the maximum value in a row, and record the column where it was found? This is my dataframe df:
a     b     c
1.2   2    0.1
2.1   1.1  3.2
0.2   1.9  8.8
3.3   7.8  0.12

I'm trying to get the max value from each row of the dataframe, and record the column from which it came.
I can do df['max_value'] = df.max(axis=1) to get the maximum value in a new column, but how can I record the column from which it came?


text:
Q: Category API for products django I have two models: Category, Products. And I want to create a separate url link like http://127.0.0.1:8000/api/categories/sneakers for each category to retrieve products from different urls. Using foreign key I can separate them but don't really know how to give them a url. Could you help me with this, please?
what I expect to see in API is:
http://127.0.0.1:8000/api/categories/sneakers

[
  {
    'id': 1,
    'name': 'Nike AirMax',
    'brand': 'Nike',
    'price': 200,
    'category': sneakers
  },
  {
    'id': 2,
    'name': 'Adidas Yeezy',
    'brand': 'Adidas',
    'price': 300,
    'category': sneakers
  }
]

http://127.0.0.1:8000/api/categories/t-shirts

[
  {
    'id': 1,
    'name': 'Black Nike T-Shirt'
    'brand': 'Nike',
    'price': 50,
    'category': t-shirts
  },
  {
    'id': 2,
    'name': 'Black Adidas T-Shir',
    'brand': 'Adidas',
    'price': 40,
    'category': t-shirts
  }
]

and so on...

A: @HezretSaryyev, your original question was different. I've edited this answer by your changed question.
You can do something like this using djangrestframework:
As example:
Your models.py
class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=50, unique=True)
    price = models.IntegerField()
    brand = models.CharField(max_length=20)
    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
    barcode = models.IntegerField(default=None, validators=[MinValueValidator(10000000), MaxValueValidator(99999999)], unique=True)
    image = models.CharField(max_length=264)

    def __str__(self):
        return self.name

Your serializers.py
Here is in serializers.py you should use this import from rest_framework import serializers, from .models import Category, Product
class CategoryNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('name',)

class ProductListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id', 'name')

class ProductDetailSerializer(serializers.ModelSerializer):
    category = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Product
        fields = ('id', 'name', 'price', 'brand', 'category', 'barcode', 'image')

class CategoryListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')

Your views.py
Here is in views.py you should use this import from rest_framework import generics, from rest_framework import views, from rest_framework.response import Response
class CategoryListAPIView(generics.ListCreateAPIView):
    queryset = Category.objects.all()
    serializer_class = serializers.CategoryListSerializer

class CategoryDetailAPIView(views.APIView):
    def get(self, request, name):
        products = Product.objects.filter(category__name=name)
        serializer = serializers.ProductDetailSerializer(products, many=True)
        return Response(serializer.data)

class ProductListAPIView(generics.ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = serializers.ProductListSerializer

class ProductDetailAPIView(generics.RetrieveAPIView):
    queryset = Product.objects.all()
    serializer_class = serializers.ProductDetailSerializer
    lookup_field = 'name'

Your urls.py
urlpatterns = [
    path('categories/', views.CategoryListAPIView.as_view(), name='category-list'),
    path('categories/<str:name>', views.CategoryDetailAPIView.as_view(), name='category-detail'),
    path('products/', views.ProductListAPIView.as_view(), name='product-list'),
    path('products/<str:name>', views.ProductDetailAPIView.as_view(), name='product-detail'),
]

A: One solution is to register a URL with a placeholder that assigns part of the path to a variable:
# urls.py

urls = [
    path('api/categories/<string:category>', views.product_by_category, name=product_by_category)
]

Now django will send a category parameter to your view that you can use to get the products you want:
# views.py

def product_by_category(request, category):
    # get the products and serialize them as JSON or render a template to HTML
    pass

You will need to replace pass with the appropriate logic to return the correct response.


text:
Q: When you have an array of structs, is there a fast way to copy a single member of the struct into a different array of that members type? (C++) I know you can simply loop on the indexes of the struct and the array, but is there something like memcpy that is faster?
Simple, but not that fast example:
struct MyStruct
{
    double member1;
    unsigned int member2;
};

const int size = 100;
MyStruct arStructs[size];
unsigned int arUnsignedInts[size];

// ...Do initialization of arStructs here...

for (int i = 0; i < size; i++)
    arUnsignedInts[i] = arStructs[i].member2;

A: Profile your version first to get a baseline.
Try loop unrolling:
for (int i = 0; (i + 4) < size; i += 4)
{
    const unsigned int a = arStructs[i + 0].member2;
    const unsigned int b = arStructs[i + 1].member2;
    const unsigned int c = arStructs[i + 2].member2;
    const unsigned int d = arStructs[i + 3].member2;

    arUnsignedInts[i + 0] = a;
    arUnsignedInts[i + 1] = b;
    arUnsignedInts[i + 2] = c;
    arUnsignedInts[i + 3] = d;
}
// Process the remainder(s)
for (; i < size; i++)
    arUnsignedInts[i] = arStructs[i].member2;

The goal is for the compiler to generate 4 reads from the array of structures into registers, then generate 4 writes from registers to the array of unsigned integers.  Hopefully, this will reduce the quantity of cache misses by loading registers from nearby entities. In your example, worst case is that the data cache is reloaded during each copy.  In my example, it reloads the cache every 4th copy.


text:
Q: custom php random function Any php random function which gives number of random numbers specified and with in the boundaries defined.
For example numbers from 1 to 5000
And I need 5 random numbers.
I know there is function which work for array indexes array_rand
I need similar for numbers and boundaries defines. At least the upper boundry defined.

A: Here I used mt_rand instead rand (much faster):
function randomNumbers($min, $max, $count = 1) {
    $randomFunc = function () use ($min, $max) { return mt_rand($min, $max); };
    return array_map($randomFunc, range(1, $count));
}

A: You can try this
 <?php
    function random_generator($digits)
      {
            srand((double) microtime() * 10000000);
            //Array of alphabets or numeric ,you can define
            $input = array ("0", "1", "2", "3","4");

            $random_generator="";// Initialize the string to store random numbers
            for($i=1;$i<$digits+1;$i++)
            { // Loop the number of times of required digits

                if(rand(1,2) == 1){// to decide the digit should be numeric or alphabet
                // Add one random alphabet
                $rand_index = array_rand($input);
                $random_generator .=$input[$rand_index]; // One char is added
            }
            else
            {
                // Add one numeric digit between 1 and 10
                $random_generator .=rand(1,10); // one number is added
            }
            // end of if else
        }
        // end of for loop

            return $random_generator;
        }

    echo random_generator(5);
?>

A: Why not make a function?
function randomArray($count, $min, $max){
    $randomArray = array();
    for ($i = 0; $i < $count; $i++) {
        $randomArray[] = rand($min, $max);
    }
    return $randomArray;
}

Your case would be:
$randoms = randomArray(5, 1, 5000);

A: Will return unique random number, you have pass 3 value to function: Min, Max and Count (number of random value)
function rand5($min,$max,$count){
    $num = array();
    for($i=0 ;i<$count;i++){
        if(!in_array(mt_rand($min,$max),$num)) {
            $num[]=mt_rand($min,$max);
        }
        else {
            $i--;
        }
    }
return $num;
}

Hope will help!

A: use of define may be alternative in PHP

<!DOCTYPE html>

<?php
// code by Bhupinder Deol
define('MIN', 1);
define('MAX', 49);
define('ROWS', 10);
define('NUMS', 6);

for($y=0;$y <ROWS;$y++){  // for loop started  for $y
             for($x=0;$x<NUMS;$x++) {
                                       $a[$x]=rand(MIN,MAX);
                                    }
                                        asort($a);
                                        $a=array_unique($a);
                            if (count($a) == NUMS)

                                  {
                                     // print_r($a);
                                                        echo "
";
                                                    foreach ($a as $value) {

                                                                               echo "$value	";

                                                                               //   echo  $value."  ";
                                                                             }

                                               echo "
";

                   `enter code here`                                   $x=0;
                                     }
                                              else
                                                   {
                                                       --$y;
                                                        $x=0;
                                                    }
                          } // for loop ended for $y
?>

 Total lottery lines  created =  <?php echo ROWS."  for ".  NUMS. "/" .MAX; ?>


text:
Q: Connecting WMB to database I am new to WMB and I want to connect WMB to database. Please letme know which database will be good and please let me know the initial steps for connecting WMB to DB.
Thanks
Amit Khandelwal

A: WMB connects to a database via DSN. So, first thing you have to do is, creating a DSN.
Steps to create DSN will vary from OS to OS. For windows follow these steps in this link.

After creating DSN you have to attach it to your broker. Use
  mqsisetdbparms for this purpose.

After giving mqsisetdbparms, you need to restart your broker.

In your message flow you have to give the same DSN name in the
  "Database Source name property.

You can check if the broker is able to connect to the database using mqsicvp command.
Regarding, "which database will be good".
WMB works fine with all well known DB providers, like oracle, DB2 etc(As it uses DSN).
But since both WMB and DB2 are IBM products, I would guess they will mingle better with each other. We are using both Oracle and DB2 and we have got no complains for any of them.
Complete video Tutorial on connecting WMB to Database
All these documentation from IBM is very confusing and it takes lots of efforts in make all these things together. I found this video tutorial on youtube which explains connecting wmb to database step by step.
Configure Database on WebSphere Message Broker or Integration Bus
Connecting WMB to Database


text:
Q: How can I read a QueryString in CodeIgniter? I know it's been asked before, but I need it for affiliate tracking...
http://www.mysite.com/controller/method/params?affiliate=123&sub_id=456
How can I get the params AND the $_GET parameters outlined in that URL?

A: You can always get the data like this:
$this->input->get('your_get_variable', TRUE);

Hope this works!

A: And yet, sometimes you need access to GET variables in CodeIgniter.
One glaring example is when you use an API that sends a post-back to your site (Paypal, etc.)
The easiest way, in my opinion, is to parse a server variable with the GET data you need since $_GET has been wiped (in my example, REQUEST_URI has my GET data.):
parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);

This allows the functionality exactly where you need it without requiring a global change to framework settings.
Here is a usage example.
class Pgate extends Controller {
   function postback() {
      parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
      $receipt = $this->input->xss_clean($_GET['receipt']);
   }
}

A: If you really want to use the query string in codeigniter you can use http://site.com?c=controller&m=method&param1=x&param2=y
This isn't the convention in codeigniter usually people use slashes to delimit params.


text:
Q: ML.NET plotting K-means clustering results? I'm experimenting with ML.NET in an unsupervised clustering scenario. My start data are less than 30 records with 5 features in a TSV file, e.g. (of course the label will be ignored):
Label   S1   S2   S3   S4   S5
alpha   0.274167987321712   0.483359746434231   0.0855784469096672   0.297939778129952   0.0332805071315372
beta   0.378208470054279   0.405409549510871   0.162317151706584   0.292342604802355   0.0551994848048085
...

My start point was the iris tutorial, a sample of K-means clustering. In my case I want 3 clusters. As I'm just learning, once created the model I'd like to use it to add the clustering data to each record in a copy of the original file, so I can examine them and plot scatter graphs.
I started with this training code (say MyModel is the POCO class representing its model, with properties for S1-S5):
// load data
MLContext mlContext = new MLContext(seed: 0);
IDataView dataView = mlContext.Data.LoadFromTextFile<MyModel>
    (dataPath, hasHeader: true, separatorChar: '\t');

// train model
const string featuresColumnName = "Features";
EstimatorChain<ClusteringPredictionTransformer<KMeansModelParameters>>
    pipeline = mlContext.Transforms
    .Concatenate(featuresColumnName, "S1", "S2", "S3", "S4", "S5")
    .Append(mlContext.Clustering.Trainers.KMeans(featuresColumnName,
    numberOfClusters: 3));

TransformerChain<ClusteringPredictionTransformer<KMeansModelParameters>>
    model = pipeline.Fit(dataView);

// save model
using (FileStream fileStream = new FileStream(modelPath,
    FileMode.Create, FileAccess.Write, FileShare.Write))
{
    mlContext.Model.Save(model, dataView.Schema, fileStream);
}

Then, I load the saved model, read every record from the original data, and get its cluster ID. This sounds a bit convoluted, but my learning intent here is inspecting the results, before playing with them. The results should be saved in a new file, together with the centroids coordinates and the points coordinates.
Yet, it does not seem that this API is transparent enough to easily access the centroids; I found only a post, which is rather old, and its code no more compiles. I rather used it as a hint to recover the data via reflection, but this is a hack.
Also, I'm not sure about the details of the data provided by the framework. I can see that every centroid has 3 vectors (named cx cy cz in the sample code), each with 5 elements (the 5 features, in their concatenated input order, I presume, i.e. from S1 to S5); also, each prediction provides a 3-fold distance (dx dy dz). If these assumptions are OK, I could assign a cluster ID to each record like this:
// for each record in the original data
foreach (MyModel record in csvReader.GetRecords<MyModel>())
{
    // get its cluster ID
    MyPrediction prediction = predictor.Predict(record);

    // get the centroids just once, as of course they are the same
    // for all the records referring their distances to them
    if (cx == null)
    {
        // get centroids (via reflection...):
        // https://github.com/dotnet/machinelearning/blob/master/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Clustering/KMeansWithOptions.cs#L49
        // https://social.msdn.microsoft.com/Forums/azure/en-US/c09171c0-d9c8-4426-83a9-36ed72a32fe7/kmeans-output-centroids-and-cluster-size?forum=MachineLearning
        VBuffer<float>[] centroids = default;
        var last = ((TransformerChain<ITransformer>)model)
            .LastTransformer;
        KMeansModelParameters kparams = (KMeansModelParameters)
            last.GetType().GetProperty("Model").GetValue(last);
        kparams.GetClusterCentroids(ref centroids, out int k);
        cx = centroids[0].GetValues().ToArray();
        cy = centroids[1].GetValues().ToArray();
        cz = centroids[2].GetValues().ToArray();
    }

    float dx = prediction.Distances[0];
    float dy = prediction.Distances[1];
    float dz = prediction.Distances[2];
    // ... calculate and save full details for the record ...
}

Given this scenario, I suppose I can get all the details about each record position in a pretrained model in the following way:

*

*dx, dy, dz are the distances.

*cx[0] cy[0] cy[0] + the distances (dx, dy, and dz respectively) should be the position of the S1 point; cx[1] cy[1] cz[1] + the distances the position of S2; and so forth up to S5 (cx[4] etc).

In this case, I could plot these data in a 3D scatter graph. Yet, I'm totally new to ML.NET, and thus I'm not sure about these assumptions, and it's well possible I'm on the wrong path. Could anyone point me in the right direction?

A: I just figured this out myself - took a bit of digging so for those interested heres some good info:
The centroids can now be retrieved right off the fit model via
VBuffer<float>[] centroids = default;
var modelParams = trainedModel.Model;
modelParams.GetClusterCentroids(ref centroids, out var k);

However the documentation here is annoyingly misleading because the centroids they claim are "coordinates" are not coordinates but rather the mean values of the features columns for the cluster.
Based on your pipeline this probably makes them pretty useless if like me you have 700 feature columns and half a dozen transformation steps.  As far as I can tell (please correct me if I'm wrong anyone!!!) there is no way to transform the centroids into Cartesian coordinates for charting.
But we can still use them.
What I ended up doing was after training my model on my data I ran all my data through the model's prediction function.  This gives me the predicted cluster id and euclidean distances to all other cluster centroids.
Using the predicted cluster id and the centroid means for the cluster you can map your datapoint's features over the means to get a "weighted value" of your data row based on the predicted cluster.  Basically a centroid will contain info that it contains a certain column 0.6533, and another column 0.211, and another column 0.  By running your datapoint features, lets say ( 5, 3, 1 ), through the centroid you'll get ( 3.2665, 0.633, 0 ).  Which is a representation of the data row as included in the predicted cluster.
This is still just a row of data however - to make them into Cartesian coordinates for a point graph I simply use a sum of the first half as X and a sum of the second half as Y.  For the example data the coord would be ( 3.8995, 0 )
Doing this we can finally get pretty charts
And here's a mostly complete code example:

VBuffer<float>[] centroids = default;
var modelParams = trainedModel.Model;
modelParams.GetClusterCentroids(ref centroids, out var k);

// extract from the VBuffer for ease
var cleanCentroids = Enumerable.Range(1, 5).ToDictionary(x => (uint)x, x =>
{
    var values = centroids[x - 1].GetValues().ToArray();
    return values;
});

var points = new Dictionary<uint, List<(double X, double Y)>>();
foreach (var dp in featuresDataset)
{
    var prediction = predictor.Predict(dp);

    var weightedCentroid = cleanCentroids[prediction.PredictedClusterId].Zip(dp.Features, (x, y) => x * y);
    var point = (X: weightedCentroid.Take(weightedCentroid.Count() / 2).Sum(), Y: weightedCentroid.Skip(weightedCentroid.Count() / 2).Sum());

     if (!points.ContainsKey(prediction.PredictedClusterId))
         points[prediction.PredictedClusterId] = new List<(double X, double Y)>();
     points[prediction.PredictedClusterId].Add(point);

}

Where featuresDataset is an array of objects that contain the feature columns being fed to the kmeans trainer.  See the microsoft docs link above for an example - featuresDataset would be testData in their sample.


text:
Q: How to find features of a word variant (using SimpleNLG)? My idea is to, given a word variant and a base form from another word, reproduce the features from the word variant in the base form.
I've been able to produce a word variant from a base form given a set of features, my problem lies on gathering these feature from the original word variant.
So far, my workaround is to use Stanford Parser and filter the POS tags of the word variant, thus recovering some (but not most) features. Then using SimpleNLG I'm able to create the new word variant.
Any other tools or libraries for Java, that provide these functionalities, are also welcome.
Thanks in advance

A: SimpleNLG is as the name suggests... simple. You may want to take a look at libraries handling language at a more semantic level. Of notable examples there is OpenCCG (http://openccg.sourceforge.net/). This is going to be a bit of work though.


text: Q: Pathway to learning perfectoid spaces. If one has as a starting point the "standard knowledge" of IMO and strong notions in algebra, topology and analysis, and if the end of the road is to reach a high level in algebraic geometry (specialised in perfectoid spaces) to be able to carry out research in the area, which subjects, books, courses , resources , seminars etc. are recommended to have a direct and complete path (achieve the desired goal)?


text:
Q: Boundary Value Analysis - When to use two value or three value? I had a few questions regarding boundary value analysis that I was hoping someone could help me with. I am learning this for a university exam based off of the ISTQB spec, not for real world application at the moment.
The first is - when should you assume to use two and three value methods of BVA? Is there any actual distinction as to when you should use one or the other, or does it depend on the specific question asked (in terms of an examination) and I would simply need to just know how to use both? Is there a default method to use?
Secondly, consider this possible question:

A smart home app measures the average temperature in the
  house and provides feedback to the occupants for different
  average temperature ranges:
  • Up to 10 C – Icy cool!
  • 11 C to 15 C - Chilled out!
  • 16 C to 19 C - Cool man!
  • 20 C to 22 C –Too warm!
  • Above 22 C - Hot and Sweaty!
  Apply 3 point BVA to the above temperature ranges. How many test cases would you consider?

The answer that was provided was that:
    For 10 - we would test 9, 10, 11.
    For 11 - we would test 10 (already tested), 11 (already tested), 12
    For 16 - we would test 15, 16, 17
    For 20 - we would test 19, 20, 21
    For 22 - we would test 21 (already tested), 22, 23
    This would result in a a total of 12 test cases.

Can somebody please explain to me as to why we would test the upper boundary in the first partition (10 degrees), but not the upper boundaries in other valid partitions (such as 15, which would lead to us testing 14,15,16 or 19 leading to testing 18,19,20). Is this because the boundary of 10 is the only boundary within that partition, as the lower boundary is open?
As a follow on, assume that the boundaries were instead:

• 0 C to 10 C – Icy cool!
  • 11 C to 15 C - Chilled out!
  • 16 C to 19 C - Cool man!
  • 20 C to 22 C –Too warm!
  • 23 - 40 C - Hot and Sweaty!

Would the values that are tested then change to the below? Would we still need to test the upper boundary in the first partition, or would we now ignore this as we have a lower boundary value?
For the lower invalid partition -2, -1, 0
For the first valid partition: -1, 0, 1
For the second valid  partition:   10, 11, 12
For the third valid  partition:   15, 16, 17
For the fourth valid  partition:   19, 20, 21
For the fifth valid  partition:   22, 23, 24
For the upper invalid partition: 40, 41, 42

Thank you in advance - I think I have been over complicating things in my head and wracking my brain over this!

A: 3-value boundaries are not strictly required. E.g. in your example 9 and 10 are from the same equivalence class. Personally I'd either skip 9 completely or randomize values across the whole partition.
In your "provided answers" the division "which cases relate to which partition" is arbitrary. Is 11 a "negative" boundary for ∞-10 range or a "positive" boundary for 11-15 range? There's no right answer. In practice you'll simply write these 8 checks w/o labelling which one is for which boundary:
* 10     - Icy
* 11, 15 - Chilled out
* 16, 19 - Cool man
* 20, 22 - Too warm
* 23     - Hot and Sweaty

If you decide to go with "3-value method" and check non-boundary values for each range you'll get additional 5 cases because there are 5 ranges.
Interestingly your "provided answer" is inconsistent. Every equivalence class has non-boundary value checked except for the "Hot and Sweaty" - it should've had 24 on the list resulting in 13 cases.
Disclaimer: this is an answer of a practitioner. I haven't read ISTQB, so if you need this info to pass a test (as opposed to using it in practice)  - use it with caution.

A: Jordan -
You have a point and I think the authors of the question you quote made a mistake. Following the ISTQB definition (CTFL 2018, Section 4.2.2): "three boundary values per boundary: the values before, at, and just over the boundary."
The problem is that almost everywhere you look, the examples given are of a single valid range, with invalid ranges on both sides ("almost everywhere" includes Jorgensen's book, "SW testing, a Craftsman's Approach", which the ISTQB syllabus quotes as reference in this case).
Following the ISTQB definition above, for EACH boundary value, you need to repeat the "before, at, and just over" analysis. For the first example, this would give you:
For 10 - we would test 9, 10, 11.
For 11 - we would test 10 (already tested), 11 (already tested), 12
For 15 - we would test 14, 15, 16
For 16 - we would test 15 (already tested), 16 (already tested), 17
For 19 - we would test 18, 19, 20
For 20 - we would test 19 (already tested), 20 (already tested), 21
For 22 - we would test 21 (already tested), 22, 23

This would result in a a total of **14** test cases.

There is one way to explain the 12 tests in the answer, and for that you need to read "The Boundary Value Fallacy" by René Tuinhout, in the Sep 2018 issue of "Testing Experience" Magazine (good luck finding it... I tried a bit but the places I found all asked me to create an account).
Following that article, the values 12, 14 and the values 17,18 can be "merged" (that is, testing with one of them is sufficient to find the type of errors that are possible in code that defines boundaries). But I will be very surprised if the writers of the question (which I understand aims at the Foundation level) were thinking of this. It is definitely an advanced topic.


text:
Q: not able to read data from internal storage in Android Application I'm using  MOTO G3 phone(Android Device). I wanted to get all PDF files list from my phone. I have followed this tutorial. http://kalisandroid.blogspot.in/2015/01/load-pdf-files.html . I got nothing. But when the same program is run in SONY phone it is displaying the files what was the actual problem. ow to resolve this problem ( i have written Android Manifest permissions also)?

A: Call this at runtime:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);

Do your code here:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}

For both version support code read this
For additional information on the subject read this